opencode-model-router 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +364 -0
  2. package/README.md +20 -0
  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
@@ -0,0 +1,1469 @@
1
+ /**
2
+ * src/router/leases.ts — the file lease registry (ADR 0007 D7, Phase 1.3). A child session that writes a file holds a
3
+ * lease on it until it completes (`until-complete`) or its plan task is integrated (`until-integrated`); a second
4
+ * writer, and a child that reads or searches the file, is refused with the holder named. Root sessions are never
5
+ * refused a read, a search or a run, and a root write is refused only while a child holds the file.
6
+ *
7
+ * Ownership is per OWNER, not per session: the owner of a lease is its holder's `taskRef` when there is one, else its
8
+ * holderID. Sessions of one plan task (the producer, a retry, its verifier or QA child) therefore never conflict with
9
+ * one another: a re-entrant write is not counted, and a read, search or run by an actor naming the same `taskRef` is
10
+ * exempt. Actors without a `taskRef` are their own owner. An actor whose holderID is recorded IS that holder: its owner
11
+ * comes from the record (it may omit `taskRef`; a different `taskRef`, `tree` or `isChild` is `invalid-holder`), and it
12
+ * is never refused a lease it holds itself.
13
+ *
14
+ * A lease has a SET of holders (all of one owner, first writer first): every session of the owner that writes the file
15
+ * joins it, and the lease ends only with the last of them (the strongest scope among them decides how long it lives,
16
+ * `until-integrated` over `until-complete`). The sessions of one taskRef must not write concurrently: two writers of
17
+ * one owner never conflict, so 3.1 must serialise the producer and its retry.
18
+ *
19
+ * Two keys per file: the LOGICAL key (repository + repo-relative path) decides write conflicts; the PHYSICAL key (the
20
+ * canonical, case-folded absolute path) decides read conflicts, so a read of the same relative path in another
21
+ * worktree is not a conflict. One logical key records every (physical, tree) pair its owner wrote it in, and reads and
22
+ * runs are checked against each of them. The `repo` a `repoKeyOf` answer names scopes the logical key: the v2 adapter
23
+ * names the checkout (work tree), so writers of one repo-relative path in two linked worktrees do not conflict
24
+ * (DF-1.1-4). An `until-integrated` write (a plan task) also conflicts with another owner's `until-integrated` lease on
25
+ * the same repo-relative path in any checkout of the answer's `shared` repository: plan tasks integrate into one branch.
26
+ * Such a conflict names the holder's own file. {@link LeaseRegistry.planHolderOf} is the matching repository-wide query
27
+ * (a plan scheduler's "who holds this path"); the logical key alone names one checkout.
28
+ *
29
+ * A path no key can be derived for is unkeyable. A spelling that may name any file (a device form, a drive-relative
30
+ * path, an 8.3 name) fails CLOSED: a child's read or write of it is refused while any other owner holds any lease.
31
+ * Other unkeyable input (empty, NUL, not a string, oversize) is an unknown target: a child write is refused while
32
+ * another owner holds a lease in the same checkout (the `repo` the seam names; an `until-integrated` write also while
33
+ * another owner's `until-integrated` lease is in any checkout of `shared`), and a read is allowed. A run directory that is unkeyable fails
34
+ * closed for a child runner while any other owner holds a lease. A drive-less rooted win32 path (`\x`) is aliasing: it
35
+ * is on the drive of the process, which the registry cannot know. Device forms other than `X:` and `Volume{guid}`
36
+ * (`\\.\pipe\…`, `\\?\GLOBALROOT\…`) are unkeyable without any filesystem call.
37
+ *
38
+ * Handoffs for 2.1: run the authority checks before the lease checks; back `repoKeyOf` with the git pointers; treat a
39
+ * `toolTargets` result with `gitRootRequired` (no concrete target) as an unknown target; hand git the `relOnDisk` of a
40
+ * key, not `rel`/`physical` (folded); serialise sessions of one taskRef; drop `until-complete` holders on restart
41
+ * (`restore(…, { dropCompleteHolders: true })`).
42
+ *
43
+ * Time is epoch milliseconds (`seams.now()`). A holder's `lastSeenAt` is refreshed by each acquire, read, search and
44
+ * run it makes; an `until-complete` holder not seen for `sweepAgeMs` is swept by {@link LeaseRegistry.sweep} or on the
45
+ * spot when it is named by a conflict.
46
+ *
47
+ * Pure policy over injected seams: the filesystem is reached only through {@link LeaseSeams}, every seam is
48
+ * synchronous, and the registry contains no `await`, so a check and its insert are atomic. The registry is unwired
49
+ * until Phase 2.1 (v2 only); `repoKeyOf` is the seam that phase backs with the repository's git pointers, and
50
+ * {@link foldKeyPath} is the function that phase uses to spell its answers.
51
+ *
52
+ * Known limits: hard links; case-insensitive POSIX volumes; a `link/..` on POSIX (resolved lexically); junctions
53
+ * created after a lease; NTFS's `$UpCase` table is only approximated by the per-unit `toUpperCase` fold; a loopback
54
+ * UNC spelling of a local drive (`\\localhost\C$\…`, `\\127.0.0.1\C$\…`) cannot be told from a remote share and keys
55
+ * apart from `C:\…`.
56
+ */
57
+ import { posix, win32 } from "node:path";
58
+ import { canonicalPath } from "../verify/canonical-path";
59
+
60
+ /**
61
+ * When a lease ends: with the holder's session (`until-complete`) or at plan-task integration (`until-integrated`). An
62
+ * `until-integrated` lease also conflicts across the checkouts of its shared repository ({@link LeaseSeams.repoKeyOf}).
63
+ */
64
+ export type LeaseScope = "until-complete" | "until-integrated";
65
+
66
+ /** One recorded lease holder (a session). */
67
+ export interface Holder {
68
+ holderID: string;
69
+ /** The session's work tree (absolute); the base of its relative paths. */
70
+ tree: string;
71
+ /** A child session; root sessions never hold a lease. */
72
+ isChild: boolean;
73
+ /** The plan task the holder works on; required for `until-integrated`. It names the OWNER of the holder's leases. */
74
+ taskRef?: string;
75
+ scope: LeaseScope;
76
+ /** `seams.now()` (epoch ms) when the holderID was first recorded. */
77
+ acquiredAt: number;
78
+ /** `seams.now()` (epoch ms) of the holder's latest acquire, read, search or run; the sweep ages from it. */
79
+ lastSeenAt: number;
80
+ }
81
+
82
+ /** A holder as the caller names it; `acquiredAt` and `lastSeenAt` are stamped by the registry. */
83
+ export type HolderInput = Omit<Holder, "acquiredAt" | "lastSeenAt">;
84
+
85
+ /** The session making a read, search or run (a subset of {@link HolderInput}); `taskRef` names its owner. */
86
+ export type LeaseActor = Pick<HolderInput, "holderID" | "tree" | "isChild" | "taskRef">;
87
+
88
+ /** The effects the registry needs, all synchronous (no `await` between a check and its insert). */
89
+ export interface LeaseSeams {
90
+ /** Native realpath; throws when the path does not exist. */
91
+ realpath(p: string): string;
92
+ /**
93
+ * The repository and work tree containing `dir`, or undefined outside any. `repo` scopes the logical (write) key of
94
+ * a file. `shared`, when given, is the repository every checkout of `repo` belongs to (`repo` itself when omitted):
95
+ * an `until-integrated` write also conflicts with another owner's `until-integrated` lease on the same repo-relative
96
+ * path in any checkout of `shared` (a plan task's work is integrated into one branch). The answer is folded by the
97
+ * registry exactly like a physical key ({@link foldKeyPath}), so either spelling is accepted.
98
+ */
99
+ repoKeyOf(dir: string): { repo: string; tree: string; shared?: string } | undefined;
100
+ /** The clock, in epoch milliseconds. */
101
+ now(): number;
102
+ }
103
+
104
+ /** Registry options. */
105
+ export interface LeaseOptions {
106
+ /** What a child `router_run` does while another holder edits its tree: annotate the result or refuse. */
107
+ runMode: "annotate" | "refuse";
108
+ /** Maximum number of leases held at once. Default 10 000. */
109
+ cap?: number;
110
+ /** Age since `lastSeenAt` at which an `until-complete` holder is swept. Default 6 h. */
111
+ sweepAgeMs?: number;
112
+ /** Path rules to apply (tests). Default `process.platform`. */
113
+ platform?: NodeJS.Platform;
114
+ }
115
+
116
+ /** The normalised identity of one file (see {@link keyOf}). */
117
+ export interface PathKey {
118
+ /** The canonical absolute path, `/`-separated, case-folded on win32: decides read conflicts. */
119
+ physical: string;
120
+ /** `r:<repo>\0<rel>` inside a repository, else `x:<physical>`: decides write conflicts. */
121
+ logical: string;
122
+ /** The work tree containing the file (canonical, folded), or null outside any repository. */
123
+ tree: string | null;
124
+ /** The repository (folded), or null outside any. */
125
+ repo: string | null;
126
+ /** The repository every checkout of `repo` belongs to (folded; `repo` when the seam names none), or null outside any. */
127
+ shared: string | null;
128
+ /** Path relative to the tree (`""` for the tree itself), or null outside any repository. FOLDED (upper-cased on win32). */
129
+ rel: string | null;
130
+ /**
131
+ * `rel` in the case the filesystem reports, `/`-separated: the spelling for a git pathspec. `physical`, `tree`,
132
+ * `repo`, `rel` and `logical` are key spellings (folded on win32) and must not be handed to git.
133
+ */
134
+ relOnDisk: string | null;
135
+ /** The absolute path as given (lexically resolved), for messages. */
136
+ display: string;
137
+ }
138
+
139
+ /** A path no stable key can be derived for. */
140
+ export interface Unkeyable {
141
+ unkeyable: string;
142
+ }
143
+
144
+ /** The outcome of {@link LeaseRegistry.acquireWrite}. */
145
+ export type AcquireResult =
146
+ | { ok: true; leased: string[]; reentrant: string[]; unkeyed: string[] }
147
+ | {
148
+ ok: false;
149
+ reason: "held";
150
+ holders: [Holder];
151
+ /**
152
+ * The requester's own file, as its `NEED MORE: lease` names it: the absolute path as given, or for an
153
+ * `until-integrated` requester (a plan task) the repo-relative path on disk when the file lies in a repository.
154
+ */
155
+ path: string;
156
+ /** The file under edit (absolute): the holder's own copy, in its checkout for a repository-wide conflict. */
157
+ heldPath: string;
158
+ key: string;
159
+ }
160
+ | {
161
+ ok: false;
162
+ reason: "unknown-target";
163
+ holders: Holder[];
164
+ /**
165
+ * Where the holders edit: the writer's `checkout`, also its `repository` for an `until-integrated` writer, or
166
+ * `anywhere` for a spelling that may name any file (a device form, a drive-relative path, an 8.3 name).
167
+ */
168
+ where: "checkout" | "repository" | "anywhere";
169
+ }
170
+ | { ok: false; reason: "cap"; limit: number; held: number }
171
+ | { ok: false; reason: "invalid-holder"; message: string };
172
+
173
+ /** The outcome of {@link LeaseRegistry.checkRead}. */
174
+ export type ReadCheck =
175
+ | { ok: true }
176
+ | { ok: false; reason: "underEdit"; holders: Holder[]; path: string }
177
+ | { ok: false; reason: "invalid-holder"; message: string };
178
+
179
+ /** The outcome of {@link LeaseRegistry.checkRun}. */
180
+ export type RunCheck =
181
+ | { ok: true }
182
+ | { ok: true; contaminatedBy: Holder[]; fileCount: number }
183
+ | { ok: false; reason: "run-refused"; holders: Holder[]; fileCount: number }
184
+ | { ok: false; reason: "invalid-holder"; message: string };
185
+
186
+ /** The outcome of {@link LeaseRegistry.filterSearchResults}. */
187
+ export interface FilterResult {
188
+ /** The entries the reader may see: the original strings, in the original order. */
189
+ kept: string[];
190
+ /** How many entries were left out. */
191
+ omitted: number;
192
+ /** The distinct holders of the omitted entries, first-seen order. */
193
+ holders: Holder[];
194
+ /** Present only when the reader is not a valid actor: every entry is then left out. */
195
+ invalid?: string;
196
+ }
197
+
198
+ /** The outcome of {@link LeaseRegistry.release}. */
199
+ export interface ReleaseResult {
200
+ released: number;
201
+ /** Leases kept because they are `until-integrated`. */
202
+ retained: number;
203
+ }
204
+
205
+ /** The outcome of {@link LeaseRegistry.releaseTask} and {@link LeaseRegistry.sweep}. */
206
+ export interface HoldersReleased {
207
+ /** Leases ended. */
208
+ released: number;
209
+ /** The ids of the holders whose leases ended. */
210
+ holders: string[];
211
+ }
212
+
213
+ /** One lease in a {@link LeaseSnapshot}: one line per holder and recorded (physical, tree) pair of a logical key. */
214
+ export interface SnapshotLease {
215
+ logical: string;
216
+ physical: string;
217
+ tree: string | null;
218
+ holderID: string;
219
+ display: string;
220
+ /** The repository every checkout of the key's repository belongs to; present only when it is not that repository. */
221
+ shared?: string;
222
+ }
223
+
224
+ /** The registry state as plain JSON. */
225
+ export interface LeaseSnapshot {
226
+ version: 1;
227
+ /** Epoch ms. */
228
+ takenAt: number;
229
+ holders: Holder[];
230
+ leases: SnapshotLease[];
231
+ }
232
+
233
+ /** The outcome of {@link LeaseRegistry.restore}. */
234
+ export type RestoreResult =
235
+ /** `skipped`: lines left out of a clash on a re-keyed key (QA-PDF13-8), one text each; absent when none. */
236
+ | { ok: true; leases: number; skipped?: string[] }
237
+ | { ok: false; reason: "invalid-snapshot"; message: string };
238
+
239
+ /** Options of {@link LeaseRegistry.restore}. */
240
+ export interface RestoreOptions {
241
+ /** Leave out the `until-complete` holders (and their leases): their sessions did not survive the restart. */
242
+ dropCompleteHolders?: boolean;
243
+ }
244
+
245
+ /** The lease registry. */
246
+ export interface LeaseRegistry {
247
+ /**
248
+ * A child session takes write leases on `path` (one path, or an array which is all-or-nothing). `null`, `[]` and any
249
+ * other value that is not a string or an array is a write whose target is unknown. A root session is only checked:
250
+ * nothing is recorded for it. Never throws.
251
+ */
252
+ acquireWrite(holder: HolderInput, path: string | readonly string[] | null): AcquireResult;
253
+ /** A child reader is refused a file another owner leases (same physical file). Root readers are never refused. */
254
+ checkRead(reader: LeaseActor, path: string): ReadCheck;
255
+ /**
256
+ * A run in `tree` while other owners edit that tree, or lease files under the run directory (nested trees,
257
+ * submodules, files outside any repository): annotate or refuse per `runMode` (roots are only annotated).
258
+ */
259
+ checkRun(runner: LeaseActor, tree: string): RunCheck;
260
+ /** Drops the entries of `paths` (relative ones against `tree`) a child reader may not see. */
261
+ filterSearchResults(reader: LeaseActor, tree: string, paths: readonly string[]): FilterResult;
262
+ /**
263
+ * DF-1.1-4: the repository-wide lookup. The first `until-integrated` (plan-task) holder of the repo-relative path of
264
+ * `path` (a relative one against `tree`) in ANY checkout of the repository `tree` belongs to (the key's `shared`
265
+ * repository), or null: the holder another plan task's write of that path would conflict with. The logical key alone
266
+ * names one checkout. Never throws.
267
+ */
268
+ planHolderOf(tree: string, path: string): Holder | null;
269
+ /** Ends the `until-complete` leases of a holder (idempotent); `until-integrated` leases are kept. */
270
+ release(holderID: string): ReleaseResult;
271
+ /** Ends every lease of the holders working on `taskRef`, whatever their scope. */
272
+ releaseTask(taskRef: string): HoldersReleased;
273
+ /** Ends the leases of `until-complete` holders not seen for `sweepAgeMs`; future stamps are never swept. */
274
+ sweep(): HoldersReleased;
275
+ /** The state as plain JSON. */
276
+ snapshot(): LeaseSnapshot;
277
+ /**
278
+ * Replaces the state with a snapshot after validating all of it (shapes and consistency; stamps in the future are
279
+ * clamped to `now()`); a rejected snapshot leaves the state unchanged. A line without `shared` whose tree `repoKeyOf`
280
+ * now keys per checkout, with the line's repository as `shared` (a snapshot from before DF-1.1-4), is re-keyed.
281
+ */
282
+ restore(snapshot: unknown, opts?: RestoreOptions): RestoreResult;
283
+ }
284
+
285
+ const DEFAULT_CAP = 10_000;
286
+ const DEFAULT_SWEEP_AGE_MS = 6 * 60 * 60 * 1000;
287
+ /** The longest path accepted (the NTFS extended-length limit), in UTF-16 units. */
288
+ const MAX_PATH_CHARS = 32_767;
289
+ /** The most segments a path may have. */
290
+ const MAX_PATH_SEGMENTS = 4_096;
291
+ /** A win32 8.3 short-name segment (`PROGRA~1`, `MARQUI~1.TXT`), which cannot be told from a long name when missing. */
292
+ const SHORT_NAME = /^[^.~\\/]{1,6}~\d+(\.[^.]{0,3})?$/i;
293
+ /** `\\.\`, `\\?\` and the NT object prefix `\??\`. */
294
+ const DEVICE_PREFIX = /^(?:[\\/]{2}[.?]|[\\/]\?\?)[\\/]/;
295
+ /** The reasons of unkeyable paths that may still name any file; they fail closed. */
296
+ const ALIASING_REASONS: ReadonlySet<string> = new Set([
297
+ "device path",
298
+ "drive-relative path",
299
+ "rooted path without a drive",
300
+ "8.3 short name in a missing path",
301
+ ]);
302
+
303
+ function isRecord(value: unknown): value is Record<string, unknown> {
304
+ return typeof value === "object" && value !== null && !Array.isArray(value);
305
+ }
306
+
307
+ function describeValue(value: unknown): string {
308
+ try {
309
+ return String(value);
310
+ } catch {
311
+ return typeof value;
312
+ }
313
+ }
314
+
315
+ function isRoot(path: string): boolean {
316
+ return path === "/" || /^[a-z]:\/$/i.test(path) || /^\/\/[^/]+\/[^/]+\/?$/.test(path);
317
+ }
318
+
319
+ /**
320
+ * Each UTF-16 unit upper-cased when that stays one unit (`ß` stays, `ſ` becomes `S`): an approximation of NTFS's table.
321
+ * A unit whose upper case is longer (`ᾳ` → `ΑΙ`) falls back to its LOWER case, so that `ᾳ` and `ᾼ` (its title case,
322
+ * whose lower case is `ᾳ`) fold to one spelling.
323
+ */
324
+ function upcaseUnits(text: string): string {
325
+ let out = "";
326
+ for (let index = 0; index < text.length; index++) {
327
+ const unit = text.charAt(index);
328
+ const upper = unit.toUpperCase();
329
+ if (upper.length === 1) {
330
+ out += upper;
331
+ continue;
332
+ }
333
+ const lower = unit.toLowerCase();
334
+ out += lower.length === 1 ? lower : unit;
335
+ }
336
+ return out;
337
+ }
338
+
339
+ /**
340
+ * The key spelling of a path: `/` separators, case-folded on win32 (see the module limits), no trailing `/` except on
341
+ * a root. Applied to physical keys, to the tree and repositories a `repoKeyOf` answers with, and to snapshot paths; the
342
+ * 2.1 adapter spells its answers with it.
343
+ */
344
+ export function foldKeyPath(text: string, platform: NodeJS.Platform = process.platform): string {
345
+ let out = text.replace(/\\/g, "/");
346
+ if (platform === "win32") out = upcaseUnits(out);
347
+ while (out.length > 1 && out.endsWith("/") && !isRoot(out)) out = out.slice(0, -1);
348
+ return out;
349
+ }
350
+
351
+ /** `\\?\X:\…`, `\\.\X:\…`, `\??\X:\…` → `X:\…`; the `UNC\h\s\…` forms → `\\h\s\…`; other device forms are unkeyable. */
352
+ function unwrapDevicePath(text: string): { path: string } | Unkeyable {
353
+ const prefix = DEVICE_PREFIX.exec(text);
354
+ if (prefix === null) return { path: text };
355
+ const rest = text.slice(prefix[0].length);
356
+ const unc = /^UNC[\\/]([\s\S]*)$/i.exec(rest);
357
+ if (unc) return { path: `\\\\${unc[1] ?? ""}` };
358
+ if (/^[A-Za-z]:(?:[\\/]|$)/.test(rest)) return { path: rest };
359
+ return { unkeyable: "device path" };
360
+ }
361
+
362
+ /** The one non-drive device form that names a volume the filesystem can resolve: `\\?\Volume{guid}\…`. */
363
+ const VOLUME_DEVICE = /^(?:[\\/]{2}[.?]|[\\/]\?\?)[\\/]Volume\{[0-9a-f-]+\}(?:[\\/]|$)/i;
364
+
365
+ /**
366
+ * {@link unwrapDevicePath}, and for a `Volume{guid}` form the DOS path the filesystem answers with, if it does. Every
367
+ * other device form (`\\.\pipe\…`, `\\?\GLOBALROOT\…`, `\\.\PhysicalDrive0`, …) is unkeyable without any filesystem
368
+ * call: resolving it could open a pipe or a device.
369
+ */
370
+ function normalizeDevice(text: string, realpath: (p: string) => string): { path: string } | Unkeyable {
371
+ const first = unwrapDevicePath(text);
372
+ if (!("unkeyable" in first)) return first;
373
+ if (!VOLUME_DEVICE.test(text)) return first;
374
+ let real: unknown;
375
+ try {
376
+ real = realpath(text);
377
+ } catch {
378
+ return first;
379
+ }
380
+ if (typeof real !== "string") return first;
381
+ const again = unwrapDevicePath(real);
382
+ return "unkeyable" in again ? first : again;
383
+ }
384
+
385
+ /**
386
+ * Why `text` is too big to key (more than 32 767 units, or with `countSegments` more than 4 096 segments), or
387
+ * undefined. The segments are counted on the resolved path, after `..` collapse.
388
+ */
389
+ function oversized(text: string, win: boolean, countSegments: boolean): string | undefined {
390
+ if (text.length > MAX_PATH_CHARS) return "path too long";
391
+ if (!countSegments) return undefined;
392
+ let segments = 1;
393
+ for (let index = 0; index < text.length; index++) {
394
+ const code = text.charCodeAt(index);
395
+ if (code === 47 || (win && code === 92)) {
396
+ segments++;
397
+ if (segments > MAX_PATH_SEGMENTS) return "too many path segments";
398
+ }
399
+ }
400
+ return undefined;
401
+ }
402
+
403
+ /** The canonical spelling of `abs` (an absolute, cleaned path) and the segments of it that do not exist. */
404
+ function canonicalize(
405
+ abs: string,
406
+ api: typeof posix,
407
+ realpath: (p: string) => string,
408
+ ): { canonical: string; tail: string[] } {
409
+ const reached: string[] = [];
410
+ const probe = (p: string): string => {
411
+ const real = realpath(p);
412
+ reached.push(p);
413
+ return real;
414
+ };
415
+ let canonical: string;
416
+ if ((api === win32) === (process.platform === "win32")) {
417
+ canonical = canonicalPath(abs, probe);
418
+ } else {
419
+ // canonicalPath resolves with the host's path rules; for the other platform's rules, the same walk with theirs.
420
+ canonical = abs;
421
+ let head = abs;
422
+ const missing: string[] = [];
423
+ for (;;) {
424
+ try {
425
+ const real = probe(head);
426
+ canonical = missing.length === 0 ? real : api.join(real, ...missing.reverse());
427
+ break;
428
+ } catch {
429
+ const parent = api.dirname(head);
430
+ if (parent === head) break;
431
+ missing.push(api.basename(head));
432
+ head = parent;
433
+ }
434
+ }
435
+ }
436
+ const head = reached[0];
437
+ const rest = head === undefined ? abs.slice(api.parse(abs).root.length) : abs.slice(head.length);
438
+ return { canonical, tail: rest.split(api.sep).filter((segment) => segment !== "") };
439
+ }
440
+
441
+ function keyOfIn(
442
+ raw: unknown,
443
+ base: string,
444
+ seams: LeaseSeams,
445
+ platform: NodeJS.Platform,
446
+ asDirectory: boolean,
447
+ ): PathKey | Unkeyable {
448
+ // 1. unkeyable inputs
449
+ if (typeof raw !== "string") return { unkeyable: "not a string" };
450
+ if (raw.trim() === "") return { unkeyable: "empty path" };
451
+ if (raw.includes("\0")) return { unkeyable: "NUL in path" };
452
+ const win = platform === "win32";
453
+ const api = win ? win32 : posix;
454
+ let text = raw;
455
+ let root = typeof base === "string" ? base : "";
456
+ const tooBig = oversized(text, win, false) ?? oversized(root, win, false);
457
+ if (tooBig !== undefined) return { unkeyable: tooBig };
458
+ // 2. win32: unwrap device forms; refuse unresolvable device forms and drive-relative paths
459
+ if (win) {
460
+ const unwrapped = normalizeDevice(text, (p) => seams.realpath(p));
461
+ if ("unkeyable" in unwrapped) return unwrapped;
462
+ text = unwrapped.path;
463
+ if (/^[A-Za-z]:(?![\\/])/.test(text)) return { unkeyable: "drive-relative path" };
464
+ // `\x` is on the drive of the process, which is not necessarily the one of the base.
465
+ if (/^[\\/](?![\\/])/.test(text)) return { unkeyable: "rooted path without a drive" };
466
+ const unwrappedBase = normalizeDevice(root, (p) => seams.realpath(p));
467
+ if ("unkeyable" in unwrappedBase) return unwrappedBase;
468
+ root = unwrappedBase.path;
469
+ }
470
+ if (!api.isAbsolute(text) && !api.isAbsolute(root)) return { unkeyable: "relative path without an absolute base" };
471
+ // 3. lexical resolution
472
+ const display = api.resolve(root, text);
473
+ const collapsed = oversized(display, win, true);
474
+ if (collapsed !== undefined) return { unkeyable: collapsed };
475
+ // 4. win32: per segment, strip a stream suffix, then trailing dots and spaces
476
+ const volume = api.parse(display).root;
477
+ let absolute = display;
478
+ if (win) {
479
+ const cleaned: string[] = [];
480
+ for (const segment of display.slice(volume.length).split(api.sep)) {
481
+ if (segment === "") continue;
482
+ const colon = segment.indexOf(":");
483
+ const name = (colon >= 0 ? segment.slice(0, colon) : segment).replace(/[. ]+$/, "");
484
+ if (name === "") return { unkeyable: "empty path segment" };
485
+ cleaned.push(name);
486
+ }
487
+ absolute = volume + cleaned.join(api.sep);
488
+ }
489
+ // 5. canonical form of the nearest existing ancestor
490
+ const { canonical: found, tail } = canonicalize(absolute, api, (p) => seams.realpath(p));
491
+ let canonical = found;
492
+ if (win) {
493
+ const unwrapped = unwrapDevicePath(canonical);
494
+ if ("unkeyable" in unwrapped) return unwrapped;
495
+ canonical = unwrapped.path;
496
+ // 6. an 8.3-looking name in the part that does not exist cannot be expanded
497
+ if (tail.some((segment) => SHORT_NAME.test(segment))) return { unkeyable: "8.3 short name in a missing path" };
498
+ }
499
+ // 7. physical key
500
+ const physical = foldKeyPath(canonical, platform);
501
+ // 8. repository identity, folded exactly like the physical key
502
+ let id: { repo: string; tree: string; shared: string } | undefined;
503
+ try {
504
+ const answer: unknown = seams.repoKeyOf(asDirectory ? canonical : api.dirname(canonical));
505
+ if (isRecord(answer) && typeof answer.repo === "string" && typeof answer.tree === "string") {
506
+ const repo = foldKeyPath(answer.repo, platform);
507
+ const shared = typeof answer.shared === "string" && answer.shared !== "" ? foldKeyPath(answer.shared, platform) : repo;
508
+ id = { repo, tree: foldKeyPath(answer.tree, platform), shared };
509
+ }
510
+ } catch {
511
+ id = undefined;
512
+ }
513
+ if (id !== undefined) {
514
+ const prefix = id.tree.endsWith("/") ? id.tree : `${id.tree}/`;
515
+ let rel: string | undefined;
516
+ if (physical === id.tree || `${physical}/` === prefix) rel = "";
517
+ else if (physical.startsWith(prefix)) rel = physical.slice(prefix.length);
518
+ if (rel !== undefined) {
519
+ // Folding keeps the length of every unit, so the tail of the unfolded path is the on-disk spelling of `rel`.
520
+ const disk = foldKeyPath(canonical, "linux");
521
+ const relOnDisk = rel === "" ? "" : disk.slice(disk.length - rel.length);
522
+ return {
523
+ physical,
524
+ logical: `r:${id.repo}\0${rel}`,
525
+ tree: id.tree,
526
+ repo: id.repo,
527
+ shared: id.shared,
528
+ rel,
529
+ relOnDisk,
530
+ display,
531
+ };
532
+ }
533
+ }
534
+ return { physical, logical: `x:${physical}`, tree: null, repo: null, shared: null, rel: null, relOnDisk: null, display };
535
+ }
536
+
537
+ /**
538
+ * The key of one file: every spelling of it (case, separators, `..`, `\\?\`, `\\.\X:\`, `\??\`, trailing dots or
539
+ * spaces, NTFS streams, junctions, symlinks and 8.3 names of existing segments) maps to the same key. `raw` is
540
+ * resolved against `base`; a path no stable key exists for (empty, NUL, over 32 767 characters or 4 096 segments,
541
+ * an unresolvable device or drive-relative form, 8.3 name in the missing part) gives `{ unkeyable: reason }`. Known
542
+ * limits: see the module doc.
543
+ */
544
+ export function keyOf(
545
+ raw: unknown,
546
+ base: string,
547
+ seams: LeaseSeams,
548
+ platform: NodeJS.Platform = process.platform,
549
+ ): PathKey | Unkeyable {
550
+ return keyOfIn(raw, base, seams, platform, false);
551
+ }
552
+
553
+ /** The run note a contaminated `router_run` result carries (holder ids joined with `, `). */
554
+ export function formatRunNote(holders: readonly (Holder | string)[], n: number): string {
555
+ const ids = holders.map((holder) => (typeof holder === "string" ? holder : holder.holderID));
556
+ return `[router] ran while ${ids.join(", ")} edits ${n} file(s); result may be contaminated`;
557
+ }
558
+
559
+ /** One (physical, tree) spelling a logical key was written in. */
560
+ interface Pair {
561
+ physical: string;
562
+ tree: string | null;
563
+ }
564
+
565
+ interface LeaseEntry {
566
+ /** The sessions holding the lease, first writer first. All of them have one owner; the lease ends with the last. */
567
+ holders: Set<string>;
568
+ /** The owner of every holder (`t:<taskRef>` or `h:<holderID>`). */
569
+ owner: string;
570
+ display: string;
571
+ /** The repository of an `r:` key, else null. */
572
+ repo: string | null;
573
+ /** The shared repository of an `r:` key ({@link PathKey.shared}), else null. */
574
+ shared: string | null;
575
+ /** Keyed by {@link pairKey}. */
576
+ pairs: Map<string, Pair>;
577
+ }
578
+
579
+ interface HolderRecord {
580
+ holder: Holder;
581
+ /** `t:<taskRef>` or `h:<holderID>`. */
582
+ owner: string;
583
+ keys: Set<string>;
584
+ }
585
+
586
+ interface State {
587
+ leases: Map<string, LeaseEntry>;
588
+ holders: Map<string, HolderRecord>;
589
+ /** repository → holderID → number of logical keys held in it. */
590
+ repoHolders: Map<string, Map<string, number>>;
591
+ tasks: Map<string, Set<string>>;
592
+ /** owner → number of recorded holders. */
593
+ owners: Map<string, number>;
594
+ /** tree (folded; "" for no tree) → the logical keys with a pair in it. Bounds a run check to its tree. */
595
+ byTree: Map<string, Set<string>>;
596
+ /** Every directory (folded) that is an ancestor-or-self of a leased physical path → the logical keys below it. */
597
+ byDir: Map<string, Set<string>>;
598
+ /** {@link wideKey} → the logical keys of that repo-relative path in every checkout. Bounds an until-integrated write check. */
599
+ byShared: Map<string, Set<string>>;
600
+ }
601
+
602
+ function emptyState(): State {
603
+ return {
604
+ leases: new Map(),
605
+ holders: new Map(),
606
+ repoHolders: new Map(),
607
+ tasks: new Map(),
608
+ owners: new Map(),
609
+ byTree: new Map(),
610
+ byDir: new Map(),
611
+ byShared: new Map(),
612
+ };
613
+ }
614
+
615
+ /** The repository-wide identity of an `r:` lease (`<shared>\0<rel>`), or null for any other. */
616
+ function wideKey(logical: string, shared: string | null): string | null {
617
+ const sep = logical.indexOf("\0");
618
+ return shared === null || !logical.startsWith("r:") || sep < 0 ? null : `${shared}\0${logical.slice(sep + 1)}`;
619
+ }
620
+
621
+ /**
622
+ * The directories a folded physical path lies under, itself included (`/a/b` → `/`, `/a`, `/a/b`; `C:/a` → `C:/`,
623
+ * `C:/a`); a root is listed with and without its trailing `/`. These are the keys of {@link State.byDir}.
624
+ */
625
+ function dirPrefixes(physical: string): string[] {
626
+ const out = new Set<string>([physical]);
627
+ for (let index = physical.indexOf("/"); index >= 0; index = physical.indexOf("/", index + 1)) {
628
+ const withSlash = physical.slice(0, index + 1);
629
+ if (isRoot(withSlash)) {
630
+ out.add(withSlash);
631
+ if (withSlash.length > 1) out.add(withSlash.slice(0, -1));
632
+ } else if (index > 0) {
633
+ out.add(physical.slice(0, index));
634
+ }
635
+ }
636
+ return [...out];
637
+ }
638
+
639
+ function addToIndex(index: Map<string, Set<string>>, key: string, logical: string): void {
640
+ const set = index.get(key) ?? new Set<string>();
641
+ set.add(logical);
642
+ index.set(key, set);
643
+ }
644
+
645
+ function removeFromIndex(index: Map<string, Set<string>>, key: string, logical: string): void {
646
+ const set = index.get(key);
647
+ if (set === undefined) return;
648
+ set.delete(logical);
649
+ if (set.size === 0) index.delete(key);
650
+ }
651
+
652
+ /** Records a (physical, tree) pair of a lease in the run-check indexes. */
653
+ function indexPair(state: State, logical: string, pair: Pair): void {
654
+ for (const dir of dirPrefixes(pair.physical)) addToIndex(state.byDir, dir, logical);
655
+ if (pair.tree !== null) addToIndex(state.byTree, pair.tree, logical);
656
+ }
657
+
658
+ function unindexLease(state: State, logical: string, entry: LeaseEntry): void {
659
+ for (const pair of entry.pairs.values()) {
660
+ for (const dir of dirPrefixes(pair.physical)) removeFromIndex(state.byDir, dir, logical);
661
+ if (pair.tree !== null) removeFromIndex(state.byTree, pair.tree, logical);
662
+ }
663
+ const wide = wideKey(logical, entry.shared);
664
+ if (wide !== null) removeFromIndex(state.byShared, wide, logical);
665
+ }
666
+
667
+ function ownerOf(holderID: string, taskRef: string | undefined): string {
668
+ return taskRef !== undefined ? `t:${taskRef}` : `h:${holderID}`;
669
+ }
670
+
671
+ function pairKey(pair: Pair): string {
672
+ return `${pair.tree ?? ""}\0${pair.physical}`;
673
+ }
674
+
675
+ function recordHolder(state: State, holder: Holder): HolderRecord {
676
+ const record: HolderRecord = { holder, owner: ownerOf(holder.holderID, holder.taskRef), keys: new Set() };
677
+ state.holders.set(holder.holderID, record);
678
+ state.owners.set(record.owner, (state.owners.get(record.owner) ?? 0) + 1);
679
+ if (holder.taskRef !== undefined) {
680
+ const ids = state.tasks.get(holder.taskRef) ?? new Set<string>();
681
+ ids.add(holder.holderID);
682
+ state.tasks.set(holder.taskRef, ids);
683
+ }
684
+ return record;
685
+ }
686
+
687
+ /** Adds a new lease, held by `record`. */
688
+ function link(state: State, record: HolderRecord, logical: string, entry: LeaseEntry): void {
689
+ state.leases.set(logical, entry);
690
+ for (const pair of entry.pairs.values()) indexPair(state, logical, pair);
691
+ const wide = wideKey(logical, entry.shared);
692
+ if (wide !== null) addToIndex(state.byShared, wide, logical);
693
+ join(state, record, logical, entry);
694
+ }
695
+
696
+ /** Adds `record` to the holders of an existing lease (its owner is the lease's). */
697
+ function join(state: State, record: HolderRecord, logical: string, entry: LeaseEntry): void {
698
+ const holderID = record.holder.holderID;
699
+ if (entry.holders.has(holderID)) return;
700
+ entry.holders.add(holderID);
701
+ record.keys.add(logical);
702
+ if (entry.repo === null) return;
703
+ const counts = state.repoHolders.get(entry.repo) ?? new Map<string, number>();
704
+ counts.set(holderID, (counts.get(holderID) ?? 0) + 1);
705
+ state.repoHolders.set(entry.repo, counts);
706
+ }
707
+
708
+ /**
709
+ * Ends the part of every lease one holder has and forgets the holder; a lease ends only with its last holder (the
710
+ * strongest scope among them decides how long it lives). Returns how many leases ended.
711
+ */
712
+ function dropHolder(state: State, holderID: string): number {
713
+ const record = state.holders.get(holderID);
714
+ if (record === undefined) return 0;
715
+ let ended = 0;
716
+ for (const logical of record.keys) {
717
+ const entry = state.leases.get(logical);
718
+ if (entry === undefined) continue;
719
+ entry.holders.delete(holderID);
720
+ if (entry.holders.size === 0) {
721
+ state.leases.delete(logical);
722
+ unindexLease(state, logical, entry);
723
+ ended++;
724
+ }
725
+ if (entry.repo === null) continue;
726
+ const counts = state.repoHolders.get(entry.repo);
727
+ if (counts === undefined) continue;
728
+ const left = (counts.get(holderID) ?? 0) - 1;
729
+ if (left > 0) counts.set(holderID, left);
730
+ else counts.delete(holderID);
731
+ if (counts.size === 0) state.repoHolders.delete(entry.repo);
732
+ }
733
+ state.holders.delete(holderID);
734
+ const owners = (state.owners.get(record.owner) ?? 0) - 1;
735
+ if (owners > 0) state.owners.set(record.owner, owners);
736
+ else state.owners.delete(record.owner);
737
+ const { taskRef } = record.holder;
738
+ if (taskRef !== undefined) {
739
+ const ids = state.tasks.get(taskRef);
740
+ if (ids !== undefined) {
741
+ ids.delete(holderID);
742
+ if (ids.size === 0) state.tasks.delete(taskRef);
743
+ }
744
+ }
745
+ return ended;
746
+ }
747
+
748
+ /** The actor as the caller names it, or why it is invalid. */
749
+ function parseActor(value: unknown, platform: NodeJS.Platform): LeaseActor | string {
750
+ if (!isRecord(value)) return "holder must be an object";
751
+ const { holderID, tree, isChild, taskRef } = value;
752
+ if (typeof holderID !== "string" || holderID.trim() === "") return "holderID must be a non-empty string";
753
+ if (typeof tree !== "string" || tree === "") return "tree must be a non-empty string";
754
+ if (!(platform === "win32" ? win32 : posix).isAbsolute(tree)) return "tree must be an absolute path";
755
+ if (typeof isChild !== "boolean") return "isChild must be a boolean";
756
+ if (taskRef !== undefined && (typeof taskRef !== "string" || taskRef.trim() === "")) {
757
+ return "taskRef must be a non-empty string";
758
+ }
759
+ return taskRef === undefined ? { holderID, tree, isChild } : { holderID, tree, isChild, taskRef };
760
+ }
761
+
762
+ /** The holder as the caller names it, or why it is invalid. */
763
+ function parseHolderInput(value: unknown, platform: NodeJS.Platform): HolderInput | string {
764
+ const actor = parseActor(value, platform);
765
+ if (typeof actor === "string") return actor;
766
+ const scope = isRecord(value) ? value.scope : undefined;
767
+ if (scope !== "until-complete" && scope !== "until-integrated") return "scope must be until-complete or until-integrated";
768
+ if (scope === "until-integrated" && actor.taskRef === undefined) return "an until-integrated lease requires a taskRef";
769
+ return { ...actor, scope };
770
+ }
771
+
772
+ /** The paths of a write as a list: a string is one path; an array (read once, so a hostile one cannot change) is its items. */
773
+ function readPaths(path: unknown): readonly unknown[] {
774
+ try {
775
+ if (Array.isArray(path)) return Array.from(path as readonly unknown[]);
776
+ return typeof path === "string" ? [path] : [];
777
+ } catch {
778
+ return [];
779
+ }
780
+ }
781
+
782
+ /** A {@link LeaseActor} with the owner its leases belong to. */
783
+ type BoundActor = LeaseActor & { owner: string };
784
+
785
+ function sameHolder(a: HolderInput, b: HolderInput): boolean {
786
+ return a.tree === b.tree && a.scope === b.scope && a.taskRef === b.taskRef && a.isChild === b.isChild;
787
+ }
788
+
789
+ function copyHolder(holder: Holder): Holder {
790
+ return { ...holder };
791
+ }
792
+
793
+ /** The seams with a per-call cache, so a batch of paths shares the canonicalisation of its directories. */
794
+ function memoize(seams: LeaseSeams): LeaseSeams {
795
+ const real = new Map<string, { value: string } | { error: unknown }>();
796
+ const repos = new Map<string, { repo: string; tree: string; shared?: string } | undefined>();
797
+ return {
798
+ realpath(p: string): string {
799
+ const hit = real.get(p);
800
+ if (hit !== undefined) {
801
+ if ("error" in hit) throw hit.error;
802
+ return hit.value;
803
+ }
804
+ try {
805
+ const value = seams.realpath(p);
806
+ real.set(p, { value });
807
+ return value;
808
+ } catch (error) {
809
+ real.set(p, { error });
810
+ throw error;
811
+ }
812
+ },
813
+ repoKeyOf(dir: string): { repo: string; tree: string; shared?: string } | undefined {
814
+ if (repos.has(dir)) return repos.get(dir);
815
+ const id = seams.repoKeyOf(dir);
816
+ repos.set(dir, id);
817
+ return id;
818
+ },
819
+ now: () => seams.now(),
820
+ };
821
+ }
822
+
823
+ /** Whether `physical` is `dir` or lies under it (both folded keys). */
824
+ function isUnder(physical: string, dir: string): boolean {
825
+ return physical === dir || physical.startsWith(dir.endsWith("/") ? dir : `${dir}/`);
826
+ }
827
+
828
+ /**
829
+ * A lease registry over `seams`. Throws a TypeError only for an invalid `runMode` or `cap`; every other input, however
830
+ * malformed, gets a result.
831
+ * Indexes: `leases` by logical key, `holders` by id, `repoHolders` by repository, `tasks` by taskRef, `owners` by owner,
832
+ * `byShared` by repository-wide identity (`<shared>\0<rel>`).
833
+ * A write check is O(1) in the registry (plus the O(depth) realpath calls of the key derivation); an `until-integrated`
834
+ * write also reads the leases of its path in every checkout (`byShared`, one per checkout that leases it), and its
835
+ * unknown-target check scans the keys of the `until-integrated` holders. A run check reads
836
+ * the leases of the run tree (`byTree`) and of the directories under the run directory (`byDir`, every ancestor of a
837
+ * leased physical path), not all of them; only an unkeyable run directory of a child scans all leases (at most `cap`).
838
+ * Every public method that takes caller input answers a hostile input (throwing getter, revoked Proxy) with
839
+ * `invalid-holder` / an unknown target instead of throwing.
840
+ */
841
+ export function createLeaseRegistry(seams: LeaseSeams, opts: LeaseOptions): LeaseRegistry {
842
+ if (!isRecord(opts) || (opts.runMode !== "annotate" && opts.runMode !== "refuse")) {
843
+ throw new TypeError('runMode must be "annotate" or "refuse"');
844
+ }
845
+ const runMode = opts.runMode;
846
+ const cap = opts.cap ?? DEFAULT_CAP;
847
+ if (typeof cap !== "number" || !Number.isSafeInteger(cap) || cap < 1) {
848
+ throw new TypeError("cap must be a positive integer");
849
+ }
850
+ const sweepAgeMs =
851
+ typeof opts.sweepAgeMs === "number" && Number.isFinite(opts.sweepAgeMs) && opts.sweepAgeMs > 0
852
+ ? opts.sweepAgeMs
853
+ : DEFAULT_SWEEP_AGE_MS;
854
+ const platform = opts.platform ?? process.platform;
855
+ let state = emptyState();
856
+
857
+ const isStale = (record: HolderRecord, now: number): boolean => {
858
+ if (record.holder.scope !== "until-complete") return false;
859
+ const age = now - record.holder.lastSeenAt;
860
+ return age >= 0 && age >= sweepAgeMs;
861
+ };
862
+
863
+ /** The record of a holder, swept on the spot (and then undefined) when it is a stale `until-complete` holder. */
864
+ const liveRecord = (holderID: string): HolderRecord | undefined => {
865
+ const record = state.holders.get(holderID);
866
+ if (record === undefined) return undefined;
867
+ if (isStale(record, seams.now())) {
868
+ dropHolder(state, holderID);
869
+ return undefined;
870
+ }
871
+ return record;
872
+ };
873
+
874
+ /** The first live holder of a lease, sweeping its stale holders on the spot; undefined when none is left. */
875
+ const liveHolderOf = (entry: LeaseEntry): HolderRecord | undefined => {
876
+ for (const id of [...entry.holders]) {
877
+ const record = liveRecord(id);
878
+ if (record !== undefined) return record;
879
+ }
880
+ return undefined;
881
+ };
882
+
883
+ /** Marks a recorded holder as alive. */
884
+ const touch = (holderID: string): void => {
885
+ const record = state.holders.get(holderID);
886
+ if (record !== undefined) record.holder.lastSeenAt = seams.now();
887
+ };
888
+
889
+ /**
890
+ * The actor of a read, search or run with its owner. An actor whose holderID is recorded IS that holder: its owner
891
+ * comes from the record (a missing `taskRef` is inherited), and a `taskRef`, `isChild` or `tree` that differs from
892
+ * the record is an invalid holder. Any other actor is its own owner, or the owner its `taskRef` names.
893
+ */
894
+ const bindActor = (value: unknown): BoundActor | string => {
895
+ const parsed = parseActor(value, platform);
896
+ if (typeof parsed === "string") return parsed;
897
+ const record = state.holders.get(parsed.holderID);
898
+ if (record === undefined) return { ...parsed, owner: ownerOf(parsed.holderID, parsed.taskRef) };
899
+ const recorded = record.holder;
900
+ if (parsed.isChild !== recorded.isChild || parsed.tree !== recorded.tree) {
901
+ return `holder ${parsed.holderID} is recorded with a different tree or isChild`;
902
+ }
903
+ if (parsed.taskRef !== undefined && parsed.taskRef !== recorded.taskRef) {
904
+ return `holder ${parsed.holderID} is recorded with a different taskRef`;
905
+ }
906
+ return recorded.taskRef === undefined
907
+ ? { holderID: parsed.holderID, tree: recorded.tree, isChild: recorded.isChild, owner: record.owner }
908
+ : { holderID: parsed.holderID, tree: recorded.tree, isChild: recorded.isChild, taskRef: recorded.taskRef, owner: record.owner };
909
+ };
910
+
911
+ /** The live holders of any owner but `selfOwner` that hold at least one lease. */
912
+ const holdersOtherThan = (selfOwner: string): Holder[] => {
913
+ const now = seams.now();
914
+ const holders: Holder[] = [];
915
+ const stale: string[] = [];
916
+ for (const [id, record] of state.holders) {
917
+ if (record.owner === selfOwner || record.keys.size === 0) continue;
918
+ if (isStale(record, now)) stale.push(id);
919
+ else holders.push(copyHolder(record.holder));
920
+ }
921
+ for (const id of stale) dropHolder(state, id);
922
+ return holders;
923
+ };
924
+
925
+ /** The live holders of any owner but `selfOwner` that lease files of `repo`. */
926
+ const holdersInRepo = (repo: string, selfOwner: string): Holder[] => {
927
+ const holders: Holder[] = [];
928
+ for (const id of [...(state.repoHolders.get(repo)?.keys() ?? [])]) {
929
+ const record = liveRecord(id);
930
+ if (record !== undefined && record.owner !== selfOwner) holders.push(copyHolder(record.holder));
931
+ }
932
+ return holders;
933
+ };
934
+
935
+ /** The live `until-integrated` holders of any owner but `selfOwner` that lease a file in a checkout of `shared`. */
936
+ const integratedHoldersIn = (shared: string, selfOwner: string): Holder[] => {
937
+ const holders: Holder[] = [];
938
+ for (const record of state.holders.values()) {
939
+ if (record.owner === selfOwner || record.holder.scope !== "until-integrated") continue;
940
+ if ([...record.keys].some((logical) => state.leases.get(logical)?.shared === shared)) holders.push(copyHolder(record.holder));
941
+ }
942
+ return holders;
943
+ };
944
+
945
+ /**
946
+ * DF-1.1-4: the first lease held by an `until-integrated` holder on the repo-relative path of `key` in any checkout of
947
+ * its shared repository, with that holder. Leases of `selfOwner` are skipped, and with `otherCheckouts` the key's own
948
+ * lease too (a write checks its own checkout through the logical key). An `until-integrated` holder is never stale, so
949
+ * nothing is swept.
950
+ */
951
+ const integratedLease = (
952
+ key: PathKey,
953
+ selfOwner: string | null,
954
+ otherCheckouts: boolean,
955
+ ): { logical: string; entry: LeaseEntry; record: HolderRecord } | undefined => {
956
+ const wide = wideKey(key.logical, key.shared);
957
+ if (wide === null) return undefined;
958
+ for (const logical of state.byShared.get(wide) ?? []) {
959
+ const entry = state.leases.get(logical);
960
+ if (entry === undefined || entry.owner === selfOwner || (otherCheckouts && logical === key.logical)) continue;
961
+ for (const id of entry.holders) {
962
+ const record = state.holders.get(id);
963
+ if (record !== undefined && record.holder.scope === "until-integrated") return { logical, entry, record };
964
+ }
965
+ }
966
+ return undefined;
967
+ };
968
+
969
+ /** The holders that make `reader` refuse `raw`, with the file's display path. */
970
+ const readConflict = (
971
+ reader: BoundActor,
972
+ raw: unknown,
973
+ base: string,
974
+ sm: LeaseSeams,
975
+ ): { holders: Holder[]; path: string } | undefined => {
976
+ if (!reader.isChild) return undefined;
977
+ const key = keyOfIn(raw, base, sm, platform, false);
978
+ if ("unkeyable" in key) {
979
+ if (!ALIASING_REASONS.has(key.unkeyable)) return undefined;
980
+ const holders = holdersOtherThan(reader.owner);
981
+ return holders.length === 0 ? undefined : { holders, path: typeof raw === "string" ? raw : describeValue(raw) };
982
+ }
983
+ const lease = state.leases.get(key.logical);
984
+ if (lease === undefined || lease.owner === reader.owner || lease.holders.has(reader.holderID)) return undefined;
985
+ if (![...lease.pairs.values()].some((pair) => pair.physical === key.physical)) return undefined;
986
+ const record = liveHolderOf(lease);
987
+ if (record === undefined) return undefined;
988
+ return { holders: [copyHolder(record.holder)], path: key.display };
989
+ };
990
+
991
+ const sweep = (): HoldersReleased => {
992
+ const now = seams.now();
993
+ const stale: string[] = [];
994
+ for (const [id, record] of state.holders) {
995
+ if (isStale(record, now)) stale.push(id);
996
+ }
997
+ let released = 0;
998
+ for (const id of stale) released += dropHolder(state, id);
999
+ return { released, holders: stale };
1000
+ };
1001
+
1002
+ const acquireWrite = (holderInput: HolderInput, path: string | readonly string[] | null): AcquireResult => {
1003
+ const parsed = parseHolderInput(holderInput, platform);
1004
+ if (typeof parsed === "string") return { ok: false, reason: "invalid-holder", message: parsed };
1005
+ const holder = parsed;
1006
+ const known = state.holders.get(holder.holderID);
1007
+ if (known !== undefined && !sameHolder(known.holder, holder)) {
1008
+ return {
1009
+ ok: false,
1010
+ reason: "invalid-holder",
1011
+ message: `holder ${holder.holderID} is already recorded with a different tree, scope, taskRef or isChild`,
1012
+ };
1013
+ }
1014
+ touch(holder.holderID);
1015
+ const owner = ownerOf(holder.holderID, holder.taskRef);
1016
+ /**
1017
+ * QA-PDF13-7: the path a refused requester names in its `NEED MORE: lease`: its own file, repo-relative (on-disk
1018
+ * spelling) for an `until-integrated` holder, whose plan runtime resolves lease paths against the repository.
1019
+ */
1020
+ const requestPath = (key: PathKey): string =>
1021
+ holder.scope === "until-integrated" && key.relOnDisk !== null && key.relOnDisk !== "" ? key.relOnDisk : key.display;
1022
+
1023
+ const raws = readPaths(path);
1024
+ const unknownTarget = raws.length === 0;
1025
+ const keys = new Map<string, PathKey>();
1026
+ const extras = new Map<string, Pair[]>();
1027
+ const unkeyed: string[] = [];
1028
+ let aliasing = false;
1029
+ for (const raw of raws) {
1030
+ const key = keyOfIn(raw, holder.tree, seams, platform, false);
1031
+ if ("unkeyable" in key) {
1032
+ unkeyed.push(typeof raw === "string" ? raw : describeValue(raw));
1033
+ if (ALIASING_REASONS.has(key.unkeyable)) aliasing = true;
1034
+ } else {
1035
+ const first = keys.get(key.logical);
1036
+ if (first === undefined) {
1037
+ keys.set(key.logical, key);
1038
+ } else if (first.physical !== key.physical || first.tree !== key.tree) {
1039
+ // Another spelling of the same logical key: one more (physical, tree) pair of the same lease. With the per-checkout
1040
+ // keys of the v2 adapter (DF-1.1-4) a key names one checkout; with a repository-wide `repo` (as `repoKeyOf`
1041
+ // may answer) it is the same repo-relative file in another worktree.
1042
+ const more = extras.get(key.logical) ?? [];
1043
+ more.push({ physical: key.physical, tree: key.tree });
1044
+ extras.set(key.logical, more);
1045
+ }
1046
+ }
1047
+ }
1048
+ const pairsOf = (key: PathKey): Pair[] => [{ physical: key.physical, tree: key.tree }, ...(extras.get(key.logical) ?? [])];
1049
+
1050
+ if (!holder.isChild) {
1051
+ for (const [logical, key] of keys) {
1052
+ const lease = state.leases.get(logical);
1053
+ if (lease === undefined) continue;
1054
+ const record = liveHolderOf(lease);
1055
+ if (record !== undefined) {
1056
+ return { ok: false, reason: "held", holders: [copyHolder(record.holder)], path: requestPath(key), heldPath: key.display, key: logical };
1057
+ }
1058
+ }
1059
+ return { ok: true, leased: [], reentrant: [], unkeyed };
1060
+ }
1061
+
1062
+ let swept = false;
1063
+ search: for (;;) {
1064
+ const fresh: PathKey[] = [];
1065
+ const reentrant: string[] = [];
1066
+ const joined: { logical: string; entry: LeaseEntry; pairs: Pair[] }[] = [];
1067
+ for (const [logical, key] of keys) {
1068
+ if (holder.scope === "until-integrated") {
1069
+ // The file under edit is the holder's own copy (in its checkout); the lease to ask for is the requester's path.
1070
+ const wide = integratedLease(key, owner, true);
1071
+ if (wide !== undefined) {
1072
+ const holders: [Holder] = [copyHolder(wide.record.holder)];
1073
+ return { ok: false, reason: "held", holders, path: requestPath(key), heldPath: wide.entry.display, key: wide.logical };
1074
+ }
1075
+ }
1076
+ const lease = state.leases.get(logical);
1077
+ if (lease === undefined) {
1078
+ fresh.push(key);
1079
+ continue;
1080
+ }
1081
+ const before = state.holders.size;
1082
+ const record = liveHolderOf(lease);
1083
+ if (state.holders.size !== before) continue search; // a stale holder was swept: look again
1084
+ if (record === undefined) {
1085
+ fresh.push(key);
1086
+ } else if (record.owner === owner) {
1087
+ reentrant.push(key.display);
1088
+ joined.push({ logical, entry: lease, pairs: pairsOf(key) });
1089
+ } else {
1090
+ return { ok: false, reason: "held", holders: [copyHolder(record.holder)], path: requestPath(key), heldPath: key.display, key: logical };
1091
+ }
1092
+ }
1093
+ if (aliasing) {
1094
+ const holders = holdersOtherThan(owner);
1095
+ if (holders.length > 0) return { ok: false, reason: "unknown-target", holders, where: "anywhere" };
1096
+ } else if (unknownTarget || unkeyed.length > 0) {
1097
+ const home = keyOfIn(holder.tree, holder.tree, seams, platform, true);
1098
+ if (!("unkeyable" in home) && home.repo !== null) {
1099
+ const holders = holdersInRepo(home.repo, owner);
1100
+ const wide = holder.scope === "until-integrated" ? home.shared : null;
1101
+ if (wide !== null) {
1102
+ for (const other of integratedHoldersIn(wide, owner)) {
1103
+ if (!holders.some((h) => h.holderID === other.holderID)) holders.push(other);
1104
+ }
1105
+ }
1106
+ if (holders.length > 0) return { ok: false, reason: "unknown-target", holders, where: wide !== null ? "repository" : "checkout" };
1107
+ }
1108
+ }
1109
+ if (state.leases.size + fresh.length > cap) {
1110
+ if (!swept) {
1111
+ swept = true;
1112
+ sweep();
1113
+ continue;
1114
+ }
1115
+ return { ok: false, reason: "cap", limit: cap, held: state.leases.size };
1116
+ }
1117
+ const stamp = seams.now();
1118
+ let record = state.holders.get(holder.holderID);
1119
+ if (record === undefined && (fresh.length > 0 || joined.length > 0)) {
1120
+ record = recordHolder(state, { ...holder, acquiredAt: stamp, lastSeenAt: stamp });
1121
+ }
1122
+ if (record !== undefined) {
1123
+ record.holder.lastSeenAt = stamp;
1124
+ for (const key of fresh) {
1125
+ link(state, record, key.logical, {
1126
+ holders: new Set(),
1127
+ owner,
1128
+ display: key.display,
1129
+ repo: key.repo,
1130
+ shared: key.shared,
1131
+ pairs: new Map(pairsOf(key).map((pair): [string, Pair] => [pairKey(pair), pair])),
1132
+ });
1133
+ }
1134
+ for (const { logical, entry, pairs } of joined) {
1135
+ join(state, record, logical, entry);
1136
+ for (const pair of pairs) {
1137
+ if (entry.pairs.has(pairKey(pair))) continue;
1138
+ entry.pairs.set(pairKey(pair), pair);
1139
+ indexPair(state, logical, pair);
1140
+ }
1141
+ }
1142
+ }
1143
+ for (const key of keys.values()) {
1144
+ const entry = state.leases.get(key.logical);
1145
+ if (entry === undefined || entry.owner !== owner) continue;
1146
+ for (const id of entry.holders) {
1147
+ const sibling = state.holders.get(id);
1148
+ if (sibling !== undefined) sibling.holder.lastSeenAt = stamp;
1149
+ }
1150
+ }
1151
+ return { ok: true, leased: fresh.map((key) => key.display), reentrant, unkeyed };
1152
+ }
1153
+ };
1154
+
1155
+ const checkRead = (readerInput: LeaseActor, path: string): ReadCheck => {
1156
+ const reader = bindActor(readerInput);
1157
+ if (typeof reader === "string") return { ok: false, reason: "invalid-holder", message: reader };
1158
+ touch(reader.holderID);
1159
+ const conflict = readConflict(reader, path, reader.tree, seams);
1160
+ return conflict === undefined
1161
+ ? { ok: true }
1162
+ : { ok: false, reason: "underEdit", holders: conflict.holders, path: conflict.path };
1163
+ };
1164
+
1165
+ const checkRun = (runnerInput: LeaseActor, tree: string): RunCheck => {
1166
+ const runner = bindActor(runnerInput);
1167
+ if (typeof runner === "string") return { ok: false, reason: "invalid-holder", message: runner };
1168
+ touch(runner.holderID);
1169
+ const key = keyOfIn(tree, runner.tree, seams, platform, true);
1170
+ const unkeyed = "unkeyable" in key;
1171
+ // A run directory no key exists for may be any directory: a root run is only annotated, a child run fails closed.
1172
+ if (unkeyed && !runner.isChild) return { ok: true };
1173
+ const now = seams.now();
1174
+ const holders = new Map<string, Holder>();
1175
+ const stale = new Set<string>();
1176
+ let fileCount = 0;
1177
+ // Candidates come from the indexes (the run tree, the directories under the run directory), not from every lease.
1178
+ const candidates = new Set<string>();
1179
+ if (unkeyed) {
1180
+ for (const logical of state.leases.keys()) candidates.add(logical);
1181
+ } else {
1182
+ for (const logical of key.tree === null ? [] : state.byTree.get(key.tree) ?? []) candidates.add(logical);
1183
+ const dir = key.physical;
1184
+ const variants = dir.endsWith("/") ? [dir, dir.slice(0, -1)] : [dir, `${dir}/`];
1185
+ for (const variant of variants) {
1186
+ for (const logical of state.byDir.get(variant) ?? []) candidates.add(logical);
1187
+ }
1188
+ }
1189
+ for (const logical of candidates) {
1190
+ const entry = state.leases.get(logical);
1191
+ if (entry === undefined || entry.owner === runner.owner || entry.holders.has(runner.holderID)) continue;
1192
+ if (!unkeyed) {
1193
+ let hit = false;
1194
+ for (const pair of entry.pairs.values()) {
1195
+ if ((key.tree !== null && pair.tree === key.tree) || isUnder(pair.physical, key.physical)) {
1196
+ hit = true;
1197
+ break;
1198
+ }
1199
+ }
1200
+ if (!hit) continue;
1201
+ }
1202
+ let first: HolderRecord | undefined;
1203
+ for (const id of entry.holders) {
1204
+ const record = state.holders.get(id);
1205
+ if (record === undefined) continue;
1206
+ if (isStale(record, now)) stale.add(id);
1207
+ else if (first === undefined) first = record;
1208
+ }
1209
+ if (first === undefined) continue;
1210
+ fileCount++;
1211
+ if (!holders.has(first.holder.holderID)) holders.set(first.holder.holderID, copyHolder(first.holder));
1212
+ }
1213
+ for (const id of stale) dropHolder(state, id);
1214
+ if (holders.size === 0) return { ok: true };
1215
+ if (!runner.isChild || runMode === "annotate") return { ok: true, contaminatedBy: [...holders.values()], fileCount };
1216
+ return { ok: false, reason: "run-refused", holders: [...holders.values()], fileCount };
1217
+ };
1218
+
1219
+ const filterSearchResults = (readerInput: LeaseActor, tree: string, paths: readonly string[]): FilterResult => {
1220
+ const list: readonly string[] = Array.isArray(paths) ? paths : [];
1221
+ const reader = bindActor(readerInput);
1222
+ if (typeof reader === "string") return { kept: [], omitted: list.length, holders: [], invalid: reader };
1223
+ touch(reader.holderID);
1224
+ const foreign = state.holders.size > (state.owners.get(reader.owner) ?? 0);
1225
+ if (!reader.isChild || !foreign) return { kept: [...list], omitted: 0, holders: [] };
1226
+ // Relative entries are the reader's: against the search tree, or against the reader's own tree when there is none.
1227
+ const base = typeof tree === "string" && (platform === "win32" ? win32 : posix).isAbsolute(tree) ? tree : reader.tree;
1228
+ const sm = memoize(seams);
1229
+ const kept: string[] = [];
1230
+ const holders = new Map<string, Holder>();
1231
+ let omitted = 0;
1232
+ for (const entry of list) {
1233
+ const conflict = readConflict(reader, entry, base, sm);
1234
+ if (conflict === undefined) {
1235
+ kept.push(entry);
1236
+ continue;
1237
+ }
1238
+ omitted++;
1239
+ for (const holder of conflict.holders) {
1240
+ if (!holders.has(holder.holderID)) holders.set(holder.holderID, holder);
1241
+ }
1242
+ }
1243
+ return { kept, omitted, holders: [...holders.values()] };
1244
+ };
1245
+
1246
+ const planHolderOf = (tree: string, path: string): Holder | null => {
1247
+ const key = keyOfIn(path, tree, seams, platform, false);
1248
+ if ("unkeyable" in key) return null;
1249
+ const found = integratedLease(key, null, false);
1250
+ return found === undefined ? null : copyHolder(found.record.holder);
1251
+ };
1252
+
1253
+ const release = (holderID: string): ReleaseResult => {
1254
+ const record = state.holders.get(holderID);
1255
+ if (record === undefined) return { released: 0, retained: 0 };
1256
+ if (record.holder.scope === "until-integrated") return { released: 0, retained: record.keys.size };
1257
+ return { released: dropHolder(state, holderID), retained: 0 };
1258
+ };
1259
+
1260
+ const releaseTask = (taskRef: string): HoldersReleased => {
1261
+ const ids = [...(state.tasks.get(taskRef) ?? [])];
1262
+ let released = 0;
1263
+ for (const id of ids) released += dropHolder(state, id);
1264
+ return { released, holders: ids };
1265
+ };
1266
+
1267
+ const snapshot = (): LeaseSnapshot => {
1268
+ const leases: SnapshotLease[] = [];
1269
+ for (const [logical, entry] of state.leases) {
1270
+ for (const holderID of entry.holders) {
1271
+ for (const pair of entry.pairs.values()) {
1272
+ const line: SnapshotLease = { logical, physical: pair.physical, tree: pair.tree, holderID, display: entry.display };
1273
+ if (entry.shared !== null && entry.shared !== entry.repo) line.shared = entry.shared;
1274
+ leases.push(line);
1275
+ }
1276
+ }
1277
+ }
1278
+ return {
1279
+ version: 1,
1280
+ takenAt: seams.now(),
1281
+ holders: [...state.holders.values()].map((record) => copyHolder(record.holder)),
1282
+ leases,
1283
+ };
1284
+ };
1285
+
1286
+ const restore = (input: unknown, restoreOpts?: RestoreOptions): RestoreResult => {
1287
+ const bad = (message: string): RestoreResult => ({ ok: false, reason: "invalid-snapshot", message });
1288
+ if (!isRecord(input)) return bad("snapshot must be an object");
1289
+ if (input.version !== 1) return bad("unsupported snapshot version");
1290
+ if (typeof input.takenAt !== "number" || !Number.isFinite(input.takenAt)) return bad("takenAt must be a finite number");
1291
+ const { holders, leases } = input;
1292
+ if (!Array.isArray(holders) || !Array.isArray(leases)) return bad("holders and leases must be arrays");
1293
+ const dropComplete = restoreOpts?.dropCompleteHolders === true;
1294
+ const api = platform === "win32" ? win32 : posix;
1295
+ const now = seams.now();
1296
+ const next = emptyState();
1297
+ const sm = memoize(seams);
1298
+ /** The seam's current answer for a tree (folded) when it names a `shared` repository, else undefined. */
1299
+ const currentIdOf = (dir: string): { repo: string; tree: string; shared: string } | undefined => {
1300
+ try {
1301
+ const answer: unknown = sm.repoKeyOf(dir);
1302
+ if (!isRecord(answer) || typeof answer.repo !== "string" || typeof answer.tree !== "string") return undefined;
1303
+ if (typeof answer.shared !== "string" || answer.shared === "") return undefined;
1304
+ const fold = (text: string): string => foldKeyPath(text, platform);
1305
+ return { repo: fold(answer.repo), tree: fold(answer.tree), shared: fold(answer.shared) };
1306
+ } catch {
1307
+ return undefined;
1308
+ }
1309
+ };
1310
+ /** Every holder of the snapshot, and whether it is kept. */
1311
+ const listed = new Map<string, boolean>();
1312
+ /** holderID → owner, for every holder of the snapshot. */
1313
+ const owners = new Map<string, string>();
1314
+ /** logical key → the owner its lines name; the holders of one lease share an owner. */
1315
+ const leaseOwners = new Map<string, string>();
1316
+ const lines = new Set<string>();
1317
+ /** QA-PDF13-8: the keys a re-keyed line was given; a clash on them is merged or skipped, never fatal. */
1318
+ const rekeyedKeys = new Set<string>();
1319
+ /** QA-PDF13-8: the lines left out of a clash on a re-keyed key (reported in the result). */
1320
+ const skipped: string[] = [];
1321
+ for (const value of holders) {
1322
+ const parsed = parseHolderInput(value, platform);
1323
+ if (typeof parsed === "string") return bad(`invalid holder: ${parsed}`);
1324
+ if (!parsed.isChild) return bad(`holder ${parsed.holderID} is not a child session`);
1325
+ const stamps: Record<string, unknown> = isRecord(value) ? value : {};
1326
+ const acquiredAt = stamps.acquiredAt;
1327
+ if (typeof acquiredAt !== "number" || !Number.isFinite(acquiredAt)) {
1328
+ return bad(`holder ${parsed.holderID} has no valid acquiredAt`);
1329
+ }
1330
+ const seen = stamps.lastSeenAt === undefined ? acquiredAt : stamps.lastSeenAt;
1331
+ if (typeof seen !== "number" || !Number.isFinite(seen)) return bad(`holder ${parsed.holderID} has an invalid lastSeenAt`);
1332
+ if (listed.has(parsed.holderID)) return bad(`duplicate holder ${parsed.holderID}`);
1333
+ const keep = !(dropComplete && parsed.scope === "until-complete");
1334
+ listed.set(parsed.holderID, keep);
1335
+ owners.set(parsed.holderID, ownerOf(parsed.holderID, parsed.taskRef));
1336
+ if (keep) {
1337
+ recordHolder(next, { ...parsed, acquiredAt: Math.min(acquiredAt, now), lastSeenAt: Math.min(seen, now) });
1338
+ }
1339
+ }
1340
+ for (const value of leases) {
1341
+ if (!isRecord(value)) return bad("a lease must be an object");
1342
+ const { logical, physical, tree, holderID, display } = value;
1343
+ if (typeof logical !== "string" || logical === "") return bad("a lease has no logical key");
1344
+ if (typeof physical !== "string" || typeof display !== "string") return bad(`lease ${logical} has no physical or display path`);
1345
+ if (tree !== null && typeof tree !== "string") return bad(`lease ${logical} has an invalid tree`);
1346
+ if (typeof holderID !== "string") return bad(`lease ${logical} has no holderID`);
1347
+ const keep = listed.get(holderID);
1348
+ if (keep === undefined) return bad(`lease ${logical} names an unknown holder ${holderID}`);
1349
+ if (physical !== foldKeyPath(physical, platform)) return bad(`lease ${logical} has a physical path that is not normalised`);
1350
+ let repo: string | null = null;
1351
+ if (logical.startsWith("x:")) {
1352
+ if (tree !== null) return bad(`lease ${logical} is outside any repository but has a tree`);
1353
+ if (logical !== `x:${physical}`) return bad(`lease ${logical} does not match its physical path`);
1354
+ if (!api.isAbsolute(physical)) return bad(`lease ${logical} has a physical path that is not absolute`);
1355
+ } else if (logical.startsWith("r:")) {
1356
+ if (typeof tree !== "string") return bad(`lease ${logical} is in a repository but has no tree`);
1357
+ if (tree !== foldKeyPath(tree, platform) || !api.isAbsolute(tree)) return bad(`lease ${logical} has a tree that is not normalised`);
1358
+ const prefix = tree.endsWith("/") ? tree : `${tree}/`;
1359
+ const rel = physical === tree ? "" : physical.startsWith(prefix) ? physical.slice(prefix.length) : undefined;
1360
+ if (rel === undefined) return bad(`lease ${logical} lies outside its tree`);
1361
+ const sep = logical.indexOf("\0");
1362
+ if (sep < 0 || logical.slice(sep + 1) !== rel) return bad(`lease ${logical} does not match its physical path`);
1363
+ repo = logical.slice(2, sep);
1364
+ if (repo !== foldKeyPath(repo, platform)) return bad(`lease ${logical} has a repository that is not normalised`);
1365
+ } else {
1366
+ return bad(`lease ${logical} has an unknown key space`);
1367
+ }
1368
+ let shared = repo;
1369
+ if (value.shared !== undefined) {
1370
+ const named = value.shared;
1371
+ if (repo === null || typeof named !== "string" || named === "" || named !== foldKeyPath(named, platform)) {
1372
+ return bad(`lease ${logical} has an invalid shared repository`);
1373
+ }
1374
+ shared = named;
1375
+ }
1376
+ // QA-PDF13-2: a line written before DF-1.1-4 carries no `shared` and its key names the repository every checkout
1377
+ // shares. When the seam now keys its tree per checkout and names that repository as `shared`, the line is re-keyed
1378
+ // (`r:<checkout>\0<rel>`), so the writers and readers of that checkout meet it again.
1379
+ let key = logical;
1380
+ let lineDisplay = display;
1381
+ let rekeyed = false;
1382
+ if (value.shared === undefined && repo !== null && typeof tree === "string") {
1383
+ const current = currentIdOf(tree);
1384
+ if (current !== undefined && current.tree === tree && current.shared === repo && current.repo !== repo) {
1385
+ key = `r:${current.repo}${logical.slice(logical.indexOf("\0"))}`;
1386
+ shared = repo;
1387
+ repo = current.repo;
1388
+ rekeyed = true;
1389
+ rekeyedKeys.add(key);
1390
+ // QA-PDF13-8: an old entry with pairs in several checkouts splits into one key per checkout, and its one
1391
+ // display names a file of the first; a part whose pair is not that file names its own (folded) path.
1392
+ if (foldKeyPath(display, platform) !== physical) lineDisplay = physical;
1393
+ }
1394
+ }
1395
+ // QA-PDF13-8: a key a re-keyed line was given may also be written under its new spelling (a line whose re-key
1396
+ // failed once was written back unchanged while a writer took the new key): a clash there is merged or skipped.
1397
+ const clash = rekeyed || rekeyedKeys.has(key);
1398
+ const pair: Pair = { physical, tree };
1399
+ // Duplicates are found in any order of the lines and whether or not the holder is kept.
1400
+ const line = JSON.stringify([key, holderID, tree, physical]);
1401
+ if (lines.has(line)) {
1402
+ if (clash) continue; // the same lease under its old and its new key: merged
1403
+ return bad(`duplicate lease ${key}`);
1404
+ }
1405
+ lines.add(line);
1406
+ const owner = owners.get(holderID) ?? "";
1407
+ const seenOwner = leaseOwners.get(key);
1408
+ if (seenOwner !== undefined && seenOwner !== owner) {
1409
+ if (!clash) return bad(`duplicate lease ${key}: held by holders of different owners`);
1410
+ // Fatal only between two kept holders; a holder that is dropped anyway gives the key up.
1411
+ if (!keep) {
1412
+ skipped.push(`lease ${key} of ${holderID}: another owner holds the key and this holder is dropped`);
1413
+ continue;
1414
+ }
1415
+ if (next.leases.has(key)) return bad(`duplicate lease ${key}: held by holders of different owners`);
1416
+ skipped.push(`lease ${key}: the lines of a dropped holder of another owner give the key up to ${holderID}`);
1417
+ }
1418
+ leaseOwners.set(key, owner);
1419
+ if (!keep) continue;
1420
+ const record = next.holders.get(holderID);
1421
+ if (record === undefined) return bad(`lease ${key} names an unknown holder ${holderID}`);
1422
+ const existing = next.leases.get(key);
1423
+ if (existing === undefined) {
1424
+ const entry: LeaseEntry = { holders: new Set(), owner, display: lineDisplay, repo, shared, pairs: new Map([[pairKey(pair), pair]]) };
1425
+ link(next, record, key, entry);
1426
+ continue;
1427
+ }
1428
+ if (existing.shared !== shared) return bad(`lease ${key} names two shared repositories`);
1429
+ join(next, record, key, existing);
1430
+ if (!existing.pairs.has(pairKey(pair))) {
1431
+ existing.pairs.set(pairKey(pair), pair);
1432
+ indexPair(next, key, pair);
1433
+ }
1434
+ }
1435
+ if (next.leases.size > cap) return bad(`${next.leases.size} leases exceed the cap of ${cap}`);
1436
+ state = next;
1437
+ return skipped.length === 0 ? { ok: true, leases: next.leases.size } : { ok: true, leases: next.leases.size, skipped };
1438
+ };
1439
+
1440
+ /** Never lets a throwing getter or revoked Proxy in the caller's input escape: `fallback` answers instead. */
1441
+ const safe = <Args extends unknown[], Result>(
1442
+ fn: (...args: Args) => Result,
1443
+ fallback: (message: string) => Result,
1444
+ ): ((...args: Args) => Result) => {
1445
+ return (...args: Args): Result => {
1446
+ try {
1447
+ return fn(...args);
1448
+ } catch (error) {
1449
+ return fallback(`the input could not be read: ${describeValue(error)}`);
1450
+ }
1451
+ };
1452
+ };
1453
+
1454
+ return {
1455
+ acquireWrite: safe(acquireWrite, (message): AcquireResult => ({ ok: false, reason: "invalid-holder", message })),
1456
+ checkRead: safe(checkRead, (message): ReadCheck => ({ ok: false, reason: "invalid-holder", message })),
1457
+ checkRun: safe(checkRun, (message): RunCheck => ({ ok: false, reason: "invalid-holder", message })),
1458
+ filterSearchResults: safe(
1459
+ filterSearchResults,
1460
+ (message): FilterResult => ({ kept: [], omitted: 0, holders: [], invalid: message }),
1461
+ ),
1462
+ planHolderOf: safe(planHolderOf, (): Holder | null => null),
1463
+ release: safe(release, (): ReleaseResult => ({ released: 0, retained: 0 })),
1464
+ releaseTask: safe(releaseTask, (): HoldersReleased => ({ released: 0, holders: [] })),
1465
+ sweep,
1466
+ snapshot,
1467
+ restore: safe(restore, (message): RestoreResult => ({ ok: false, reason: "invalid-snapshot", message })),
1468
+ };
1469
+ }