pi-better-background-tasks 0.12.2 → 0.13.1

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.
@@ -414,7 +414,15 @@ export function historyTailLine(state: FailureState): string | undefined {
414
414
  return history ? `Also in history: ${history}` : undefined;
415
415
  }
416
416
 
417
- const INCIDENT_CURSOR_PREFIX = "i1.";
417
+ /**
418
+ * Current incident cursor prefix. The prefix is the cursor format: it replaced
419
+ * the in-payload `x` version field so that two position witnesses fit in the
420
+ * same space (these cursors are printed inside 1 KiB incident summaries, where
421
+ * every byte competes with the count line). `i1.` cursors are still recognised
422
+ * for routing but decode as stale.
423
+ */
424
+ const INCIDENT_CURSOR_PREFIX = "i2.";
425
+ const LEGACY_INCIDENT_CURSOR_PREFIXES = ["i1."];
418
426
  const encoder = new TextEncoder();
419
427
 
420
428
  /** Longest summary or disposition-reason excerpt a compact row shows, in UTF-8 bytes. */
@@ -599,7 +607,7 @@ export interface FailureIncidentPage {
599
607
  cursor: string;
600
608
  nextCursor: string;
601
609
  hasMore: boolean;
602
- reset?: "stale-cursor" | "source-replaced";
610
+ reset?: "stale-cursor" | "source-replaced" | "cursor-corrupt";
603
611
  /** The first line continues a row begun on an earlier page. */
604
612
  startsPartial: boolean;
605
613
  /** The last line is the start of a row that continues on the next page. */
@@ -630,39 +638,67 @@ function resourceTag(resource: string | undefined): string | undefined {
630
638
  }
631
639
 
632
640
  /**
633
- * Incident cursor format. `x` is the format version: cursors minted before scope and row detail
634
- * existed (no `x`) carry byte offsets into full-detail rows of every active incident, so they reset
635
- * as stale instead of resuming inside a compact row. `h`: the explicit history view; `f`: full rows.
641
+ * Incident cursor (`i2.`). `h`: the explicit history view; `f`: full rows; `q` is an integrity tag
642
+ * over the other fields; `v` and `w` are two independent witnesses of the same fact — this page
643
+ * set at this row and byte offset (#617). A hand-copied cursor used to decode into a still
644
+ * parseable payload whose row digest no longer matched, which was reported as a replaced source and
645
+ * replayed the first page forever; it also used to resume at its decoded offset even when the page
646
+ * set had moved, skipping a failure that had just been inserted ahead of the cursor. A corrupt
647
+ * cursor now resumes only when a witness recomputed from the current rows proves its offset, and
648
+ * otherwise restarts at the first row. Both witnesses are short because these cursors are printed
649
+ * inside 1 KiB incident summaries.
636
650
  */
637
- const INCIDENT_CURSOR_FORMAT = 2;
638
- interface IncidentCursor { o: number; b: number; v: string; n: number; r?: string; h?: 1; f?: 1 }
651
+ interface IncidentCursor { o: number; b: number; v: string; w: string; n: number; r?: string; h?: 1; f?: 1 }
652
+ interface DecodedIncidentCursor { cursor: IncidentCursor; corrupt: boolean }
653
+
654
+ function incidentDigest(domain: string, revision: string, o: number, b: number): string {
655
+ return createHash("sha256").update(`${domain}\0${revision}\0${o}\0${b}`).digest("base64url");
656
+ }
657
+
658
+ /** Digest of this page set at this row and byte offset. */
659
+ function incidentPositionDigest(revision: string, o: number, b: number): string {
660
+ return incidentDigest("v", revision, o, b).slice(0, 16);
661
+ }
662
+
663
+ /** Independent witness of the same position, so damage to either digest alone stays usable. */
664
+ function incidentPositionWitness(revision: string, o: number, b: number): string {
665
+ return incidentDigest("w", revision, b, o).slice(0, 4);
666
+ }
667
+
668
+ function incidentCursorTag(payload: Record<string, unknown>): string {
669
+ const { q: _ignored, ...rest } = payload;
670
+ return createHash("sha256").update(JSON.stringify(rest)).digest("base64url").slice(0, 4);
671
+ }
639
672
 
640
673
  function encodeIncidentCursor(cursor: IncidentCursor): string {
641
- return INCIDENT_CURSOR_PREFIX + Buffer.from(JSON.stringify({ k: "i", x: INCIDENT_CURSOR_FORMAT, o: cursor.o, ...(cursor.b ? { b: cursor.b } : {}),
642
- v: cursor.v, n: cursor.n, ...(cursor.r !== undefined ? { r: cursor.r } : {}), ...(cursor.h ? { h: 1 } : {}),
643
- ...(cursor.f ? { f: 1 } : {}) }), "utf8").toString("base64url");
674
+ const payload = { o: cursor.o, ...(cursor.b ? { b: cursor.b } : {}), v: cursor.v, n: cursor.n,
675
+ ...(cursor.r !== undefined ? { r: cursor.r } : {}), ...(cursor.h ? { h: 1 } : {}),
676
+ ...(cursor.f ? { f: 1 } : {}), w: cursor.w };
677
+ return INCIDENT_CURSOR_PREFIX + Buffer.from(JSON.stringify({ ...payload, q: incidentCursorTag(payload) }), "utf8").toString("base64url");
644
678
  }
645
679
 
646
- function decodeIncidentCursor(cursor: string | undefined): IncidentCursor | undefined {
680
+ function decodeIncidentCursor(cursor: string | undefined): DecodedIncidentCursor | undefined {
647
681
  if (!cursor || !cursor.startsWith(INCIDENT_CURSOR_PREFIX)) return undefined;
648
682
  try {
649
- const parsed = JSON.parse(Buffer.from(cursor.slice(INCIDENT_CURSOR_PREFIX.length), "base64url").toString("utf8")) as { k?: string; x?: number; o?: number; b?: number; v?: string; n?: number; r?: string; h?: number; f?: number };
650
- if (parsed?.k === "i" && parsed.x === INCIDENT_CURSOR_FORMAT && typeof parsed.v === "string") {
651
- return { o: Math.max(0, Math.floor(parsed.o ?? 0)), b: Math.max(0, Math.floor(parsed.b ?? 0)), v: parsed.v,
683
+ const parsed = JSON.parse(Buffer.from(cursor.slice(INCIDENT_CURSOR_PREFIX.length), "base64url").toString("utf8")) as { o?: number; b?: number; v?: string; n?: number; r?: string; h?: number; f?: number; q?: string; w?: string };
684
+ if (typeof parsed?.v === "string" && typeof parsed.w === "string") {
685
+ return { corrupt: typeof parsed.q !== "string" || parsed.q !== incidentCursorTag(parsed), cursor: {
686
+ o: Math.max(0, Math.floor(parsed.o ?? 0)), b: Math.max(0, Math.floor(parsed.b ?? 0)), v: parsed.v, w: parsed.w,
652
687
  n: Math.max(0, Math.floor(parsed.n ?? 0)), ...(typeof parsed.r === "string" ? { r: parsed.r } : {}),
653
- ...(parsed.h === 1 ? { h: 1 as const } : {}), ...(parsed.f === 1 ? { f: 1 as const } : {}) };
688
+ ...(parsed.h === 1 ? { h: 1 as const } : {}), ...(parsed.f === 1 ? { f: 1 as const } : {}) } };
654
689
  }
655
690
  } catch { /* stale */ }
656
691
  return undefined;
657
692
  }
658
693
 
659
694
  export function isIncidentCursor(cursor: string | undefined): boolean {
660
- return Boolean(cursor?.startsWith(INCIDENT_CURSOR_PREFIX));
695
+ if (!cursor) return false;
696
+ return cursor.startsWith(INCIDENT_CURSOR_PREFIX) || LEGACY_INCIDENT_CURSOR_PREFIXES.some((prefix) => cursor.startsWith(prefix));
661
697
  }
662
698
 
663
699
  /** The scope an incident cursor pages, or undefined for anything that is not an incident cursor. */
664
700
  export function incidentCursorScope(cursor: string | undefined): IncidentScope | undefined {
665
- const parsed = decodeIncidentCursor(cursor);
701
+ const parsed = decodeIncidentCursor(cursor)?.cursor;
666
702
  return parsed ? (parsed.h ? "all" : "actionable") : undefined;
667
703
  }
668
704
 
@@ -697,7 +733,8 @@ export interface IncidentPageRequest extends IncidentRowOptions {
697
733
  */
698
734
  export function pageFailureIncidents(state: FailureState, request: IncidentPageRequest = {}): FailureIncidentPage {
699
735
  // A cursor carries its view: following a history cursor stays in history without the flag.
700
- const parsed = request.cursor ? decodeIncidentCursor(request.cursor) : undefined;
736
+ const decoded = request.cursor ? decodeIncidentCursor(request.cursor) : undefined;
737
+ const parsed = decoded?.cursor;
701
738
  const scope: IncidentScope = request.scope ?? (parsed?.h ? "all" : "actionable");
702
739
  const detail: IncidentDetail = request.detail ?? (parsed?.f ? "full" : "compact");
703
740
  const lines = formatFailureLines(state, { scope, detail });
@@ -708,14 +745,28 @@ export function pageFailureIncidents(state: FailureState, request: IncidentPageR
708
745
  let byte = 0;
709
746
  let reset: FailureIncidentPage["reset"];
710
747
  if (request.cursor) {
711
- if (!parsed || parsed.r !== resource || Boolean(parsed.h) !== (scope === "all") || Boolean(parsed.f) !== (detail === "full")) reset = "stale-cursor";
712
- else if (parsed.v !== revision) reset = "source-replaced";
748
+ const corrupt = decoded?.corrupt === true;
749
+ if (!parsed || parsed.r !== resource || Boolean(parsed.h) !== (scope === "all") || Boolean(parsed.f) !== (detail === "full")) {
750
+ reset = corrupt ? "cursor-corrupt" : "stale-cursor";
751
+ } else if (corrupt) {
752
+ // A hand-copied cursor is corruption, not a replaced source (#617), and
753
+ // its offset is never trusted on the payload's word. It resumes only
754
+ // when a witness recomputed from the current rows proves this exact
755
+ // position in this exact page set; otherwise it restarts at the first
756
+ // row, so a failure inserted ahead of the cursor is not skipped.
757
+ reset = "cursor-corrupt";
758
+ const witnessed = parsed.o <= total
759
+ && (parsed.v === incidentPositionDigest(revision, parsed.o, parsed.b)
760
+ || parsed.w === incidentPositionWitness(revision, parsed.o, parsed.b));
761
+ if (witnessed) { offset = parsed.o; byte = offset < total ? parsed.b : 0; }
762
+ } else if (parsed.v !== incidentPositionDigest(revision, parsed.o, parsed.b)) reset = "source-replaced";
713
763
  else { offset = Math.min(total, parsed.o); byte = offset < total ? parsed.b : 0; }
714
764
  }
715
765
  const maxBytes = Number.isFinite(request.maxBytes) && (request.maxBytes ?? -1) >= 0
716
766
  ? Math.floor(request.maxBytes as number)
717
767
  : 2 * 1024;
718
- const mint = (o: number, b: number) => encodeIncidentCursor({ o, b, v: revision, n: total, ...(resource !== undefined ? { r: resource } : {}),
768
+ const mint = (o: number, b: number) => encodeIncidentCursor({ o, b, v: incidentPositionDigest(revision, o, b),
769
+ w: incidentPositionWitness(revision, o, b), n: total, ...(resource !== undefined ? { r: resource } : {}),
719
770
  ...(scope === "all" ? { h: 1 as const } : {}), ...(detail === "full" ? { f: 1 as const } : {}) });
720
771
  const parts: string[] = [];
721
772
  let used = 0;
@@ -786,7 +837,7 @@ export function incidentVerbatimPage(state: FailureState, request: IncidentPageR
786
837
  nextCursor: string;
787
838
  omittedBytes: number;
788
839
  omittedRows: number;
789
- reset?: "stale-cursor" | "source-replaced";
840
+ reset?: "stale-cursor" | "source-replaced" | "cursor-corrupt";
790
841
  } {
791
842
  const page = pageFailureIncidents(state, request);
792
843
  const scope = request.scope ?? incidentCursorScope(request.cursor) ?? "actionable";
@@ -830,9 +881,12 @@ export function incidentCursorAt(state: FailureState, offset: number, resource?:
830
881
  const scope = options.scope ?? "actionable";
831
882
  const detail = options.detail ?? "compact";
832
883
  const lines = formatFailureLines(state, { scope, detail });
884
+ const revision = incidentRevision(state, scope, detail);
885
+ const o = Math.max(0, Math.floor(offset));
833
886
  const tag = resourceTag(resource);
834
- return encodeIncidentCursor({ o: Math.max(0, Math.floor(offset)), b: 0, v: incidentRevision(state, scope, detail), n: lines.length,
835
- ...(tag !== undefined ? { r: tag } : {}), ...(scope === "all" ? { h: 1 as const } : {}), ...(options.detail === "full" ? { f: 1 as const } : {}) });
887
+ return encodeIncidentCursor({ o, b: 0, v: incidentPositionDigest(revision, o, 0), w: incidentPositionWitness(revision, o, 0),
888
+ n: lines.length, ...(tag !== undefined ? { r: tag } : {}), ...(scope === "all" ? { h: 1 as const } : {}),
889
+ ...(options.detail === "full" ? { f: 1 as const } : {}) });
836
890
  }
837
891
 
838
892
  const MIN_PARTIAL_ROW_BYTES = 96;
@@ -135,7 +135,14 @@ export const OUTPUT_PAGE_DEFAULTS = {
135
135
 
136
136
  export type OutputBudgetSurface = keyof typeof OUTPUT_BUDGET_BYTES;
137
137
 
138
- export type PageReset = "stale-cursor" | "source-replaced" | "compacted";
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
- return CURSOR_PREFIX + Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
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" || (parsed.r ?? undefined) !== resource) {
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" || parsed.r !== resource) {
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
- const o = Math.max(0, Math.floor(parsed.o ?? 0));
649
- const n = Math.max(0, Math.floor(parsed.n ?? 0));
650
- const headLength = Math.max(0, Math.floor(parsed.hl ?? 0));
651
- const generationChanged = generation !== undefined && parsed.g !== generation;
652
- const bytesIntact = o <= n
653
- && n <= size
654
- && headLength <= size
655
- && (!parsed.h || shortHash(head.subarray(0, headLength)) === parsed.h)
656
- && (o === 0 || windowHash(o) === parsed.w);
657
- if (generationChanged) {
658
- // The consumer declared a compaction/replacement of this file.
659
- reset = "compacted";
660
- } else if (!bytesIntact) {
661
- // Same file object as far as stat can tell, but the bytes behind the
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
- offset = o;
667
- snapshot = n;
668
- appendReady = parsed.a === 1;
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
- lines.push(`hasMore=${page.hasMore} ${amount}${cursor}`);
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
  }