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.
Files changed (47) hide show
  1. package/README.md +131 -4
  2. package/package.json +3 -1
  3. package/src/adapter-contract.ts +16 -2
  4. package/src/batch.ts +108 -0
  5. package/src/delivery-observer.ts +42 -0
  6. package/src/goal-provider.ts +72 -5
  7. package/src/index.ts +39 -0
  8. package/src/navigator-provider.ts +175 -6
  9. package/src/observed-waits.ts +3677 -0
  10. package/src/output.ts +22 -2
  11. package/src/process.ts +100 -1
  12. package/src/runtime.ts +189 -10
  13. package/src/sandbox.ts +276 -2
  14. package/src/shared-callback-batcher.ts +18 -1
  15. package/src/shared-execution-policy.ts +2 -0
  16. package/src/shared-failure-observations.ts +78 -24
  17. package/src/shared-log-utils.ts +277 -31
  18. package/src/shared-operation-coordinator/index.ts +113 -0
  19. package/src/shared-operation-coordinator/src/errors.ts +75 -0
  20. package/src/shared-operation-coordinator/src/operations.ts +376 -0
  21. package/src/shared-operation-coordinator/src/outbox.ts +431 -0
  22. package/src/shared-operation-coordinator/src/rows.ts +439 -0
  23. package/src/shared-operation-coordinator/src/schema.ts +244 -0
  24. package/src/shared-operation-coordinator/src/sqlite.ts +239 -0
  25. package/src/shared-operation-coordinator/src/store.ts +397 -0
  26. package/src/shared-operation-coordinator/src/types.ts +648 -0
  27. package/src/shared-operation-coordinator/src/validate.ts +239 -0
  28. package/src/shared-operation-coordinator/src/waits.ts +1378 -0
  29. package/src/stall.ts +4 -1
  30. package/src/supervisor/README.md +111 -0
  31. package/src/supervisor/emit-runner.mjs +101 -0
  32. package/src/supervisor/generated/conditions.mjs +96 -0
  33. package/src/supervisor/generated/identity.mjs +95 -0
  34. package/src/supervisor/generated/process-identity.mjs +43 -0
  35. package/src/supervisor/generated/process.mjs +514 -0
  36. package/src/supervisor/generated/runner.mjs +872 -0
  37. package/src/supervisor/generated/store.mjs +605 -0
  38. package/src/supervisor/generated/types.mjs +50 -0
  39. package/src/supervisor/identity.ts +99 -0
  40. package/src/supervisor/index.ts +37 -0
  41. package/src/supervisor/invocation.ts +44 -0
  42. package/src/supervisor/runner.ts +982 -0
  43. package/src/supervisor/store.ts +649 -0
  44. package/src/supervisor/supervisor.ts +730 -0
  45. package/src/supervisor/types.ts +384 -0
  46. package/src/tools.ts +410 -12
  47. package/src/types.ts +41 -1
package/src/sandbox.ts CHANGED
@@ -27,11 +27,11 @@
27
27
 
28
28
  import { accessSync, constants, mkdirSync, realpathSync, statSync } from "node:fs";
29
29
  import { homedir } from "node:os";
30
- import { delimiter, dirname, resolve } from "node:path";
30
+ import { delimiter, dirname, isAbsolute, resolve } from "node:path";
31
31
 
32
32
  import { commandExecution } from "./process.js";
33
33
  import { baseDir } from "./registry.js";
34
- import { compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
34
+ import { canonicalizePath, compileWritePolicy, describeSandboxSupport, directApplicationTarget, maybeBuildSandboxCommand, type SandboxSeams } from "./shared-sandbox-core.js";
35
35
 
36
36
  type SandboxPermissions = {
37
37
  /** `write` = read, create and overwrite in place; `read-write` = Write & delete. */
@@ -455,6 +455,280 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
455
455
  ...(permissions ? { permissions } : {}) };
456
456
  }
457
457
 
458
+ /**
459
+ * The parent-captured task authority a worker conversation launches background
460
+ * tasks under.
461
+ *
462
+ * This is a structural subset of the Subagents task policy and is declared here
463
+ * on purpose: `pi-better-background-tasks` must keep working when the Subagents
464
+ * package is absent, so it never imports that package. The parent supplies the
465
+ * object from the policy it captured at worker launch; it is never built from
466
+ * model tool arguments, so a child cannot widen its own authority by asking for
467
+ * a different profile. The object is treated as immutable; the resolved plan is
468
+ * a copy that later changes to the source cannot alter.
469
+ *
470
+ * A present `root` means the worker was confined. An unconfined worker (the
471
+ * `sandbox:false` opt-out) has no captured task authority and passes `undefined`
472
+ * (or `null`). A `PermissionProfile`-shaped source may also express that with
473
+ * `permissions.enabled === false`.
474
+ *
475
+ * Supported intersection contract:
476
+ *
477
+ * - No worker authority: the current Background tasks profile applies unchanged.
478
+ * - Worker confined, Background tasks off: the worker's confinement and settings
479
+ * are preserved exactly.
480
+ * - Both confined, same canonical root: project/outside/credential levels take
481
+ * the weaker side, commands/network/shell are ANDed, the command cap is the
482
+ * smaller one, and deny paths are unioned.
483
+ * - Both confined with different canonical roots, or either confined side
484
+ * publishing no permission levels to intersect, refuses the launch. Dropping
485
+ * one side's file or command rules would be a weaker profile than either
486
+ * owner approved.
487
+ */
488
+ export interface WorkerSandboxPolicy {
489
+ /** Canonical project directory the parent confined the worker to. */
490
+ readonly root: string;
491
+ readonly permissions?: WorkerSandboxPermissions;
492
+ /** Concrete paths that stay non-writable inside `root`. */
493
+ readonly denyWrite?: readonly string[];
494
+ }
495
+
496
+ /** The capability levels and command switches a worker was launched with. */
497
+ export interface WorkerSandboxPermissions {
498
+ readonly projectFiles: "off" | "read" | "write" | "read-write";
499
+ readonly outsideProject: "off" | "read" | "write" | "read-write";
500
+ readonly storedCredentials: "off" | "read" | "read-write";
501
+ readonly commands: boolean;
502
+ readonly network: boolean;
503
+ readonly shell?: boolean;
504
+ readonly commandTimeoutSeconds?: number | null;
505
+ /** Present only on a `PermissionProfile`-shaped source; false = not confined. */
506
+ readonly enabled?: boolean;
507
+ }
508
+
509
+ /** Thrown when a parent-supplied worker policy is malformed; nothing was launched. */
510
+ export class InvalidWorkerSandboxPolicyError extends Error {
511
+ constructor(detail: string) {
512
+ super(`Invalid worker sandbox policy: ${detail}`);
513
+ this.name = "InvalidWorkerSandboxPolicyError";
514
+ }
515
+ }
516
+
517
+ const FILE_ACCESS_RANK = Object.freeze({ off: 0, read: 1, write: 2, "read-write": 3 } as const);
518
+ const CREDENTIAL_ACCESS_RANK = Object.freeze({ off: 0, read: 1, "read-write": 2 } as const);
519
+
520
+ type WorkerAuthority =
521
+ | { readonly confined: false }
522
+ | { readonly confined: true; readonly root: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions };
523
+
524
+ /**
525
+ * Validate and normalize the parent-captured authority before anything else
526
+ * happens. Levels are checked as a whole profile so a typo cannot narrow itself
527
+ * silently, and a relative root or deny entry is refused rather than resolved
528
+ * against Pi's own cwd.
529
+ */
530
+ function readWorkerAuthority(value: WorkerSandboxPolicy | null | undefined): WorkerAuthority {
531
+ if (value === null || value === undefined) return { confined: false };
532
+ if (typeof value !== "object" || Array.isArray(value)) {
533
+ throw new InvalidWorkerSandboxPolicyError("the parent-captured policy must be an object.");
534
+ }
535
+ const raw = value as unknown as Record<string, unknown>;
536
+ if (typeof raw.root !== "string" || raw.root.length === 0 || !isAbsolute(raw.root)) {
537
+ throw new InvalidWorkerSandboxPolicyError("root must be an absolute path.");
538
+ }
539
+ const root = canonicalizePath(raw.root);
540
+ if (root === dirname(root) || root === canonicalizePath(homedir())) {
541
+ throw new InvalidWorkerSandboxPolicyError("root must be a project directory, not the filesystem or home root.");
542
+ }
543
+ const denyWrite = raw.denyWrite;
544
+ if (denyWrite !== undefined && (!Array.isArray(denyWrite) ||
545
+ !denyWrite.every((entry) => typeof entry === "string" && isAbsolute(entry)))) {
546
+ throw new InvalidWorkerSandboxPolicyError("denyWrite must be a list of absolute paths.");
547
+ }
548
+ const deny = Object.freeze([...new Set((denyWrite as string[] | undefined) ?? [])]);
549
+
550
+ if (raw.permissions === undefined) {
551
+ return { confined: true, root, denyWrite: deny };
552
+ }
553
+ const source = raw.permissions;
554
+ if (!source || typeof source !== "object" || Array.isArray(source)) {
555
+ throw new InvalidWorkerSandboxPolicyError("permissions must be an object.");
556
+ }
557
+ const p = source as Record<string, unknown>;
558
+ if (p.enabled !== undefined && typeof p.enabled !== "boolean") {
559
+ throw new InvalidWorkerSandboxPolicyError("permissions.enabled must be a boolean.");
560
+ }
561
+ // A PermissionProfile that is not enabled grants no task authority at all.
562
+ if (p.enabled === false) return { confined: false };
563
+ if (typeof p.projectFiles !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.projectFiles)) {
564
+ throw new InvalidWorkerSandboxPolicyError("permissions.projectFiles must be off, read, write or read-write.");
565
+ }
566
+ if (typeof p.outsideProject !== "string" || !Object.hasOwn(FILE_ACCESS_RANK, p.outsideProject)) {
567
+ throw new InvalidWorkerSandboxPolicyError("permissions.outsideProject must be off, read, write or read-write.");
568
+ }
569
+ if (typeof p.storedCredentials !== "string" || !Object.hasOwn(CREDENTIAL_ACCESS_RANK, p.storedCredentials)) {
570
+ throw new InvalidWorkerSandboxPolicyError("permissions.storedCredentials must be off, read or read-write.");
571
+ }
572
+ if (typeof p.commands !== "boolean") {
573
+ throw new InvalidWorkerSandboxPolicyError("permissions.commands must be a boolean.");
574
+ }
575
+ if (typeof p.network !== "boolean") {
576
+ throw new InvalidWorkerSandboxPolicyError("permissions.network must be a boolean.");
577
+ }
578
+ if (p.shell !== undefined && typeof p.shell !== "boolean") {
579
+ throw new InvalidWorkerSandboxPolicyError("permissions.shell must be a boolean.");
580
+ }
581
+ if (p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null && !isCommandTimeoutSeconds(p.commandTimeoutSeconds)) {
582
+ throw new InvalidWorkerSandboxPolicyError(`permissions.commandTimeoutSeconds must be null or a positive, finite number of seconds up to ${MAX_COMMAND_TIMEOUT_SECONDS}.`);
583
+ }
584
+ const permissions: SandboxPermissions = {
585
+ projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
586
+ outsideProject: p.outsideProject as SandboxPermissions["outsideProject"],
587
+ storedCredentials: p.storedCredentials as SandboxPermissions["storedCredentials"],
588
+ commands: p.commands,
589
+ network: p.network,
590
+ ...(p.shell === undefined ? {} : { shell: p.shell }),
591
+ ...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds as number | null }),
592
+ };
593
+ return { confined: true, root, denyWrite: deny, permissions: Object.freeze(permissions) };
594
+ }
595
+
596
+ /** The weaker of two file-access levels; deletion is never broader than writes. */
597
+ function weakerFileAccess(
598
+ a: SandboxPermissions["projectFiles"],
599
+ b: SandboxPermissions["projectFiles"],
600
+ ): SandboxPermissions["projectFiles"] {
601
+ return FILE_ACCESS_RANK[a] <= FILE_ACCESS_RANK[b] ? a : b;
602
+ }
603
+
604
+ function weakerCredentialAccess(
605
+ a: SandboxPermissions["storedCredentials"],
606
+ b: SandboxPermissions["storedCredentials"],
607
+ ): SandboxPermissions["storedCredentials"] {
608
+ return CREDENTIAL_ACCESS_RANK[a] <= CREDENTIAL_ACCESS_RANK[b] ? a : b;
609
+ }
610
+
611
+ /** Intersect two already-validated capability profiles. */
612
+ function intersectPermissions(background: SandboxPermissions, worker: SandboxPermissions): SandboxPermissions {
613
+ const backgroundCap = isCommandTimeoutSeconds(background.commandTimeoutSeconds) ? background.commandTimeoutSeconds : undefined;
614
+ const workerCap = isCommandTimeoutSeconds(worker.commandTimeoutSeconds) ? worker.commandTimeoutSeconds : undefined;
615
+ const cap = backgroundCap === undefined ? workerCap
616
+ : workerCap === undefined ? backgroundCap : Math.min(backgroundCap, workerCap);
617
+ const shellGiven = background.shell !== undefined || worker.shell !== undefined;
618
+ const capGiven = background.commandTimeoutSeconds !== undefined || worker.commandTimeoutSeconds !== undefined;
619
+ return Object.freeze({
620
+ projectFiles: weakerFileAccess(background.projectFiles, worker.projectFiles),
621
+ outsideProject: weakerFileAccess(background.outsideProject, worker.outsideProject),
622
+ storedCredentials: weakerCredentialAccess(background.storedCredentials, worker.storedCredentials),
623
+ commands: background.commands && worker.commands,
624
+ network: background.network && worker.network,
625
+ ...(shellGiven ? { shell: background.shell !== false && worker.shell !== false } : {}),
626
+ ...(capGiven ? { commandTimeoutSeconds: cap ?? null } : {}),
627
+ });
628
+ }
629
+
630
+ /**
631
+ * The policy snapshot stored behind a worker-authored plan, so provenance and
632
+ * {@link backgroundExecutionLimits} read the effective authority rather than
633
+ * the parent's published profile.
634
+ */
635
+ function workerPlanPolicy(
636
+ plan: { readonly writableRoot: string; readonly denyWrite: readonly string[]; readonly permissions?: SandboxPermissions },
637
+ reason: string,
638
+ ): ForegroundSandboxPolicy {
639
+ return Object.freeze({
640
+ state: "enabled",
641
+ writableRoot: plan.writableRoot,
642
+ denyWrite: Object.freeze([...plan.denyWrite]),
643
+ reason,
644
+ ...(plan.permissions ? { permissions: Object.freeze({ ...plan.permissions, enabled: true }) } : {}),
645
+ policySource: "background",
646
+ });
647
+ }
648
+
649
+ /**
650
+ * Resolve how a worker-launched local background task must be confined.
651
+ *
652
+ * The effective authority is always the worker's captured task authority and
653
+ * the current Background tasks profile, never the parent session's sibling Main
654
+ * profile. When the publisher sends a Background column this reads that column;
655
+ * a legacy publisher with one profile keeps its historical meaning, which is
656
+ * already what Background tasks enforce.
657
+ *
658
+ * Validation runs before any task state exists. A malformed policy, an invalid
659
+ * command cap or level, a disabled worker command capability, differing
660
+ * canonical roots, or an unsupported intersection refuses the launch instead of
661
+ * dropping a rule. The returned plan is an immutable snapshot: it is captured
662
+ * through {@link capturePlan} so later command checks and
663
+ * {@link backgroundExecutionLimits} keep the authority this launch started with.
664
+ */
665
+ export function resolveWorkerSandboxPlan(
666
+ pi: unknown,
667
+ workerPolicy?: WorkerSandboxPolicy | null,
668
+ operation?: unknown,
669
+ tool = "bg_task_spawn",
670
+ ): ForegroundSandboxPlan {
671
+ const background = currentForegroundSandboxPolicy(pi);
672
+ let worker: WorkerAuthority;
673
+ try {
674
+ worker = readWorkerAuthority(workerPolicy);
675
+ } catch (error) {
676
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
677
+ throw error;
678
+ }
679
+
680
+ // No captured authority: the current Background tasks profile is the whole
681
+ // answer, exactly as it is for a parent-launched task.
682
+ if (!worker.confined) return capturePlan(planFor(background), background);
683
+
684
+ // Commands Off is the worker's master switch, independent of Background being
685
+ // on or off. It is checked before any plan is built.
686
+ if (worker.permissions && !worker.permissions.commands) {
687
+ const snapshot = { writableRoot: worker.root, denyWrite: worker.denyWrite, permissions: worker.permissions };
688
+ const policy = workerPlanPolicy(snapshot, "The worker task authority disables commands.");
689
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "command-execution", basis: "policy-refusal", outcome: "denied" });
690
+ throw new ForegroundSandboxBlockedError(policy,
691
+ "The worker task authority disables commands. Change the Subagents permissions before launching background tasks.");
692
+ }
693
+
694
+ const backgroundOff = !background || background.state === "inactive" || background.state === "disabled";
695
+ if (backgroundOff) {
696
+ // Preserve the worker's own confinement even though no Background profile is
697
+ // enforcing anything. Its settings are copied, never linked to the source.
698
+ const plan = {
699
+ confined: true as const,
700
+ writableRoot: worker.root,
701
+ denyWrite: Object.freeze([...worker.denyWrite]),
702
+ ...(worker.permissions ? { permissions: worker.permissions } : {}),
703
+ };
704
+ return capturePlan(plan, workerPlanPolicy(plan, "Worker task authority applies; the Background tasks profile is off."));
705
+ }
706
+
707
+ try {
708
+ const base = planFor(background);
709
+ if (!base.confined) throw new Error("Worker sandbox resolution expected a confined Background tasks plan.");
710
+ const backgroundRoot = canonicalizePath(base.writableRoot);
711
+ if (backgroundRoot !== worker.root) {
712
+ throw new ForegroundSandboxBlockedError(background,
713
+ `Cannot intersect the Background tasks root ${JSON.stringify(backgroundRoot)} with the worker root ${JSON.stringify(worker.root)}: they confine different directories, so a correct intersection cannot be constructed. Refusing rather than dropping either side's rules.`);
714
+ }
715
+ if (!base.permissions || !worker.permissions) {
716
+ throw new ForegroundSandboxBlockedError(background,
717
+ `Cannot intersect the Background tasks profile with the worker task authority because ${base.permissions ? "the worker" : "the Background tasks profile"} publishes no permission levels (file access, commands, network). Refusing rather than dropping the other side's controls; update the sandbox packages or set permissions in /sandbox.`);
718
+ }
719
+ const permissions = intersectPermissions(base.permissions, worker.permissions);
720
+ const denyWrite = Object.freeze([...new Set([...base.denyWrite, ...worker.denyWrite])]);
721
+ const plan = { confined: true as const, writableRoot: backgroundRoot, denyWrite, permissions };
722
+ return capturePlan(plan, workerPlanPolicy(plan,
723
+ "Worker task authority intersected with the Background tasks profile (weaker levels, ANDed switches, smallest cap, deny paths unioned)."));
724
+ } catch (error) {
725
+ if (error instanceof ForegroundSandboxBlockedError) {
726
+ backgroundDiagnostics(background)?.observe({ tool, operation, resource: "sandbox-backend", basis: "policy-refusal", outcome: "denied" });
727
+ }
728
+ throw error;
729
+ }
730
+ }
731
+
458
732
  /**
459
733
  * The application, shell, and time switches captured with one launch plan.
460
734
  *
@@ -604,7 +604,7 @@ export function createCallbackBatcher(
604
604
 
605
605
  const enqueue = (event: CallbackBatchEvent): boolean => {
606
606
  if (event.callback === false) return false;
607
- const key = eventKey(event);
607
+ const key = completionKey(event);
608
608
  if (pending.has(key) || inFlight.has(key)) return false;
609
609
  pending.set(key, { event, sequence: sequence++ });
610
610
  schedule(windowMs);
@@ -884,6 +884,23 @@ function eventKey(event: Pick<CallbackBatchEvent, "source" | "id" | "status">):
884
884
  return `${event.source}\u0000${event.id}\u0000${event.status}`;
885
885
  }
886
886
 
887
+ /**
888
+ * Ordinary completion identity is the run/task id, not the status wording (#624).
889
+ *
890
+ * The status field is a snapshot taken when a notification is enqueued (failure
891
+ * notes, observation gaps, timing reason). Including it in the key meant a
892
+ * not-yet-delivered run whose status changed between enqueues entered the
893
+ * pending map twice; one flush then rendered both rows and the caller saw one
894
+ * completion twice. Urgent events keep the status in their key: those are
895
+ * distinct transitions (orphaned, lost, a timing wake, a failure key), not
896
+ * restatements of a single ordinary completion. The first queued snapshot is the
897
+ * one delivered; a later status wording for the same id is dropped rather than
898
+ * re-queued, and the durable result stays the authority for failure detail.
899
+ */
900
+ function completionKey(event: Pick<CallbackBatchEvent, "source" | "id">): string {
901
+ return `${event.source}\u0000${event.id}`;
902
+ }
903
+
887
904
  function eventDisposition(
888
905
  event: Pick<CallbackBatchEvent, "isDelivered" | "getSuppressionReason">,
889
906
  ): | { kind: "deliver" } | { kind: "delivered" } | { kind: "deferred" } | { kind: "suppressed"; reason: string } {
@@ -7,6 +7,8 @@ const EXECUTION_POLICY = [
7
7
  "Serialize only for a concrete dependency, conflicting writes or ownership, resource or concurrency limit, documented rollout gate, or explicit availability requirement. Record the reason in the plan or explain it to the user. Do not invent a canary or host-by-host availability requirement.",
8
8
  "If concurrency raises an unresolved material operational trade-off (for example, draining all hosts could leave no available runners), ask the user once before the affected operations. Continue independent preparation meanwhile. Existing authorization, safety checks, workflow prerequisites, and human-approved rollout constraints remain binding; urgency does not waive them.",
9
9
  "Choose the execution mechanism after deciding what can run together: foreground tools for small, tightly coupled, or interactive work; subagents for bounded independent reasoning or implementation when the active delegation mode permits; background tasks for independent long-running commands or waits. Manual delegation forbids proactive subagents, not concurrent foreground tools or background commands. Use available batch or parallel tool interfaces where appropriate and inspect every launch receipt for failures or skipped work.",
10
+ "Established command-only jobs and external waits belong to background operations, including in coordinator mode. Use bg_task_spawn for a long command and bg_task_watch for a repeated check; use watch_delivery for supported merge delivery so a stateful domain watcher observes the queue. A subagent assignment must require reasoning or implementation beyond launching and waiting. Workers retain their assigned validation: use supervised background tools and wait_for_operations to park, then resume the same conversation to interpret and acknowledge the terminal result. A linked external wait must have a registered observer and an execution owner. Continue independent work while it runs; a task launch or a completed parked attempt is not completion of the assignment.",
11
+ "If a worker hands back a command, the coordinator launches it through background tools with the supplied cwd and inspects its terminal result before claiming verification. Workers may run focused implementation checks; moving a command to a worker does not make it a background task.",
10
12
  "A unit waiting or failing does not block other ready independent units unless the evidence shows a shared blocker. Preserve each unit's guards and rollback boundary. Before completing verification, the plan, or the goal, inspect and integrate every relevant terminal result or failure; launch is not completion.",
11
13
  ].join("\n");
12
14
 
@@ -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;