opencode-model-router 2.8.0 → 2.9.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.
Files changed (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -380,11 +380,15 @@
380
380
  // ===============================================================================================
381
381
 
382
382
  import { randomBytes } from "node:crypto";
383
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
384
+ import { appendFile, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
385
+ import { dirname, isAbsolute, join, resolve } from "node:path";
383
386
 
384
387
  import type { DoD } from "./dod";
385
388
  import type { PerimeterObservation } from "./gate";
386
389
  import type { LinkPin } from "./pin";
387
390
  import type { RiskAssessment, RiskLevel } from "./risk";
391
+ import { deserializeReference, serializeReference, type DispatchReference } from "./reference";
388
392
  import type { ChangedPath } from "./runner";
389
393
  import type { CheckPlacement, ReferenceState, Verdict } from "./types";
390
394
 
@@ -446,6 +450,10 @@ export const BACKGROUND_RETRY_BASE_MS = 30_000;
446
450
  export const BACKGROUND_MAX_ATTEMPTS = 3;
447
451
  /** R14: queued background requests; the oldest is dropped beyond it (it stays unverified). */
448
452
  export const BACKGROUND_QUEUE_MAX = MAX_ENTRIES_GLOBAL;
453
+ /** Phase 2.1: the verdict of a held entry past pendingTtlMs. */
454
+ export const HELD_TTL_REASON = "verification did not finish within pendingTtlMs";
455
+ /** Phase 2.1: the verdict of a held entry whose runs kept ending retryable. */
456
+ export const HELD_EXHAUSTED_REASON = `verification did not finish after ${BACKGROUND_MAX_ATTEMPTS} attempts`;
449
457
  /** R14: undelivered late notices per orchestrator session, and in total. */
450
458
  export const LATE_NOTICES_PER_SESSION = MAX_ENTRIES_PER_SESSION;
451
459
  export const LATE_NOTICES_MAX = MAX_ENTRIES_GLOBAL;
@@ -456,7 +464,7 @@ export const REPORTED_MEMO_MAX = TOMBSTONE_MAX;
456
464
  // Types
457
465
  // ---------------------------------------------------------------------------------------------
458
466
 
459
- export type PendingState = "unverified" | "verifying" | "verified";
467
+ export type PendingState = "unverified" | "verifying" | "verified" | "held";
460
468
 
461
469
  /**
462
470
  * R3 cross-repo P2e: the frozen perimeter of a deferred entry (data only; the registry stores it, nothing here
@@ -540,6 +548,12 @@ export interface PendingRegistration {
540
548
  readonly concurrentDispatches?: number;
541
549
  /** QA-3.1-3: the tool whose call discarded the dispatch snapshot (the change set is then unavailable). */
542
550
  readonly contaminatedBy?: string;
551
+ /**
552
+ * Phase 2.1 (v2 only): the handle reserved with `reserveHandle` at the background ack. The entry starts in
553
+ * state "held" and is excluded from listPending; `hold` names the child whose result is held.
554
+ */
555
+ readonly handle?: string;
556
+ readonly hold?: HoldRef;
543
557
  /**
544
558
  * I7 (P0.2, S12): the checkout the producer returned on (the deferred finish's tree snapshot). router_verify refuses a tree
545
559
  * on another branch by then, or one it cannot read while a branch was recorded. Absent: no snapshot then, and no check.
@@ -554,6 +568,26 @@ export interface PendingRegistration {
554
568
  readonly perimeter?: DeferredPerimeter;
555
569
  /** R3 cross-repo P2e: the check placements of a deferred entry (an `undefined` slot: no placement). Absent: none. */
556
570
  readonly placements?: readonly (CheckPlacement | undefined)[];
571
+ /**
572
+ * QA-SYNC1-3 (held entries, v2): the held gate checks a perimeter (I4) / the dispatch-time head (I7), neither journaled. Only
573
+ * the fact is journaled (`hadPerimeter` / `hadHead`), so the entry restored after a restart is unverifiable instead of being
574
+ * re-gated with fewer checks. The live entry is unchanged. Absent: none.
575
+ */
576
+ readonly heldPerimeter?: true;
577
+ readonly heldHead?: true;
578
+ /**
579
+ * QA-SYNC1-3 (held entries, v2): the head state read when the dispatch began, journaled as plain data (`dispatchHead`, with
580
+ * `hadHead`) so the gate re-run after a restart runs the same branch check. Absent: no head (or `heldHead` without a value).
581
+ */
582
+ readonly dispatchHead?: DispatchHeadState;
583
+ }
584
+
585
+ /** QA-SYNC1-3: a journaled dispatch-time head (verify/head.ts HeadState as plain data: `branch` null when detached). */
586
+ export interface DispatchHeadState {
587
+ readonly root: string;
588
+ readonly head: string;
589
+ readonly branch: string | null;
590
+ readonly reflog?: number;
557
591
  }
558
592
 
559
593
  /** I7 (P0.2): HEAD and branch at return (TreeSnapshot.head / .branch: a short name, null when detached, absent when unknown). */
@@ -566,6 +600,23 @@ export interface ReturnedTree {
566
600
  readonly reflog?: number;
567
601
  }
568
602
 
603
+ /** The held child behind a "held" entry (phase 2.1 section 2.3). */
604
+ export interface HoldRef {
605
+ readonly childSessionID: string;
606
+ readonly callID: string;
607
+ }
608
+
609
+ /** A record in pending.jsonl (phase 2.1 section 11.1); structurally the background journal's record. */
610
+ export type PendingRecord = { v: 1; kind: string } & Record<string, unknown>;
611
+
612
+ /** QA-2.1-33: the records one journal object's owner needs after a restart; called by every `recreate` of the shared path. */
613
+ export type PendingSnapshotProvider = () => readonly PendingRecord[] | Promise<readonly PendingRecord[]>;
614
+
615
+ /** The append-only journal seam; passed only when `ctx.routerHost === "v2"`. */
616
+ export interface PendingJournal {
617
+ append(record: PendingRecord, opts?: { fsync?: boolean }): Promise<void>;
618
+ }
619
+
569
620
  /** What a verification of one handle produced (2.4.3 builds it from the gate result). */
570
621
  export interface VerificationResult {
571
622
  readonly verdict: Verdict;
@@ -615,6 +666,8 @@ export interface PendingEntry {
615
666
  readonly concurrentDispatches?: number;
616
667
  /** PendingRegistration.contaminatedBy, as registered. */
617
668
  readonly contaminatedBy?: string;
669
+ /** Set while the child's result is held until the verdict (phase 2.1). */
670
+ readonly hold?: HoldRef;
618
671
  /** PendingRegistration.returnedTree, as registered. */
619
672
  readonly returnedTree?: ReturnedTree;
620
673
  /** PendingRegistration.unattributedWriters, as registered. */
@@ -623,6 +676,18 @@ export interface PendingEntry {
623
676
  readonly perimeter?: DeferredPerimeter;
624
677
  /** PendingRegistration.placements, frozen. Absent when not provided or released. */
625
678
  readonly placements?: readonly (CheckPlacement | undefined)[];
679
+ /**
680
+ * Restored after a restart from a registration that had a perimeter, which is not journaled: router_verify settles the entry
681
+ * unverifiable with {@link PERIMETER_LOST_REASON}, never a pass. Absent otherwise.
682
+ */
683
+ readonly perimeterLost?: true;
684
+ /**
685
+ * QA-SYNC1-3: restored after a restart from a held registration whose gate checked the dispatch-time head (`heldHead`), which
686
+ * is not journaled: the branch cannot be confirmed, so the entry settles unverifiable with {@link HEAD_LOST_REASON}. Absent otherwise.
687
+ */
688
+ readonly headLost?: true;
689
+ /** QA-SYNC1-3: PendingRegistration.dispatchHead (restored from the journal after a restart). Absent: none. */
690
+ readonly dispatchHead?: DispatchHeadState;
626
691
  readonly createdAt: number;
627
692
  readonly state: PendingState;
628
693
  /** Set while state is "verifying". */
@@ -710,10 +775,42 @@ export interface PendingRegistryOptions {
710
775
  readonly maxWeight?: number;
711
776
  /** Logging hook; never throws into the registry (a throwing hook is ignored). */
712
777
  readonly onEvict?: (entry: PendingEntry, cause: EvictionCause) => void;
778
+ /** Phase 2.1: called once when an entry reaches its terminal "verified" state (a throwing hook is ignored). */
779
+ readonly onVerdict?: (entry: PendingEntry, result: SettledVerification) => void;
780
+ /** Phase 2.1, v2 only: persistence of entries and state changes. Absent on v1. */
781
+ readonly persist?: PendingJournal;
782
+ /** QA-2.1-4: lifetime of a reserved handle that is neither registered nor released; default HELD_RESERVATION_TTL_MS. */
783
+ readonly reservationTtlMs?: number;
784
+ }
785
+
786
+ /**
787
+ * QA-2.1-4: a reserved handle lives at most this long. Longer than the background sweep (ATTEMPT_SWEEP_AGE_MS, 6 h,
788
+ * background.ts), which releases the handle of every attempt it closes, so the TTL only catches a path that never ends.
789
+ */
790
+ export const HELD_RESERVATION_TTL_MS = 7 * 3600_000;
791
+
792
+ export interface RestoreReport {
793
+ readonly restored: number;
794
+ /** Held entries past pendingTtlMs, settled UNVERIFIABLE. */
795
+ readonly expiredHeld: number;
796
+ readonly dropped: number;
713
797
  }
714
798
 
715
799
  export interface PendingRegistry {
800
+ /** Idempotent on `dispatchID`: a second register returns the existing entry's handle. */
716
801
  register(reg: PendingRegistration): RegisterResult;
802
+ /** Draws a handle for a held dispatch before its entry exists; undefined when no slot is free. */
803
+ reserveHandle(sessionID: string): string | undefined;
804
+ /** Gives a reserved handle back (the ack failed, or the dispatch is not held after all). */
805
+ releaseHandle(handle: string): void;
806
+ /** The entry registered under `dispatchID` (callID), if still stored. */
807
+ findByDispatch(dispatchID: string): PendingEntry | undefined;
808
+ /** The session's "held" entries, newest first (they are never listed by listPending). */
809
+ listHeld(sessionID: string): readonly PendingEntry[];
810
+ /** True when a register for `sessionID` would find a slot (entry caps; held entries are never evicted). */
811
+ hasSlot(sessionID: string): boolean;
812
+ /** v2 only: rebuilds entries from pending.jsonl records (fold by key; stale ones dropped, held ones settled). */
813
+ restore(records: readonly PendingRecord[], options: { readonly now: number }): RestoreReport;
717
814
  get(sessionID: string, handle: string): Lookup;
718
815
  listUnverified(sessionID: string, limit?: number): readonly PendingEntry[];
719
816
  listOpen(sessionID: string): readonly PendingEntry[];
@@ -731,6 +828,8 @@ export interface PendingRegistry {
731
828
  recordRejection(record: RejectionRecord): void;
732
829
  findLineage(query: LineageQuery): LineageMatch | undefined;
733
830
  stats(): PendingRegistryStats;
831
+ /** QA-2.1-16 (v2 only): the `entry` and `state` records of every live entry (a vanished journal is rewritten from them). */
832
+ persistedRecords(): PendingRecord[];
734
833
  dispose(): void;
735
834
  }
736
835
 
@@ -825,6 +924,18 @@ interface EntryRecord {
825
924
  readonly unattributedWriters: readonly string[] | undefined;
826
925
  perimeter: DeferredPerimeter | undefined;
827
926
  placements: readonly (CheckPlacement | undefined)[] | undefined;
927
+ /**
928
+ * Restored from a journal record whose registration had a perimeter (`hadPerimeter`), which is never journaled: the entry
929
+ * is unverifiable ({@link PERIMETER_LOST_REASON}). False for a live registration and for records without the flag.
930
+ */
931
+ readonly perimeterLost: boolean;
932
+ /** QA-SYNC1-3: PendingRegistration.heldPerimeter / .heldHead (journaled as `hadPerimeter` / `hadHead`); false otherwise. */
933
+ readonly heldPerimeter: boolean;
934
+ readonly heldHead: boolean;
935
+ /** QA-SYNC1-3: PendingRegistration.dispatchHead, as registered or restored (journaled as `dispatchHead`). */
936
+ readonly dispatchHead: DispatchHeadState | undefined;
937
+ /** QA-SYNC1-3: restored from a record with `hadHead` but no `dispatchHead` ({@link HEAD_LOST_REASON}). False for a live registration. */
938
+ readonly headLost: boolean;
828
939
  dod: DoD | undefined;
829
940
  reference: Promise<ReferenceState>;
830
941
  changedFiles: readonly ChangedPath[] | "unavailable";
@@ -840,6 +951,10 @@ interface EntryRecord {
840
951
  live: boolean;
841
952
  /** QA-2.4-3: router_verify reported the verdict to the session (markReplayed). */
842
953
  replayed: boolean;
954
+ /** Phase 2.1: the held child behind a "held" entry; undefined for every other entry. */
955
+ readonly hold: HoldRef | undefined;
956
+ /** Phase 2.1: retryable settles of a held entry so far (BACKGROUND_MAX_ATTEMPTS bound). */
957
+ holdAttempts: number;
843
958
  }
844
959
 
845
960
  type LookupMiss = Extract<Lookup, { readonly kind: "expired" | "unknown" }>;
@@ -896,6 +1011,1219 @@ function isNonEmptyString(value: unknown): value is string {
896
1011
  return typeof value === "string" && value.length > 0;
897
1012
  }
898
1013
 
1014
+ function isRiskAssessment(value: unknown): value is RiskAssessment {
1015
+ if (typeof value !== "object" || value === null) return false;
1016
+ const v = value as Record<string, unknown>;
1017
+ return (
1018
+ (v.level === "low" || v.level === "medium" || v.level === "high") &&
1019
+ Array.isArray(v.reasons) &&
1020
+ v.reasons.every((r) => typeof r === "string")
1021
+ );
1022
+ }
1023
+
1024
+ function isChangedFiles(value: unknown): value is readonly ChangedPath[] {
1025
+ return (
1026
+ Array.isArray(value) &&
1027
+ value.every((p) => typeof p === "object" && p !== null && typeof (p as Record<string, unknown>).path === "string")
1028
+ );
1029
+ }
1030
+
1031
+ /** A persisted definition of done; the structure is trusted past this check (written by this module). */
1032
+ function isDoD(value: unknown): value is DoD {
1033
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1034
+ }
1035
+
1036
+ /** A journaled `returnedTree` (entryRecord): `head` a string, `branch` a string or null, `root` non-empty, `reflog` a count. */
1037
+ function isReturnedTree(value: unknown): value is ReturnedTree {
1038
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
1039
+ const v = value as Record<string, unknown>;
1040
+ if (typeof v.head !== "string") return false;
1041
+ if (v.branch !== undefined && v.branch !== null && typeof v.branch !== "string") return false;
1042
+ if (v.root !== undefined && !isNonEmptyString(v.root)) return false;
1043
+ if (v.reflog !== undefined && !(typeof v.reflog === "number" && Number.isSafeInteger(v.reflog) && v.reflog >= 0)) return false;
1044
+ return true;
1045
+ }
1046
+
1047
+ /** A journaled `unattributedWriters` (entryRecord): tool names, each a non-empty string. */
1048
+ function isUnattributedWriters(value: unknown): value is readonly string[] {
1049
+ return Array.isArray(value) && value.every(isNonEmptyString);
1050
+ }
1051
+
1052
+ /** One journaled placement slot (entryRecord): null for a check without one, else a {@link CheckPlacement}. */
1053
+ function isPlacementSlot(value: unknown): value is CheckPlacement | null {
1054
+ if (value === null) return true;
1055
+ if (typeof value !== "object" || Array.isArray(value)) return false;
1056
+ const v = value as Record<string, unknown>;
1057
+ if (!isNonEmptyString(v.cwd) || typeof v.foreign !== "boolean") return false;
1058
+ if (v.top !== undefined && !isNonEmptyString(v.top)) return false;
1059
+ return v.scope === undefined || v.scope === "affected" || v.scope === "full";
1060
+ }
1061
+
1062
+ /** A journaled `placements` (entryRecord): index-aligned slots, each valid ({@link isPlacementSlot}). */
1063
+ function isPlacements(value: unknown): value is readonly (CheckPlacement | null)[] {
1064
+ return Array.isArray(value) && value.every(isPlacementSlot);
1065
+ }
1066
+
1067
+ /** The known fields of a journaled returned tree, copied (nothing else is restored). */
1068
+ function restoredReturnedTree(tree: ReturnedTree): ReturnedTree {
1069
+ return Object.freeze({
1070
+ head: tree.head,
1071
+ ...(tree.branch !== undefined ? { branch: tree.branch } : {}),
1072
+ ...(tree.root !== undefined ? { root: tree.root } : {}),
1073
+ ...(tree.reflog !== undefined ? { reflog: tree.reflog } : {}),
1074
+ });
1075
+ }
1076
+
1077
+ /** The known fields of journaled placements, copied; a null slot is a check without a placement. */
1078
+ function restoredPlacements(placements: readonly (CheckPlacement | null)[]): readonly (CheckPlacement | undefined)[] {
1079
+ return Object.freeze(placements.map((p) => (p === null ? undefined : Object.freeze({
1080
+ cwd: p.cwd,
1081
+ top: p.top,
1082
+ foreign: p.foreign,
1083
+ ...(p.scope !== undefined ? { scope: p.scope } : {}),
1084
+ }))));
1085
+ }
1086
+
1087
+ /**
1088
+ * The reason `router_verify` gives a restored entry whose registration had a perimeter: the perimeter (link pins, observed
1089
+ * statuses) is not journaled, so the entry can no longer be verified as registered (never a pass).
1090
+ */
1091
+ export const PERIMETER_LOST_REASON = "perimeter lost in restart";
1092
+ /**
1093
+ * QA-SYNC1-3: a journaled `dispatchHead`: `root` and `head` non-empty strings, `branch` a non-empty string or null (detached),
1094
+ * `reflog` absent or a non-negative integer, and no other key. Strict: anything else drops the record.
1095
+ */
1096
+ function isDispatchHead(value: unknown): value is DispatchHeadState {
1097
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
1098
+ const keys = Object.keys(value);
1099
+ if (keys.some((key) => key !== "root" && key !== "head" && key !== "branch" && key !== "reflog")) return false;
1100
+ const root: unknown = Reflect.get(value, "root");
1101
+ const head: unknown = Reflect.get(value, "head");
1102
+ const branch: unknown = Reflect.get(value, "branch");
1103
+ const reflog: unknown = Reflect.get(value, "reflog");
1104
+ return isNonEmptyString(root) && isNonEmptyString(head) && (branch === null || isNonEmptyString(branch))
1105
+ && (reflog === undefined || (typeof reflog === "number" && Number.isInteger(reflog) && reflog >= 0));
1106
+ }
1107
+ /** QA-SYNC1-3: a validated journaled head as a frozen HeadState. */
1108
+ function restoredDispatchHead(value: DispatchHeadState): DispatchHeadState {
1109
+ return Object.freeze({ root: value.root, head: value.head, branch: value.branch, ...(value.reflog !== undefined ? { reflog: value.reflog } : {}) });
1110
+ }
1111
+ /** QA-SYNC1-3: a restored held entry whose record says it had a dispatch-time head but carries none (the head cannot be confirmed). */
1112
+ export const HEAD_LOST_REASON = "cannot confirm the branch: the dispatch-time head was lost in restart, so the checks could verify another branch. Re-dispatch, or send a fresh [acceptance] block.";
1113
+
1114
+ export const REFERENCE_UNRESTORED_REASON = "reference could not be restored after a restart";
1115
+
1116
+ export interface PendingFileJournal extends PendingJournal {
1117
+ /**
1118
+ * Every parseable record of the file, in order; a torn or invalid line and an unknown `v` are skipped. A file that is
1119
+ * missing although this process saw it, wrote it or compacted it has vanished: `load` rejects (QA-2.1-8, fail closed) until
1120
+ * `recreate` rewrites it (QA-2.1-16). Every journal of the same path in this process shares one read (QA-2.1-15).
1121
+ */
1122
+ load(): Promise<PendingRecord[]>;
1123
+ /** Resolves when every append so far has reached the file. Never rejects. */
1124
+ flush(): Promise<void>;
1125
+ /**
1126
+ * QA-2.1-8: rewrites the file with `records` only (a temp file, fsync'd, renamed over the journal), behind every
1127
+ * append so far. Afterwards the file exists, so a later missing file counts as vanished.
1128
+ */
1129
+ compact(records: readonly PendingRecord[]): Promise<void>;
1130
+ /**
1131
+ * QA-2.1-16: rewrites the journal from `records` (the caller's in-memory state: every record a later restore needs),
1132
+ * the same way as `compact` (a temp file, fsync'd, renamed over the journal; the directory is created when missing),
1133
+ * behind every append so far. It is the recovery of a vanished journal: once it resolves, the vanished state is
1134
+ * reset, so later `load` and `append` calls succeed again. Rejects (and changes nothing) when the rewrite fails;
1135
+ * the caller then stays fail closed and may retry.
1136
+ *
1137
+ * QA-2.1-33: the rewrite is the union of `records` (the caller's own state: its own provider is not asked again) and
1138
+ * the snapshot of every other journal object of the same path in this process that registered a provider
1139
+ * (`setSnapshotProvider`), one record per identity (`mergePendingSnapshots`), so one instance's recreate never drops
1140
+ * another instance's records. A provider that throws or rejects fails the recreate.
1141
+ */
1142
+ recreate(records: readonly PendingRecord[]): Promise<void>;
1143
+ /**
1144
+ * QA-2.1-33: registers (or, with undefined, removes) this journal object's snapshot provider: the records a later
1145
+ * restore needs from this object's owner. Every `recreate` of the path in this process by ANOTHER journal object calls
1146
+ * it inside the shared queue (this object's own `recreate` takes its state from `records`). Removed on `dispose`.
1147
+ */
1148
+ setSnapshotProvider(provider: PendingSnapshotProvider | undefined): void;
1149
+ /** QA-2.1-8: why the compaction at start failed (the journal then stays as it was); undefined when it did not fail. */
1150
+ readonly compactionError: string | undefined;
1151
+ /**
1152
+ * QA-2.1-22: releases this journal object after its last append. When it is the last journal of the path in this
1153
+ * process, the process's writer mark is removed. Never rejects; idempotent.
1154
+ */
1155
+ dispose(): Promise<void>;
1156
+ }
1157
+
1158
+ export interface PendingFileJournalOptions {
1159
+ /** QA-2.1-8: compact the journal after the first successful load (default true). */
1160
+ readonly compactAtStart?: boolean;
1161
+ /** QA-2.1-8: the compaction also drops unheld entries and `inflight` records older than this (default: no age limit). */
1162
+ readonly ttlMs?: number;
1163
+ /** QA-2.1-22: told once when the compaction at start fails (`compactionError`); a throwing sink is ignored. */
1164
+ readonly warn?: (message: string) => void;
1165
+ /**
1166
+ * QA-2.1-22: another live process's writer mark older than this is stale (pid reuse) and does not block the compaction
1167
+ * at start; default WRITER_MARK_STALE_MS. A writer refreshes its mark at most every quarter of it while it appends.
1168
+ */
1169
+ readonly writerStaleMs?: number;
1170
+ /** Injected clock for the writer marks; default Date.now. */
1171
+ readonly now?: () => number;
1172
+ }
1173
+
1174
+ /**
1175
+ * QA-2.1-22: a writer mark of another live pid older than this does not block the compaction at start (a reused pid never
1176
+ * re-stamps it). A live writer re-stamps its mark every quarter of it while it appends.
1177
+ */
1178
+ export const WRITER_MARK_STALE_MS = 3600_000;
1179
+
1180
+ /** QA-2.1-22: the warning of a failed compaction at start (once per journal path and process). */
1181
+ export const PENDING_COMPACTION_FAILED = "pending journal compaction failed";
1182
+
1183
+ /** The message of a `load` that finds the journal gone after this process knew it (QA-2.1-8). */
1184
+ export const PENDING_JOURNAL_VANISHED = "pending journal vanished";
1185
+
1186
+ /** QA-2.1-8: the per-user state directory name of the pending journal. */
1187
+ export const PENDING_STATE_DIRNAME = "opencode-model-router";
1188
+
1189
+ /**
1190
+ * QA-2.1-8: the durable per-user directory of `pending.jsonl`, `pending.claims` and `pending.writers`: never the temp directory
1191
+ * (a temp sweep would delete held results and in-flight records). `$XDG_STATE_HOME/opencode-model-router` when that variable is
1192
+ * an absolute path (not on Windows), else `<home>/.local/state/opencode-model-router` (next to the `~/.config/opencode` override
1193
+ * file, on every platform). Pure.
1194
+ */
1195
+ export function resolvePendingJournalDir(env: { readonly homedir: string; readonly platform: string; readonly xdgStateHome?: string | undefined }): string {
1196
+ const xdg = env.xdgStateHome;
1197
+ if (env.platform !== "win32" && xdg !== undefined && xdg !== "" && isAbsolute(xdg)) return join(xdg, PENDING_STATE_DIRNAME);
1198
+ return join(env.homedir, ".local", "state", PENDING_STATE_DIRNAME);
1199
+ }
1200
+
1201
+ /**
1202
+ * Phase 2.1 section 11: the append-only `pending.jsonl` (v2 only). One writer per process: every journal
1203
+ * created for the same resolved path in this process shares one append queue, one compaction and one writer
1204
+ * mark (QA-2.1-15), so two plugin instances can never drop each other's records. Appends are serialized, and
1205
+ * `fsync: true` appends reach the disk before they resolve. Appends never recreate a vanished file: once this
1206
+ * process knew the file, a missing one fails the append and the next `load` (QA-2.1-8) until `recreate`
1207
+ * rewrites it from the caller's state (QA-2.1-16).
1208
+ */
1209
+ export function createPendingFileJournal(path: string, options: PendingFileJournalOptions = {}): PendingFileJournal {
1210
+ const key = sharedJournalKey(path);
1211
+ let found = SHARED_JOURNALS.get(key);
1212
+ if (found === undefined) {
1213
+ found = {
1214
+ path: resolve(path),
1215
+ tail: Promise.resolve(),
1216
+ madeDir: false,
1217
+ known: false,
1218
+ loading: undefined,
1219
+ lastRead: undefined,
1220
+ compactionScheduled: false,
1221
+ compactionError: undefined,
1222
+ compactionWarned: false,
1223
+ markAt: undefined,
1224
+ refs: 0,
1225
+ providers: processSnapshotProviders(key),
1226
+ };
1227
+ SHARED_JOURNALS.set(key, found);
1228
+ }
1229
+ const state: SharedJournal = found;
1230
+ state.refs += 1;
1231
+ let disposed = false;
1232
+ /** QA-2.1-33: this journal object's key in `state.providers`. */
1233
+ const self = {};
1234
+ const file = state.path;
1235
+ const now = options.now ?? Date.now;
1236
+ const staleMs = options.writerStaleMs ?? WRITER_MARK_STALE_MS;
1237
+ const writersDir = join(dirname(file), PENDING_WRITERS_DIRNAME);
1238
+ const markName = `${process.pid}.${PROCESS_CLAIM_TOKEN}`;
1239
+
1240
+ async function ensureFile(): Promise<void> {
1241
+ if (!state.madeDir) {
1242
+ await mkdir(dirname(file), { recursive: true });
1243
+ state.madeDir = true;
1244
+ }
1245
+ // `wx` creates the file once; afterwards the append below must find it ("a" alone would recreate a vanished file).
1246
+ if (!state.known) {
1247
+ try {
1248
+ await writeFile(file, "", { flag: "wx" });
1249
+ } catch (error) {
1250
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
1251
+ }
1252
+ state.known = true;
1253
+ return;
1254
+ }
1255
+ try {
1256
+ await stat(file);
1257
+ } catch (error) {
1258
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") throw new Error(PENDING_JOURNAL_VANISHED);
1259
+ throw error;
1260
+ }
1261
+ }
1262
+ /** Queues `work` behind every append, compaction and rewrite of this path in this process; the queue survives a failure. */
1263
+ function enqueue(work: () => Promise<void>): Promise<void> {
1264
+ const write = state.tail.then(work);
1265
+ state.tail = write.catch((error: unknown) => {
1266
+ void error; // surfaced to this caller below; the chain keeps going for the next append
1267
+ });
1268
+ return write;
1269
+ }
1270
+ function append(record: PendingRecord, opts?: { fsync?: boolean }): Promise<void> {
1271
+ const line = `${JSON.stringify(record)}\n`;
1272
+ return enqueue(async () => {
1273
+ await ensureFile();
1274
+ await refreshMark();
1275
+ if (opts?.fsync === true) {
1276
+ const handle = await open(file, "a");
1277
+ try {
1278
+ await handle.appendFile(line, "utf8");
1279
+ await handle.sync();
1280
+ } finally {
1281
+ await handle.close();
1282
+ }
1283
+ } else {
1284
+ await appendFile(file, line, "utf8");
1285
+ }
1286
+ });
1287
+ }
1288
+ return {
1289
+ append,
1290
+ async flush() {
1291
+ await state.tail;
1292
+ },
1293
+ compact(records) {
1294
+ // `replaceFile` also forgets the last read: a rewrite with the same size and mtime must still be read again.
1295
+ return enqueue(() => replaceFile(records));
1296
+ },
1297
+ recreate(records) {
1298
+ // QA-2.1-16: the writers directory may have vanished with the journal, so the mark is written again right away.
1299
+ // QA-2.1-33: the snapshots are taken inside the queue, so every append queued before this rewrite is in them too.
1300
+ return enqueue(async () => {
1301
+ await replaceFile(await unionOfSnapshots(records));
1302
+ state.markAt = undefined;
1303
+ await refreshMark();
1304
+ });
1305
+ },
1306
+ setSnapshotProvider(provider) {
1307
+ if (provider === undefined || disposed) state.providers.delete(self);
1308
+ else state.providers.set(self, provider);
1309
+ },
1310
+ load() {
1311
+ // QA-2.1-8: concurrent loads share one read, and a file unchanged since the last read (size and mtime) is not read again.
1312
+ const loading = (state.loading ??= readRecords().finally(() => {
1313
+ state.loading = undefined;
1314
+ }));
1315
+ return loading.then((records) => [...records]);
1316
+ },
1317
+ get compactionError() {
1318
+ return state.compactionError;
1319
+ },
1320
+ dispose() {
1321
+ if (disposed) return Promise.resolve();
1322
+ disposed = true;
1323
+ state.providers.delete(self);
1324
+ state.refs -= 1;
1325
+ if (state.refs > 0) return Promise.resolve();
1326
+ const done = state.tail
1327
+ .then(async () => {
1328
+ // Another journal of this path may have been created while the queue drained: it keeps the mark.
1329
+ if (state.refs > 0) return;
1330
+ state.markAt = undefined;
1331
+ await rm(join(writersDir, markName), { force: true });
1332
+ })
1333
+ .catch((error: unknown) => {
1334
+ void error; // a mark that cannot be removed dies with this pid (a dead pid's mark is stale) or ages out
1335
+ })
1336
+ .finally(() => {
1337
+ if (state.refs === 0 && SHARED_JOURNALS.get(key) === state) SHARED_JOURNALS.delete(key);
1338
+ });
1339
+ state.tail = done;
1340
+ return done;
1341
+ },
1342
+ };
1343
+
1344
+ async function readRecords(): Promise<readonly PendingRecord[]> {
1345
+ let info: { size: number; mtimeMs: number };
1346
+ let text: string;
1347
+ try {
1348
+ info = await stat(file);
1349
+ const last = state.lastRead;
1350
+ if (last !== undefined && last.size === info.size && last.mtimeMs === info.mtimeMs) {
1351
+ scheduleCompaction();
1352
+ return last.records;
1353
+ }
1354
+ text = await readFile(file, "utf8");
1355
+ } catch (error) {
1356
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
1357
+ if (state.known) throw new Error(PENDING_JOURNAL_VANISHED);
1358
+ return [];
1359
+ }
1360
+ throw error;
1361
+ }
1362
+ state.known = true;
1363
+ const records = parsePendingText(text);
1364
+ state.lastRead = { size: info.size, mtimeMs: info.mtimeMs, records };
1365
+ scheduleCompaction();
1366
+ return records;
1367
+ }
1368
+
1369
+ function scheduleCompaction(): void {
1370
+ if (state.compactionScheduled || options.compactAtStart === false) return;
1371
+ state.compactionScheduled = true;
1372
+ void compactAtStart();
1373
+ }
1374
+
1375
+ /**
1376
+ * QA-2.1-8: the first successful load in this process compacts the journal (`compactPendingRecords`), behind every append of
1377
+ * this process (one queue per path, QA-2.1-15), and only while no other live process holds a fresh writer mark on the same
1378
+ * journal (`pending.writers`): another process's append could land in the file the rename replaces. A failure keeps the
1379
+ * journal as it was (`compactionError`, told once to `warn`, QA-2.1-22).
1380
+ */
1381
+ function compactAtStart(): Promise<void> {
1382
+ const write = state.tail.then(async () => {
1383
+ if (await otherLiveWriter()) return;
1384
+ let text: string;
1385
+ try {
1386
+ text = await readFile(file, "utf8");
1387
+ } catch (error) {
1388
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
1389
+ throw error;
1390
+ }
1391
+ const records = parsePendingText(text);
1392
+ const kept = compactPendingRecords(records, { now: now(), ...(options.ttlMs === undefined ? {} : { ttlMs: options.ttlMs }) });
1393
+ if (kept.length >= records.length) return;
1394
+ await replaceFile(kept);
1395
+ });
1396
+ const settled = write.catch((error: unknown) => {
1397
+ const message = error instanceof Error ? error.message : String(error);
1398
+ state.compactionError = message;
1399
+ if (state.compactionWarned) return;
1400
+ state.compactionWarned = true;
1401
+ try {
1402
+ options.warn?.(`${PENDING_COMPACTION_FAILED}: ${message}`);
1403
+ } catch (warnError) {
1404
+ void warnError; // a throwing warn sink is ignored
1405
+ }
1406
+ });
1407
+ state.tail = settled;
1408
+ return settled;
1409
+ }
1410
+
1411
+ /**
1412
+ * QA-2.1-33: `records` (the caller's own state) plus the snapshot of every OTHER journal object of this path that
1413
+ * registered a provider, in registration order: the caller's own provider is not asked again. QA-DF1-18: the journal
1414
+ * objects of every module copy of the plugin in this process count (`processSnapshotProviders`). One record per identity
1415
+ * (`mergePendingSnapshots`): the same hold or attempt reaches the union from several sources with other field values.
1416
+ * A throwing provider fails the recreate, which then changes nothing.
1417
+ */
1418
+ async function unionOfSnapshots(records: readonly PendingRecord[]): Promise<PendingRecord[]> {
1419
+ const sources: (readonly PendingRecord[])[] = [records];
1420
+ for (const [owner, provider] of [...state.providers]) {
1421
+ if (owner !== self) sources.push(await provider());
1422
+ }
1423
+ return mergePendingSnapshots(sources);
1424
+ }
1425
+
1426
+ async function replaceFile(records: readonly PendingRecord[]): Promise<void> {
1427
+ const body = records.map((record) => `${JSON.stringify(record)}\n`).join("");
1428
+ await mkdir(dirname(file), { recursive: true });
1429
+ state.madeDir = true;
1430
+ // QA-DF1-18: per module copy (`<pid>.<token>`): two copies of the plugin in one process never share a temp file.
1431
+ const temp = `${file}.${process.pid}.${PROCESS_CLAIM_TOKEN}.compact`;
1432
+ try {
1433
+ const handle = await open(temp, "w");
1434
+ try {
1435
+ await handle.writeFile(body, "utf8");
1436
+ await handle.sync();
1437
+ } finally {
1438
+ await handle.close();
1439
+ }
1440
+ await rename(temp, file);
1441
+ } catch (error) {
1442
+ // QA-2.1-22: a failed write or rename leaves no temp file behind.
1443
+ await rm(temp, { force: true }).catch((cleanupError: unknown) => {
1444
+ void cleanupError; // the next rewrite opens the temp file with "w" and replaces it
1445
+ });
1446
+ throw error;
1447
+ }
1448
+ state.known = true;
1449
+ state.lastRead = undefined;
1450
+ }
1451
+
1452
+ /** QA-2.1-22: writes this process's writer mark `{pid, token, at}` (`<pid>.<token>`, one per process and path). */
1453
+ async function writeMark(): Promise<void> {
1454
+ await mkdir(writersDir, { recursive: true });
1455
+ const at = now();
1456
+ await writeFile(join(writersDir, markName), `${JSON.stringify({ pid: process.pid, token: PROCESS_CLAIM_TOKEN, at })}\n`);
1457
+ state.markAt = at;
1458
+ }
1459
+
1460
+ /**
1461
+ * QA-2.1-22: a writer re-stamps its mark while it appends (at most every quarter of `writerStaleMs`), so another process never
1462
+ * takes a live writer's mark for a reused pid's. Best effort: a mark that cannot be written is tried again at the next append.
1463
+ */
1464
+ async function refreshMark(): Promise<void> {
1465
+ if (state.markAt !== undefined && now() - state.markAt < staleMs / 4) return;
1466
+ try {
1467
+ await writeMark();
1468
+ } catch (error) {
1469
+ void error; // the append itself must not fail for its mark; the next append tries again
1470
+ }
1471
+ }
1472
+
1473
+ /**
1474
+ * Marks this process as a writer of the journal and reports whether another live process holds a fresh mark too
1475
+ * (QA-2.1-22): a dead pid's mark is removed; a live pid's mark older than `writerStaleMs` (a reused pid: a live writer
1476
+ * re-stamps its mark while it appends) does not block. QA-DF1-18: a mark of this pid under another token is another module
1477
+ * copy of the plugin in this process while it is fresh (`siblingCopyIsLive`) and blocks; a stale one is an earlier process
1478
+ * that had this pid and is removed.
1479
+ */
1480
+ async function otherLiveWriter(): Promise<boolean> {
1481
+ await writeMark();
1482
+ let other = false;
1483
+ for (const name of await readdir(writersDir)) {
1484
+ if (name === markName) continue;
1485
+ const pid = Number.parseInt(name.split(".")[0] ?? "", 10);
1486
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid && isAlive(pid)) {
1487
+ const age = await markAge(join(writersDir, name));
1488
+ if (age !== undefined && age <= staleMs) other = true;
1489
+ continue;
1490
+ }
1491
+ if (pid === process.pid && (await siblingCopyIsLive(name))) {
1492
+ // QA-DF1-18: another module copy of this plugin in this process (same pid, another token) is a live writer.
1493
+ other = true;
1494
+ continue;
1495
+ }
1496
+ await rm(join(writersDir, name), { force: true });
1497
+ }
1498
+ return other;
1499
+ }
1500
+
1501
+ /**
1502
+ * QA-DF1-18: a mark of this pid under another token is a separately loaded module copy of this plugin in this process
1503
+ * (one per booted location), or an earlier process that had this pid. It is a live writer while it is fresh: its mark
1504
+ * was stamped within `writerStaleMs` (a writer re-stamps it while it appends), or a beat file of one of the copy's
1505
+ * instances under `pending.instances` (`<copy token>.<instance>`, `writeInstanceBeat`) is fresh (`CLAIM_STALE_MS`).
1506
+ * Otherwise it is stale and removed, as before: an earlier process of this pid, or a copy that neither appends nor beats.
1507
+ */
1508
+ async function siblingCopyIsLive(name: string): Promise<boolean> {
1509
+ const cut = name.indexOf(".");
1510
+ const token = cut < 0 ? "" : name.slice(cut + 1);
1511
+ if (token === "" || token === PROCESS_CLAIM_TOKEN) return false;
1512
+ const age = await markAge(join(writersDir, name));
1513
+ if (age === undefined) return false;
1514
+ if (age <= staleMs) return true;
1515
+ return moduleCopyBeatIsFresh(join(dirname(file), PENDING_INSTANCES_DIRNAME), token, process.pid, now(), CLAIM_STALE_MS);
1516
+ }
1517
+
1518
+ /** The age of a writer mark (its `at`, else its mtime); undefined when it is gone. */
1519
+ async function markAge(markPath: string): Promise<number | undefined> {
1520
+ let text: string;
1521
+ let mtimeMs: number;
1522
+ try {
1523
+ mtimeMs = (await stat(markPath)).mtimeMs;
1524
+ text = await readFile(markPath, "utf8");
1525
+ } catch (error) {
1526
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
1527
+ throw error;
1528
+ }
1529
+ return now() - (parseMarkAt(text) ?? mtimeMs);
1530
+ }
1531
+ }
1532
+
1533
+ /** QA-2.1-15: the state every journal of one path in this process shares (one append queue, one compaction, one mark). */
1534
+ interface SharedJournal {
1535
+ readonly path: string;
1536
+ tail: Promise<unknown>;
1537
+ madeDir: boolean;
1538
+ /** This process read, wrote or compacted the file: from now on a missing file has vanished (until `recreate`). */
1539
+ known: boolean;
1540
+ /** QA-2.1-8: the read in flight (shared) and the last read with the file's size and mtime (not read again while unchanged). */
1541
+ loading: Promise<readonly PendingRecord[]> | undefined;
1542
+ lastRead: { size: number; mtimeMs: number; records: readonly PendingRecord[] } | undefined;
1543
+ compactionScheduled: boolean;
1544
+ compactionError: string | undefined;
1545
+ compactionWarned: boolean;
1546
+ /** When this process last wrote its writer mark; undefined: not written since the start, `recreate` or `dispose`. */
1547
+ markAt: number | undefined;
1548
+ /** Journal objects of this path in this process that are not disposed. */
1549
+ refs: number;
1550
+ /**
1551
+ * QA-2.1-33: the snapshot provider of each journal object of this path that registered one (`setSnapshotProvider`).
1552
+ * QA-DF1-18: the same map in every module copy of the process (`processSnapshotProviders`).
1553
+ */
1554
+ readonly providers: Map<object, PendingSnapshotProvider>;
1555
+ }
1556
+
1557
+ /** QA-2.1-15: one shared journal state per resolved path in this process (case-insensitive on Windows). */
1558
+ const SHARED_JOURNALS = new Map<string, SharedJournal>();
1559
+
1560
+ /**
1561
+ * QA-DF1-18: the snapshot providers of a journal path, shared by every module copy of this plugin in the process (one copy per
1562
+ * booted location; each has its own `SHARED_JOURNALS`), so a `recreate` in one copy also merges the records another copy
1563
+ * holds. Kept on `globalThis` under a registered symbol; a value that is not a map is replaced.
1564
+ */
1565
+ const PROCESS_PROVIDERS_KEY = Symbol.for("opencode-model-router.pending.snapshot-providers.v1");
1566
+
1567
+ function processSnapshotProviders(key: string): Map<object, PendingSnapshotProvider> {
1568
+ const holder = globalThis as unknown as Record<symbol, unknown>;
1569
+ let all = holder[PROCESS_PROVIDERS_KEY];
1570
+ if (!(all instanceof Map)) {
1571
+ all = new Map<string, Map<object, PendingSnapshotProvider>>();
1572
+ holder[PROCESS_PROVIDERS_KEY] = all;
1573
+ }
1574
+ const byPath = all as Map<string, Map<object, PendingSnapshotProvider>>;
1575
+ let found = byPath.get(key);
1576
+ if (found === undefined) {
1577
+ found = new Map();
1578
+ byPath.set(key, found);
1579
+ }
1580
+ return found;
1581
+ }
1582
+
1583
+ /**
1584
+ * QA-2.1-16/-33: what identifies a record a recreation rewrites from memory: its kind and its attempt key, else its handle
1585
+ * (`hold`, `hold-text`, `posting`, `posted`, entry and state records). Undefined for a record with neither. Pure.
1586
+ */
1587
+ export function pendingRecordIdentity(record: { readonly kind: string; readonly [field: string]: unknown }): string | undefined {
1588
+ const id = typeof record.key === "string" ? record.key : typeof record.handle === "string" ? record.handle : undefined;
1589
+ return id === undefined ? undefined : `${record.kind}\u0000${id}`;
1590
+ }
1591
+
1592
+ /**
1593
+ * QA-2.1-33: merges record lists (the caller's state, then each other instance's snapshot) into one list with one record
1594
+ * per identity (`pendingRecordIdentity`; a record without one is identified by its serialized form), whichever list or
1595
+ * position it comes from: the same hold may arrive from the adapter, the plugin and another instance with other field
1596
+ * values or field order. Of one identity the newest record (`at`) is kept, on a tie the most complete one (more fields),
1597
+ * else the first; it takes the position of the first occurrence, so the order of the first list is kept. Pure.
1598
+ */
1599
+ export function mergePendingSnapshots(lists: ReadonlyArray<readonly PendingRecord[]>): PendingRecord[] {
1600
+ const positions = new Map<string, number>();
1601
+ const union: PendingRecord[] = [];
1602
+ for (const list of lists) {
1603
+ for (const record of list) {
1604
+ const id = pendingRecordIdentity(record) ?? `json\u0000${JSON.stringify(record)}`;
1605
+ const position = positions.get(id);
1606
+ if (position === undefined) {
1607
+ positions.set(id, union.length);
1608
+ union.push(record);
1609
+ continue;
1610
+ }
1611
+ const kept = union[position];
1612
+ if (kept === undefined || supersedes(record, kept)) union[position] = record;
1613
+ }
1614
+ }
1615
+ return union;
1616
+ }
1617
+
1618
+ /** QA-2.1-33: whether `candidate` replaces `kept` (same identity): a newer `at`, else (same or no `at`) more fields. */
1619
+ function supersedes(candidate: PendingRecord, kept: PendingRecord): boolean {
1620
+ const next = typeof candidate.at === "number" && Number.isFinite(candidate.at) ? candidate.at : undefined;
1621
+ const prev = typeof kept.at === "number" && Number.isFinite(kept.at) ? kept.at : undefined;
1622
+ if (next !== undefined && prev !== undefined && next !== prev) return next > prev;
1623
+ if (next !== undefined && prev === undefined) return true;
1624
+ if (next === undefined && prev !== undefined) return false;
1625
+ return Object.keys(candidate).length > Object.keys(kept).length;
1626
+ }
1627
+
1628
+ /** QA-2.1-22: the directory of the writer marks, next to `pending.jsonl`. */
1629
+ export const PENDING_WRITERS_DIRNAME = "pending.writers";
1630
+
1631
+ function sharedJournalKey(path: string): string {
1632
+ const full = resolve(path);
1633
+ return process.platform === "win32" ? full.toLowerCase() : full;
1634
+ }
1635
+
1636
+ function parseMarkAt(text: string): number | undefined {
1637
+ try {
1638
+ const rec: unknown = JSON.parse(text);
1639
+ if (typeof rec !== "object" || rec === null) return undefined;
1640
+ const at = (rec as Record<string, unknown>).at;
1641
+ return typeof at === "number" && Number.isFinite(at) ? at : undefined;
1642
+ } catch (error) {
1643
+ void error; // a torn mark: its mtime decides
1644
+ return undefined;
1645
+ }
1646
+ }
1647
+
1648
+ /** Parses `pending.jsonl` text: a torn or invalid line and an unknown `v` are skipped. */
1649
+ function parsePendingText(text: string): PendingRecord[] {
1650
+ const records: PendingRecord[] = [];
1651
+ for (const line of text.split("\n")) {
1652
+ if (line.trim() === "") continue;
1653
+ let parsed: unknown;
1654
+ try {
1655
+ parsed = JSON.parse(line);
1656
+ } catch (error) {
1657
+ void error; // a torn line (crash mid-write) is skipped
1658
+ continue;
1659
+ }
1660
+ if (typeof parsed !== "object" || parsed === null) continue;
1661
+ const rec = parsed as Record<string, unknown>;
1662
+ if (rec.v !== 1 || typeof rec.kind !== "string") continue;
1663
+ records.push({ ...rec, v: 1, kind: rec.kind });
1664
+ }
1665
+ return records;
1666
+ }
1667
+
1668
+ /** `process.kill(pid, 0)`: alive, or alive but not ours (EPERM). */
1669
+ function isAlive(pid: number): boolean {
1670
+ try {
1671
+ process.kill(pid, 0);
1672
+ return true;
1673
+ } catch (error) {
1674
+ return (error as NodeJS.ErrnoException).code === "EPERM";
1675
+ }
1676
+ }
1677
+
1678
+ /**
1679
+ * QA-2.1-8: the records of `pending.jsonl` that still matter, in journal order. The pending registry's `restore` and
1680
+ * `foldDormantRecords` read the result exactly as they read the full journal: superseded `entry`/`ref`/`state` records, entries
1681
+ * that ended `verified`, everything a `tomb` or a `forget` closed (and those records themselves), `inflight` records closed by
1682
+ * `processed` (and every `processed` record: no attempt of an earlier process survives to need its key), the `hold-text` and
1683
+ * older `posting` records of a hold, the follow-ups of a posted hold (its `hold` and `posted` stay: an inactive placeholder,
1684
+ * QA-2.1-10), and records that change nothing (a `state` or follow-up of an unknown handle) are dropped. With `ttlMs`, unheld
1685
+ * entries and `inflight` records older than it go too (the readers drop them anyway). Unknown kinds are kept. Pure.
1686
+ */
1687
+ export function compactPendingRecords(records: readonly PendingRecord[], opts: { now: number; ttlMs?: number }): PendingRecord[] {
1688
+ const keep = records.map(() => true);
1689
+ const str = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined);
1690
+ const parentOf = (rec: PendingRecord): string | undefined => str(rec.parent) ?? str(rec.parentSessionID);
1691
+ const childOf = (rec: PendingRecord): string | undefined => str(rec.child) ?? str(rec.childSessionID);
1692
+ const drop = (...indexes: Array<number | undefined>): void => {
1693
+ for (const index of indexes) if (index !== undefined) keep[index] = false;
1694
+ };
1695
+ const entries = new Map<string, { entry: number; ref?: number; state?: number; stateValue: string; parent?: string; held: boolean; at: number }>();
1696
+ const holds = new Map<string, { hold: number; text?: number; posting?: number; posted?: number; parent?: string }>();
1697
+ const inflight = new Map<string, { index: number; parent?: string; at: number }>();
1698
+ const dropEntry = (handle: string): void => {
1699
+ const e = entries.get(handle);
1700
+ if (e !== undefined) drop(e.entry, e.ref, e.state);
1701
+ entries.delete(handle);
1702
+ };
1703
+ const dropHold = (handle: string): void => {
1704
+ const h = holds.get(handle);
1705
+ if (h !== undefined) drop(h.hold, h.text, h.posting, h.posted);
1706
+ holds.delete(handle);
1707
+ };
1708
+ records.forEach((rec, index) => {
1709
+ const handle = str(rec.handle);
1710
+ const callID = str(rec.callID);
1711
+ switch (rec.kind) {
1712
+ case "entry": {
1713
+ if (handle === undefined) return;
1714
+ dropEntry(handle);
1715
+ const at = typeof rec.createdAt === "number" ? rec.createdAt : opts.now;
1716
+ const parent = str(rec.parent);
1717
+ entries.set(handle, {
1718
+ entry: index, stateValue: str(rec.state) ?? "unverified", held: rec.state === "held", at, ...(parent === undefined ? {} : { parent }),
1719
+ });
1720
+ return;
1721
+ }
1722
+ case "ref": {
1723
+ const e = handle === undefined ? undefined : entries.get(handle);
1724
+ // A ref with no stored entry of its handle applies by `callID` in `restore`: kept as it is.
1725
+ if (e === undefined) return;
1726
+ drop(e.ref);
1727
+ e.ref = index;
1728
+ return;
1729
+ }
1730
+ case "state": {
1731
+ const e = handle === undefined ? undefined : entries.get(handle);
1732
+ if (e === undefined || typeof rec.state !== "string" || rec.state === "") {
1733
+ drop(index);
1734
+ return;
1735
+ }
1736
+ drop(e.state);
1737
+ e.state = index;
1738
+ e.stateValue = rec.state;
1739
+ return;
1740
+ }
1741
+ case "tomb": {
1742
+ // QA-2.1-28: a tomb ends a pending ENTRY (TTL, eviction, session gone). A hold is the adapter's and ends only with
1743
+ // `posted` (then an inactive placeholder) or `forget`: a tomb never takes the placeholder that hides the raw completion.
1744
+ if (handle !== undefined) dropEntry(handle);
1745
+ if (callID !== undefined) {
1746
+ drop(inflight.get(callID)?.index);
1747
+ inflight.delete(callID);
1748
+ }
1749
+ drop(index);
1750
+ return;
1751
+ }
1752
+ case "forget": {
1753
+ const session = str(rec.session);
1754
+ if (session !== undefined) {
1755
+ for (const [h, e] of [...entries]) if (e.parent === session) dropEntry(h);
1756
+ for (const [h, v] of [...holds]) if (v.parent === session) dropHold(h);
1757
+ for (const [c, v] of [...inflight]) {
1758
+ if (v.parent !== session) continue;
1759
+ drop(v.index);
1760
+ inflight.delete(c);
1761
+ }
1762
+ }
1763
+ drop(index);
1764
+ return;
1765
+ }
1766
+ case "inflight": {
1767
+ // `foldDormantRecords` takes an inflight record only with a call, a parent and a child; any other changes nothing.
1768
+ if (callID === undefined || parentOf(rec) === undefined || childOf(rec) === undefined) return;
1769
+ drop(inflight.get(callID)?.index);
1770
+ const parent = parentOf(rec);
1771
+ inflight.set(callID, { index, at: typeof rec.at === "number" ? rec.at : 0, ...(parent === undefined ? {} : { parent }) });
1772
+ return;
1773
+ }
1774
+ case "processed": {
1775
+ if (callID !== undefined) {
1776
+ drop(inflight.get(callID)?.index);
1777
+ inflight.delete(callID);
1778
+ }
1779
+ drop(index);
1780
+ return;
1781
+ }
1782
+ case "hold": {
1783
+ if (handle === undefined || parentOf(rec) === undefined || childOf(rec) === undefined) return;
1784
+ dropHold(handle);
1785
+ const parent = parentOf(rec);
1786
+ holds.set(handle, { hold: index, ...(parent === undefined ? {} : { parent }) });
1787
+ return;
1788
+ }
1789
+ case "hold-text":
1790
+ case "posting": {
1791
+ const h = handle === undefined ? undefined : holds.get(handle);
1792
+ if (h === undefined || h.posted !== undefined) {
1793
+ drop(index);
1794
+ return;
1795
+ }
1796
+ if (rec.kind === "hold-text") {
1797
+ drop(h.text);
1798
+ h.text = index;
1799
+ } else {
1800
+ drop(h.posting);
1801
+ h.posting = index;
1802
+ }
1803
+ return;
1804
+ }
1805
+ case "posted": {
1806
+ const h = handle === undefined ? undefined : holds.get(handle);
1807
+ if (h === undefined) {
1808
+ drop(index);
1809
+ return;
1810
+ }
1811
+ drop(h.text, h.posting, h.posted);
1812
+ h.text = undefined;
1813
+ h.posting = undefined;
1814
+ h.posted = index;
1815
+ return;
1816
+ }
1817
+ default:
1818
+ return;
1819
+ }
1820
+ });
1821
+ for (const [handle, e] of entries) {
1822
+ if (e.stateValue === "verified") {
1823
+ // QA-2.1-17: the verdict of a hold that never started posting stays (its entry and `state`): the next start posts it.
1824
+ const h = holds.get(handle);
1825
+ if (h === undefined || h.posting !== undefined || h.posted !== undefined) dropEntry(handle);
1826
+ } else if (opts.ttlMs !== undefined && !e.held && opts.now - e.at >= opts.ttlMs) dropEntry(handle);
1827
+ }
1828
+ if (opts.ttlMs !== undefined) {
1829
+ for (const v of inflight.values()) if (opts.now - v.at > opts.ttlMs) drop(v.index);
1830
+ }
1831
+ // QA-2.1-28: the cap `foldDormantRecords` applies at load applies here too: past MAX_DORMANT_POSTED_HOLDS posted
1832
+ // placeholders, the oldest go (their `hold` and `posted` lines); an unposted hold is never dropped (no age, as at load).
1833
+ let postedHolds = 0;
1834
+ for (const h of holds.values()) if (h.posted !== undefined) postedHolds += 1;
1835
+ for (const [handle, h] of [...holds]) {
1836
+ if (postedHolds <= MAX_DORMANT_POSTED_HOLDS) break;
1837
+ if (h.posted === undefined) continue;
1838
+ dropHold(handle);
1839
+ postedHolds -= 1;
1840
+ }
1841
+ return records.filter((_, index) => keep[index]);
1842
+ }
1843
+
1844
+ // ---- Phase 2.1 section 11.3: reload of the in-flight / hold records (v2 only) -----------------------------------------
1845
+
1846
+ /** The records of one parent session that survived a restart; dormant until the new process sees that session. */
1847
+ export interface DormantSession {
1848
+ /**
1849
+ * `hold` records not tombstoned or forgotten (no TTL, section 11.3), each followed by its `hold-text` and newest `posting`
1850
+ * record, or, for a posted hold, by its `posted` record only (an inactive placeholder, QA-2.1-10). In journal order per hold.
1851
+ */
1852
+ holds: PendingRecord[];
1853
+ /** `inflight` records without a `processed` record, younger than the TTL. */
1854
+ inflight: PendingRecord[];
1855
+ }
1856
+
1857
+ /** The idempotency key of a `processed` record: its `key`, else `child NUL callID` (section 10). */
1858
+ export function processedKeyOf(record: Readonly<Record<string, unknown>>): string | undefined {
1859
+ if (typeof record.key === "string" && record.key !== "") return record.key;
1860
+ if (typeof record.child === "string" && typeof record.callID === "string") return `${record.child}\u0000${record.callID}`;
1861
+ return undefined;
1862
+ }
1863
+
1864
+ /**
1865
+ * Folds the parsed records of `pending.jsonl` (section 11.3): `forget` removes a session's earlier records, `processed` closes an
1866
+ * `inflight`, `posted` turns a `hold` into an inactive placeholder, and a tombstoned `callID` closes its `inflight` (QA-2.1-28: a
1867
+ * `tomb` never closes a hold). Inflight records older than `ttlMs` are dropped; hold records never expire. Pure.
1868
+ */
1869
+ export function foldDormantRecords(
1870
+ records: readonly PendingRecord[],
1871
+ opts: { now: number; ttlMs: number },
1872
+ ): { sessions: Map<string, DormantSession>; processed: Set<string> } {
1873
+ const processed = new Set<string>();
1874
+ const inflight = new Map<string, PendingRecord>();
1875
+ /** handle -> the `hold` record, then its follow-ups (`hold-text`, the newest `posting`, `posted`). */
1876
+ const holds = new Map<string, { hold: PendingRecord; text?: PendingRecord; posting?: PendingRecord; posted?: PendingRecord }>();
1877
+ /** QA-2.1-17: handle -> the newest `state` record that settled its entry `verified` with a verdict. */
1878
+ const verdicts = new Map<string, PendingRecord>();
1879
+ const str = (value: unknown): string | undefined => (typeof value === "string" && value !== "" ? value : undefined);
1880
+ /** The adapter writes `parentSessionID` / `childSessionID` on `inflight`, `parent` / `child` on `hold`: both are read. */
1881
+ const parentOf = (rec: PendingRecord): string | undefined => str(rec.parent) ?? str(rec.parentSessionID);
1882
+ const childOf = (rec: PendingRecord): string | undefined => str(rec.child) ?? str(rec.childSessionID);
1883
+ for (const rec of records) {
1884
+ switch (rec.kind) {
1885
+ case "inflight": {
1886
+ const callID = str(rec.callID);
1887
+ if (callID !== undefined && parentOf(rec) !== undefined && childOf(rec) !== undefined) inflight.set(callID, rec);
1888
+ break;
1889
+ }
1890
+ case "processed": {
1891
+ const key = processedKeyOf(rec);
1892
+ if (key !== undefined) processed.add(key);
1893
+ const callID = str(rec.callID);
1894
+ if (callID !== undefined) inflight.delete(callID);
1895
+ break;
1896
+ }
1897
+ case "hold": {
1898
+ const handle = str(rec.handle);
1899
+ if (handle !== undefined && parentOf(rec) !== undefined && childOf(rec) !== undefined) holds.set(handle, { hold: rec });
1900
+ break;
1901
+ }
1902
+ case "hold-text": {
1903
+ const held = holds.get(str(rec.handle) ?? "");
1904
+ if (held !== undefined && held.posted === undefined && typeof rec.text === "string") held.text = rec;
1905
+ break;
1906
+ }
1907
+ case "posting": {
1908
+ const held = holds.get(str(rec.handle) ?? "");
1909
+ if (held !== undefined && held.posted === undefined) held.posting = rec;
1910
+ break;
1911
+ }
1912
+ case "state": {
1913
+ const handle = str(rec.handle);
1914
+ if (handle !== undefined && rec.state === "verified" && rec.verdict !== null && typeof rec.verdict === "object") verdicts.set(handle, rec);
1915
+ break;
1916
+ }
1917
+ case "posted": {
1918
+ // QA-2.1-10: a posted hold survives as an inactive placeholder (the host history still holds the raw completion).
1919
+ const held = holds.get(str(rec.handle) ?? "");
1920
+ if (held !== undefined) holds.set(str(rec.handle) ?? "", { hold: held.hold, posted: rec });
1921
+ break;
1922
+ }
1923
+ case "tomb": {
1924
+ // QA-2.1-28: an entry tomb never closes a hold (its placeholder, or a hold still owed a verdict): see compaction.
1925
+ const callID = str(rec.callID);
1926
+ if (callID !== undefined) inflight.delete(callID);
1927
+ break;
1928
+ }
1929
+ case "forget": {
1930
+ const session = str(rec.session);
1931
+ if (session === undefined) break;
1932
+ for (const [key, value] of inflight) if (parentOf(value) === session) inflight.delete(key);
1933
+ for (const [key, value] of holds) if (parentOf(value.hold) === session) holds.delete(key);
1934
+ break;
1935
+ }
1936
+ default:
1937
+ break;
1938
+ }
1939
+ }
1940
+ // Posted placeholders are bounded (newest kept); an unposted hold is never dropped here.
1941
+ let posted = 0;
1942
+ for (const value of holds.values()) if (value.posted !== undefined) posted += 1;
1943
+ for (const [key, value] of holds) {
1944
+ if (posted <= MAX_DORMANT_POSTED_HOLDS) break;
1945
+ if (value.posted === undefined) continue;
1946
+ holds.delete(key);
1947
+ posted -= 1;
1948
+ }
1949
+ const sessions = new Map<string, DormantSession>();
1950
+ const sessionOf = (parent: string): DormantSession => {
1951
+ let session = sessions.get(parent);
1952
+ if (session === undefined) {
1953
+ session = { holds: [], inflight: [] };
1954
+ sessions.set(parent, session);
1955
+ }
1956
+ return session;
1957
+ };
1958
+ for (const rec of inflight.values()) {
1959
+ const at = typeof rec.at === "number" ? rec.at : 0;
1960
+ if (opts.now - at > opts.ttlMs) continue;
1961
+ sessionOf(parentOf(rec) ?? "").inflight.push(rec);
1962
+ }
1963
+ for (const [handle, value] of holds) {
1964
+ const list = sessionOf(parentOf(value.hold) ?? "").holds;
1965
+ list.push(value.hold);
1966
+ if (value.text !== undefined) list.push(value.text);
1967
+ if (value.posting !== undefined) list.push(value.posting);
1968
+ if (value.posted !== undefined) list.push(value.posted);
1969
+ // QA-2.1-17: a verdict the gate reached (its entry's `verified` state) but never started posting is handed over with the
1970
+ // hold, so the adopter posts it instead of running the gate again.
1971
+ const verdict = verdicts.get(handle);
1972
+ if (verdict !== undefined && value.posting === undefined && value.posted === undefined) list.push(verdict);
1973
+ }
1974
+ return { sessions, processed };
1975
+ }
1976
+
1977
+ /** Posted holds kept as inactive placeholders across a restart (QA-2.1-10); = MAX_HOLDS_GLOBAL (background.ts). */
1978
+ export const MAX_DORMANT_POSTED_HOLDS = 10_000;
1979
+
1980
+ /**
1981
+ * Section 11.3: the exclusive claim file `<claimsDir>\<id>` (`wx`, `{pid, at}`) that stops two host processes from verifying or
1982
+ * posting for one session twice. A claim of a dead pid (or of this process) is stale and is taken over. True when this process owns it.
1983
+ */
1984
+ export function claimPendingSession(
1985
+ claimsDir: string,
1986
+ sessionID: string,
1987
+ seams: {
1988
+ pid: number;
1989
+ now: number;
1990
+ isAlive(pid: number): boolean;
1991
+ /** Identifies this process beyond its pid (QA-2.1-13, PID reuse); default: one random token per module load. */
1992
+ token?: string;
1993
+ /** A live pid's claim older than this is taken over (a reused pid never refreshes it); default `CLAIM_STALE_MS`. */
1994
+ staleMs?: number;
1995
+ /** DF-1-10: the directory of the instance beat files (`writeInstanceBeat`); unset: only this module's live tokens count. */
1996
+ beatsDir?: string;
1997
+ },
1998
+ ): boolean {
1999
+ const file = join(claimsDir, encodeURIComponent(sessionID));
2000
+ const token = seams.token ?? PROCESS_CLAIM_TOKEN;
2001
+ const body = `${JSON.stringify({ pid: seams.pid, token, at: seams.now })}\n`;
2002
+ mkdirSync(claimsDir, { recursive: true });
2003
+ try {
2004
+ writeFileSync(file, body, { flag: "wx" });
2005
+ return true;
2006
+ } catch (error) {
2007
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
2008
+ }
2009
+ const owner = readClaim(file);
2010
+ // QA-2.1-13: a claim of this pid is this process's own or that of a dead process whose pid this one reuses (its token
2011
+ // differs): taken either way. Another pid refuses while it is alive and its claim is fresh; a live pid whose claim is older
2012
+ // than `staleMs` is most likely a reused pid (a live owner re-stamps its claims, `refreshPendingClaims`). The token never
2013
+ // makes another live pid's claim ours: two processes of one test share the module token.
2014
+ const fresh = owner?.at !== undefined && seams.now - owner.at <= (seams.staleMs ?? CLAIM_STALE_MS);
2015
+ if (owner?.pid !== undefined && owner.pid !== seams.pid && fresh && seams.isAlive(owner.pid)) return false;
2016
+ // QA-2.1-19: a claim of this pid under the token of ANOTHER live plugin instance of this process is that instance's.
2017
+ // DF-1-10: a sibling instance may run a separately loaded copy of this module (one per booted location), whose tokens this
2018
+ // copy's set never holds; its fresh beat file (`writeInstanceBeat`) marks it live just the same. No beat file: as before.
2019
+ if (owner?.pid === seams.pid && owner.token !== undefined && owner.token !== token
2020
+ && (LIVE_INSTANCE_TOKENS.has(owner.token) || (seams.beatsDir !== undefined && instanceBeatIsFresh(seams.beatsDir, owner.token, seams.pid, seams.now, seams.staleMs ?? CLAIM_STALE_MS)))) return false;
2021
+ writeFileSync(file, body);
2022
+ return true;
2023
+ }
2024
+
2025
+ /** QA-2.1-19: the claim tokens of the live plugin instances of this process (`createInstanceClaimToken`). */
2026
+ const LIVE_INSTANCE_TOKENS = new Set<string>();
2027
+
2028
+ /**
2029
+ * QA-2.1-19: a claim token for one plugin instance. While it is not released, a claim this process wrote under it is
2030
+ * refused to every other instance of the process (`claimPendingSession`); once released (dispose), the claim is stale for
2031
+ * them and is taken over. Idempotent release. DF-1-10: with `beatsDir`, `beat()` re-stamps the instance's beat file (the
2032
+ * owner calls it with its claims) and `release()` removes it, so instances in other module copies see it too. QA-DF1-22:
2033
+ * with `beatsDir`, the stale beats of crashed instances are swept first (`sweepInstanceBeats`).
2034
+ */
2035
+ export function createInstanceClaimToken(beatsDir?: string): { readonly token: string; beat(now?: number): void; release(): void } {
2036
+ if (beatsDir !== undefined) sweepInstanceBeats(beatsDir, { now: Date.now() });
2037
+ const token = `${PROCESS_CLAIM_TOKEN}.${toHex(randomBytes(4))}`;
2038
+ LIVE_INSTANCE_TOKENS.add(token);
2039
+ const beat = (now: number = Date.now()): void => {
2040
+ if (beatsDir !== undefined && LIVE_INSTANCE_TOKENS.has(token)) writeInstanceBeat(beatsDir, token, { pid: process.pid, now });
2041
+ };
2042
+ return {
2043
+ token,
2044
+ beat,
2045
+ release: () => {
2046
+ LIVE_INSTANCE_TOKENS.delete(token);
2047
+ if (beatsDir !== undefined) removeInstanceBeat(beatsDir, token);
2048
+ },
2049
+ };
2050
+ }
2051
+
2052
+ /**
2053
+ * DF-1-10: the beat file of one plugin instance, `<beatsDir>\<token>` (`{pid, at}`). One host process may load a separate copy
2054
+ * of this module per booted location, and `LIVE_INSTANCE_TOKENS` never holds a sibling copy's tokens; a beat of the claim's pid
2055
+ * younger than the stale bound marks that instance live to every copy (`claimPendingSession`). Written with the instance's
2056
+ * first claim, re-stamped with the claims (`CLAIM_REFRESH_MS`), removed on release; a crashed instance's beat goes stale
2057
+ * (`sweepInstanceBeats` removes it when the next instance starts). QA-DF1-22: written to a temp file renamed over the beat,
2058
+ * so a reader never sees a half-written beat; where the rename fails (a reader holds the file open on win32) the beat is
2059
+ * written in place, and a reader that finds it half-written goes by its mtime. Never throws.
2060
+ */
2061
+ export function writeInstanceBeat(beatsDir: string, token: string, seams: { pid: number; now: number }): void {
2062
+ const target = join(beatsDir, encodeURIComponent(token));
2063
+ const temp = `${target}${BEAT_TEMP_SUFFIX}`;
2064
+ const body = `${JSON.stringify({ pid: seams.pid, token, at: seams.now })}\n`;
2065
+ try {
2066
+ mkdirSync(beatsDir, { recursive: true });
2067
+ try {
2068
+ writeFileSync(temp, body);
2069
+ renameSync(temp, target);
2070
+ } catch (error) {
2071
+ void error; // the beat is written in place instead; a torn one is read by its mtime (`beatFileIsFresh`)
2072
+ rmSync(temp, { force: true });
2073
+ writeFileSync(target, body);
2074
+ }
2075
+ } catch (error) {
2076
+ void error; // no beat: a sibling copy takes this instance's claims over, as before DF-1-10
2077
+ }
2078
+ }
2079
+
2080
+ /** QA-DF1-22: the suffix of a beat's temp file (`writeInstanceBeat`); never a beat itself. */
2081
+ const BEAT_TEMP_SUFFIX = ".beat-tmp";
2082
+
2083
+ /**
2084
+ * QA-DF1-22: removes the beat files under `beatsDir` that are no longer fresh (`beatFileIsFresh`, any pid: a live
2085
+ * instance re-stamps its beat well within `staleMs`) and leftover temp files of the same age: the beats of crashed
2086
+ * instances. A fresh beat, by its `at` or (unreadable) by its mtime, stays. Returns how many files it removed. Never throws.
2087
+ */
2088
+ export function sweepInstanceBeats(beatsDir: string, seams: { now: number; staleMs?: number }): number {
2089
+ const staleMs = seams.staleMs ?? CLAIM_STALE_MS;
2090
+ let names: string[];
2091
+ try {
2092
+ names = readdirSync(beatsDir);
2093
+ } catch (error) {
2094
+ void error; // no beats directory yet: nothing to sweep
2095
+ return 0;
2096
+ }
2097
+ let removed = 0;
2098
+ for (const name of names) {
2099
+ const path = join(beatsDir, name);
2100
+ const fresh = name.endsWith(BEAT_TEMP_SUFFIX) ? mtimeIsFresh(path, seams.now, staleMs) : beatFileIsFresh(path, undefined, seams.now, staleMs);
2101
+ if (fresh) continue;
2102
+ try {
2103
+ rmSync(path, { force: true });
2104
+ removed += 1;
2105
+ } catch (error) {
2106
+ void error; // a beat that cannot be removed is tried again at the next start
2107
+ }
2108
+ }
2109
+ return removed;
2110
+ }
2111
+
2112
+ /** DF-1-10: removes an instance's beat file (release, dispose). Never throws. */
2113
+ export function removeInstanceBeat(beatsDir: string, token: string): void {
2114
+ try {
2115
+ rmSync(join(beatsDir, encodeURIComponent(token)), { force: true });
2116
+ } catch (error) {
2117
+ void error; // a beat that cannot be removed goes stale after CLAIM_STALE_MS
2118
+ }
2119
+ }
2120
+
2121
+ /** DF-1-10: the instance of `token` (on `pid`) re-stamped its beat file within `staleMs`. */
2122
+ function instanceBeatIsFresh(beatsDir: string, token: string, pid: number, now: number, staleMs: number): boolean {
2123
+ return beatFileIsFresh(join(beatsDir, encodeURIComponent(token)), pid, now, staleMs);
2124
+ }
2125
+
2126
+ /**
2127
+ * QA-DF1-18: a beat of one module copy's instances (`<copy token>.<instance>`, `createInstanceClaimToken`) on `pid` is
2128
+ * fresh. Never throws: an unreadable beats directory counts as no beat.
2129
+ */
2130
+ function moduleCopyBeatIsFresh(beatsDir: string, copyToken: string, pid: number, now: number, staleMs: number): boolean {
2131
+ let names: string[];
2132
+ try {
2133
+ names = readdirSync(beatsDir);
2134
+ } catch (error) {
2135
+ void error; // no beats directory: no beat
2136
+ return false;
2137
+ }
2138
+ const prefix = encodeURIComponent(`${copyToken}.`);
2139
+ return names.some((name) => name.startsWith(prefix) && !name.endsWith(BEAT_TEMP_SUFFIX) && beatFileIsFresh(join(beatsDir, name), pid, now, staleMs));
2140
+ }
2141
+
2142
+ /**
2143
+ * QA-DF1-22: a beat file stamped within `staleMs` (its `at`) by `pid` (any pid when undefined). A beat that cannot be read or
2144
+ * parsed (half-written, torn) goes by its mtime, failing closed: a fresh mtime counts as a live instance. A vanished beat is
2145
+ * not fresh.
2146
+ */
2147
+ function beatFileIsFresh(path: string, pid: number | undefined, now: number, staleMs: number): boolean {
2148
+ const beat = readClaim(path);
2149
+ if (beat?.at !== undefined) return (pid === undefined || beat.pid === pid) && now - beat.at <= staleMs;
2150
+ if (beat?.pid !== undefined && pid !== undefined && beat.pid !== pid) return false;
2151
+ return mtimeIsFresh(path, now, staleMs);
2152
+ }
2153
+
2154
+ /** QA-DF1-22: the file's mtime lies within `staleMs` of `now`; false when it is gone or cannot be stat'ed. */
2155
+ function mtimeIsFresh(path: string, now: number, staleMs: number): boolean {
2156
+ try {
2157
+ return now - statSync(path).mtimeMs <= staleMs;
2158
+ } catch (error) {
2159
+ void error; // a vanished file is not fresh
2160
+ return false;
2161
+ }
2162
+ }
2163
+
2164
+ /** DF-1-10: the per-user directory of the instance beat files, next to `pending.claims`. */
2165
+ export const PENDING_INSTANCES_DIRNAME = "pending.instances";
2166
+
2167
+ /**
2168
+ * QA-2.1-13/-34: a claim of another pid older than this no longer protects it, even while that pid is alive: a live owner
2169
+ * re-stamps its claims every `CLAIM_REFRESH_MS` (`refreshPendingClaims`), so a claim this old belongs to a crashed process
2170
+ * whose pid was reused.
2171
+ */
2172
+ export const CLAIM_STALE_MS = 5 * 60_000;
2173
+ /** QA-2.1-34: how often a live owner re-stamps its claims; well within `CLAIM_STALE_MS`. */
2174
+ export const CLAIM_REFRESH_MS = 60_000;
2175
+
2176
+ /** One token per module load: two processes that share a pid over time never share a token. */
2177
+ const PROCESS_CLAIM_TOKEN = toHex(randomBytes(8));
2178
+
2179
+ function readClaim(file: string): { pid?: number; token?: string; at?: number } | undefined {
2180
+ let parsed: unknown;
2181
+ try {
2182
+ parsed = JSON.parse(readFileSync(file, "utf8"));
2183
+ } catch (error) {
2184
+ // An unreadable or vanished claim is stale; whoever claims next rewrites it.
2185
+ void error;
2186
+ return undefined;
2187
+ }
2188
+ if (typeof parsed !== "object" || parsed === null) return undefined;
2189
+ const rec = parsed as Record<string, unknown>;
2190
+ return {
2191
+ ...(typeof rec.pid === "number" ? { pid: rec.pid } : {}),
2192
+ ...(typeof rec.token === "string" ? { token: rec.token } : {}),
2193
+ ...(typeof rec.at === "number" ? { at: rec.at } : {}),
2194
+ };
2195
+ }
2196
+
2197
+ /**
2198
+ * QA-2.1-13: gives a session's claim back (session deleted, process disposing). Only this process's own claim (its token) is
2199
+ * removed; a claim another process took over stays. Never throws.
2200
+ */
2201
+ export function releasePendingClaim(claimsDir: string, sessionID: string, token: string = PROCESS_CLAIM_TOKEN): boolean {
2202
+ const file = join(claimsDir, encodeURIComponent(sessionID));
2203
+ if (readClaim(file)?.token !== token) return false;
2204
+ try {
2205
+ rmSync(file, { force: true });
2206
+ return true;
2207
+ } catch (error) {
2208
+ void error; // a claim that cannot be removed goes stale after CLAIM_STALE_MS
2209
+ return false;
2210
+ }
2211
+ }
2212
+
2213
+ /** QA-2.1-13: re-stamps this process's claims so a live owner never looks stale. Never throws. */
2214
+ export function refreshPendingClaims(claimsDir: string, sessionIDs: Iterable<string>, seams: { pid: number; now: number; token?: string }): void {
2215
+ const token = seams.token ?? PROCESS_CLAIM_TOKEN;
2216
+ for (const sessionID of sessionIDs) {
2217
+ const file = join(claimsDir, encodeURIComponent(sessionID));
2218
+ if (readClaim(file)?.token !== token) continue;
2219
+ try {
2220
+ writeFileSync(file, `${JSON.stringify({ pid: seams.pid, token, at: seams.now })}\n`);
2221
+ } catch (error) {
2222
+ void error; // a claim that cannot be refreshed goes stale; the next claim attempt decides again
2223
+ }
2224
+ }
2225
+ }
2226
+
899
2227
  /**
900
2228
  * Eviction order (R7, QA-2.4-4): verified entries only, oldest first. An unverified or verifying
901
2229
  * entry is never evicted by a cap: its delegation would leave the pending list silently and read as
@@ -933,6 +2261,130 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
933
2261
  const tombstones = new Map<string, string>();
934
2262
  const ledger = new Map<string, LedgerRecord[]>();
935
2263
  const counters = { seq: 0, weight: 0, hookFailures: 0 };
2264
+ /** Phase 2.1: dispatchID -> the entry registered under it (idempotent register, findByDispatch). */
2265
+ const byDispatch = new Map<string, EntryRecord>();
2266
+ /** Phase 2.1: handles drawn by reserveHandle and neither registered nor released: handle -> session. */
2267
+ const reserved = new Map<string, string>();
2268
+ /** QA-2.1-4: when each reservation was drawn; `maintain` drops it after `reservationTtlMs`. */
2269
+ const reservedAt = new Map<string, number>();
2270
+ const reservationTtlMs = options.reservationTtlMs ?? HELD_RESERVATION_TTL_MS;
2271
+ const persist = options.persist;
2272
+
2273
+ function reservedCount(sessionID: string | undefined, except: string | undefined): number {
2274
+ let n = 0;
2275
+ for (const [handle, sid] of reserved) {
2276
+ if (handle !== except && (sessionID === undefined || sid === sessionID)) n += 1;
2277
+ }
2278
+ return n;
2279
+ }
2280
+
2281
+ /** Appends to pending.jsonl (v2 only); a journal failure is counted, never thrown into the registry. */
2282
+ function journal(record: PendingRecord, opts?: { fsync?: boolean }): void {
2283
+ if (persist === undefined) return;
2284
+ try {
2285
+ void persist.append(record, opts).catch(() => {
2286
+ counters.hookFailures += 1;
2287
+ });
2288
+ } catch {
2289
+ counters.hookFailures += 1;
2290
+ }
2291
+ }
2292
+
2293
+ function persistEntry(rec: EntryRecord): void {
2294
+ if (persist === undefined) return;
2295
+ journal(entryRecord(rec), { fsync: rec.hold !== undefined });
2296
+ }
2297
+
2298
+ function entryRecord(rec: EntryRecord): PendingRecord {
2299
+ return {
2300
+ v: 1,
2301
+ kind: "entry",
2302
+ handle: rec.handle,
2303
+ parent: rec.orchestratorSessionID,
2304
+ child: rec.hold?.childSessionID ?? rec.producerSessionID,
2305
+ callID: rec.dispatchID,
2306
+ producer: rec.producerSessionID,
2307
+ tier: rec.producerTier,
2308
+ dod: rec.dod ?? null,
2309
+ changedFiles: rec.changedFiles,
2310
+ changedFilesDropped: rec.changedFilesDropped,
2311
+ reference: null,
2312
+ risk: rec.risk,
2313
+ description: rec.description,
2314
+ root: rec.root ?? null,
2315
+ cwd: rec.cwd,
2316
+ state: rec.state,
2317
+ createdAt: rec.createdAt,
2318
+ dispatchedAt: rec.dispatchedAt,
2319
+ ...(rec.concurrentDispatches !== undefined ? { concurrentDispatches: rec.concurrentDispatches } : {}),
2320
+ ...(rec.contaminatedBy !== undefined ? { contaminatedBy: rec.contaminatedBy } : {}),
2321
+ // Cross-repo (2.8.0): the plain-data registration fields, validated again by restore(). The perimeter holds promises and
2322
+ // is never journaled: only the fact that the entry had one, so a restored entry is unverifiable instead of passing.
2323
+ ...(rec.returnedTree !== undefined ? { returnedTree: { ...rec.returnedTree } } : {}),
2324
+ ...(rec.unattributedWriters !== undefined ? { unattributedWriters: [...rec.unattributedWriters] } : {}),
2325
+ ...(rec.placements !== undefined ? { placements: rec.placements.map((p) => (p === undefined ? null : { ...p })) } : {}),
2326
+ ...(rec.perimeter !== undefined || rec.perimeterLost || rec.heldPerimeter ? { hadPerimeter: true } : {}),
2327
+ // QA-SYNC1-3: a held gate's dispatch-time head is journaled as plain data, with the fact that it had one; a record
2328
+ // that had a head but carries no value restores as head-lost.
2329
+ ...(rec.heldHead || rec.headLost || rec.dispatchHead !== undefined ? { hadHead: true } : {}),
2330
+ ...(rec.dispatchHead !== undefined ? { dispatchHead: { ...rec.dispatchHead } } : {}),
2331
+ };
2332
+ }
2333
+
2334
+ function persistReference(rec: EntryRecord, reference: DispatchReference): void {
2335
+ if (persist === undefined) return;
2336
+ journal({ v: 1, kind: "ref", handle: rec.handle, callID: rec.dispatchID, reference: serializeReference(reference) });
2337
+ }
2338
+
2339
+ function persistState(rec: EntryRecord, at: number): void {
2340
+ if (persist === undefined) return;
2341
+ journal(stateRecord(rec, at));
2342
+ }
2343
+
2344
+ function stateRecord(rec: EntryRecord, at: number): PendingRecord {
2345
+ return {
2346
+ v: 1,
2347
+ kind: "state",
2348
+ handle: rec.handle,
2349
+ state: rec.state,
2350
+ at,
2351
+ ...(rec.state === "verified" && rec.result !== undefined ? { verdict: rec.result.verdict } : {}),
2352
+ };
2353
+ }
2354
+
2355
+ /** QA-2.1-16: the `entry` and `state` records of every live entry, for rewriting a vanished journal. */
2356
+ function persistedRecords(): PendingRecord[] {
2357
+ const at = now();
2358
+ const out: PendingRecord[] = [];
2359
+ for (const rec of byHandle.values()) {
2360
+ if (!rec.live) continue;
2361
+ out.push(entryRecord(rec), stateRecord(rec, at));
2362
+ }
2363
+ return out;
2364
+ }
2365
+
2366
+ function hasSlot(sessionID: string): boolean {
2367
+ maintain(now());
2368
+ const session = sessions.get(sessionID);
2369
+ const evictableHere = session === undefined ? 0 : evictionCandidates(session.values()).length;
2370
+ if ((session?.size ?? 0) + reservedCount(sessionID, undefined) - evictableHere + 1 > maxPerSession) return false;
2371
+ const evictable = evictionCandidates(byHandle.values()).length;
2372
+ return byHandle.size + reservedCount(undefined, undefined) - evictable + 1 <= maxGlobal;
2373
+ }
2374
+
2375
+ function reserveHandle(sessionID: string): string | undefined {
2376
+ if (!isNonEmptyString(sessionID) || !hasSlot(sessionID)) return undefined;
2377
+ const handle = drawHandle();
2378
+ if (handle === undefined) return undefined;
2379
+ reserved.set(handle, sessionID);
2380
+ reservedAt.set(handle, now());
2381
+ return handle;
2382
+ }
2383
+
2384
+ function unreserve(handle: string): void {
2385
+ reserved.delete(handle);
2386
+ reservedAt.delete(handle);
2387
+ }
936
2388
 
937
2389
  function snapshot(rec: EntryRecord): PendingEntry {
938
2390
  return Object.freeze({
@@ -953,10 +2405,14 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
953
2405
  digests: rec.digests,
954
2406
  ...(rec.concurrentDispatches !== undefined ? { concurrentDispatches: rec.concurrentDispatches } : {}),
955
2407
  ...(rec.contaminatedBy !== undefined ? { contaminatedBy: rec.contaminatedBy } : {}),
2408
+ ...(rec.hold !== undefined ? { hold: rec.hold } : {}),
956
2409
  ...(rec.returnedTree !== undefined ? { returnedTree: rec.returnedTree } : {}),
957
2410
  ...(rec.unattributedWriters !== undefined ? { unattributedWriters: rec.unattributedWriters } : {}),
958
2411
  ...(rec.perimeter !== undefined ? { perimeter: rec.perimeter } : {}),
959
2412
  ...(rec.placements !== undefined ? { placements: rec.placements } : {}),
2413
+ ...(rec.perimeterLost ? { perimeterLost: true as const } : {}),
2414
+ ...(rec.headLost ? { headLost: true as const } : {}),
2415
+ ...(rec.dispatchHead !== undefined ? { dispatchHead: rec.dispatchHead } : {}),
960
2416
  createdAt: rec.createdAt,
961
2417
  state: rec.state,
962
2418
  verifyingSince: rec.verifyingSince,
@@ -981,8 +2437,14 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
981
2437
  session?.delete(rec.handle);
982
2438
  if (session !== undefined && session.size === 0) sessions.delete(rec.orchestratorSessionID);
983
2439
  byHandle.delete(rec.handle);
2440
+ if (byDispatch.get(rec.dispatchID) === rec) byDispatch.delete(rec.dispatchID);
984
2441
  counters.weight -= rec.pathWeight + rec.refWeight;
985
2442
  addTombstone(rec.handle, rec.orchestratorSessionID);
2443
+ // A disposed or forgotten entry is not dead on disk: dispose keeps held entries for the next start,
2444
+ // and forget has its own record.
2445
+ if (cause !== "disposed" && cause !== "session-gone") {
2446
+ journal({ v: 1, kind: "tomb", handle: rec.handle, cause, at: now() });
2447
+ }
986
2448
  try {
987
2449
  const hook = options.onEvict;
988
2450
  if (hook === undefined) return;
@@ -1037,23 +2499,47 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1037
2499
  }
1038
2500
 
1039
2501
  /** Resolves a run and moves the entry out of "verifying" (settle, reap). */
1040
- function finishRun(rec: EntryRecord, settled: SettledVerification): void {
2502
+ function finishRun(rec: EntryRecord, settledIn: SettledVerification): void {
1041
2503
  const run = rec.run;
2504
+ let settled = settledIn;
2505
+ if (settled.retryable && rec.hold !== undefined) {
2506
+ // Phase 2.1: a held entry retries up to BACKGROUND_MAX_ATTEMPTS, then ends UNVERIFIABLE.
2507
+ rec.holdAttempts += 1;
2508
+ if (rec.holdAttempts >= BACKGROUND_MAX_ATTEMPTS) {
2509
+ settled = Object.freeze({
2510
+ verdict: syntheticVerdict(HELD_EXHAUSTED_REASON),
2511
+ retryable: false,
2512
+ handle: settled.handle,
2513
+ settledAt: settled.settledAt,
2514
+ });
2515
+ }
2516
+ }
1042
2517
  rec.run = undefined;
1043
2518
  rec.verifyingSince = undefined;
1044
2519
  rec.result = settled;
1045
2520
  if (settled.retryable) {
1046
- rec.state = "unverified";
2521
+ rec.state = rec.hold !== undefined ? "held" : "unverified";
1047
2522
  } else {
1048
2523
  rec.state = "verified";
1049
2524
  release(rec);
1050
2525
  }
2526
+ persistState(rec, settled.settledAt);
1051
2527
  run?.resolve(settled);
2528
+ if (!settled.retryable && options.onVerdict !== undefined) {
2529
+ try {
2530
+ options.onVerdict(snapshot(rec), settled);
2531
+ } catch {
2532
+ // A verdict hook must never break the registry (PendingRegistryOptions.onVerdict).
2533
+ counters.hookFailures += 1;
2534
+ }
2535
+ }
1052
2536
  }
1053
2537
 
1054
2538
  /** Reaping, TTL eviction and ledger expiry (R7). Returns the number of evicted entries. */
1055
2539
  function maintain(at: number): number {
1056
2540
  let evicted = 0;
2541
+ // QA-2.1-4: a reservation nobody registered nor released (a lost ack, a crashed path) frees its slot after the TTL.
2542
+ for (const [handle, since] of [...reservedAt]) if (at - since >= reservationTtlMs) unreserve(handle);
1057
2543
  for (const rec of [...byHandle.values()]) {
1058
2544
  if (rec.state === "verifying" && rec.verifyingSince !== undefined && rec.verifyingSince + maxVerifyingMs <= at) {
1059
2545
  finishRun(rec, {
@@ -1064,6 +2550,16 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1064
2550
  });
1065
2551
  }
1066
2552
  if (rec.state === "verifying") continue;
2553
+ if (rec.state === "held" && !rec.doomed && isExpired(rec, at)) {
2554
+ // A held entry is never evicted by a TTL: its verdict ends UNVERIFIABLE and is posted.
2555
+ finishRun(rec, {
2556
+ verdict: syntheticVerdict(HELD_TTL_REASON),
2557
+ retryable: false,
2558
+ handle: rec.handle,
2559
+ settledAt: at,
2560
+ });
2561
+ continue;
2562
+ }
1067
2563
  if (rec.doomed) {
1068
2564
  evict(rec, "session-gone");
1069
2565
  evicted += 1;
@@ -1112,7 +2608,7 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1112
2608
  for (let i = 0; i < HANDLE_MAX_DRAWS; i += 1) {
1113
2609
  const candidate = HANDLE_PREFIX + toHex(random(HANDLE_RANDOM_BYTES));
1114
2610
  if (!HANDLE_PATTERN.test(candidate)) continue;
1115
- if (byHandle.has(candidate) || tombstones.has(candidate)) continue;
2611
+ if (byHandle.has(candidate) || tombstones.has(candidate) || reserved.has(candidate)) continue;
1116
2612
  return candidate;
1117
2613
  }
1118
2614
  return undefined;
@@ -1133,6 +2629,24 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1133
2629
  const at = now();
1134
2630
  maintain(at);
1135
2631
 
2632
+ // Phase 2.1: idempotent on dispatchID (a replayed finish registers once).
2633
+ const existing = byDispatch.get(reg.dispatchID);
2634
+ if (existing !== undefined && existing.live && existing.orchestratorSessionID === reg.orchestratorSessionID) {
2635
+ return { ok: true, handle: existing.handle, evicted: [] };
2636
+ }
2637
+ const ownReservation =
2638
+ reg.handle !== undefined && reserved.get(reg.handle) === reg.orchestratorSessionID ? reg.handle : undefined;
2639
+ if (reg.handle !== undefined && ownReservation === undefined) {
2640
+ if (!HANDLE_PATTERN.test(reg.handle)) {
2641
+ return { ok: false, code: "invalid-input", detail: "handle is not a router verification handle" };
2642
+ }
2643
+ if (byHandle.has(reg.handle) || tombstones.has(reg.handle) || reserved.has(reg.handle)) {
2644
+ return { ok: false, code: "handle-collision", detail: "the requested handle is already in use" };
2645
+ }
2646
+ }
2647
+ const reservedHere = reservedCount(reg.orchestratorSessionID, ownReservation);
2648
+ const reservedAll = reservedCount(undefined, ownReservation);
2649
+
1136
2650
  const incoming = reg.changedFiles;
1137
2651
  let changedFiles: readonly ChangedPath[] | "unavailable" = "unavailable";
1138
2652
  let changedFilesDropped = 0;
@@ -1152,7 +2666,7 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1152
2666
  const victims: Array<{ rec: EntryRecord; cause: EvictionCause }> = [];
1153
2667
  const chosen = new Set<EntryRecord>();
1154
2668
  if (session !== undefined) {
1155
- let count = session.size;
2669
+ let count = session.size + reservedHere;
1156
2670
  for (const rec of evictionCandidates(session.values())) {
1157
2671
  if (count + 1 <= maxPerSession) break;
1158
2672
  victims.push({ rec, cause: "session-cap" });
@@ -1162,10 +2676,10 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1162
2676
  if (count + 1 > maxPerSession) {
1163
2677
  return { ok: false, code: "registry-full", detail: `session holds ${count} unverified or verifying entries` };
1164
2678
  }
1165
- } else if (maxPerSession < 1) {
2679
+ } else if (maxPerSession < 1 + reservedHere) {
1166
2680
  return { ok: false, code: "registry-full", detail: "per-session cap is 0" };
1167
2681
  }
1168
- let count = byHandle.size - victims.length;
2682
+ let count = byHandle.size - victims.length + reservedAll;
1169
2683
  let weight = counters.weight - victims.reduce((sum, v) => sum + v.rec.pathWeight + v.rec.refWeight, 0);
1170
2684
  for (const rec of evictionCandidates(byHandle.values())) {
1171
2685
  if (count + 1 <= maxGlobal && weight + pathWeight <= maxWeight) break;
@@ -1179,11 +2693,12 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1179
2693
  return { ok: false, code: "registry-full", detail: "the pending registry cannot hold another entry" };
1180
2694
  }
1181
2695
 
1182
- const handle = drawHandle();
2696
+ const handle = reg.handle ?? drawHandle();
1183
2697
  if (handle === undefined) {
1184
2698
  return { ok: false, code: "handle-collision", detail: `no free handle after ${HANDLE_MAX_DRAWS} draws` };
1185
2699
  }
1186
2700
  for (const v of victims) evict(v.rec, v.cause);
2701
+ unreserve(handle);
1187
2702
 
1188
2703
  const reference = reg.reference.then(
1189
2704
  (state) => state,
@@ -1215,11 +2730,16 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1215
2730
  ? Object.freeze([...reg.unattributedWriters]) : undefined,
1216
2731
  perimeter,
1217
2732
  placements,
2733
+ perimeterLost: false,
2734
+ heldPerimeter: reg.heldPerimeter === true,
2735
+ heldHead: reg.heldHead === true,
2736
+ dispatchHead: reg.dispatchHead !== undefined ? Object.freeze({ ...reg.dispatchHead }) : undefined,
2737
+ headLost: false,
1218
2738
  dod: reg.dod,
1219
2739
  reference,
1220
2740
  changedFiles,
1221
2741
  digests,
1222
- state: "unverified",
2742
+ state: reg.hold !== undefined ? "held" : "unverified",
1223
2743
  verifyingSince: undefined,
1224
2744
  result: undefined,
1225
2745
  run: undefined,
@@ -1229,18 +2749,23 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1229
2749
  doomed: false,
1230
2750
  live: true,
1231
2751
  replayed: false,
2752
+ hold: reg.hold,
2753
+ holdAttempts: 0,
1232
2754
  };
1233
2755
  const target = session ?? new Map<string, EntryRecord>();
1234
2756
  target.set(handle, rec);
1235
2757
  sessions.set(reg.orchestratorSessionID, target);
1236
2758
  byHandle.set(handle, rec);
2759
+ byDispatch.set(reg.dispatchID, rec);
1237
2760
  counters.weight += pathWeight;
1238
2761
 
1239
2762
  // R7: the reference's weight is added when it resolves "captured" (a promise callback).
1240
2763
  void reference.then((state) => {
1241
2764
  if (!rec.live || rec.released || state.kind !== "captured") return;
1242
2765
  admitReferenceWeight(rec, state.reference.untracked.size + state.reference.tracked.size);
2766
+ persistReference(rec, state.reference);
1243
2767
  });
2768
+ persistEntry(rec);
1244
2769
 
1245
2770
  return { ok: true, handle, evicted: victims.map((v) => v.rec.handle) };
1246
2771
  }
@@ -1265,6 +2790,7 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1265
2790
  rec.state = "verifying";
1266
2791
  rec.verifyingSince = at;
1267
2792
  rec.run = run;
2793
+ persistState(rec, at);
1268
2794
  let used = false;
1269
2795
  const settle = (result: VerificationResult): boolean => {
1270
2796
  if (used || rec.run !== run || !rec.live) return false;
@@ -1297,6 +2823,141 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1297
2823
  .sort((a, b) => b.createdAt - a.createdAt || b.seq - a.seq);
1298
2824
  }
1299
2825
 
2826
+ /**
2827
+ * Phase 2.1 section 11.3 (v2 only): folds pending.jsonl records by key and rebuilds the live entries.
2828
+ * Unverified entries past pendingTtlMs are dropped; held ones are settled UNVERIFIABLE (and reported
2829
+ * through onVerdict) instead. Nothing is written back: the records are already on disk.
2830
+ */
2831
+ function restore(records: readonly PendingRecord[], opts: { readonly now: number }): RestoreReport {
2832
+ const folded = new Map<string, { entry: PendingRecord; reference: unknown; state: string }>();
2833
+ for (const r of records) {
2834
+ const handle = isNonEmptyString(r.handle) ? r.handle : undefined;
2835
+ if (r.kind === "entry" && handle !== undefined) {
2836
+ folded.set(handle, { entry: r, reference: undefined, state: isNonEmptyString(r.state) ? r.state : "unverified" });
2837
+ } else if (r.kind === "ref") {
2838
+ const target = handle !== undefined ? folded.get(handle) : undefined;
2839
+ if (target !== undefined) target.reference = r.reference;
2840
+ else for (const f of folded.values()) if (f.entry.callID === r.callID) f.reference = r.reference;
2841
+ } else if (r.kind === "state" && handle !== undefined) {
2842
+ const target = folded.get(handle);
2843
+ if (target !== undefined && isNonEmptyString(r.state)) target.state = r.state;
2844
+ } else if (r.kind === "tomb" && handle !== undefined) {
2845
+ folded.delete(handle);
2846
+ } else if (r.kind === "forget") {
2847
+ for (const [h, f] of [...folded]) if (f.entry.parent === r.session) folded.delete(h);
2848
+ }
2849
+ }
2850
+ let restored = 0;
2851
+ let expiredHeld = 0;
2852
+ let dropped = 0;
2853
+ for (const [handle, f] of folded) {
2854
+ const e = f.entry;
2855
+ const parent = isNonEmptyString(e.parent) ? e.parent : undefined;
2856
+ const callID = isNonEmptyString(e.callID) ? e.callID : undefined;
2857
+ const child = isNonEmptyString(e.child) ? e.child : undefined;
2858
+ const producer = isNonEmptyString(e.producer) ? e.producer : child;
2859
+ // Cross-repo (2.8.0) fields: absent on records written before they were journaled (restored without them, as those
2860
+ // entries never had the checks); present but malformed drops the record, like any other invalid record.
2861
+ const crossRepoInvalid = (e.returnedTree !== undefined && !isReturnedTree(e.returnedTree))
2862
+ || (e.unattributedWriters !== undefined && !isUnattributedWriters(e.unattributedWriters))
2863
+ || (e.placements !== undefined && !isPlacements(e.placements))
2864
+ || (e.hadPerimeter !== undefined && e.hadPerimeter !== true)
2865
+ || (e.hadHead !== undefined && e.hadHead !== true)
2866
+ // QA-SYNC1-3: a journaled head is validated strictly; a head without `hadHead` is malformed too.
2867
+ || (e.dispatchHead !== undefined && (!isDispatchHead(e.dispatchHead) || e.hadHead !== true));
2868
+ if (
2869
+ parent === undefined || callID === undefined || producer === undefined || parent === producer ||
2870
+ !HANDLE_PATTERN.test(handle) || f.state === "verified" || byHandle.has(handle) || byDispatch.has(callID) || crossRepoInvalid
2871
+ ) {
2872
+ dropped += 1;
2873
+ continue;
2874
+ }
2875
+ const held = e.state === "held" && child !== undefined;
2876
+ const createdAt = typeof e.createdAt === "number" && Number.isFinite(e.createdAt) ? e.createdAt : opts.now;
2877
+ const expired = opts.now - createdAt >= ttlMs;
2878
+ const session = sessions.get(parent);
2879
+ if (!held && (expired || byHandle.size >= maxGlobal || (session?.size ?? 0) >= maxPerSession)) {
2880
+ dropped += 1;
2881
+ continue;
2882
+ }
2883
+ const changedFiles = isChangedFiles(e.changedFiles) ? e.changedFiles : "unavailable";
2884
+ const restoredRef = deserializeReference(f.reference);
2885
+ const placements = isPlacements(e.placements) ? restoredPlacements(e.placements) : undefined;
2886
+ // QA-SYNC1-10: the weight `register` counts (changed files and placements; a perimeter is never restored).
2887
+ const pathWeight = (changedFiles === "unavailable" ? 0 : changedFiles.length) + (placements !== undefined ? placements.length : 0);
2888
+ const refWeight = restoredRef === undefined ? 0 : restoredRef.untracked.size + restoredRef.tracked.size;
2889
+ counters.seq += 1;
2890
+ const rec: EntryRecord = {
2891
+ handle,
2892
+ seq: counters.seq,
2893
+ orchestratorSessionID: parent,
2894
+ dispatchID: callID,
2895
+ producerSessionID: producer,
2896
+ producerTier: typeof e.tier === "string" ? e.tier : "",
2897
+ description: typeof e.description === "string" ? e.description : "",
2898
+ cwd: typeof e.cwd === "string" ? e.cwd : "",
2899
+ root: isNonEmptyString(e.root) ? e.root : undefined,
2900
+ dispatchedAt: typeof e.dispatchedAt === "number" && Number.isFinite(e.dispatchedAt) ? e.dispatchedAt : createdAt,
2901
+ createdAt,
2902
+ risk: isRiskAssessment(e.risk) ? e.risk : unattributedRisk(),
2903
+ changedFilesDropped: typeof e.changedFilesDropped === "number" ? e.changedFilesDropped : 0,
2904
+ concurrentDispatches: typeof e.concurrentDispatches === "number" ? e.concurrentDispatches : undefined,
2905
+ contaminatedBy: isNonEmptyString(e.contaminatedBy) ? e.contaminatedBy : undefined,
2906
+ dod: isDoD(e.dod) ? e.dod : undefined,
2907
+ reference: Promise.resolve<ReferenceState>(
2908
+ restoredRef !== undefined
2909
+ ? { kind: "captured", reference: restoredRef }
2910
+ : { kind: "none", reason: REFERENCE_UNRESTORED_REASON },
2911
+ ),
2912
+ changedFiles,
2913
+ digests: undefined,
2914
+ state: held ? "held" : "unverified",
2915
+ verifyingSince: undefined,
2916
+ result: undefined,
2917
+ run: undefined,
2918
+ pathWeight,
2919
+ refWeight,
2920
+ released: false,
2921
+ doomed: false,
2922
+ live: true,
2923
+ replayed: false,
2924
+ hold: held && child !== undefined ? { childSessionID: child, callID } : undefined,
2925
+ // Cross-repo (2.8.0): validated above; the perimeter itself is never journaled, only `hadPerimeter`.
2926
+ returnedTree: isReturnedTree(e.returnedTree) ? restoredReturnedTree(e.returnedTree) : undefined,
2927
+ unattributedWriters: isUnattributedWriters(e.unattributedWriters) && e.unattributedWriters.length > 0
2928
+ ? Object.freeze([...e.unattributedWriters]) : undefined,
2929
+ perimeter: undefined,
2930
+ placements,
2931
+ perimeterLost: e.hadPerimeter === true,
2932
+ heldPerimeter: false,
2933
+ heldHead: false,
2934
+ // QA-SYNC1-3: the dispatch-time head a held gate checked, journaled as plain data; the gate re-run compares it again.
2935
+ dispatchHead: isDispatchHead(e.dispatchHead) ? restoredDispatchHead(e.dispatchHead) : undefined,
2936
+ // `hadHead` without a head value: the branch cannot be confirmed after the restart.
2937
+ headLost: e.hadHead === true && !isDispatchHead(e.dispatchHead),
2938
+ holdAttempts: 0,
2939
+ };
2940
+ const target = session ?? new Map<string, EntryRecord>();
2941
+ target.set(handle, rec);
2942
+ sessions.set(parent, target);
2943
+ byHandle.set(handle, rec);
2944
+ byDispatch.set(callID, rec);
2945
+ counters.weight += pathWeight + refWeight;
2946
+ if (held && expired) {
2947
+ finishRun(rec, {
2948
+ verdict: syntheticVerdict(HELD_TTL_REASON),
2949
+ retryable: false,
2950
+ handle,
2951
+ settledAt: opts.now,
2952
+ });
2953
+ expiredHeld += 1;
2954
+ } else {
2955
+ restored += 1;
2956
+ }
2957
+ }
2958
+ return { restored, expiredHeld, dropped };
2959
+ }
2960
+
1300
2961
  return {
1301
2962
  register,
1302
2963
  get(sessionID, handle) {
@@ -1315,9 +2976,24 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1315
2976
  listPending(sessionID, options) {
1316
2977
  const states: PendingState[] = options?.verifying === true ? ["unverified", "verifying", "verified"] : ["unverified", "verified"];
1317
2978
  return listByState(sessionID, states)
1318
- .filter((r) => r.state !== "verified" || awaitsReplay(r))
2979
+ .filter((r) => r.hold === undefined && (r.state !== "verified" || awaitsReplay(r)))
2980
+ .map(snapshot);
2981
+ },
2982
+ reserveHandle,
2983
+ releaseHandle(handle) {
2984
+ unreserve(handle);
2985
+ },
2986
+ hasSlot,
2987
+ findByDispatch(dispatchID) {
2988
+ const rec = byDispatch.get(dispatchID);
2989
+ return rec !== undefined && rec.live ? snapshot(rec) : undefined;
2990
+ },
2991
+ listHeld(sessionID) {
2992
+ return listByState(sessionID, ["held", "verifying"])
2993
+ .filter((r) => r.hold !== undefined)
1319
2994
  .map(snapshot);
1320
2995
  },
2996
+ restore,
1321
2997
  markReplayed(sessionID, handles) {
1322
2998
  const session = sessions.get(sessionID);
1323
2999
  if (session === undefined) return;
@@ -1327,6 +3003,7 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1327
3003
  }
1328
3004
  },
1329
3005
  markVerifying,
3006
+ persistedRecords,
1330
3007
  sweep(nowMs) {
1331
3008
  return maintain(nowMs ?? now());
1332
3009
  },
@@ -1340,6 +3017,10 @@ export function createPendingRegistry(options: PendingRegistryOptions): PendingR
1340
3017
  if (sid === sessionID) tombstones.delete(handle);
1341
3018
  }
1342
3019
  ledger.delete(sessionID);
3020
+ for (const [handle, sid] of [...reserved]) {
3021
+ if (sid === sessionID) unreserve(handle);
3022
+ }
3023
+ journal({ v: 1, kind: "forget", session: sessionID, at: now() });
1343
3024
  },
1344
3025
  recordRejection,
1345
3026
  findLineage(query) {