@srobroek/pi-delivery 0.0.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3379 @@
1
+ // @bun
2
+ // Generated by scripts/build.ts. Do not edit.
3
+ // lib/src/worktree-claims.ts
4
+ import { createHash } from "crypto";
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "fs";
6
+ import { join, resolve } from "path";
7
+ var MAX_FILE_BYTES = 64 * 1024;
8
+ var text = (value) => typeof value === "string" && value !== "" ? value : undefined;
9
+ var finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
10
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11
+ function parseClaim(value) {
12
+ if (!isObject(value))
13
+ return;
14
+ const directory = text(value.directory);
15
+ const branch = text(value.branch);
16
+ const sessionID = text(value.sessionID);
17
+ const parentID = text(value.parentID);
18
+ const createdAt = finite(value.createdAt);
19
+ if (!directory || !branch || !sessionID || !parentID || createdAt === undefined)
20
+ return;
21
+ const resumedAt = finite(value.resumedAt);
22
+ return { directory, branch, sessionID, parentID, createdAt, generation: finite(value.generation) ?? 0, ...resumedAt === undefined ? {} : { resumedAt } };
23
+ }
24
+ function canonicalDirectory(path) {
25
+ try {
26
+ return realpathSync(path);
27
+ } catch {
28
+ return resolve(path);
29
+ }
30
+ }
31
+ function claimKey(directory) {
32
+ return createHash("sha1").update(canonicalDirectory(directory)).digest("hex");
33
+ }
34
+ var claimFile = (commonDir, directory) => join(commonDir, "opencode", "lane-claims", `${claimKey(directory)}.json`);
35
+ function readJson(path, parse) {
36
+ let raw;
37
+ try {
38
+ raw = readFileSync(path, "utf8");
39
+ } catch (error) {
40
+ return error.code === "ENOENT" ? { kind: "missing" } : { kind: "unreadable", reason: error.message };
41
+ }
42
+ if (raw.length > MAX_FILE_BYTES)
43
+ return { kind: "unreadable", reason: "file too large" };
44
+ try {
45
+ const value = parse(JSON.parse(raw));
46
+ return value === undefined ? { kind: "unreadable", reason: "unrecognised content" } : { kind: "present", value };
47
+ } catch (error) {
48
+ return { kind: "unreadable", reason: error.message };
49
+ }
50
+ }
51
+ var readClaim = (commonDir, directory) => readJson(claimFile(commonDir, directory), parseClaim);
52
+ function ownershipOf(read) {
53
+ if (read.kind === "present")
54
+ return { owner: "lane", claim: read.value };
55
+ if (read.kind === "unreadable")
56
+ return { owner: "unknown", reason: read.reason };
57
+ return { owner: "none" };
58
+ }
59
+
60
+ // lib/src/worktree-locks.ts
61
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
62
+ import { mkdirSync as mkdirSync2, readdirSync as readdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
63
+ import { join as join2 } from "path";
64
+
65
+ // lib/src/lease-lock.ts
66
+ import { AsyncLocalStorage } from "async_hooks";
67
+ import { randomUUID } from "crypto";
68
+ import { closeSync as closeSync2, openSync as openSync2, statSync, unlinkSync, writeSync } from "fs";
69
+ import { hostname } from "os";
70
+
71
+ // lib/src/bounded-read.ts
72
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "fs";
73
+ var MAX_LEDGER_FILE_BYTES = 64 * 1024;
74
+ function readBoundedBytes(path, maxBytes) {
75
+ let fd;
76
+ try {
77
+ if (!lstatSync(path).isFile())
78
+ return { kind: "unreadable", reason: "not-regular" };
79
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
80
+ const info = fstatSync(fd);
81
+ if (!info.isFile())
82
+ return { kind: "unreadable", reason: "not-regular" };
83
+ if (info.size > maxBytes)
84
+ return { kind: "unreadable", reason: "too-large" };
85
+ const buffer = Buffer.alloc(info.size);
86
+ let offset = 0;
87
+ while (offset < buffer.length) {
88
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
89
+ if (read === 0)
90
+ break;
91
+ offset += read;
92
+ }
93
+ return { kind: "bytes", bytes: offset === buffer.length ? buffer : buffer.subarray(0, offset) };
94
+ } catch (error) {
95
+ const code = error.code;
96
+ if (code === "ENOENT")
97
+ return { kind: "absent" };
98
+ return code === "ELOOP" ? { kind: "unreadable", reason: "not-regular" } : { kind: "unreadable", reason: "io", code };
99
+ } finally {
100
+ if (fd !== undefined)
101
+ closeSync(fd);
102
+ }
103
+ }
104
+ function readBounded(path, maxBytes = MAX_LEDGER_FILE_BYTES) {
105
+ const read = readBoundedBytes(path, maxBytes);
106
+ if (read.kind === "absent")
107
+ return { kind: "absent" };
108
+ return read.kind === "bytes" ? { kind: "text", text: read.bytes.toString("utf8") } : { kind: "unreadable" };
109
+ }
110
+
111
+ // lib/src/subprocess.ts
112
+ import { constants as constants2 } from "os";
113
+ var EXIT_GRACE_MS = 2000;
114
+ var EXIT_POLL_MS = 100;
115
+ function goneWatch(graceMs, pollMs) {
116
+ const polls = Math.max(1, Math.ceil(graceMs / Math.max(1, pollMs)));
117
+ let since = null;
118
+ let seen = 0;
119
+ return (alive) => {
120
+ if (alive) {
121
+ since = null;
122
+ seen = 0;
123
+ return false;
124
+ }
125
+ since ??= Date.now();
126
+ seen++;
127
+ return seen > polls && Date.now() - since >= graceMs;
128
+ };
129
+ }
130
+ function processAlive(pid) {
131
+ try {
132
+ process.kill(pid, 0);
133
+ return true;
134
+ } catch (error) {
135
+ return error.code === "EPERM";
136
+ }
137
+ }
138
+ function killChild(child, group) {
139
+ if (group) {
140
+ try {
141
+ process.kill(-child.pid, "SIGKILL");
142
+ return;
143
+ } catch {}
144
+ }
145
+ try {
146
+ child.kill("SIGKILL");
147
+ } catch {}
148
+ }
149
+ function unref(timer) {
150
+ timer.unref?.();
151
+ }
152
+ function capture(stream) {
153
+ if (!(stream instanceof ReadableStream))
154
+ return { text: Promise.resolve(""), snapshot: () => "", cancel: () => {} };
155
+ const reader = stream.getReader();
156
+ const decoder = new TextDecoder;
157
+ let collected = "";
158
+ const text = (async () => {
159
+ try {
160
+ for (;; ) {
161
+ const chunk = await reader.read();
162
+ if (chunk.done)
163
+ break;
164
+ collected += decoder.decode(chunk.value, { stream: true });
165
+ }
166
+ } catch {}
167
+ collected += decoder.decode();
168
+ return collected;
169
+ })();
170
+ const cancel = () => {
171
+ try {
172
+ reader.cancel().catch(() => {
173
+ return;
174
+ });
175
+ } catch {}
176
+ };
177
+ return { text, snapshot: () => collected, cancel };
178
+ }
179
+ function supervise(child, options = {}) {
180
+ const grace = Math.max(0, options.graceMs ?? EXIT_GRACE_MS);
181
+ const pollMs = Math.max(1, options.pollMs ?? EXIT_POLL_MS);
182
+ const alive = options.alive ?? processAlive;
183
+ const group = options.group ?? false;
184
+ const { signal, timeoutMs } = options;
185
+ const out = capture(child.stdout);
186
+ const err = capture(child.stderr);
187
+ return new Promise((resolve) => {
188
+ let ended = null;
189
+ let exitSeen = false;
190
+ let settled = false;
191
+ const gone = goneWatch(grace, pollMs);
192
+ let deadline;
193
+ let graceTimer;
194
+ const settle = (run) => {
195
+ if (settled)
196
+ return;
197
+ settled = true;
198
+ clearTimeout(deadline);
199
+ clearTimeout(graceTimer);
200
+ clearInterval(poller);
201
+ signal?.removeEventListener("abort", onAbort);
202
+ resolve(run);
203
+ };
204
+ const end = (cause) => {
205
+ if (ended !== null || settled)
206
+ return;
207
+ ended = cause;
208
+ if (cause !== "lost" || group)
209
+ killChild(child, group);
210
+ out.cancel();
211
+ err.cancel();
212
+ graceTimer = setTimeout(() => settle({ kind: cause, stdout: out.snapshot(), stderr: err.snapshot() }), grace);
213
+ if (options.unref)
214
+ unref(graceTimer);
215
+ };
216
+ const onAbort = () => end("aborted");
217
+ const poller = setInterval(() => {
218
+ if (exitSeen || ended !== null || settled)
219
+ return;
220
+ if (gone(alive(child.pid)))
221
+ end("lost");
222
+ }, pollMs);
223
+ unref(poller);
224
+ if (timeoutMs !== undefined && timeoutMs > 0 && Number.isFinite(timeoutMs)) {
225
+ deadline = setTimeout(() => end("timeout"), timeoutMs);
226
+ if (options.unref)
227
+ unref(deadline);
228
+ }
229
+ signal?.addEventListener("abort", onAbort, { once: true });
230
+ if (signal?.aborted)
231
+ onAbort();
232
+ child.exited.then(() => {
233
+ exitSeen = true;
234
+ }, () => {
235
+ return;
236
+ });
237
+ Promise.all([child.exited, out.text, err.text]).then(([exitCode, stdout, stderr]) => {
238
+ if (ended !== null)
239
+ settle({ kind: ended, stdout, stderr });
240
+ else
241
+ settle({ kind: "exited", exitCode, signalCode: signalName(child.signalCode), stdout, stderr });
242
+ }, () => end("lost"));
243
+ });
244
+ }
245
+ function signalName(code) {
246
+ if (code === null || code === undefined)
247
+ return null;
248
+ if (typeof code === "string")
249
+ return code;
250
+ return Object.entries(constants2.signals).find(([, n]) => n === code)?.[0] ?? String(code);
251
+ }
252
+
253
+ // lib/src/lease-lock.ts
254
+ var LEASE_MS = 120000;
255
+ var RENEW_MS = 20000;
256
+ var WAIT_MS = 120000;
257
+ var POLL_MS = 20;
258
+ var POLL_MAX_MS = 400;
259
+ function parseLeaseRecord(value) {
260
+ if (value === null || typeof value !== "object" || Array.isArray(value))
261
+ return;
262
+ const { host, pid, owner, token, taken, expires } = value;
263
+ if (typeof host !== "string" || typeof owner !== "string" || typeof token !== "string")
264
+ return;
265
+ if (typeof pid !== "number" || !Number.isInteger(pid) || typeof taken !== "number" || typeof expires !== "number")
266
+ return;
267
+ return { host, pid, owner, token, taken, expires };
268
+ }
269
+ function leaseAbandoned(record, facts) {
270
+ if (record === undefined)
271
+ return facts.ageMs > facts.leaseMs;
272
+ if (record.host === facts.host && !facts.alive(record.pid))
273
+ return true;
274
+ return facts.now > record.expires;
275
+ }
276
+ var insideLock = new AsyncLocalStorage;
277
+ var stealPathFor = (lock) => `${lock}.steal`;
278
+ function backoffDelayMs(attempt, random = Math.random) {
279
+ const ceiling = Math.min(POLL_MAX_MS, POLL_MS * 2 ** Math.min(attempt, 16));
280
+ return Math.max(1, Math.round(ceiling / 2 + ceiling / 2 * random()));
281
+ }
282
+ var ageOf = (path, now) => {
283
+ try {
284
+ return now - statSync(path).mtimeMs;
285
+ } catch {
286
+ return 0;
287
+ }
288
+ };
289
+ function abandoned(path, c) {
290
+ const record = readBounded(path);
291
+ if (record.kind !== "text")
292
+ return false;
293
+ let parsed;
294
+ try {
295
+ parsed = parseLeaseRecord(JSON.parse(record.text));
296
+ } catch {
297
+ parsed = undefined;
298
+ }
299
+ return leaseAbandoned(parsed, { now: c.now(), host: c.host, alive: c.alive, leaseMs: c.leaseMs, ageMs: ageOf(path, c.now()) });
300
+ }
301
+ var recordFor = (c, token) => {
302
+ const taken = c.now();
303
+ return { host: c.host, pid: process.pid, owner: c.owner.slice(0, 256), token, taken, expires: taken + c.leaseMs };
304
+ };
305
+ function stillOurs(lock, token, host) {
306
+ try {
307
+ const record = readBounded(lock);
308
+ if (record.kind !== "text")
309
+ return false;
310
+ const parsed = parseLeaseRecord(JSON.parse(record.text));
311
+ return parsed?.token === token && parsed.pid === process.pid && parsed.host === host;
312
+ } catch {
313
+ return false;
314
+ }
315
+ }
316
+ function takeOverIfAbandoned(c) {
317
+ if (!abandoned(c.lock, c))
318
+ return;
319
+ c.afterJudged?.();
320
+ let fd;
321
+ try {
322
+ fd = openSync2(c.steal, "wx");
323
+ } catch (error) {
324
+ if (error.code !== "EEXIST")
325
+ return;
326
+ if (abandoned(c.steal, c)) {
327
+ try {
328
+ unlinkSync(c.steal);
329
+ } catch {}
330
+ }
331
+ return;
332
+ }
333
+ try {
334
+ writeSync(fd, JSON.stringify(recordFor(c, `steal-${randomUUID()}`)));
335
+ if (abandoned(c.lock, c))
336
+ unlinkSync(c.lock);
337
+ } catch {} finally {
338
+ closeSync2(fd);
339
+ try {
340
+ unlinkSync(c.steal);
341
+ } catch {}
342
+ }
343
+ }
344
+ function withOwnership(c, token, change) {
345
+ let fd;
346
+ try {
347
+ fd = openSync2(c.steal, "wx");
348
+ } catch (error) {
349
+ if (error.code === "EEXIST")
350
+ return "busy";
351
+ throw error;
352
+ }
353
+ try {
354
+ if (!stillOurs(c.lock, token, c.host))
355
+ return "lost";
356
+ change();
357
+ return "done";
358
+ } finally {
359
+ closeSync2(fd);
360
+ try {
361
+ unlinkSync(c.steal);
362
+ } catch {}
363
+ }
364
+ }
365
+ function rewrite(c, token) {
366
+ return withOwnership(c, token, () => {
367
+ const fd = openSync2(c.lock, "w");
368
+ try {
369
+ writeSync(fd, JSON.stringify(recordFor(c, token)));
370
+ } finally {
371
+ closeSync2(fd);
372
+ }
373
+ });
374
+ }
375
+ async function withLease(lockPath, options, work) {
376
+ const held = insideLock.getStore();
377
+ if (held?.has(lockPath))
378
+ return { kind: "done", value: await work() };
379
+ const c = {
380
+ lock: lockPath,
381
+ steal: stealPathFor(lockPath),
382
+ now: options.now ?? Date.now,
383
+ host: options.host ?? hostname().split(".")[0] ?? "localhost",
384
+ alive: options.alive ?? processAlive,
385
+ leaseMs: options.leaseMs ?? LEASE_MS,
386
+ owner: options.owner,
387
+ afterJudged: options.seams?.afterJudged
388
+ };
389
+ const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
390
+ const random = options.random ?? Math.random;
391
+ const deadline = Date.now() + (options.waitMs ?? WAIT_MS);
392
+ const token = `${process.pid}-${Date.now()}-${randomUUID()}`;
393
+ let attempt = 0;
394
+ let fd;
395
+ while (fd === undefined) {
396
+ try {
397
+ fd = openSync2(lockPath, "wx");
398
+ writeSync(fd, JSON.stringify(recordFor(c, token)));
399
+ } catch (error) {
400
+ if (fd !== undefined) {
401
+ closeSync2(fd);
402
+ fd = undefined;
403
+ }
404
+ const code = error.code;
405
+ if (code !== "EEXIST")
406
+ return { kind: "failed", reason: `the lock at ${lockPath} could not be taken (${code ?? "unknown error"})` };
407
+ if (readBounded(lockPath).kind === "unreadable" || readBounded(c.steal).kind === "unreadable") {
408
+ return { kind: "failed", reason: `the lock path ${lockPath} (or its steal lock) is not a small regular file, so its holder cannot be read safely` };
409
+ }
410
+ takeOverIfAbandoned(c);
411
+ if (Date.now() >= deadline) {
412
+ return { kind: "failed", busy: true, reason: `the lock at ${lockPath} stayed held for ${Math.round((options.waitMs ?? WAIT_MS) / 1000 * 10) / 10}s` };
413
+ }
414
+ await sleep(Math.min(backoffDelayMs(attempt++, random), Math.max(1, deadline - Date.now())));
415
+ }
416
+ }
417
+ const owned = fd;
418
+ const heartbeat = setInterval(() => {
419
+ try {
420
+ if (rewrite(c, token) === "lost")
421
+ clearInterval(heartbeat);
422
+ } catch {}
423
+ }, options.renewMs ?? RENEW_MS);
424
+ heartbeat.unref?.();
425
+ try {
426
+ const value = await insideLock.run(new Set([...held ?? [], lockPath]), async () => work());
427
+ return { kind: "done", value };
428
+ } finally {
429
+ clearInterval(heartbeat);
430
+ try {
431
+ closeSync2(owned);
432
+ } catch {}
433
+ const releaseBy = Date.now() + 2000;
434
+ for (;; ) {
435
+ try {
436
+ if (withOwnership(c, token, () => unlinkSync(lockPath)) !== "busy")
437
+ break;
438
+ } catch {
439
+ break;
440
+ }
441
+ if (Date.now() >= releaseBy)
442
+ break;
443
+ await sleep(POLL_MS);
444
+ }
445
+ }
446
+ }
447
+
448
+ // lib/src/worktree-locks.ts
449
+ var HOLD_EXPIRY_MS = 24 * 3600000;
450
+ var sha1 = (text) => createHash2("sha1").update(text).digest("hex");
451
+ var isObject2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
452
+ var LOCK_TTL_MS = 120000;
453
+ var lockFile = (commonDir, directory) => join2(commonDir, "opencode", "locks", `${sha1(canonicalDirectory(directory))}.lock`);
454
+
455
+ class LockTimeout extends Error {
456
+ directory;
457
+ constructor(directory, detail = "") {
458
+ super(`could not lock ${directory}${detail === "" ? "" : ` (${detail})`}`);
459
+ this.directory = directory;
460
+ this.name = "LockTimeout";
461
+ }
462
+ }
463
+ async function withDiskLock(commonDir, directory, options, work) {
464
+ const path = lockFile(commonDir, directory);
465
+ mkdirSync2(join2(path, ".."), { recursive: true });
466
+ const result = await withLease(path, {
467
+ owner: options.sessionID,
468
+ leaseMs: options.ttlMs ?? LOCK_TTL_MS,
469
+ waitMs: options.waitMs ?? 30000,
470
+ ...options.renewMs === undefined ? {} : { renewMs: options.renewMs },
471
+ ...options.now === undefined ? {} : { now: options.now },
472
+ ...options.host === undefined ? {} : { host: options.host },
473
+ ...options.alive === undefined ? {} : { alive: options.alive },
474
+ ...options.sleep === undefined ? {} : { sleep: options.sleep },
475
+ ...options.seams === undefined ? {} : { seams: options.seams }
476
+ }, work);
477
+ if (result.kind === "done")
478
+ return result.value;
479
+ throw new LockTimeout(directory, result.reason);
480
+ }
481
+ function parseHold(value) {
482
+ if (!isObject2(value))
483
+ return;
484
+ const { sessionID, directory, jobs, updatedAt } = value;
485
+ if (typeof sessionID !== "string" || typeof directory !== "string" || typeof updatedAt !== "number" || !Array.isArray(jobs))
486
+ return;
487
+ const parsed = [];
488
+ for (const job of jobs) {
489
+ if (!isObject2(job) || typeof job.kind !== "string" || typeof job.id !== "string")
490
+ return;
491
+ parsed.push({ kind: job.kind, id: job.id });
492
+ }
493
+ return { sessionID, directory, jobs: parsed, updatedAt };
494
+ }
495
+ var holdsDir = (commonDir, directory) => join2(commonDir, "opencode", "holds", sha1(canonicalDirectory(directory)));
496
+ var PENDING_SUFFIX = ".pending.json";
497
+ function readHolds(commonDir, directory) {
498
+ const dir = holdsDir(commonDir, directory);
499
+ let names;
500
+ try {
501
+ names = readdirSync2(dir).filter((name) => name.endsWith(".json"));
502
+ } catch (error) {
503
+ const absent = error.code === "ENOENT";
504
+ return { holds: [], unreadable: !absent, ...absent ? { missing: true } : {} };
505
+ }
506
+ const holds = [];
507
+ let unreadable = false;
508
+ for (const name of names) {
509
+ try {
510
+ const hold = parseHold(JSON.parse(readFileSync2(join2(dir, name), "utf8")));
511
+ if (hold === undefined)
512
+ unreadable = true;
513
+ else
514
+ holds.push(name.endsWith(PENDING_SUFFIX) ? { ...hold, pendingFile: join2(dir, name) } : hold);
515
+ } catch {
516
+ unreadable = true;
517
+ }
518
+ }
519
+ return { holds, unreadable };
520
+ }
521
+ function elapsed(ms) {
522
+ const seconds = Math.max(0, Math.floor(ms / 1000));
523
+ if (seconds < 60)
524
+ return `${seconds} s`;
525
+ const minutes = Math.floor(seconds / 60);
526
+ return minutes < 60 ? `${minutes} min` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`;
527
+ }
528
+ function holdBlock(read, now, expiryMs = HOLD_EXPIRY_MS) {
529
+ if (read.unreadable)
530
+ return "the background-work records cannot be read";
531
+ const live = read.holds.find((hold) => hold.jobs.length > 0 && now - hold.updatedAt < expiryMs);
532
+ if (live === undefined)
533
+ return;
534
+ const first = live.jobs[0];
535
+ const running = `session ${live.sessionID} has ${live.jobs.length} background job(s) running (${first?.kind} ${first?.id})`;
536
+ if (live.pendingFile === undefined)
537
+ return running;
538
+ const ignoredAfter = new Date(live.updatedAt + expiryMs).toISOString();
539
+ const jobs = live.jobs.map((job) => `${job.kind} ${job.id}`).join(", ");
540
+ return `${running}; recorded before its lock was taken, ${elapsed(now - live.updatedAt)} ago; ignored after ${ignoredAfter}; ${live.pendingFile}; ` + `delete it only after session ${live.sessionID}'s ${live.jobs.length} job(s) (${jobs}) have finished and that session has ended`;
541
+ }
542
+ function holdsWritable(commonDir, directory) {
543
+ const dir = holdsDir(commonDir, directory);
544
+ try {
545
+ mkdirSync2(dir, { recursive: true });
546
+ const probe = join2(dir, `.probe.${randomUUID2()}`);
547
+ writeFileSync2(probe, "");
548
+ rmSync2(probe, { force: true });
549
+ return true;
550
+ } catch {
551
+ return false;
552
+ }
553
+ }
554
+ function holdsState(commonDir, directory, now, expiryMs = HOLD_EXPIRY_MS) {
555
+ const read = readHolds(commonDir, directory);
556
+ const blocked = holdBlock(read, now, expiryMs);
557
+ if (blocked !== undefined)
558
+ return blocked;
559
+ if (!holdsWritable(commonDir, directory))
560
+ return "the coordination store is not writable, so running work cannot be ruled out";
561
+ return;
562
+ }
563
+ async function lockedWorktreeRead(commonDir, directory, lock, read) {
564
+ let entered = false;
565
+ try {
566
+ return await withDiskLock(commonDir, directory, lock, async () => {
567
+ entered = true;
568
+ return { locked: true, value: await read() };
569
+ });
570
+ } catch (error) {
571
+ if (entered)
572
+ throw error;
573
+ const message = error instanceof LockTimeout ? `the worktree is locked by another remover (${error.message})` : `the lock could not be taken (${error instanceof Error ? error.message : String(error)})`;
574
+ return { locked: false, reason: message };
575
+ }
576
+ }
577
+ async function lockedWorktreeRemoval(commonDir, directory, lock, steps) {
578
+ const outcome = await lockedWorktreeRead(commonDir, directory, lock, async () => {
579
+ const reason = await steps.recheck();
580
+ if (reason !== undefined)
581
+ return { removed: false, reason };
582
+ return { removed: true, value: await steps.remove() };
583
+ });
584
+ return outcome.locked ? outcome.value : { removed: false, reason: outcome.reason };
585
+ }
586
+
587
+ // plugins/delivery/opencode/src/auto-cleanup.ts
588
+ function ownershipDeferral(ownership) {
589
+ if (ownership.owner === "lane")
590
+ return "owned by subagent-worktree lane";
591
+ if (ownership.owner === "unknown")
592
+ return `lane claim unreadable (${ownership.reason})`;
593
+ return;
594
+ }
595
+
596
+ // plugins/delivery/opencode/src/cleanup.ts
597
+ import { existsSync as existsSync2, lstatSync as lstatSync4, realpathSync as realpathSync4 } from "fs";
598
+ import { basename as basename3, dirname as dirname4, isAbsolute as isAbsolute2, join as join6, resolve as resolve5, sep as sep2 } from "path";
599
+ import { isDeepStrictEqual } from "util";
600
+
601
+ // lib/src/checkout-marker.ts
602
+ import { lstatSync as lstatSync2, readlinkSync } from "fs";
603
+ import { dirname, join as join3 } from "path";
604
+ var MAX_LINKS = 40;
605
+ function physical(path) {
606
+ const pending = (path.startsWith("/") ? path : `${process.cwd()}/${path}`).split("/").reverse();
607
+ let resolved = "";
608
+ let isDirectory = true;
609
+ let links = 0;
610
+ while (pending.length > 0) {
611
+ const part = pending.pop();
612
+ if (!isDirectory)
613
+ return null;
614
+ if (part === "" || part === ".")
615
+ continue;
616
+ if (part === "..") {
617
+ resolved = resolved.slice(0, resolved.lastIndexOf("/"));
618
+ continue;
619
+ }
620
+ const candidate = `${resolved}/${part}`;
621
+ try {
622
+ const stat = lstatSync2(candidate);
623
+ if (!stat.isSymbolicLink()) {
624
+ resolved = candidate;
625
+ isDirectory = stat.isDirectory();
626
+ continue;
627
+ }
628
+ if (++links > MAX_LINKS)
629
+ return null;
630
+ const target = readlinkSync(candidate);
631
+ if (target.startsWith("/"))
632
+ resolved = "";
633
+ pending.push(...target.split("/").reverse());
634
+ } catch {
635
+ return null;
636
+ }
637
+ }
638
+ return resolved === "" ? "/" : resolved;
639
+ }
640
+ function physicalFrom(base, value) {
641
+ return physical(value.startsWith("/") ? value : `${base}/${value}`);
642
+ }
643
+ function gitFileValue(text) {
644
+ if (!text.startsWith("gitdir: "))
645
+ return null;
646
+ const value = text.slice("gitdir: ".length).replace(/\r?\n$/, "");
647
+ return value === "" || /[\r\n]/.test(value) ? null : value;
648
+ }
649
+ function commondirValue(text) {
650
+ const value = text.replace(/\r?\n$/, "");
651
+ return value === "" || /[\r\n]/.test(value) ? null : value;
652
+ }
653
+ function verifyCheckout(checkout, commonDir) {
654
+ const entry = join3(checkout, ".git");
655
+ const workTree = checkout;
656
+ let stat;
657
+ try {
658
+ stat = lstatSync2(entry);
659
+ } catch (error) {
660
+ const code = error.code;
661
+ return { state: code === "ENOENT" || code === "ENOTDIR" ? "absent" : "unsafe" };
662
+ }
663
+ if (stat.isSymbolicLink())
664
+ return { state: "unsafe" };
665
+ const pin = (gitDir) => ({ GIT_DIR: gitDir, GIT_WORK_TREE: workTree, GIT_COMMON_DIR: commonDir });
666
+ if (stat.isDirectory()) {
667
+ const real = physical(entry);
668
+ return real === commonDir ? { state: "same", pin: pin(commonDir) } : { state: real === null ? "unsafe" : "foreign" };
669
+ }
670
+ if (!stat.isFile())
671
+ return { state: "unsafe" };
672
+ const marker = readBounded(entry);
673
+ if (marker.kind !== "text")
674
+ return { state: "unsafe" };
675
+ const named = gitFileValue(marker.text);
676
+ const gitDir = named === null ? null : physicalFrom(checkout, named);
677
+ if (gitDir === null)
678
+ return { state: "unsafe" };
679
+ let claimed = gitDir;
680
+ const commondir = readBounded(join3(gitDir, "commondir"));
681
+ if (commondir.kind === "unreadable")
682
+ return { state: "unsafe" };
683
+ if (commondir.kind === "text") {
684
+ const value = commondirValue(commondir.text);
685
+ const resolved = value === null ? null : physicalFrom(gitDir, value);
686
+ if (resolved === null)
687
+ return { state: "unsafe" };
688
+ claimed = resolved;
689
+ }
690
+ if (claimed !== commonDir)
691
+ return { state: "foreign" };
692
+ if (gitDir === commonDir)
693
+ return { state: "same", pin: pin(gitDir) };
694
+ const worktrees = physical(join3(commonDir, "worktrees"));
695
+ return worktrees !== null && dirname(gitDir) === worktrees ? { state: "same", pin: pin(gitDir) } : { state: "unsafe" };
696
+ }
697
+ function inspectCheckoutMarker(checkout, commonDir) {
698
+ const real = physical(checkout);
699
+ return real === null ? "absent" : verifyCheckout(real, commonDir).state;
700
+ }
701
+
702
+ // lib/src/worktree-state.ts
703
+ var OPERATION_MARKERS = [
704
+ { name: "MERGE_HEAD", operation: "merge" },
705
+ { name: "rebase-merge", operation: "rebase" },
706
+ { name: "rebase-apply", operation: "rebase" },
707
+ { name: "CHERRY_PICK_HEAD", operation: "cherry-pick" },
708
+ { name: "REVERT_HEAD", operation: "revert" },
709
+ { name: "BISECT_LOG", operation: "bisect" }
710
+ ];
711
+ function operationsInProgress(present) {
712
+ const names = new Set(present);
713
+ return [...new Set(OPERATION_MARKERS.filter((marker) => names.has(marker.name)).map((marker) => marker.operation))];
714
+ }
715
+ function stashesOnBranch(subjects, branch) {
716
+ return subjects.split(/\r?\n/).filter((line) => line.startsWith(`WIP on ${branch}:`) || line.startsWith(`On ${branch}:`));
717
+ }
718
+ // plugins/delivery/package.json
719
+ var package_default = {
720
+ name: "delivery",
721
+ version: "0.14.0",
722
+ description: "Pull-request landing with merge proof and receipts, receipt-driven worktree cleanup, delivery agents and fan-out instructions for OpenCode V2.",
723
+ private: true,
724
+ type: "module",
725
+ "agent-plugins": {
726
+ description: "Pull-request landing with merge proof and receipts, receipt-driven worktree cleanup, delivery agents and fan-out instructions for OpenCode V2.",
727
+ category: "development",
728
+ harnesses: [
729
+ "opencode",
730
+ "pi"
731
+ ],
732
+ scope: "global",
733
+ piAgents: false,
734
+ discrepancies: "pi (and OMP, which loads the pi bundle) gets only an explicit delivery_cleanup for the session's repository: no delivery_land, automatic cleanup or clone registry.",
735
+ prerequisites: [
736
+ {
737
+ bin: "git",
738
+ for: "delivery_cleanup's worktree, ref and remote proofs, git worktree remove and git branch -d",
739
+ required: true,
740
+ install: {
741
+ url: "https://git-scm.com/downloads"
742
+ }
743
+ },
744
+ {
745
+ bin: "gh",
746
+ for: "delivery_cleanup's pull-request read (gh pr view) for a GitHub receipt",
747
+ install: {
748
+ mise: "aqua:cli/cli",
749
+ url: "https://cli.github.com"
750
+ }
751
+ },
752
+ {
753
+ bin: "glab",
754
+ for: "delivery_cleanup's merge-request read (glab mr view) for a GitLab receipt",
755
+ install: {
756
+ url: "https://gitlab.com/gitlab-org/cli#installation"
757
+ }
758
+ },
759
+ {
760
+ bin: "bd",
761
+ for: "delivery_cleanup's read-only bd show of a receipt's beads when the repository's Beads ledger is active",
762
+ install: {
763
+ mise: "aqua:gastownhall/beads",
764
+ url: "https://github.com/gastownhall/beads/blob/main/docs/getting-started/installation.md"
765
+ }
766
+ }
767
+ ],
768
+ entries: {
769
+ index: "index"
770
+ },
771
+ piEntries: {
772
+ "delivery-cleanup": "delivery-cleanup"
773
+ }
774
+ }
775
+ };
776
+
777
+ // plugins/delivery/opencode/src/forge-adapter.ts
778
+ import { mkdirSync as mkdirSync3, mkdtempSync, realpathSync as realpathSync2, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "fs";
779
+ import { devNull as devNull2, tmpdir } from "os";
780
+ import { basename, dirname as dirname2, join as join4, resolve as resolve2, sep } from "path";
781
+
782
+ // lib/src/safe-git.ts
783
+ import { devNull } from "os";
784
+ var SAFE_GIT_CONFIG = [
785
+ ["core.fsmonitor", "false"],
786
+ ["core.hooksPath", devNull]
787
+ ];
788
+ var SAFE_GIT_ARGS = [...SAFE_GIT_CONFIG.flatMap(([key, value]) => ["-c", `${key}=${value}`]), "--no-optional-locks"];
789
+ var HARDENED_GIT_CONFIG = [
790
+ ...SAFE_GIT_CONFIG,
791
+ ["core.attributesFile", devNull],
792
+ ["log.showSignature", "false"],
793
+ ["gpg.program", devNull],
794
+ ["gpg.ssh.program", devNull],
795
+ ["gpg.x509.program", devNull],
796
+ ["commit.gpgSign", "false"],
797
+ ["tag.gpgSign", "false"],
798
+ ["gpg.ssh.defaultKeyCommand", ""],
799
+ ["core.sshCommand", ""],
800
+ ["credential.helper", ""],
801
+ ["diff.external", ""]
802
+ ];
803
+
804
+ // plugins/delivery/opencode/src/forge-adapter.ts
805
+ var FORGE_TIMEOUT_MS = 1e4;
806
+ var FORGE_REDIRECTORS = [
807
+ "GH_REPO",
808
+ "GH_HOST",
809
+ "GITLAB_HOST",
810
+ "GL_HOST",
811
+ "GITLAB_URI",
812
+ "GITLAB_API_HOST"
813
+ ];
814
+ function forgeEnvironment(env) {
815
+ const clean = Object.create(null);
816
+ for (const [key, value] of Object.entries(env)) {
817
+ if (value === undefined || FORGE_REDIRECTORS.includes(key))
818
+ continue;
819
+ clean[key] = value;
820
+ }
821
+ return clean;
822
+ }
823
+ var GITLAB_MAX_PATH_SEGMENTS = 21;
824
+ var GITHUB_TARGET = Object.freeze({ forge: "github", canonicalHost: "github.com" });
825
+ var GITLAB_TARGET = Object.freeze({ forge: "gitlab", canonicalHost: "gitlab.com" });
826
+ var GITLAB_CUSTOM_TARGET = Object.freeze({ forge: "gitlab", canonicalHost: "gitlab.example.com" });
827
+ var FORGE_HOSTS = Object.freeze(Object.assign(Object.create(null), {
828
+ "github.com": GITHUB_TARGET,
829
+ "ssh.github.com": GITHUB_TARGET,
830
+ "gitlab.com": GITLAB_TARGET,
831
+ "altssh.gitlab.com": GITLAB_TARGET,
832
+ "gitlab.example.com": GITLAB_CUSTOM_TARGET,
833
+ "ssh.gitlab.example.com": GITLAB_CUSTOM_TARGET
834
+ }));
835
+ var ALLOWED_SCHEME = /^(?:https|ssh):\/\//i;
836
+ var ANY_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
837
+ var SCP_LIKE = /^(?:[^@/:]+@)?([^@/:]+):(?!\/)/;
838
+ var REPO_SEGMENT = /^[A-Za-z0-9._-]+$/;
839
+ var REMOTE_NAME = /^[A-Za-z0-9._][A-Za-z0-9._/-]*(?![\s\S])/;
840
+ var REF_FORBIDDEN = /[~^:?*[\]\\\s;&|<>$`(){}'"!#]/;
841
+ var LS_REMOTE_PROTOCOL_POLICY = [
842
+ "-c",
843
+ "protocol.allow=never",
844
+ "-c",
845
+ "protocol.file.allow=always",
846
+ "-c",
847
+ "protocol.https.allow=always",
848
+ "-c",
849
+ "protocol.ssh.allow=always",
850
+ "-c",
851
+ "protocol.ext.allow=never",
852
+ "-c",
853
+ "core.sshCommand=ssh",
854
+ "-c",
855
+ "core.askPass=",
856
+ "-c",
857
+ "credential.helper=",
858
+ "-c",
859
+ "credential.interactive=never"
860
+ ];
861
+ function gitObservationEnvironment(source = process.env) {
862
+ const env = Object.create(null);
863
+ for (const [key, value] of Object.entries(source)) {
864
+ if (value === undefined || key.startsWith("GIT_") || key === "SSH_ASKPASS" || key === "SSH_ASKPASS_REQUIRE")
865
+ continue;
866
+ env[key] = value;
867
+ }
868
+ env.GIT_ALLOW_PROTOCOL = "file:https:ssh";
869
+ env.GIT_TERMINAL_PROMPT = "0";
870
+ env.GIT_NO_LAZY_FETCH = "1";
871
+ return env;
872
+ }
873
+ var GIT_OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
874
+ function hasControlCharacter(value) {
875
+ for (let index = 0;index < value.length; index++) {
876
+ const code = value.charCodeAt(index);
877
+ if (code < 32 || code === 127)
878
+ return true;
879
+ }
880
+ return false;
881
+ }
882
+ function singleRemoteRecord(stdout) {
883
+ const record = stdout.endsWith(`\r
884
+ `) ? stdout.slice(0, -2) : stdout.endsWith(`
885
+ `) ? stdout.slice(0, -1) : stdout;
886
+ if (record === "" || hasControlCharacter(record) || record !== record.trim())
887
+ return null;
888
+ return record;
889
+ }
890
+ function isSafeArgument(value) {
891
+ return value !== "" && !value.startsWith("-") && !hasControlCharacter(value);
892
+ }
893
+ function isValidBranchName(branch) {
894
+ if (!isSafeArgument(branch))
895
+ return false;
896
+ if (REF_FORBIDDEN.test(branch))
897
+ return false;
898
+ if (branch === "@" || branch.includes("..") || branch.includes("@{"))
899
+ return false;
900
+ for (const component of branch.split("/")) {
901
+ if (component === "" || component.startsWith("."))
902
+ return false;
903
+ if (component.endsWith(".") || component.endsWith(".lock"))
904
+ return false;
905
+ }
906
+ return true;
907
+ }
908
+ function normalizeRepoPath(forge, repo) {
909
+ const supported = supportedForge(forge);
910
+ if (supported === null)
911
+ return null;
912
+ const segments = repo.trim().split("/");
913
+ const maxSegments = supported === "github" ? 2 : GITLAB_MAX_PATH_SEGMENTS;
914
+ if (segments.length < 2 || segments.length > maxSegments)
915
+ return null;
916
+ for (const segment of segments) {
917
+ if (!REPO_SEGMENT.test(segment))
918
+ return null;
919
+ if (segment === "." || segment === ".." || segment.startsWith("-"))
920
+ return null;
921
+ }
922
+ return segments.join("/");
923
+ }
924
+ function hostOf(remoteUrl) {
925
+ for (let index = 0;index < remoteUrl.length; index++) {
926
+ const code = remoteUrl.charCodeAt(index);
927
+ if (code <= 31 || code === 127)
928
+ return null;
929
+ }
930
+ const url = remoteUrl.trim();
931
+ if (url === "" || url.includes("\\"))
932
+ return null;
933
+ if (ALLOWED_SCHEME.test(url)) {
934
+ try {
935
+ const host = new URL(url).hostname.toLowerCase();
936
+ return host === "" ? null : host;
937
+ } catch {
938
+ return null;
939
+ }
940
+ }
941
+ if (ANY_SCHEME.test(url))
942
+ return null;
943
+ const scpHost = SCP_LIKE.exec(url)?.[1];
944
+ return scpHost === undefined || scpHost === "" ? null : scpHost.toLowerCase();
945
+ }
946
+ async function feed(stdin, input) {
947
+ try {
948
+ await stdin.write(input);
949
+ await stdin.end();
950
+ } catch {}
951
+ }
952
+ var runCli = async (argv, options) => {
953
+ if (argv.length === 0) {
954
+ return { ok: false, exitCode: null, stdout: "", stderr: "", error: "no command to run" };
955
+ }
956
+ const timeout = Math.max(1, Math.trunc(options.timeoutMs));
957
+ const { signal, input } = options;
958
+ if (options.signal?.aborted === true) {
959
+ return {
960
+ ok: false,
961
+ exitCode: null,
962
+ stdout: "",
963
+ stderr: "",
964
+ error: `${argv[0]} was not started: the call was aborted`
965
+ };
966
+ }
967
+ let proc;
968
+ try {
969
+ proc = Bun.spawn(argv, {
970
+ cwd: options.cwd,
971
+ env: options.env,
972
+ stdin: input === undefined ? "ignore" : "pipe",
973
+ stdout: "pipe",
974
+ stderr: "pipe",
975
+ detached: true
976
+ });
977
+ } catch (cause) {
978
+ const error = cause instanceof Error ? cause.message : String(cause);
979
+ return { ok: false, exitCode: null, stdout: "", stderr: "", error };
980
+ }
981
+ const child = proc;
982
+ const run = supervise(child, { timeoutMs: timeout, signal, group: true });
983
+ if (input !== undefined && child.stdin !== undefined)
984
+ await feed(child.stdin, input);
985
+ const result = await run;
986
+ const { stdout: out, stderr: err } = result;
987
+ const failed = (error) => ({ ok: false, exitCode: null, stdout: out, stderr: err, error });
988
+ if (result.kind === "timeout")
989
+ return failed(`${argv[0]} was killed by the ${timeout}ms timeout`);
990
+ if (result.kind === "aborted")
991
+ return failed(`${argv[0]} was killed by an abort`);
992
+ if (result.kind === "lost")
993
+ return failed(`${argv[0]} ended without reporting an exit status`);
994
+ if (result.signalCode !== null)
995
+ return failed(`${argv[0]} was terminated by ${result.signalCode}`);
996
+ return { ok: true, exitCode: result.exitCode, stdout: out, stderr: err };
997
+ };
998
+ function forgeTarget(remoteUrl) {
999
+ if (remoteUrl === null)
1000
+ return null;
1001
+ const host = hostOf(remoteUrl);
1002
+ if (host === null)
1003
+ return null;
1004
+ const descriptor = Object.getOwnPropertyDescriptor(FORGE_HOSTS, host);
1005
+ if (descriptor === undefined || !("value" in descriptor))
1006
+ return null;
1007
+ const target = descriptor.value;
1008
+ if (target === GITHUB_TARGET)
1009
+ return GITHUB_TARGET;
1010
+ if (target === GITLAB_TARGET)
1011
+ return GITLAB_TARGET;
1012
+ if (target === GITLAB_CUSTOM_TARGET)
1013
+ return GITLAB_CUSTOM_TARGET;
1014
+ return null;
1015
+ }
1016
+ function repoPathFromRemote(remoteUrl) {
1017
+ const url = remoteUrl.trim();
1018
+ if (url === "")
1019
+ return null;
1020
+ let path;
1021
+ if (ALLOWED_SCHEME.test(url)) {
1022
+ try {
1023
+ path = new URL(url).pathname;
1024
+ } catch {
1025
+ return null;
1026
+ }
1027
+ } else {
1028
+ const scp = /^(?:[^@/:]+@)?[^@/:]+:(?!\/)(.+)$/.exec(url);
1029
+ const tail = scp?.[1];
1030
+ if (tail === undefined)
1031
+ return null;
1032
+ path = tail;
1033
+ }
1034
+ const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "");
1035
+ return trimmed === "" ? null : trimmed;
1036
+ }
1037
+ var WHOLE_SCP_LIKE = /^(?:([A-Za-z0-9._-]+)@)?([A-Za-z0-9.-]+):([^@?#\s]+)$/;
1038
+ var UNREADABLE_REMOTE = "<unreadable remote url>";
1039
+ function redactRemote(remoteUrl) {
1040
+ const url = remoteUrl.trim();
1041
+ if (ALLOWED_SCHEME.test(url)) {
1042
+ let parsed;
1043
+ try {
1044
+ parsed = new URL(url);
1045
+ } catch {
1046
+ return UNREADABLE_REMOTE;
1047
+ }
1048
+ if (parsed.username === "" && parsed.password === "" && parsed.search === "" && parsed.hash === "")
1049
+ return url;
1050
+ parsed.username = "";
1051
+ parsed.password = "";
1052
+ parsed.search = "";
1053
+ parsed.hash = "";
1054
+ return parsed.toString();
1055
+ }
1056
+ const scp = WHOLE_SCP_LIKE.exec(url);
1057
+ const host = scp?.[2];
1058
+ const path = scp?.[3];
1059
+ return host === undefined || path === undefined ? UNREADABLE_REMOTE : `${host}:${path}`;
1060
+ }
1061
+ function describeFailure(argv, result) {
1062
+ const label = argv.join(" ");
1063
+ if (result.error !== undefined)
1064
+ return `${label} did not complete: ${result.error}`;
1065
+ const observed = result.exitCode === null ? "no exit status" : `exit ${result.exitCode}`;
1066
+ const stderr = result.stderr.trim();
1067
+ const detail = stderr === "" ? "" : `; stderr: ${stderr.slice(0, 400)}`;
1068
+ return `${label} observed ${observed}, expected exit 0${detail}`;
1069
+ }
1070
+ function supportedForge(forge) {
1071
+ return forge === "github" || forge === "gitlab" ? forge : null;
1072
+ }
1073
+ var GITLAB_HOSTS = Object.freeze([
1074
+ GITLAB_TARGET.canonicalHost,
1075
+ GITLAB_CUSTOM_TARGET.canonicalHost
1076
+ ]);
1077
+ function stdoutProvesExactHead(stdout, expectedRef) {
1078
+ if (stdout === "")
1079
+ return false;
1080
+ const record = stdout.endsWith(`
1081
+ `) ? stdout.slice(0, -1) : stdout;
1082
+ if (record === "" || record.includes(`
1083
+ `) || record.includes("\r"))
1084
+ return false;
1085
+ const separator = record.indexOf("\t");
1086
+ if (separator <= 0 || record.indexOf("\t", separator + 1) !== -1)
1087
+ return false;
1088
+ return GIT_OID.test(record.slice(0, separator)) && record.slice(separator + 1) === expectedRef;
1089
+ }
1090
+ function absenceVerdict(result, ref) {
1091
+ if (!result.ok || result.error !== undefined)
1092
+ return "unknown";
1093
+ if (result.exitCode === 0)
1094
+ return stdoutProvesExactHead(result.stdout, ref) ? "present" : "unknown";
1095
+ if (result.exitCode === 2 && result.stdout === "" && result.stderr === "")
1096
+ return "absent";
1097
+ return "unknown";
1098
+ }
1099
+ function lsRemoteArgv(remote, ref) {
1100
+ return [
1101
+ "git",
1102
+ ...LS_REMOTE_PROTOCOL_POLICY,
1103
+ "ls-remote",
1104
+ "--exit-code",
1105
+ "--heads",
1106
+ "--upload-pack=git-upload-pack",
1107
+ remote,
1108
+ ref
1109
+ ];
1110
+ }
1111
+ var FETCH_CHECKOUT_PINS = [
1112
+ "-c",
1113
+ `core.hooksPath=${devNull2}`,
1114
+ "-c",
1115
+ "core.fsmonitor=false",
1116
+ "-c",
1117
+ "core.alternateRefsCommand="
1118
+ ];
1119
+ var MAX_SHALLOW_BYTES = 4 * 1024 * 1024;
1120
+ var GITHUB_BRANCH_QUERY = "query($owner: String!, $name: String!, $ref: String!) { repository(owner: $owner, name: $name) { nameWithOwner ref(qualifiedName: $ref) { prefix name target { __typename oid } } } }";
1121
+ function githubBranchArgv(repo, branch) {
1122
+ const path = normalizeRepoPath("github", repo);
1123
+ if (path === null || !isValidBranchName(branch))
1124
+ return null;
1125
+ const [owner = "", name = ""] = path.split("/");
1126
+ return [
1127
+ "gh",
1128
+ "api",
1129
+ "graphql",
1130
+ "--hostname",
1131
+ GITHUB_TARGET.canonicalHost,
1132
+ "-f",
1133
+ `query=${GITHUB_BRANCH_QUERY}`,
1134
+ "-f",
1135
+ `owner=${owner}`,
1136
+ "-f",
1137
+ `name=${name}`,
1138
+ "-f",
1139
+ `ref=refs/heads/${branch}`
1140
+ ];
1141
+ }
1142
+ function ownData(holder, key) {
1143
+ if (typeof holder !== "object" || holder === null || Array.isArray(holder))
1144
+ return null;
1145
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
1146
+ return descriptor === undefined || !("value" in descriptor) ? null : { value: descriptor.value };
1147
+ }
1148
+ function githubBranchVerdict(result, repo, branch) {
1149
+ const ref = `refs/heads/${branch}`;
1150
+ const label = `gh api graphql (${ref} of ${repo})`;
1151
+ const unknown = (observed) => ({ verdict: "unknown", reason: `${label}: ${observed}` });
1152
+ if (!result.ok || result.error !== undefined || result.exitCode !== 0) {
1153
+ return { verdict: "unknown", reason: describeFailure([label], result) };
1154
+ }
1155
+ let payload;
1156
+ try {
1157
+ payload = JSON.parse(result.stdout);
1158
+ } catch {
1159
+ return unknown("observed output that is not JSON, expected one GraphQL response object");
1160
+ }
1161
+ if (ownData(payload, "errors") !== null) {
1162
+ return unknown(`observed GraphQL errors ${JSON.stringify(ownData(payload, "errors")?.value).slice(0, 300)}`);
1163
+ }
1164
+ const repository = ownData(ownData(payload, "data")?.value, "repository")?.value;
1165
+ const name = ownData(repository, "nameWithOwner")?.value;
1166
+ if (typeof name !== "string" || name.toLowerCase() !== repo.toLowerCase()) {
1167
+ return unknown(`observed repository ${JSON.stringify(name ?? null)}, expected ${JSON.stringify(repo)}`);
1168
+ }
1169
+ const field = ownData(repository, "ref");
1170
+ if (field === null)
1171
+ return unknown("observed no ref field, expected the ref or an explicit null");
1172
+ if (field.value === null)
1173
+ return { verdict: "absent" };
1174
+ const target = ownData(field.value, "target")?.value;
1175
+ const oid = ownData(target, "oid")?.value;
1176
+ if (ownData(field.value, "prefix")?.value !== "refs/heads/" || ownData(field.value, "name")?.value !== branch || ownData(target, "__typename")?.value !== "Commit" || typeof oid !== "string" || !GIT_OID.test(oid)) {
1177
+ return unknown(`observed a ref that is not ${ref} at a commit id, expected exactly that ref or null`);
1178
+ }
1179
+ return { verdict: "present", oid };
1180
+ }
1181
+ async function observeGithubBranch(repo, branch, run = runCli, environment = process.env) {
1182
+ const path = normalizeRepoPath("github", repo);
1183
+ const argv = path === null ? null : githubBranchArgv(path, branch);
1184
+ if (path === null || argv === null) {
1185
+ return {
1186
+ verdict: "unknown",
1187
+ reason: `gh api graphql: observed repository ${JSON.stringify(repo)} and branch ${JSON.stringify(branch)}, expected "<owner>/<name>" and a valid branch name`
1188
+ };
1189
+ }
1190
+ const env = Object.assign(Object.create(null), forgeEnvironment(environment), {
1191
+ GH_HOST: GITHUB_TARGET.canonicalHost
1192
+ });
1193
+ return githubBranchVerdict(await run(argv, { timeoutMs: FORGE_TIMEOUT_MS, env }), path, branch);
1194
+ }
1195
+ var PROBE_REMOTE = "delivery-absence-probe";
1196
+ var PROBE_HEAD = `ref: refs/heads/main
1197
+ `;
1198
+ var PROBE_CONFIG = `[core]
1199
+ repositoryformatversion = 0
1200
+ bare = true
1201
+ `;
1202
+ function isolatedProbeRepository(directory) {
1203
+ const gitDir = join4(directory, "probe.git");
1204
+ try {
1205
+ mkdirSync3(join4(gitDir, "objects"), { recursive: true });
1206
+ mkdirSync3(join4(gitDir, "refs"), { recursive: true });
1207
+ writeFileSync3(join4(gitDir, "HEAD"), PROBE_HEAD);
1208
+ writeFileSync3(join4(gitDir, "config"), PROBE_CONFIG);
1209
+ return gitDir;
1210
+ } catch {
1211
+ return null;
1212
+ }
1213
+ }
1214
+ function urlProbeEnvironment(source, url, probeDirectory, gitDir) {
1215
+ const env = Object.assign(Object.create(null), gitObservationEnvironment(source));
1216
+ env.GIT_CONFIG_GLOBAL = devNull2;
1217
+ env.GIT_CONFIG_NOSYSTEM = "1";
1218
+ env.GIT_CONFIG_COUNT = "1";
1219
+ env.GIT_CONFIG_KEY_0 = `remote.${PROBE_REMOTE}.url`;
1220
+ env.GIT_CONFIG_VALUE_0 = url;
1221
+ env.GIT_CEILING_DIRECTORIES = probeDirectory;
1222
+ env.GIT_DIR = gitDir;
1223
+ return env;
1224
+ }
1225
+ function absenceProbe(remoteOrUrl, branch, cwd, environment) {
1226
+ if (!isSafeArgument(remoteOrUrl) || !isValidBranchName(branch))
1227
+ return null;
1228
+ const ref = `refs/heads/${branch}`;
1229
+ if (forgeTarget(remoteOrUrl) !== null) {
1230
+ let neutral;
1231
+ try {
1232
+ neutral = realpathSync2(mkdtempSync(join4(tmpdir(), "forge-ls-remote-")));
1233
+ } catch {
1234
+ return null;
1235
+ }
1236
+ const dispose = () => {
1237
+ try {
1238
+ rmSync3(neutral, { recursive: true, force: true });
1239
+ } catch {}
1240
+ };
1241
+ const gitDir = isolatedProbeRepository(neutral);
1242
+ if (gitDir === null) {
1243
+ dispose();
1244
+ return null;
1245
+ }
1246
+ return {
1247
+ argv: lsRemoteArgv(PROBE_REMOTE, ref),
1248
+ options: {
1249
+ cwd: neutral,
1250
+ timeoutMs: FORGE_TIMEOUT_MS,
1251
+ env: urlProbeEnvironment(environment, remoteOrUrl, neutral, gitDir)
1252
+ },
1253
+ ref,
1254
+ dispose
1255
+ };
1256
+ }
1257
+ if (cwd.trim() === "")
1258
+ return null;
1259
+ return {
1260
+ argv: lsRemoteArgv(remoteOrUrl, ref),
1261
+ options: { cwd, timeoutMs: FORGE_TIMEOUT_MS, env: gitObservationEnvironment(environment) },
1262
+ ref,
1263
+ dispose: () => {
1264
+ return;
1265
+ }
1266
+ };
1267
+ }
1268
+ async function remoteBranchAbsent(remoteOrUrl, branch, cwd, run = runCli, environment = process.env) {
1269
+ const probe = absenceProbe(remoteOrUrl, branch, cwd, environment);
1270
+ if (probe === null)
1271
+ return "unknown";
1272
+ try {
1273
+ return absenceVerdict(await run(probe.argv, probe.options), probe.ref);
1274
+ } finally {
1275
+ probe.dispose();
1276
+ }
1277
+ }
1278
+
1279
+ // plugins/delivery/opencode/src/landing-receipt.ts
1280
+ import { createHash as createHash3, randomBytes } from "crypto";
1281
+ import {
1282
+ closeSync as closeSync3,
1283
+ constants as constants3,
1284
+ fchmodSync,
1285
+ fstatSync as fstatSync2,
1286
+ linkSync,
1287
+ lstatSync as lstatSync3,
1288
+ mkdirSync as mkdirSync4,
1289
+ opendirSync,
1290
+ openSync as openSync3,
1291
+ readFileSync as readFileSync3,
1292
+ readSync as readSync2,
1293
+ realpathSync as realpathSync3,
1294
+ unlinkSync as unlinkSync2,
1295
+ writeFileSync as writeFileSync4
1296
+ } from "fs";
1297
+ import { homedir } from "os";
1298
+ import { basename as basename2, dirname as dirname3, isAbsolute, join as join5, resolve as resolve3 } from "path";
1299
+ var RECEIPT_SCHEMA = "omp.receipt.landing";
1300
+ var RECEIPT_SCHEMAS = [RECEIPT_SCHEMA, "delivery.receipt.landing"];
1301
+ var RECEIPT_VERSION = 1;
1302
+ var GIT_TIMEOUT_MS = 5000;
1303
+ var MAX_RECEIPT_BYTES = 256 * 1024;
1304
+ var MAX_LISTED_RECEIPTS = 1000;
1305
+ var MAX_TEMP_ATTEMPTS = 5;
1306
+ var MAX_RECEIPT_EPOCH = 253402300799999;
1307
+ var REPO_KEY = /^[0-9a-f]{16}$/;
1308
+ var REPO_KEY_TEXT = "16 lowercase hex characters";
1309
+ var RECEIPT_ID = /^[0-9]{1,15}-(?:[0-9a-f]{12}|nomerge)$/;
1310
+ var RECEIPT_ID_TEXT = 'epoch millis of at most 15 digits, "-", then 12 lowercase hex characters or "nomerge"';
1311
+ var EMITTED_AT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-](\d{2}):(\d{2}))$/;
1312
+ var RECEIPT_FILE = /^[0-9]{1,15}-(?:[0-9a-f]{12}|nomerge)\.json$/;
1313
+ var MERGE_OID = /^[0-9a-f]{12,}$/;
1314
+ var spawnGit = async (argv, cwd, timeoutMs, signal) => {
1315
+ const options = {
1316
+ cwd,
1317
+ env: process.env,
1318
+ timeoutMs,
1319
+ signal
1320
+ };
1321
+ const result = await runCli(["git", ...SAFE_GIT_ARGS, ...argv], options);
1322
+ return result.ok && result.error === undefined && result.exitCode === 0 ? result.stdout : null;
1323
+ };
1324
+ var REPOSITORY_OBSERVATION_ARGS = [
1325
+ "rev-parse",
1326
+ "--path-format=absolute",
1327
+ "--git-common-dir",
1328
+ "--show-toplevel"
1329
+ ];
1330
+ function physicalDirectory(path) {
1331
+ try {
1332
+ const real = realpathSync3(path);
1333
+ return lstatSync3(real).isDirectory() ? real : null;
1334
+ } catch {
1335
+ return null;
1336
+ }
1337
+ }
1338
+ function checkoutGitDirectory(checkout) {
1339
+ const marker = join5(checkout, ".git");
1340
+ try {
1341
+ const stat = lstatSync3(marker);
1342
+ if (stat.isDirectory())
1343
+ return physicalDirectory(marker);
1344
+ if (!stat.isFile() || stat.size > 4096)
1345
+ return null;
1346
+ const match = /^gitdir: (.+)\r?\n?$/.exec(readFileSync3(marker, "utf8"));
1347
+ if (match === null)
1348
+ return null;
1349
+ const target = match[1];
1350
+ if (target === undefined || target === "" || target.includes("\x00"))
1351
+ return null;
1352
+ return physicalDirectory(isAbsolute(target) ? target : resolve3(checkout, target));
1353
+ } catch {
1354
+ return null;
1355
+ }
1356
+ }
1357
+ function repoKeyOf(commonDir) {
1358
+ return createHash3("sha256").update(commonDir).digest("hex").slice(0, 16);
1359
+ }
1360
+ function repositoryPaths(output) {
1361
+ const body = output.endsWith(`
1362
+ `) ? output.slice(0, -1) : output;
1363
+ const records = body.split(`
1364
+ `);
1365
+ if (records.length !== 2)
1366
+ return null;
1367
+ const [common, top] = records;
1368
+ if (common === undefined || top === undefined || common === "" || top === "")
1369
+ return null;
1370
+ if (!isAbsolute(common) || !isAbsolute(top))
1371
+ return null;
1372
+ if (common.includes("\x00") || top.includes("\x00") || common.includes("\r") || top.includes("\r"))
1373
+ return null;
1374
+ const commonDir = physicalDirectory(common);
1375
+ const topLevel = physicalDirectory(top);
1376
+ return commonDir === null || topLevel === null ? null : { commonDir, topLevel };
1377
+ }
1378
+ async function repositoryContext(cwd, run = spawnGit, timeoutMs = GIT_TIMEOUT_MS) {
1379
+ const printed = await run(REPOSITORY_OBSERVATION_ARGS, cwd, timeoutMs);
1380
+ if (printed === null || printed === "")
1381
+ return null;
1382
+ const paths = repositoryPaths(printed);
1383
+ if (paths === null)
1384
+ return null;
1385
+ const topLevelGitDir = checkoutGitDirectory(paths.topLevel);
1386
+ if (topLevelGitDir === null)
1387
+ return null;
1388
+ let candidate = paths.topLevel;
1389
+ if (topLevelGitDir !== paths.commonDir) {
1390
+ const canonicalCandidate = physicalDirectory(dirname3(paths.commonDir));
1391
+ if (canonicalCandidate === null || checkoutGitDirectory(canonicalCandidate) !== paths.commonDir)
1392
+ return null;
1393
+ candidate = canonicalCandidate;
1394
+ }
1395
+ const root = physicalDirectory(candidate);
1396
+ if (root === null)
1397
+ return null;
1398
+ const key = repoKeyOf(paths.commonDir);
1399
+ return {
1400
+ key,
1401
+ commonDir: paths.commonDir,
1402
+ topLevel: paths.topLevel,
1403
+ ledger: { root, active: ledgerActive(root) }
1404
+ };
1405
+ }
1406
+ async function repoKey(cwd, run = spawnGit, timeoutMs = GIT_TIMEOUT_MS) {
1407
+ const printed = await run(["rev-parse", "--git-common-dir"], cwd, timeoutMs);
1408
+ if (printed === null || printed === "")
1409
+ return null;
1410
+ const common = printed.endsWith(`
1411
+ `) ? printed.slice(0, -1) : printed;
1412
+ if (common === "" || common.includes(`
1413
+ `) || common.includes("\r") || common.includes("\x00"))
1414
+ return null;
1415
+ const real = physicalDirectory(isAbsolute(common) ? common : resolve3(cwd, common));
1416
+ return real === null ? null : repoKeyOf(real);
1417
+ }
1418
+ function ledgerActive(dir) {
1419
+ const beads = join5(resolve3(dir), ".beads");
1420
+ let beadsStat;
1421
+ try {
1422
+ beadsStat = lstatSync3(beads);
1423
+ } catch (error) {
1424
+ return error.code !== "ENOENT";
1425
+ }
1426
+ if (!beadsStat.isDirectory())
1427
+ return true;
1428
+ try {
1429
+ return !lstatSync3(join5(beads, "RETIRED")).isFile();
1430
+ } catch {
1431
+ return true;
1432
+ }
1433
+ }
1434
+ async function canonicalLedger(cwd, run = spawnGit, timeoutMs = GIT_TIMEOUT_MS) {
1435
+ return (await repositoryContext(cwd, run, timeoutMs))?.ledger ?? null;
1436
+ }
1437
+ function receiptDirectory(env = process.env, key) {
1438
+ const configured = env.DELIVERY_RECEIPTS_DIR?.trim() ?? "";
1439
+ const home = env.HOME?.trim() ?? "";
1440
+ const receipts = configured === "" ? join5(home === "" ? homedir() : home, ".omp", "receipts") : resolve3(configured);
1441
+ if (key === undefined)
1442
+ return receipts;
1443
+ if (!REPO_KEY.test(key))
1444
+ throw new Error(`repo.key: observed ${show(key)}, expected ${REPO_KEY_TEXT}`);
1445
+ return join5(receipts, key);
1446
+ }
1447
+ function provenReceiptDirectory(env, key) {
1448
+ const composed = resolve3(receiptDirectory(env, key));
1449
+ const receiptsName = basename2(dirname3(composed));
1450
+ const parent = dirname3(dirname3(composed));
1451
+ const missing = (error) => {
1452
+ const code = error.code;
1453
+ return code === "ENOENT" || code === "ENOTDIR" ? "absent" : "unreadable";
1454
+ };
1455
+ let root;
1456
+ try {
1457
+ root = realpathSync3(parent);
1458
+ } catch (error) {
1459
+ return { ok: false, reason: missing(error), at: parent, directory: composed };
1460
+ }
1461
+ const directory = join5(root, receiptsName, key);
1462
+ for (const at of [root, dirname3(directory), directory]) {
1463
+ let stat;
1464
+ try {
1465
+ stat = lstatSync3(at);
1466
+ } catch (error) {
1467
+ return { ok: false, reason: missing(error), at, directory };
1468
+ }
1469
+ if (stat.isSymbolicLink())
1470
+ return { ok: false, reason: "symlink", at, directory };
1471
+ if (!stat.isDirectory())
1472
+ return { ok: false, reason: "not-directory", at, directory };
1473
+ }
1474
+ return { ok: true, directory };
1475
+ }
1476
+ function receiptId(now, mergeCommitOid) {
1477
+ if (!Number.isSafeInteger(now) || now < 0 || now > MAX_RECEIPT_EPOCH) {
1478
+ throw new Error(`now: observed ${show(now)}, expected an integer from 0 through ${MAX_RECEIPT_EPOCH} whose ISO timestamp has a four-digit year`);
1479
+ }
1480
+ if (mergeCommitOid === null)
1481
+ return `${now}-nomerge`;
1482
+ const oid = mergeCommitOid.trim().toLowerCase();
1483
+ if (!MERGE_OID.test(oid)) {
1484
+ throw new Error(`pr.mergeCommitOid: observed ${show(mergeCommitOid)}, expected at least 12 hex characters, or null for no merge commit`);
1485
+ }
1486
+ return `${now}-${oid.slice(0, 12)}`;
1487
+ }
1488
+ function closeoutCommands(beadId, pr, mergeSha, receiptPath) {
1489
+ return {
1490
+ update: `bd update ${beadId} --set-metadata pr=${pr} --set-metadata merge_sha=${mergeSha}`,
1491
+ close: `bd close ${beadId} --reason "PR #${pr} merged as ${mergeSha}; receipt ${receiptPath}"`
1492
+ };
1493
+ }
1494
+ var V1_KEYS = {
1495
+ schema: true,
1496
+ version: true,
1497
+ receiptId: true,
1498
+ emittedAt: true,
1499
+ emitter: true,
1500
+ repo: true,
1501
+ pr: true,
1502
+ branch: true,
1503
+ worktree: true,
1504
+ beads: true,
1505
+ proof: true,
1506
+ outcome: true,
1507
+ supersedes: true,
1508
+ notes: true
1509
+ };
1510
+ function carriedKeys(prior) {
1511
+ const carried = Object.create(null);
1512
+ if (prior === null || prior === undefined)
1513
+ return carried;
1514
+ for (const key of Object.getOwnPropertyNames(prior)) {
1515
+ if (Object.hasOwn(V1_KEYS, key))
1516
+ continue;
1517
+ const descriptor = Object.getOwnPropertyDescriptor(prior, key);
1518
+ if (descriptor === undefined || !descriptor.enumerable || !("value" in descriptor))
1519
+ continue;
1520
+ carried[key] = descriptor.value;
1521
+ }
1522
+ return carried;
1523
+ }
1524
+ function buildReceipt(input) {
1525
+ const now = input.now ?? Date.now();
1526
+ const receipt = {
1527
+ ...carriedKeys(input.continues),
1528
+ schema: RECEIPT_SCHEMA,
1529
+ version: RECEIPT_VERSION,
1530
+ receiptId: receiptId(now, input.pr.mergeCommitOid),
1531
+ emittedAt: new Date(now).toISOString(),
1532
+ emitter: input.emitter,
1533
+ repo: input.repo,
1534
+ pr: input.pr,
1535
+ branch: input.branch,
1536
+ worktree: input.worktree,
1537
+ beads: input.beads,
1538
+ proof: input.proof,
1539
+ outcome: input.outcome,
1540
+ supersedes: input.supersedes !== undefined ? input.supersedes : input.continues?.receiptId ?? null
1541
+ };
1542
+ if (input.notes !== undefined)
1543
+ receipt.notes = input.notes;
1544
+ return receipt;
1545
+ }
1546
+ var TEXT = { kind: "text" };
1547
+ var NULLABLE_TEXT = { kind: "nullableText" };
1548
+ var INTEGER = { kind: "integer" };
1549
+ var BOOLEAN = { kind: "boolean" };
1550
+ var OBJECT = { kind: "object" };
1551
+ var IDS = { kind: "ids" };
1552
+ var FORGE = { kind: "enum", values: ["github", "gitlab", "unknown"] };
1553
+ var AUTO_DELETE = { kind: "enum", values: ["on", "off", "unknown"] };
1554
+ var OUTCOME = { kind: "enum", values: ["landed", "cleaned", "partial"] };
1555
+ var KEY_SHAPE = { kind: "pattern", pattern: REPO_KEY, text: REPO_KEY_TEXT, nullable: false };
1556
+ var ID_SHAPE = { kind: "pattern", pattern: RECEIPT_ID, text: RECEIPT_ID_TEXT, nullable: false };
1557
+ var NULLABLE_ID_SHAPE = { kind: "pattern", pattern: RECEIPT_ID, text: RECEIPT_ID_TEXT, nullable: true };
1558
+ var REQUIRED = [
1559
+ ["", "receiptId", ID_SHAPE],
1560
+ ["", "emittedAt", TEXT],
1561
+ ["emitter", "plugin", TEXT],
1562
+ ["emitter", "version", TEXT],
1563
+ ["emitter", "tool", TEXT],
1564
+ ["repo", "key", KEY_SHAPE],
1565
+ ["repo", "canonicalRoot", TEXT],
1566
+ ["repo", "remote", TEXT],
1567
+ ["repo", "forge", FORGE],
1568
+ ["repo", "nameWithOwner", TEXT],
1569
+ ["pr", "number", INTEGER],
1570
+ ["pr", "url", TEXT],
1571
+ ["pr", "state", TEXT],
1572
+ ["pr", "baseRefName", TEXT],
1573
+ ["pr", "headRefName", TEXT],
1574
+ ["pr", "headRefOid", TEXT],
1575
+ ["pr", "mergeCommitOid", NULLABLE_TEXT],
1576
+ ["pr", "mergedAt", NULLABLE_TEXT],
1577
+ ["branch", "name", TEXT],
1578
+ ["branch", "deletedRemote", BOOLEAN],
1579
+ ["branch", "remoteAbsenceVerifiedAt", NULLABLE_TEXT],
1580
+ ["branch", "autoDeleteSetting", AUTO_DELETE],
1581
+ ["worktree", "path", NULLABLE_TEXT],
1582
+ ["worktree", "removed", BOOLEAN],
1583
+ ["worktree", "localRefDeleted", BOOLEAN],
1584
+ ["worktree", "absenceVerifiedAt", NULLABLE_TEXT],
1585
+ ["beads", "ids", IDS],
1586
+ ["beads", "ledgerActive", BOOLEAN],
1587
+ ["proof", "method", TEXT],
1588
+ ["proof", "observedAt", TEXT],
1589
+ ["proof", "evidence", OBJECT],
1590
+ ["", "outcome", OUTCOME],
1591
+ ["", "supersedes", NULLABLE_ID_SHAPE]
1592
+ ];
1593
+ function isRecord(value) {
1594
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1595
+ }
1596
+ function ownDataProperty(holder, key) {
1597
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
1598
+ if (descriptor === undefined || !descriptor.enumerable || !("value" in descriptor))
1599
+ return { ok: false };
1600
+ return { ok: true, value: descriptor.value };
1601
+ }
1602
+ function show(value) {
1603
+ if (value === undefined)
1604
+ return "absent";
1605
+ if (value === null)
1606
+ return "null";
1607
+ if (Array.isArray(value))
1608
+ return `array of ${value.length}`;
1609
+ switch (typeof value) {
1610
+ case "string":
1611
+ return `string ${JSON.stringify(value)}`;
1612
+ case "number":
1613
+ case "boolean":
1614
+ return `${typeof value} ${String(value)}`;
1615
+ case "object":
1616
+ return "object";
1617
+ default:
1618
+ return typeof value;
1619
+ }
1620
+ }
1621
+ function expectationText(expectation) {
1622
+ switch (expectation.kind) {
1623
+ case "text":
1624
+ return "a non-empty string";
1625
+ case "nullableText":
1626
+ return "a non-empty string or null";
1627
+ case "integer":
1628
+ return "an integer";
1629
+ case "boolean":
1630
+ return "a boolean";
1631
+ case "object":
1632
+ return "an object";
1633
+ case "ids":
1634
+ return "an array of non-empty strings";
1635
+ case "enum":
1636
+ return `one of ${expectation.values.map((allowed) => JSON.stringify(allowed)).join(", ")}`;
1637
+ case "pattern":
1638
+ return expectation.nullable ? `${expectation.text}, or null` : expectation.text;
1639
+ }
1640
+ }
1641
+ function refuse(field, observed, expected) {
1642
+ return { ok: false, reason: `${field}: observed ${show(observed)}, expected ${expected}` };
1643
+ }
1644
+ function checkField(root, container, key, expectation) {
1645
+ let holder = root;
1646
+ if (container !== "") {
1647
+ const property = ownDataProperty(root, container);
1648
+ const nested = property.ok ? property.value : undefined;
1649
+ if (!isRecord(nested))
1650
+ return refuse(container, nested, "an object");
1651
+ holder = nested;
1652
+ }
1653
+ const field = container === "" ? key : `${container}.${key}`;
1654
+ const property = ownDataProperty(holder, key);
1655
+ const value = property.ok ? property.value : undefined;
1656
+ const nonEmptyString = typeof value === "string" && value.trim() !== "";
1657
+ switch (expectation.kind) {
1658
+ case "text":
1659
+ return nonEmptyString ? null : refuse(field, value, expectationText(expectation));
1660
+ case "nullableText":
1661
+ return value === null || nonEmptyString ? null : refuse(field, value, expectationText(expectation));
1662
+ case "integer":
1663
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? null : refuse(field, value, "a positive safe integer");
1664
+ case "boolean":
1665
+ return typeof value === "boolean" ? null : refuse(field, value, expectationText(expectation));
1666
+ case "object":
1667
+ return isRecord(value) ? null : refuse(field, value, expectationText(expectation));
1668
+ case "ids": {
1669
+ if (!Array.isArray(value))
1670
+ return refuse(field, value, expectationText(expectation));
1671
+ for (let index = 0;index < value.length; index += 1) {
1672
+ const id = value[index];
1673
+ if (typeof id !== "string" || id.trim() === "") {
1674
+ return refuse(`${field}[${index}]`, id, "a non-empty string");
1675
+ }
1676
+ }
1677
+ return null;
1678
+ }
1679
+ case "enum":
1680
+ return typeof value === "string" && expectation.values.includes(value) ? null : refuse(field, value, expectationText(expectation));
1681
+ case "pattern":
1682
+ if (expectation.nullable && value === null)
1683
+ return null;
1684
+ return typeof value === "string" && expectation.pattern.test(value) ? null : refuse(field, value, expectationText(expectation));
1685
+ }
1686
+ }
1687
+ function epochOf(idOrFilename) {
1688
+ return Number(idOrFilename.slice(0, idOrFilename.indexOf("-")));
1689
+ }
1690
+ function sameInstant(id, emittedAt) {
1691
+ if (typeof emittedAt !== "string") {
1692
+ return refuse("emittedAt", emittedAt, "an ISO-8601 instant such as 2026-09-21T12:00:00.000Z");
1693
+ }
1694
+ const match = EMITTED_AT.exec(emittedAt);
1695
+ if (match === null) {
1696
+ return refuse("emittedAt", emittedAt, "an ISO-8601 instant such as 2026-09-21T12:00:00.000Z");
1697
+ }
1698
+ const year = Number(match[1]);
1699
+ const month = Number(match[2]);
1700
+ const day = Number(match[3]);
1701
+ const hour = Number(match[4]);
1702
+ const minute = Number(match[5]);
1703
+ const second = Number(match[6]);
1704
+ const offsetHour = match[9] === undefined ? 0 : Number(match[9]);
1705
+ const offsetMinute = match[10] === undefined ? 0 : Number(match[10]);
1706
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1707
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
1708
+ if (daysInMonth === undefined || day < 1 || day > daysInMonth || hour > 23 || minute > 59 || second > 59 || offsetHour > 23 || offsetMinute > 59) {
1709
+ return refuse("emittedAt", emittedAt, "a real calendar date");
1710
+ }
1711
+ const parsed = Date.parse(emittedAt);
1712
+ if (Number.isNaN(parsed))
1713
+ return refuse("emittedAt", emittedAt, "a real calendar date");
1714
+ const epoch = epochOf(id);
1715
+ if (parsed !== epoch) {
1716
+ return refuse("emittedAt", `${emittedAt} (${parsed})`, `the same instant as receiptId's epoch ${epoch}`);
1717
+ }
1718
+ return null;
1719
+ }
1720
+ function sameMergeCommit(id, mergeCommitOid) {
1721
+ const suffix = id.slice(id.indexOf("-") + 1);
1722
+ if (mergeCommitOid === null) {
1723
+ return suffix === "nomerge" ? null : refuse("receiptId", id, 'a "nomerge" suffix when pr.mergeCommitOid is null');
1724
+ }
1725
+ if (typeof mergeCommitOid !== "string") {
1726
+ return refuse("pr.mergeCommitOid", mergeCommitOid, "at least 12 hex characters, or null");
1727
+ }
1728
+ const normalized = mergeCommitOid.trim().toLowerCase();
1729
+ if (!MERGE_OID.test(normalized)) {
1730
+ return refuse("pr.mergeCommitOid", mergeCommitOid, "at least 12 hex characters, or null");
1731
+ }
1732
+ const expected = normalized.slice(0, 12);
1733
+ return suffix === expected ? null : refuse("receiptId", id, `a suffix equal to pr.mergeCommitOid's normalized prefix ${expected}`);
1734
+ }
1735
+ var RECEIPT_METHOD_UNKNOWN = "unknown";
1736
+ function crossFieldClaims(value) {
1737
+ const beads = value.beads;
1738
+ if (beads.ledgerActive && beads.ids.length === 0) {
1739
+ return refuse("beads.ids", beads.ids, "at least one bead id when beads.ledgerActive is true");
1740
+ }
1741
+ const proof = value.proof;
1742
+ if (value.outcome === "landed" && proof.method.trim() === RECEIPT_METHOD_UNKNOWN) {
1743
+ return refuse("proof.method", proof.method, 'the provider CLI and verb that observed the landing, never "unknown", when outcome is "landed"');
1744
+ }
1745
+ return null;
1746
+ }
1747
+ function validateReceipt(value) {
1748
+ if (!isRecord(value))
1749
+ return refuse("receipt", value, "an object");
1750
+ const schemaProperty = ownDataProperty(value, "schema");
1751
+ const schema = schemaProperty.ok ? schemaProperty.value : undefined;
1752
+ if (!RECEIPT_SCHEMAS.some((known) => known === schema)) {
1753
+ return {
1754
+ ok: false,
1755
+ reason: `foreign schema: observed ${show(schema)}, expected one of ${RECEIPT_SCHEMAS.map((known) => JSON.stringify(known)).join(", ")}`
1756
+ };
1757
+ }
1758
+ const versionProperty = ownDataProperty(value, "version");
1759
+ const version = versionProperty.ok ? versionProperty.value : undefined;
1760
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
1761
+ return refuse("version", version, `an integer from 1 to ${RECEIPT_VERSION}`);
1762
+ }
1763
+ if (version > RECEIPT_VERSION) {
1764
+ return {
1765
+ ok: false,
1766
+ reason: `version: observed ${version}, expected at most ${RECEIPT_VERSION}; this consumer implements version ${RECEIPT_VERSION}`
1767
+ };
1768
+ }
1769
+ for (const [container, key, expectation] of REQUIRED) {
1770
+ const failure = checkField(value, container, key, expectation);
1771
+ if (failure !== null)
1772
+ return failure;
1773
+ }
1774
+ const drift = sameInstant(value.receiptId, value.emittedAt);
1775
+ if (drift !== null)
1776
+ return drift;
1777
+ const mergeIdentity = sameMergeCommit(value.receiptId, value.pr.mergeCommitOid);
1778
+ if (mergeIdentity !== null)
1779
+ return mergeIdentity;
1780
+ const claims = crossFieldClaims(value);
1781
+ if (claims !== null)
1782
+ return claims;
1783
+ const notesProperty = Object.getOwnPropertyDescriptor(value, "notes");
1784
+ if (notesProperty !== undefined && (!notesProperty.enumerable || !("value" in notesProperty) || typeof notesProperty.value !== "string")) {
1785
+ const notes = "value" in notesProperty ? notesProperty.value : undefined;
1786
+ return refuse("notes", notes, "an own enumerable string data property when present");
1787
+ }
1788
+ return { ok: true, receipt: value };
1789
+ }
1790
+ function readBounded2(path) {
1791
+ let fd;
1792
+ try {
1793
+ fd = openSync3(path, constants3.O_RDONLY | constants3.O_NONBLOCK | constants3.O_NOFOLLOW);
1794
+ } catch {
1795
+ return refuse("path", path, "a readable receipt file");
1796
+ }
1797
+ try {
1798
+ const stat = fstatSync2(fd);
1799
+ if (!stat.isFile())
1800
+ return refuse("path", `${path} (not a regular file)`, "a regular file");
1801
+ const buffer = Buffer.allocUnsafe(MAX_RECEIPT_BYTES + 1);
1802
+ let filled = 0;
1803
+ while (filled < buffer.length) {
1804
+ const read = readSync2(fd, buffer, filled, buffer.length - filled, null);
1805
+ if (read === 0)
1806
+ break;
1807
+ filled += read;
1808
+ }
1809
+ if (filled > MAX_RECEIPT_BYTES) {
1810
+ return refuse("path", `${path} (over ${MAX_RECEIPT_BYTES} bytes)`, `at most ${MAX_RECEIPT_BYTES} bytes`);
1811
+ }
1812
+ return { ok: true, text: buffer.toString("utf8", 0, filled) };
1813
+ } finally {
1814
+ try {
1815
+ closeSync3(fd);
1816
+ } catch {}
1817
+ }
1818
+ }
1819
+ function publish(temporary, target, payload) {
1820
+ try {
1821
+ linkSync(temporary, target);
1822
+ return;
1823
+ } catch (error) {
1824
+ if (error.code !== "EEXIST")
1825
+ throw error;
1826
+ }
1827
+ let safeMetadata = false;
1828
+ try {
1829
+ const stat = lstatSync3(target);
1830
+ safeMetadata = !stat.isSymbolicLink() && stat.isFile() && (stat.mode & 511) === 384;
1831
+ } catch {}
1832
+ const existing = safeMetadata ? readBounded2(target) : null;
1833
+ if (existing?.ok && existing.text === payload)
1834
+ return;
1835
+ const detail = existing === null ? "unsafe metadata" : existing.ok ? "different content" : `unreadable content (${existing.reason})`;
1836
+ throw new Error(`${target}: observed an existing receipt with ${detail}, expected none or a non-symlink regular 0600 file with byte-identical content`);
1837
+ }
1838
+ function writeReceipt(receipt, directory, options) {
1839
+ const validation = validateReceipt(receipt);
1840
+ if (!validation.ok)
1841
+ throw new Error(`refusing to persist an invalid receipt: ${validation.reason}`);
1842
+ const into = resolve3(directory ?? receiptDirectory(process.env, receipt.repo.key));
1843
+ mkdirSync4(into, { recursive: true, mode: 448 });
1844
+ let directoryFd;
1845
+ try {
1846
+ directoryFd = openSync3(into, constants3.O_RDONLY | constants3.O_DIRECTORY | constants3.O_NOFOLLOW);
1847
+ } catch {
1848
+ throw new Error(`${into}: observed an unsafe receipt directory, expected a non-symlink directory`);
1849
+ }
1850
+ try {
1851
+ const stat = fstatSync2(directoryFd);
1852
+ if (!stat.isDirectory()) {
1853
+ throw new Error(`${into}: observed a non-directory, expected a non-symlink directory`);
1854
+ }
1855
+ fchmodSync(directoryFd, 448);
1856
+ } finally {
1857
+ closeSync3(directoryFd);
1858
+ }
1859
+ const targetName = `${receipt.receiptId}.json`;
1860
+ const target = join5(into, targetName);
1861
+ const payload = `${JSON.stringify(receipt, null, 2)}
1862
+ `;
1863
+ const payloadBytes = Buffer.byteLength(payload, "utf8");
1864
+ if (payloadBytes > MAX_RECEIPT_BYTES) {
1865
+ throw new Error(`refusing to persist an oversized receipt: observed ${payloadBytes} serialised bytes, expected at most ${MAX_RECEIPT_BYTES} (the reader's limit)`);
1866
+ }
1867
+ const nextName = options?.tempName ?? (() => `.${receipt.receiptId}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
1868
+ let temporary = "";
1869
+ let fd;
1870
+ for (let attempt = 1;fd === undefined; attempt += 1) {
1871
+ const temporaryName = nextName();
1872
+ if (typeof temporaryName !== "string" || temporaryName === "" || temporaryName === "." || temporaryName === ".." || temporaryName === targetName || temporaryName.includes("/") || temporaryName.includes("\\") || temporaryName.includes("\x00")) {
1873
+ throw new Error(`temporary file: observed ${show(temporaryName)}, expected a safe basename distinct from ${JSON.stringify(targetName)}`);
1874
+ }
1875
+ temporary = join5(into, temporaryName);
1876
+ try {
1877
+ fd = openSync3(temporary, "wx", 384);
1878
+ } catch (error) {
1879
+ if (error.code !== "EEXIST")
1880
+ throw error;
1881
+ if (attempt >= MAX_TEMP_ATTEMPTS) {
1882
+ throw new Error(`temporary file: observed ${attempt} name collisions in ${into}, expected a free name`);
1883
+ }
1884
+ }
1885
+ }
1886
+ try {
1887
+ fchmodSync(fd, 384);
1888
+ writeFileSync4(fd, payload);
1889
+ closeSync3(fd);
1890
+ fd = undefined;
1891
+ publish(temporary, target, payload);
1892
+ } catch (error) {
1893
+ if (fd !== undefined) {
1894
+ try {
1895
+ closeSync3(fd);
1896
+ } catch {}
1897
+ }
1898
+ try {
1899
+ unlinkSync2(temporary);
1900
+ } catch {}
1901
+ throw error;
1902
+ }
1903
+ try {
1904
+ unlinkSync2(temporary);
1905
+ } catch {}
1906
+ return target;
1907
+ }
1908
+ function readReceipt(path) {
1909
+ const canonicalPath = resolve3(path);
1910
+ if (path !== canonicalPath) {
1911
+ return refuse("path", path, `the canonical receipt path ${canonicalPath}`);
1912
+ }
1913
+ const name = basename2(path);
1914
+ if (!RECEIPT_FILE.test(name)) {
1915
+ return refuse("path", path, "a canonical receiptId.json basename");
1916
+ }
1917
+ const read = readBounded2(path);
1918
+ if (!read.ok)
1919
+ return read;
1920
+ let parsed;
1921
+ try {
1922
+ parsed = JSON.parse(read.text);
1923
+ } catch {
1924
+ return refuse("path", `${path} (unparseable)`, "a JSON object");
1925
+ }
1926
+ const validation = validateReceipt(parsed);
1927
+ if (!validation.ok)
1928
+ return validation;
1929
+ const expected = `${validation.receipt.receiptId}.json`;
1930
+ if (name !== expected) {
1931
+ return refuse("path", name, `${expected} from the payload receiptId`);
1932
+ }
1933
+ return validation;
1934
+ }
1935
+ function isNewer(a, b) {
1936
+ if (a.epoch !== b.epoch)
1937
+ return a.epoch > b.epoch;
1938
+ return a.name > b.name;
1939
+ }
1940
+ function keepNewest(kept, candidate) {
1941
+ let low = 0;
1942
+ let high = kept.length;
1943
+ while (low < high) {
1944
+ const mid = low + high >>> 1;
1945
+ const at = kept[mid];
1946
+ if (at !== undefined && isNewer(at, candidate))
1947
+ low = mid + 1;
1948
+ else
1949
+ high = mid;
1950
+ }
1951
+ kept.splice(low, 0, candidate);
1952
+ }
1953
+ function newestReceipts(directory) {
1954
+ let dir;
1955
+ try {
1956
+ dir = opendirSync(directory);
1957
+ } catch {
1958
+ return [];
1959
+ }
1960
+ const kept = [];
1961
+ try {
1962
+ for (let entry = dir.readSync();entry !== null; entry = dir.readSync()) {
1963
+ if (!entry.isFile() || !RECEIPT_FILE.test(entry.name))
1964
+ continue;
1965
+ const result = readReceipt(join5(directory, entry.name));
1966
+ if (!result.ok)
1967
+ continue;
1968
+ if (kept.length >= MAX_LISTED_RECEIPTS) {
1969
+ throw new Error(`receipt directory scan exceeds cap of ${MAX_LISTED_RECEIPTS} valid receipts: ${directory}`);
1970
+ }
1971
+ keepNewest(kept, {
1972
+ epoch: epochOf(entry.name),
1973
+ name: entry.name,
1974
+ receipt: result.receipt
1975
+ });
1976
+ }
1977
+ } finally {
1978
+ try {
1979
+ dir.closeSync();
1980
+ } catch {}
1981
+ }
1982
+ return kept.map((candidate) => candidate.receipt);
1983
+ }
1984
+ function listReceipts(directory, filter) {
1985
+ const receipts = [];
1986
+ for (const receipt of newestReceipts(directory)) {
1987
+ if (filter?.pr !== undefined && receipt.pr.number !== filter.pr)
1988
+ continue;
1989
+ if (filter?.branch !== undefined && receipt.branch.name !== filter.branch)
1990
+ continue;
1991
+ receipts.push(receipt);
1992
+ }
1993
+ return receipts;
1994
+ }
1995
+
1996
+ // plugins/delivery/opencode/src/target-repo.ts
1997
+ import { resolve as resolve4 } from "path";
1998
+ async function remotePaths(read, cwd) {
1999
+ const listed = await read(cwd, ["remote"]);
2000
+ if (listed === null)
2001
+ return [];
2002
+ const remotes = [];
2003
+ for (const name of listed.split(`
2004
+ `).filter((line) => REMOTE_NAME.test(line))) {
2005
+ const printed = await read(cwd, ["remote", "get-url", name]);
2006
+ const url = printed === null ? null : singleRemoteRecord(printed);
2007
+ const target = url === null ? null : forgeTarget(url);
2008
+ const raw = url === null ? null : repoPathFromRemote(url);
2009
+ remotes.push({ name, path: target === null || raw === null ? null : normalizeRepoPath(target.forge, raw) });
2010
+ }
2011
+ return remotes;
2012
+ }
2013
+ function cloneInput(input) {
2014
+ for (const field of ["repoPath", "worktree"]) {
2015
+ const value = input[field]?.trim();
2016
+ if (value !== undefined && value !== "")
2017
+ return { field, value };
2018
+ }
2019
+ return null;
2020
+ }
2021
+ function missingCloneReason(repo, sessionRepos) {
2022
+ const session = sessionRepos.length === 0 ? "none" : sessionRepos.map((path) => JSON.stringify(path)).join(", ");
2023
+ return `repo: observed ${JSON.stringify(repo)}, expected the session's repository (${session}) or a local clone of it: pass \`worktree\` (a worktree of ${repo}) or \`repoPath\` (a checkout of ${repo}); nothing was read from it, merged or written`;
2024
+ }
2025
+ function cloneMismatchReason(repo, field, path, remotes) {
2026
+ const seen = remotes.map((remote) => `${remote.name}=${remote.path ?? "none"}`).join(", ");
2027
+ return `${field}: observed ${JSON.stringify(path)} whose remotes are ${seen === "" ? "absent" : seen}, expected one naming ${JSON.stringify(repo)}; nothing was merged or written`;
2028
+ }
2029
+ function notACloneReason(field, path) {
2030
+ return `${field}: observed ${JSON.stringify(path)}, expected the path of an existing Git checkout of the requested repo; nothing was merged or written`;
2031
+ }
2032
+ async function retargetRepository(input, sessionCwd, read) {
2033
+ const raw = input.repo?.trim() ?? "";
2034
+ const repo = raw === "" ? null : normalizeRepoPath("gitlab", raw);
2035
+ if (repo === null) {
2036
+ return input.repoPath?.trim() ? { reason: `repoPath: observed ${JSON.stringify(input.repoPath)} without repo, expected repo as "<owner>/<name>" of that checkout` } : { cwd: sessionCwd, retargeted: false };
2037
+ }
2038
+ const session = await remotePaths(read, sessionCwd);
2039
+ if (session.some((remote) => remote.path === repo))
2040
+ return { cwd: sessionCwd, retargeted: false };
2041
+ const clone = cloneInput(input);
2042
+ if (clone === null) {
2043
+ const names = session.flatMap((remote) => remote.path === null ? [] : [remote.path]);
2044
+ return { reason: missingCloneReason(repo, names) };
2045
+ }
2046
+ const dir = resolve4(sessionCwd, clone.value);
2047
+ const printed = await read(dir, REPOSITORY_OBSERVATION_ARGS);
2048
+ const context = printed === null ? null : await repositoryContext(dir, (argv) => argv.length === REPOSITORY_OBSERVATION_ARGS.length && argv.every((part, index) => part === REPOSITORY_OBSERVATION_ARGS[index]) ? printed : null);
2049
+ if (context === null)
2050
+ return { reason: notACloneReason(clone.field, dir) };
2051
+ const remotes = await remotePaths(read, dir);
2052
+ if (!remotes.some((remote) => remote.path === repo)) {
2053
+ return { reason: cloneMismatchReason(repo, clone.field, dir, remotes) };
2054
+ }
2055
+ return { cwd: context.ledger.root, retargeted: true, commonDir: context.commonDir };
2056
+ }
2057
+
2058
+ // plugins/delivery/opencode/src/cleanup.ts
2059
+ var CLEANUP_BOUNDS = {
2060
+ refReadMs: 5000,
2061
+ treeScanMs: 60000,
2062
+ bdShowMs: 120000,
2063
+ mutationMs: 600000
2064
+ };
2065
+ var MAX_CLI_JSON_BYTES = 1024 * 1024;
2066
+ var MAX_DIRTY_PATHS = 8;
2067
+ var LOCAL_REF_PREFIX = "refs/heads/";
2068
+ var PR_FIELDS = "number,url,state,baseRefName,headRefName,headRefOid,mergeCommit,mergedAt";
2069
+ function removalRoute(listed, target, canonical = (path) => physicalPath(path) ?? path) {
2070
+ const want = canonical(target);
2071
+ return listed.some((entry) => canonical(entry.directory) === want) ? "host" : "git";
2072
+ }
2073
+ function targetAbsence(disk, registration) {
2074
+ if (disk === "present" || registration === "present")
2075
+ return "present";
2076
+ return disk === "absent" && registration === "absent" ? "absent" : "unknown";
2077
+ }
2078
+ function show2(value) {
2079
+ if (typeof value === "string")
2080
+ return JSON.stringify(value);
2081
+ if (value === undefined)
2082
+ return "missing";
2083
+ try {
2084
+ return JSON.stringify(value);
2085
+ } catch {
2086
+ return String(value);
2087
+ }
2088
+ }
2089
+ function refuse2(field, observed, expected) {
2090
+ return { ok: false, reason: `${field}: observed ${show2(observed)}, expected ${expected}` };
2091
+ }
2092
+ function isFailure(value) {
2093
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2094
+ return false;
2095
+ const descriptor = Object.getOwnPropertyDescriptor(value, "ok");
2096
+ return descriptor !== undefined && "value" in descriptor && descriptor.value === false;
2097
+ }
2098
+ var MAX_LISTED_CANDIDATES = 10;
2099
+ function describeCandidates(candidates) {
2100
+ const shown = candidates.slice(0, MAX_LISTED_CANDIDATES).map((c) => {
2101
+ const state = c.receipt.worktree.removed ? "cleaned" : "uncleaned";
2102
+ return `pr ${c.receipt.pr.number} branch ${show2(c.receipt.branch.name)} ${state} receipt ${c.path}`;
2103
+ });
2104
+ const more = candidates.length > shown.length ? ` (+${candidates.length - shown.length} more)` : "";
2105
+ return `${shown.join("; ")}${more}`;
2106
+ }
2107
+ function describeSelector(selector, scope) {
2108
+ if (selector.pr !== undefined)
2109
+ return `pr ${selector.pr}`;
2110
+ if (selector.branch !== undefined)
2111
+ return `branch ${show2(selector.branch)}`;
2112
+ if (selector.worktree !== undefined)
2113
+ return `worktree ${show2(selector.worktree)}`;
2114
+ if (selector.repo !== undefined)
2115
+ return `repo ${show2(selector.repo)}`;
2116
+ return scope;
2117
+ }
2118
+ function selectReceipt(candidates, selector, scope = "this repository") {
2119
+ const seen = new Set;
2120
+ let pool = candidates.filter((c) => {
2121
+ const key = `${c.receipt.repo.nameWithOwner}#${c.receipt.pr.number}`;
2122
+ if (seen.has(key))
2123
+ return false;
2124
+ seen.add(key);
2125
+ return true;
2126
+ });
2127
+ if (selector.repo !== undefined)
2128
+ pool = pool.filter((c) => c.receipt.repo.nameWithOwner === selector.repo);
2129
+ const explicit = selector.pr !== undefined || selector.branch !== undefined || selector.worktree !== undefined;
2130
+ if (!explicit && selector.head === undefined) {
2131
+ const open = pool.filter((c) => !c.receipt.worktree.removed);
2132
+ if (open.length > 0)
2133
+ pool = open;
2134
+ }
2135
+ if (selector.pr !== undefined)
2136
+ pool = pool.filter((c) => c.receipt.pr.number === selector.pr);
2137
+ if (selector.branch !== undefined)
2138
+ pool = pool.filter((c) => c.receipt.branch.name === selector.branch);
2139
+ if (selector.worktree !== undefined) {
2140
+ const want = resolve5(selector.worktree);
2141
+ pool = pool.filter((c) => c.receipt.worktree.path !== null && resolve5(c.receipt.worktree.path) === want);
2142
+ }
2143
+ const head = selector.head;
2144
+ if (head !== undefined && (pool.length > 1 || !explicit)) {
2145
+ const byOid = pool.filter((c) => c.receipt.pr.headRefOid === head.oid);
2146
+ pool = byOid.length > 0 ? byOid : pool.filter((c) => c.receipt.branch.name === head.branch);
2147
+ }
2148
+ const [only] = pool;
2149
+ if (pool.length === 1 && only !== undefined)
2150
+ return { ok: true, candidate: only };
2151
+ const listing = candidates.length === 0 ? "no receipts" : `candidates: ${describeCandidates(candidates)}`;
2152
+ if (pool.length === 0) {
2153
+ return refuse2("receipt", null, `the newest validated receipt for ${describeSelector(selector, scope)}; ${listing}`);
2154
+ }
2155
+ return refuse2("receipt", `${pool.length} matching receipts`, `exactly one: pass receipt, pr or branch to choose; ${describeCandidates(pool)}`);
2156
+ }
2157
+ function removalReport(receipt, path, target, facts) {
2158
+ const removed = facts.worktreeRemoved ? [`worktree ${path}`] : [];
2159
+ const skipped = [];
2160
+ const branch = receipt.branch.name;
2161
+ if (facts.localRefDeleted)
2162
+ removed.push(`local branch ${branch}`);
2163
+ else if (facts.localRefPlan === "absent")
2164
+ skipped.push(`local branch ${branch} was already gone`);
2165
+ else if (facts.localRefPlan === "moved")
2166
+ skipped.push(`local branch ${branch} left in place: it no longer points at the reviewed head`);
2167
+ if (!target.detached && target.branch !== null && target.branch !== `${LOCAL_REF_PREFIX}${branch}`) {
2168
+ skipped.push(`branch ${target.branch.slice(LOCAL_REF_PREFIX.length)} (the worktree's own) left in place`);
2169
+ }
2170
+ return { removed, skipped: [...skipped, ...facts.unfinished] };
2171
+ }
2172
+ var withNotes = (report, notes) => notes.length === 0 ? report : { ...report, skipped: [...report.skipped, ...notes] };
2173
+ function acceptWorktree(record, receipt) {
2174
+ const failure = compare("worktree.HEAD", record.head, receipt.pr.headRefOid);
2175
+ if (failure !== null)
2176
+ return failure;
2177
+ if (record.detached || record.branch === null)
2178
+ return { ok: true, branch: "detached" };
2179
+ return { ok: true, branch: record.branch === `${LOCAL_REF_PREFIX}${receipt.branch.name}` ? "same" : "renamed" };
2180
+ }
2181
+ function stashBranches(receiptBranch, target) {
2182
+ if (target.detached || target.branch === null)
2183
+ return [receiptBranch, DETACHED_STASH_BRANCH];
2184
+ const own = target.branch.slice(LOCAL_REF_PREFIX.length);
2185
+ return own === receiptBranch ? [receiptBranch] : [receiptBranch, own];
2186
+ }
2187
+ var DETACHED_STASH_BRANCH = "(no branch)";
2188
+ function planLocalRef(observedOid, reviewedOid) {
2189
+ if (observedOid === null)
2190
+ return "absent";
2191
+ return observedOid === reviewedOid ? "delete" : "moved";
2192
+ }
2193
+ function commandLabel(argv) {
2194
+ return argv.map((value) => JSON.stringify(value)).join(" ");
2195
+ }
2196
+ function completed(result) {
2197
+ return result.ok && result.exitCode === 0 && result.error === undefined;
2198
+ }
2199
+ function commandFailure(field, argv, result, expected) {
2200
+ const exit = result.exitCode === null ? "no exit status" : `exit ${result.exitCode}`;
2201
+ const error = result.error === undefined ? "" : `, error ${result.error}`;
2202
+ const stderr = result.stderr.trim() === "" ? "" : `, stderr ${result.stderr.trim().slice(0, 400)}`;
2203
+ return refuse2(field, `${commandLabel(argv)} (${exit}${error}${stderr})`, expected);
2204
+ }
2205
+ var DELETING_HINT = /--force|-f -f|\s-D\b/;
2206
+ function gitMessage(text) {
2207
+ const first = (text.trim().split(/\r?\n/)[0] ?? "").replace(/[,;]\s*use .*$/i, "").trim();
2208
+ const hint = DELETING_HINT.exec(first);
2209
+ return (hint === null ? first : `${first.slice(0, hint.index).trim()} \u2026`).slice(0, 400);
2210
+ }
2211
+ var MUTATION_ENV = { LC_ALL: "C" };
2212
+ var CLEAN_CHECK_REFUSAL = /^fatal: '.*' contains modified or untracked files(?:,|$)/m;
2213
+ function mutationFailure(field, argv, result) {
2214
+ const exit = result.exitCode === null ? "no exit status" : `exit ${result.exitCode}`;
2215
+ const error = result.error === undefined ? "" : `, error ${result.error}`;
2216
+ const message = gitMessage(result.stderr);
2217
+ return refuse2(field, `${commandLabel(argv)} (${exit}${error}${message === "" ? "" : `, stderr ${message}`})`, "exit 0");
2218
+ }
2219
+ function own(holder, key) {
2220
+ const descriptor = Object.getOwnPropertyDescriptor(holder, key);
2221
+ if (descriptor?.enumerable !== true || !("value" in descriptor))
2222
+ return;
2223
+ return descriptor.value;
2224
+ }
2225
+ function record(value) {
2226
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2227
+ }
2228
+ function text2(holder, key) {
2229
+ const value = own(holder, key);
2230
+ return typeof value === "string" && value !== "" ? value : null;
2231
+ }
2232
+ function integer(holder, key) {
2233
+ const value = own(holder, key);
2234
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
2235
+ }
2236
+ function parseJsonObject(field, result) {
2237
+ if (!completed(result))
2238
+ return commandFailure(field, [], result, "a successful bounded forge read");
2239
+ if (Buffer.byteLength(result.stdout) > MAX_CLI_JSON_BYTES) {
2240
+ return refuse2(field, `JSON over ${MAX_CLI_JSON_BYTES} bytes`, `at most ${MAX_CLI_JSON_BYTES} bytes`);
2241
+ }
2242
+ let parsed;
2243
+ try {
2244
+ parsed = JSON.parse(result.stdout);
2245
+ } catch {
2246
+ return refuse2(field, "unparseable JSON", "a JSON object from the forge");
2247
+ }
2248
+ return record(parsed) ?? refuse2(field, parsed, "a JSON object from the forge");
2249
+ }
2250
+ function normalizedOid(value) {
2251
+ if (typeof value !== "string")
2252
+ return null;
2253
+ const oid = value.trim().toLowerCase();
2254
+ return oid === "" ? null : oid;
2255
+ }
2256
+ async function resolveRemoteIdentity(receipt, run, cwd, forgeEnv, env, refReadMs, pin) {
2257
+ const remote = receipt.repo.remote;
2258
+ if (!REMOTE_NAME.test(remote))
2259
+ return refuse2("repo.remote", remote, "a git remote name");
2260
+ const argv = ["git", ...SAFE_GIT_ARGS, "remote", "get-url", remote];
2261
+ const expected = `exactly one URL record for the configured remote ${remote} in ${cwd}`;
2262
+ const result = await run(argv, { cwd, timeoutMs: refReadMs, env: { ...gitObservationEnvironment(env), ...pin } });
2263
+ if (!completed(result))
2264
+ return commandFailure("repo.remote", argv, result, expected);
2265
+ const remoteText = singleRemoteRecord(result.stdout);
2266
+ if (remoteText === null)
2267
+ return refuse2("repo.remote", "malformed Git remote output", expected);
2268
+ const target = forgeTarget(remoteText);
2269
+ const remoteUrl = redactRemote(remoteText);
2270
+ if (target === null) {
2271
+ return refuse2("repo.forge", `"unknown" for remote ${remote} at ${show2(remoteUrl)}`, '"github" or "gitlab"');
2272
+ }
2273
+ const forgeFailure = compare("repo.forge", target.forge, receipt.repo.forge);
2274
+ if (forgeFailure !== null)
2275
+ return forgeFailure;
2276
+ const fromRemote = repoPathFromRemote(remoteText);
2277
+ const nameWithOwner = fromRemote === null ? null : normalizeRepoPath(target.forge, fromRemote);
2278
+ if (nameWithOwner === null) {
2279
+ const shape = target.forge === "github" ? 'exactly "<owner>/<name>"' : 'a bounded "<group>/.../<project>" path';
2280
+ return refuse2("repo.nameWithOwner", fromRemote, `${shape} from remote ${remote} at ${show2(remoteUrl)}`);
2281
+ }
2282
+ const identityFailure = compare("repo.nameWithOwner", nameWithOwner, receipt.repo.nameWithOwner);
2283
+ if (identityFailure !== null)
2284
+ return identityFailure;
2285
+ const cliRepo = `${target.canonicalHost}/${nameWithOwner}`;
2286
+ const commandEnv = Object.assign(Object.create(null), forgeEnv, target.forge === "github" ? { GH_HOST: target.canonicalHost } : { GITLAB_HOST: target.canonicalHost, GITLAB_API_HOST: target.canonicalHost });
2287
+ return { forge: target.forge, nameWithOwner, cliRepo, remoteUrl: remoteText, env: commandEnv };
2288
+ }
2289
+ async function githubObservation(receipt, identity, run) {
2290
+ const argv = ["gh", "pr", "view", String(receipt.pr.number), "--repo", identity.cliRepo, "--json", PR_FIELDS];
2291
+ const method = argv.slice(0, 3).join(" ");
2292
+ const result = await run(argv, { timeoutMs: FORGE_TIMEOUT_MS, env: identity.env });
2293
+ if (!completed(result))
2294
+ return commandFailure("pr", argv, result, "a successful bounded GitHub pull-request read");
2295
+ const root = parseJsonObject("pr", result);
2296
+ if (isFailure(root))
2297
+ return root;
2298
+ const mergeCommit = record(own(root, "mergeCommit"));
2299
+ return {
2300
+ number: integer(root, "number") ?? -1,
2301
+ url: text2(root, "url") ?? "",
2302
+ state: text2(root, "state") ?? "",
2303
+ baseRefName: text2(root, "baseRefName") ?? "",
2304
+ headRefName: text2(root, "headRefName") ?? "",
2305
+ headRefOid: text2(root, "headRefOid") ?? "",
2306
+ mergeCommitOid: mergeCommit === null ? null : normalizedOid(own(mergeCommit, "oid")),
2307
+ mergedAt: text2(root, "mergedAt"),
2308
+ method
2309
+ };
2310
+ }
2311
+ async function gitlabObservation(receipt, identity, run) {
2312
+ const argv = ["glab", "mr", "view", String(receipt.pr.number), "--repo", identity.cliRepo, "--output", "json"];
2313
+ const method = argv.slice(0, 3).join(" ");
2314
+ const result = await run(argv, { timeoutMs: FORGE_TIMEOUT_MS, env: identity.env });
2315
+ if (!completed(result))
2316
+ return commandFailure("pr", argv, result, "a successful bounded GitLab merge-request read");
2317
+ const root = parseJsonObject("pr", result);
2318
+ if (isFailure(root))
2319
+ return root;
2320
+ const mergeCommit = normalizedOid(own(root, "merge_commit_sha"));
2321
+ return {
2322
+ number: integer(root, "iid") ?? -1,
2323
+ url: text2(root, "web_url") ?? "",
2324
+ state: text2(root, "state") ?? "",
2325
+ baseRefName: text2(root, "target_branch") ?? "",
2326
+ headRefName: text2(root, "source_branch") ?? "",
2327
+ headRefOid: text2(root, "sha") ?? "",
2328
+ mergeCommitOid: mergeCommit ?? normalizedOid(own(root, "squash_commit_sha")),
2329
+ mergedAt: text2(root, "merged_at"),
2330
+ method
2331
+ };
2332
+ }
2333
+ async function observePullRequest(receipt, run = runCli, cwd = receipt.repo.canonicalRoot, env = process.env, refReadMs = CLEANUP_BOUNDS.refReadMs, pin) {
2334
+ const identity = await resolveRemoteIdentity(receipt, run, cwd, forgeEnvironment(env), env, refReadMs, pin);
2335
+ if (isFailure(identity))
2336
+ return identity;
2337
+ const pr = identity.forge === "github" ? await githubObservation(receipt, identity, run) : await gitlabObservation(receipt, identity, run);
2338
+ return isFailure(pr) ? pr : { identity, pr };
2339
+ }
2340
+ function compare(field, observed, expected) {
2341
+ return observed === expected ? null : refuse2(field, observed, `receipt value ${show2(expected)}`);
2342
+ }
2343
+ function verifyObservation(receipt, observed) {
2344
+ const observedState = observed.state.trim().toUpperCase();
2345
+ const receiptState = receipt.pr.state.trim().toUpperCase();
2346
+ const comparisons = [
2347
+ ["pr.number", observed.number, receipt.pr.number],
2348
+ ["pr.url", observed.url, receipt.pr.url],
2349
+ ["pr.state", observedState, "MERGED"],
2350
+ ["receipt.pr.state", receiptState, "MERGED"],
2351
+ ["pr.baseRefName", observed.baseRefName, receipt.pr.baseRefName],
2352
+ ["pr.headRefName", observed.headRefName, receipt.pr.headRefName],
2353
+ ["pr.headRefOid", observed.headRefOid, receipt.pr.headRefOid],
2354
+ ["pr.mergeCommitOid", observed.mergeCommitOid, receipt.pr.mergeCommitOid],
2355
+ ["pr.mergedAt", observed.mergedAt, receipt.pr.mergedAt]
2356
+ ];
2357
+ for (const [field, actual, expected] of comparisons) {
2358
+ const failure = compare(field, actual, expected);
2359
+ if (failure !== null)
2360
+ return failure;
2361
+ }
2362
+ if (observed.headRefName !== receipt.branch.name) {
2363
+ return refuse2("pr.headRefName", observed.headRefName, `receipt branch.name ${show2(receipt.branch.name)}`);
2364
+ }
2365
+ return null;
2366
+ }
2367
+ function untrustedDirectory(proof) {
2368
+ return refuse2("receipt.directory", `${proof.at} (${proof.reason})`, "an existing non-symlink directory at and below the receipt root");
2369
+ }
2370
+ function canonicalReceiptPath(raw, cwd, directory) {
2371
+ const supplied = resolve5(cwd, raw);
2372
+ let parent;
2373
+ try {
2374
+ parent = realpathSync4(dirname4(supplied));
2375
+ } catch {
2376
+ parent = null;
2377
+ }
2378
+ if (parent !== directory)
2379
+ return refuse2("receipt.path", supplied, `a direct entry under ${show2(directory)}`);
2380
+ const target = join6(directory, basename3(supplied));
2381
+ let stat;
2382
+ try {
2383
+ stat = lstatSync4(target);
2384
+ } catch {
2385
+ return refuse2("receipt.path", target, "an existing canonical non-symlink receipt file");
2386
+ }
2387
+ if (stat.isSymbolicLink() || !stat.isFile()) {
2388
+ return refuse2("receipt.path", target, "a canonical non-symlink regular receipt file");
2389
+ }
2390
+ return target;
2391
+ }
2392
+ var FOREIGN_HINT = "a worktree of a repository other than this session's is never read from here: run delivery_cleanup from a session in that repository";
2393
+ function foreignRepository() {
2394
+ return refuse2("worktree.owner", "a receipt or worktree of a repository other than this session's", "delivery_cleanup run from a session in that repository; a checkout of another repository is untrusted, so nothing was read or removed");
2395
+ }
2396
+ async function resolveReceipt(params, cwd, env, refReadMs, git, head) {
2397
+ const key = await repoKey(cwd, git, refReadMs);
2398
+ if (key === null) {
2399
+ return {
2400
+ tag: "refused",
2401
+ failure: refuse2("repo.key", null, "a repository key derived from the current Git common directory")
2402
+ };
2403
+ }
2404
+ const proof = provenReceiptDirectory(env, key);
2405
+ const directory = proof.directory;
2406
+ let receipt = null;
2407
+ let receiptPath = null;
2408
+ if (params.receipt !== undefined) {
2409
+ const named = basename3(dirname4(resolve5(cwd, params.receipt)));
2410
+ if (/^[0-9a-f]{16}$/.test(named) && named !== key)
2411
+ return { tag: "refused", failure: foreignRepository() };
2412
+ if (!proof.ok)
2413
+ return { tag: "refused", failure: untrustedDirectory(proof) };
2414
+ const path = canonicalReceiptPath(params.receipt, cwd, directory);
2415
+ if (typeof path !== "string")
2416
+ return { tag: "refused", failure: path };
2417
+ const read = readReceipt(path);
2418
+ if (!read.ok)
2419
+ return { tag: "refused", failure: { ok: false, reason: read.reason } };
2420
+ receipt = read.receipt;
2421
+ receiptPath = path;
2422
+ } else {
2423
+ if (!proof.ok && proof.reason !== "absent")
2424
+ return { tag: "refused", failure: untrustedDirectory(proof) };
2425
+ const listed = proof.ok ? listReceipts(directory) : [];
2426
+ const candidates = listed.map((item) => ({ receipt: item, path: join6(directory, `${item.receiptId}.json`) }));
2427
+ const selection = selectReceipt(candidates, { pr: params.pr, branch: params.branch, worktree: params.worktree, repo: params.repo, head }, `repo.key ${key}`);
2428
+ if (!selection.ok) {
2429
+ const hint = params.worktree === undefined ? "" : `; ${FOREIGN_HINT}`;
2430
+ return { tag: "refused", failure: { ok: false, reason: `${selection.reason}${hint}` } };
2431
+ }
2432
+ receipt = selection.candidate.receipt;
2433
+ receiptPath = selection.candidate.path;
2434
+ }
2435
+ if (receipt === null) {
2436
+ return { tag: "refused", failure: refuse2("receipt", null, "a validated receipt") };
2437
+ }
2438
+ if (receiptPath === null)
2439
+ return {
2440
+ tag: "refused",
2441
+ failure: refuse2("receipt.path", null, "the canonical path for the selected validated receipt")
2442
+ };
2443
+ if (receipt.repo.key !== key) {
2444
+ return { tag: "refused", failure: refuse2("repo.key", receipt.repo.key, `current repository key ${key}`) };
2445
+ }
2446
+ if (receipt.worktree.path === null) {
2447
+ return { tag: "refused", failure: refuse2("worktree.path", null, "a linked-worktree path recorded by the receipt") };
2448
+ }
2449
+ return { tag: "resolved", receipt, path: receiptPath };
2450
+ }
2451
+ function verifyArguments(params, receipt) {
2452
+ const requested = [
2453
+ ["pr", params.pr, receipt.pr.number],
2454
+ ["branch", params.branch, receipt.branch.name],
2455
+ ["worktree", params.worktree, receipt.worktree.path],
2456
+ ["remote", params.remote, receipt.repo.remote],
2457
+ ["repo", params.repo, receipt.repo.nameWithOwner]
2458
+ ];
2459
+ for (const [field, supplied, expected] of requested) {
2460
+ if (supplied === undefined)
2461
+ continue;
2462
+ const failure = compare(field, supplied, expected);
2463
+ if (failure !== null)
2464
+ return failure;
2465
+ }
2466
+ return null;
2467
+ }
2468
+ async function runGit(run, cwd, args, timeoutMs, pin, extra = {}) {
2469
+ return run(["git", ...SAFE_GIT_ARGS, ...args], {
2470
+ cwd,
2471
+ timeoutMs,
2472
+ env: { ...gitObservationEnvironment(process.env), ...extra, ...pin }
2473
+ });
2474
+ }
2475
+ function worktreePathState(path) {
2476
+ let stat;
2477
+ try {
2478
+ stat = lstatSync4(path);
2479
+ } catch (error) {
2480
+ return error.code === "ENOENT" ? "absent" : "unsafe";
2481
+ }
2482
+ if (stat.isSymbolicLink() || !stat.isDirectory())
2483
+ return "unsafe";
2484
+ try {
2485
+ realpathSync4(path);
2486
+ return "directory";
2487
+ } catch {
2488
+ return "unsafe";
2489
+ }
2490
+ }
2491
+ var removalElsewhere = (path) => "the tree has only deleted tracked files: a removal is running or stopped part-way (another process outside " + "the delivery worktree lock, such as another harness's delivery plugin or another tool that removes worktrees " + `without the delivery lock, or an earlier cleanup that failed); this call removed nothing; inspect ${path} and save any changes in it`;
2492
+ function dirtyPaths(output) {
2493
+ return output.split(/\r?\n/).filter(Boolean).map((line) => line.length > 3 ? line.slice(3) : line).slice(0, MAX_DIRTY_PATHS);
2494
+ }
2495
+ var isDeletion = (line) => line.startsWith(" D") || line.startsWith("D ");
2496
+ async function treeStatus(target, run, timeoutMs) {
2497
+ const status = await runGit(run, target.cwd, ["status", "--porcelain"], timeoutMs, target.pin);
2498
+ return completed(status) ? status.stdout.split(/\r?\n/).filter(Boolean) : null;
2499
+ }
2500
+ var statusSummary = (lines) => show2({ paths: dirtyPaths(lines.join(`
2501
+ `)), total: lines.length });
2502
+ var changedAfterProof = (lines) => `the tree changed after the last proof (${statusSummary(lines)}); nothing was removed; save those changes before cleaning up again`;
2503
+ var inspectAdvice = (path, left) => `inspect ${path} and save any changes in it before removing what is left${left !== null && left.length > 0 ? ` (git status there: ${statusSummary(left)})` : ""}`;
2504
+ async function verifyCleanTarget(path, run, timeoutMs, pin, branches = []) {
2505
+ const state = worktreePathState(path);
2506
+ if (state !== "directory")
2507
+ return refuse2("worktree.path", `${path} (${state})`, "a present non-symlink directory");
2508
+ const argv = ["status", "--porcelain"];
2509
+ const result = await runGit(run, path, argv, timeoutMs, pin);
2510
+ if (!completed(result))
2511
+ return commandFailure("worktree.status", ["git", ...argv], result, "exit 0 with empty output");
2512
+ if (result.stdout !== "") {
2513
+ const all = result.stdout.split(/\r?\n/).filter(Boolean);
2514
+ const dirty = refuse2("worktree.status", { paths: dirtyPaths(result.stdout), total: all.length }, "no dirty paths (empty porcelain output)");
2515
+ return all.every((line) => line.startsWith(" D ")) ? { ok: false, reason: `${dirty.reason}; ${removalElsewhere(path)}` } : dirty;
2516
+ }
2517
+ const gitDir = pin?.GIT_DIR;
2518
+ if (gitDir === undefined)
2519
+ return refuse2("worktree.operation", path, "a verified git directory to read operation markers from");
2520
+ const operations = operationsInProgress(OPERATION_MARKERS.map((marker) => marker.name).filter((name) => existsSync2(resolve5(gitDir, name))));
2521
+ if (operations.length > 0)
2522
+ return refuse2("worktree.operation", operations, "no merge, rebase, cherry-pick, revert or bisect in progress");
2523
+ if (branches.length > 0) {
2524
+ const stashArgv = ["stash", "list", "--format=%gs"];
2525
+ const stash = await runGit(run, path, stashArgv, timeoutMs, pin);
2526
+ if (!completed(stash))
2527
+ return commandFailure("worktree.stash", ["git", ...stashArgv], stash, "exit 0");
2528
+ const entries = branches.flatMap((branch) => stashesOnBranch(stash.stdout, branch));
2529
+ if (entries.length > 0) {
2530
+ return refuse2("worktree.stash", entries.slice(0, MAX_DIRTY_PATHS), `no stash entries on ${branches.map(show2).join(" or ")}`);
2531
+ }
2532
+ }
2533
+ return null;
2534
+ }
2535
+ async function verifyPushed(path, run, refReadMs, pin) {
2536
+ const upstreamArgv = ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"];
2537
+ const upstream = await runGit(run, path, upstreamArgv, refReadMs, pin);
2538
+ if (upstream.error !== undefined || !upstream.ok) {
2539
+ return commandFailure("branch.upstream", ["git", ...upstreamArgv], upstream, "a completed upstream read");
2540
+ }
2541
+ if (upstream.exitCode !== 0 || upstream.stdout.trim() === "")
2542
+ return "pr-head";
2543
+ const countArgv = ["rev-list", "--count", "@{upstream}..HEAD"];
2544
+ const countResult = await runGit(run, path, countArgv, refReadMs, pin);
2545
+ if (!completed(countResult)) {
2546
+ return commandFailure("branch.unpushed", ["git", ...countArgv], countResult, "exit 0 and count 0");
2547
+ }
2548
+ const raw = countResult.stdout.trim();
2549
+ const count = /^[0-9]+$/.test(raw) ? Number(raw) : Number.NaN;
2550
+ if (!Number.isSafeInteger(count))
2551
+ return refuse2("branch.unpushed", raw, "a non-negative integer count");
2552
+ if (count !== 0)
2553
+ return refuse2("branch.unpushed", count, "0 commits above the upstream");
2554
+ return "upstream";
2555
+ }
2556
+ var LEDGER_SELECTORS = [
2557
+ "BEADS_DIR",
2558
+ "BEADS_DB",
2559
+ "BD_DB",
2560
+ "BD_SOCKET",
2561
+ "BEADS_DOLT_SHARED_SERVER",
2562
+ "HARNESS_BEADS_PIN"
2563
+ ];
2564
+ function withoutLedgerSelectors(env) {
2565
+ const rest = { ...env };
2566
+ for (const name of LEDGER_SELECTORS)
2567
+ delete rest[name];
2568
+ return rest;
2569
+ }
2570
+ function unwrapEnvelope(value) {
2571
+ const root = record(value);
2572
+ if (root === null || own(root, "schema_version") === undefined)
2573
+ return value;
2574
+ return own(root, "data");
2575
+ }
2576
+ async function verifyLedger(receipt, cwd, receiptPath, run, timeoutMs, refReadMs, git, env) {
2577
+ const classification = await canonicalLedger(cwd, git, refReadMs);
2578
+ if (classification === null) {
2579
+ return refuse2("beads.ledgerActive", `no ledger classification from ${cwd}`, "a repository whose canonical root can be resolved, so the receipt's ledger claim can be recomputed rather than trusted");
2580
+ }
2581
+ const landedSha = receipt.pr.mergeCommitOid ?? "missing";
2582
+ const nativeSteps = receipt.beads.ids.flatMap((id) => {
2583
+ const { update, close } = closeoutCommands(id, receipt.pr.number, landedSha, receiptPath);
2584
+ return [update, close];
2585
+ });
2586
+ if (classification.active !== receipt.beads.ledgerActive) {
2587
+ return {
2588
+ ok: false,
2589
+ reason: `beads.ledgerActive: observed ${receipt.beads.ledgerActive} stored in the receipt, expected ${classification.active}, recomputed at canonical root ${show2(classification.root)}; ${classification.active ? `this repository's ledger is active, so for each receipt bead in child-before-parent order run ${nativeSteps.join("; ")}, then delivery_cleanup` : `the receipt was written against a ledger this repository does not have, so nothing was removed because the canonical ledger classification disagreed with the receipt; to recover, run delivery_land for PR #${receipt.pr.number} again${receipt.worktree.path === null ? "" : ` with worktree ${show2(receipt.worktree.path)}`}, which proves the already-merged request without merging and writes a fresh receipt, then run delivery_cleanup with that new receipt`}`
2590
+ };
2591
+ }
2592
+ if (!classification.active)
2593
+ return null;
2594
+ const argv = ["bd", "show", ...receipt.beads.ids, "--json"];
2595
+ const result = await run(argv, {
2596
+ cwd: classification.root,
2597
+ timeoutMs,
2598
+ env: { ...withoutLedgerSelectors(env), BD_JSON_ENVELOPE: "1", BD_NO_PAGER: "1", BD_NON_INTERACTIVE: "1" }
2599
+ });
2600
+ if (!completed(result))
2601
+ return commandFailure("beads", argv, result, "a successful read-only bd show");
2602
+ if (Buffer.byteLength(result.stdout) > MAX_CLI_JSON_BYTES) {
2603
+ return refuse2("beads", `JSON over ${MAX_CLI_JSON_BYTES} bytes`, `at most ${MAX_CLI_JSON_BYTES} bytes`);
2604
+ }
2605
+ let parsed;
2606
+ try {
2607
+ parsed = unwrapEnvelope(JSON.parse(result.stdout));
2608
+ } catch {
2609
+ return refuse2("beads", "unparseable JSON", "an issue array from read-only bd show");
2610
+ }
2611
+ if (!Array.isArray(parsed))
2612
+ return refuse2("beads", parsed, "an issue array from read-only bd show");
2613
+ const rows = new Map;
2614
+ for (const item of parsed) {
2615
+ const issue = record(item);
2616
+ const id = issue === null ? null : text2(issue, "id");
2617
+ if (issue === null || id === null)
2618
+ return refuse2("beads", item, "issues with string ids");
2619
+ const prior = rows.get(id);
2620
+ if (prior !== undefined && !isDeepStrictEqual(prior, issue)) {
2621
+ return refuse2(`beads.${id}`, [prior, issue], "duplicate bd show rows for one bead id to be identical");
2622
+ }
2623
+ if (prior === undefined)
2624
+ rows.set(id, issue);
2625
+ }
2626
+ for (const id of receipt.beads.ids) {
2627
+ const issue = rows.get(id);
2628
+ const { update, close } = closeoutCommands(id, receipt.pr.number, landedSha, receiptPath);
2629
+ if (issue === undefined)
2630
+ return refuse2(`beads.${id}`, null, `a bead returned by bd show before ${update} then ${close}`);
2631
+ const status = text2(issue, "status");
2632
+ if (status !== "closed")
2633
+ return refuse2(`beads.${id}.status`, status, `"closed" after ${update} then ${close}`);
2634
+ const metadata = record(own(issue, "metadata"));
2635
+ const mergeSha = metadata === null ? undefined : own(metadata, "merge_sha");
2636
+ if (typeof mergeSha !== "string" || mergeSha !== receipt.pr.mergeCommitOid) {
2637
+ return refuse2(`beads.${id}.metadata.merge_sha`, mergeSha, `receipt pr.mergeCommitOid ${show2(receipt.pr.mergeCommitOid)} after ${update} then ${close}`);
2638
+ }
2639
+ }
2640
+ return null;
2641
+ }
2642
+ function parseWorktreeList(output) {
2643
+ const records = [];
2644
+ let current = null;
2645
+ for (const line of output.split(`
2646
+ `)) {
2647
+ if (line === "") {
2648
+ if (current !== null)
2649
+ records.push(current);
2650
+ current = null;
2651
+ continue;
2652
+ }
2653
+ if (line.startsWith("worktree ")) {
2654
+ if (current !== null)
2655
+ records.push(current);
2656
+ current = { path: line.slice(9), head: "", branch: null, detached: false, prunable: false };
2657
+ continue;
2658
+ }
2659
+ if (current === null)
2660
+ continue;
2661
+ if (line.startsWith("HEAD "))
2662
+ current.head = line.slice(5);
2663
+ else if (line.startsWith("branch "))
2664
+ current.branch = line.slice(7);
2665
+ else if (line === "detached")
2666
+ current.detached = true;
2667
+ else if (line.startsWith("prunable"))
2668
+ current.prunable = true;
2669
+ }
2670
+ if (current !== null)
2671
+ records.push(current);
2672
+ return records;
2673
+ }
2674
+ async function readWorktrees(cwd, run, refReadMs, pin) {
2675
+ const argv = ["worktree", "list", "--porcelain"];
2676
+ const result = await runGit(run, cwd, argv, refReadMs, pin);
2677
+ if (!completed(result))
2678
+ return commandFailure("worktree.list", ["git", ...argv], result, "exit 0 porcelain records");
2679
+ const records = parseWorktreeList(result.stdout);
2680
+ if (records.length === 0)
2681
+ return refuse2("worktree.list", [], "at least the repository's main worktree");
2682
+ const malformed = records.find((item) => item.path === "" || !isAbsolute2(item.path));
2683
+ if (malformed !== undefined)
2684
+ return refuse2("worktree.list.path", malformed.path, "a non-empty absolute path in every record");
2685
+ return records;
2686
+ }
2687
+ async function isForeignCheckout(path, cwd, records, run, refReadMs) {
2688
+ const real = physicalPath(path);
2689
+ if (real !== null && recordForTarget([...records], real) !== null)
2690
+ return false;
2691
+ const argv = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
2692
+ const result = await runGit(run, cwd, argv, refReadMs);
2693
+ const session = completed(result) ? physicalPath(result.stdout.trim()) : null;
2694
+ return session !== null && ["foreign", "unsafe"].includes(inspectCheckoutMarker(path, session));
2695
+ }
2696
+ function physicalPath(path) {
2697
+ return physical(path);
2698
+ }
2699
+ function invocationInsideTarget(cwd, target) {
2700
+ const invocation = physicalPath(cwd);
2701
+ const resolved = physicalPath(target);
2702
+ if (invocation === null || resolved === null)
2703
+ return false;
2704
+ return invocation === resolved || invocation.startsWith(`${resolved}${sep2}`);
2705
+ }
2706
+ function recordForTarget(records, expected) {
2707
+ for (const item of records) {
2708
+ if (physicalPath(item.path) === expected)
2709
+ return item;
2710
+ }
2711
+ return null;
2712
+ }
2713
+ function storedRecordForTarget(records, target) {
2714
+ const expected = resolve5(target);
2715
+ for (const item of records) {
2716
+ if (resolve5(item.path) === expected)
2717
+ return item;
2718
+ }
2719
+ return null;
2720
+ }
2721
+ function registeredRecord(records, target) {
2722
+ const canonical = (path) => {
2723
+ const full = resolve5(path);
2724
+ const real = physicalPath(full);
2725
+ if (real !== null)
2726
+ return real;
2727
+ const parent = physicalPath(dirname4(full));
2728
+ return parent === null ? full : join6(parent, basename3(full));
2729
+ };
2730
+ const expected = canonical(target);
2731
+ for (const item of records) {
2732
+ if (canonical(item.path) === expected)
2733
+ return item;
2734
+ }
2735
+ return null;
2736
+ }
2737
+ async function verifyTargetIdentity(receipt, cwd, run, refReadMs, git) {
2738
+ const path = receipt.worktree.path;
2739
+ const listed = await readWorktrees(cwd, run, refReadMs);
2740
+ if (!Array.isArray(listed))
2741
+ return listed;
2742
+ const main = listed[0];
2743
+ if (main === undefined)
2744
+ return refuse2("worktree.list", [], "a main worktree record");
2745
+ const physicalTarget = physicalPath(path);
2746
+ if (physicalTarget === null)
2747
+ return refuse2("worktree.path", path, "an exact live record in git worktree list --porcelain");
2748
+ if (physicalTarget === physicalPath(main.path))
2749
+ return refuse2("worktree.path", path, `a linked worktree other than main ${show2(main.path)}`);
2750
+ const target = recordForTarget(listed, physicalTarget);
2751
+ if (target === null && await isForeignCheckout(path, cwd, listed, run, refReadMs))
2752
+ return refuse2("worktree.path", path, "a worktree in the current repository");
2753
+ if (target === null || target.prunable)
2754
+ return refuse2("worktree.path", path, "an exact live record in git worktree list --porcelain");
2755
+ const common = (await repositoryContext(cwd, git, refReadMs))?.commonDir ?? null;
2756
+ const verdict = common === null ? { state: "unsafe" } : verifyCheckout(physicalTarget, common);
2757
+ if (verdict.state !== "same" || common === null) {
2758
+ return refuse2("worktree.marker", `${path} (.git ${verdict.state})`, "a regular .git file naming a directory under this repository's worktrees/ whose commondir is this repository; nothing was read in the worktree");
2759
+ }
2760
+ const accepted = acceptWorktree(target, receipt);
2761
+ if (!accepted.ok)
2762
+ return accepted;
2763
+ if (worktreePathState(physicalTarget) !== "directory" || worktreePathState(path) !== "directory") {
2764
+ return refuse2("worktree.path", `${path} (unsafe)`, "the listed non-symlink directory");
2765
+ }
2766
+ return { records: listed, target, main, common, pin: verdict.pin, cwd: physicalTarget };
2767
+ }
2768
+ async function verifyLocalRef(receipt, cwd, run, refReadMs, pin) {
2769
+ const presence = await localRefAbsence(cwd, receipt.branch.name, run, refReadMs, pin);
2770
+ if (presence === "unknown")
2771
+ return refuse2("branch.localRef", "unreadable", "a readable local ref state");
2772
+ if (presence === "absent")
2773
+ return planLocalRef(null, receipt.pr.headRefOid);
2774
+ const ref = `${LOCAL_REF_PREFIX}${receipt.branch.name}`;
2775
+ const argv = ["rev-parse", "--verify", ref];
2776
+ const result = await runGit(run, cwd, argv, refReadMs, pin);
2777
+ if (!completed(result))
2778
+ return commandFailure("branch.localRef", ["git", ...argv], result, `exit 0 and oid ${receipt.pr.headRefOid}`);
2779
+ return planLocalRef(result.stdout.trim(), receipt.pr.headRefOid);
2780
+ }
2781
+ async function revalidateBoundary(receipt, cwd, run, bounds, git) {
2782
+ const identity = await verifyTargetIdentity(receipt, cwd, run, bounds.refReadMs, git);
2783
+ if (isFailure(identity))
2784
+ return identity;
2785
+ const ref = await verifyLocalRef(receipt, cwd, run, bounds.refReadMs);
2786
+ if (isFailure(ref))
2787
+ return ref;
2788
+ const clean = await verifyCleanTarget(identity.cwd, run, bounds.treeScanMs, identity.pin, stashBranches(receipt.branch.name, identity.target));
2789
+ if (clean !== null)
2790
+ return clean;
2791
+ const pushed = await verifyPushed(identity.cwd, run, bounds.refReadMs, identity.pin);
2792
+ return isFailure(pushed) ? pushed : identity;
2793
+ }
2794
+ async function registrationAbsence(cwd, trustedPath, run, refReadMs, pin) {
2795
+ const listed = await readWorktrees(cwd, run, refReadMs, pin);
2796
+ if (!Array.isArray(listed))
2797
+ return "unknown";
2798
+ return storedRecordForTarget(listed, trustedPath) === null ? "absent" : "present";
2799
+ }
2800
+ function pathAbsence(path) {
2801
+ try {
2802
+ lstatSync4(path);
2803
+ return "present";
2804
+ } catch (error) {
2805
+ return error.code === "ENOENT" ? "absent" : "unknown";
2806
+ }
2807
+ }
2808
+ async function localRefAbsence(cwd, branch, run, refReadMs, pin) {
2809
+ const argv = ["show-ref", "--verify", "--quiet", `${LOCAL_REF_PREFIX}${branch}`];
2810
+ const result = await runGit(run, cwd, argv, refReadMs, pin);
2811
+ if (result.error !== undefined || !result.ok)
2812
+ return "unknown";
2813
+ if (result.exitCode === 0)
2814
+ return "present";
2815
+ if (result.exitCode === 1 && result.stdout === "" && result.stderr === "")
2816
+ return "absent";
2817
+ return "unknown";
2818
+ }
2819
+ function safeExecutionCwd(receipt, records, invocationCwd) {
2820
+ const target = physicalPath(receipt.worktree.path);
2821
+ const preferred = records.find((item) => item.branch === `${LOCAL_REF_PREFIX}${receipt.pr.baseRefName}` && physicalPath(item.path) !== target);
2822
+ if (preferred !== undefined && worktreePathState(preferred.path) === "directory")
2823
+ return preferred.path;
2824
+ const invocation = records.find((item) => physicalPath(item.path) === physicalPath(invocationCwd) && physicalPath(item.path) !== target);
2825
+ if (invocation !== undefined && worktreePathState(invocation.path) === "directory")
2826
+ return invocation.path;
2827
+ const main = records[0];
2828
+ return main !== undefined && physicalPath(main.path) !== target && worktreePathState(main.path) === "directory" ? main.path : null;
2829
+ }
2830
+ function markersStillBound(boundary, executionDir, executionPin) {
2831
+ const checks = [
2832
+ ["worktree.marker", boundary.cwd, boundary.pin],
2833
+ ["worktree.executionCwd", executionDir, executionPin]
2834
+ ];
2835
+ for (const [field, directory, pin] of checks) {
2836
+ const verdict = physicalPath(directory) === directory ? verifyCheckout(directory, boundary.common) : { state: "moved" };
2837
+ const same = verdict.state === "same" && verdict.pin.GIT_DIR === pin.GIT_DIR && verdict.pin.GIT_COMMON_DIR === pin.GIT_COMMON_DIR;
2838
+ if (!same) {
2839
+ return refuse2(field, `${directory} (.git ${verdict.state === "same" ? "names another admin directory" : verdict.state}) at the moment of removal`, "the marker proved before the final checks, unchanged when the removal starts; nothing was removed");
2840
+ }
2841
+ }
2842
+ return null;
2843
+ }
2844
+ function nextReceiptEpoch(receipt, now) {
2845
+ const observed = Math.trunc(now());
2846
+ const prior = Date.parse(receipt.emittedAt);
2847
+ return Math.max(observed, Number.isFinite(prior) ? prior + 1 : observed);
2848
+ }
2849
+ function branchDeleteArgs(branch) {
2850
+ return ["branch", "-d", "--", branch];
2851
+ }
2852
+ async function cleanupDelivery(params, sessionCwd, deps = {}) {
2853
+ const { repo: requested, repoPath, ...rest } = params;
2854
+ const repo = requested?.trim() === "" ? undefined : requested?.trim();
2855
+ if (repo === undefined && repoPath === undefined)
2856
+ return cleanupInRepository(rest, sessionCwd, deps);
2857
+ const refReadMs = { ...CLEANUP_BOUNDS, ...deps.bounds }.refReadMs;
2858
+ const run = (argv, options) => (deps.run ?? runCli)(argv, { ...options, signal: deps.signal });
2859
+ const read = async (at, argv) => {
2860
+ const result = await runGit(run, at, [...argv], refReadMs);
2861
+ return completed(result) ? result.stdout : null;
2862
+ };
2863
+ const target = await retargetRepository({ repo, repoPath, worktree: rest.worktree }, sessionCwd, read);
2864
+ if ("reason" in target)
2865
+ return { ok: false, reason: target.reason };
2866
+ if (!target.retargeted)
2867
+ return cleanupInRepository({ ...rest, repo }, target.cwd, deps);
2868
+ if (deps.coordinate === undefined)
2869
+ return { ok: false, reason: uncoordinatedReason(repo ?? "", target.cwd) };
2870
+ const coordination = await deps.coordinate({ common: target.commonDir, root: target.cwd });
2871
+ if (isFailure(coordination))
2872
+ return coordination;
2873
+ const { coordinate: _session, ...shared } = deps;
2874
+ return cleanupInRepository({ ...rest, repo }, target.cwd, {
2875
+ ...shared,
2876
+ proofSection: coordination.proofSection,
2877
+ removalSection: coordination.removalSection,
2878
+ finalCheck: coordination.finalCheck,
2879
+ afterRemoval: coordination.afterRemoval,
2880
+ host: coordination.host,
2881
+ authorize: coordination.authorize ?? deps.authorize
2882
+ });
2883
+ }
2884
+ function uncoordinatedReason(repo, root) {
2885
+ return `repo: observed ${JSON.stringify(repo.trim())}, a repository other than this session's, with no coordination given for its lane claims, holds and denials; run delivery_cleanup from a session in ${root}, or through the delivery tool, which coordinates there; nothing was removed`;
2886
+ }
2887
+ async function cleanupInRepository(params, cwd, deps) {
2888
+ const { signal } = deps;
2889
+ const bounds = { ...CLEANUP_BOUNDS, ...deps.bounds };
2890
+ const commit = deps.run ?? runCli;
2891
+ const run = (argv, options) => commit(argv, { ...options, signal });
2892
+ const observe = deps.git ?? spawnGit;
2893
+ const git = (argv, at, timeoutMs) => observe(argv, at, timeoutMs, signal);
2894
+ const now = deps.now ?? Date.now;
2895
+ const env = deps.env ?? process.env;
2896
+ const worktreeHead = async () => {
2897
+ if (params.receipt !== undefined || params.worktree === undefined || params.worktree.trim() === "")
2898
+ return;
2899
+ const listed = await readWorktrees(cwd, run, bounds.refReadMs);
2900
+ if (!Array.isArray(listed))
2901
+ return;
2902
+ const record = storedRecordForTarget(listed, resolve5(cwd, params.worktree.trim()));
2903
+ if (record === null)
2904
+ return;
2905
+ const branch = record.detached || record.branch === null ? null : record.branch.slice(LOCAL_REF_PREFIX.length);
2906
+ return { branch, oid: record.head };
2907
+ };
2908
+ const foreignWorktree = async () => {
2909
+ if (params.worktree === undefined || params.worktree.trim() === "")
2910
+ return false;
2911
+ const listed = await readWorktrees(cwd, run, bounds.refReadMs);
2912
+ return Array.isArray(listed) && await isForeignCheckout(resolve5(cwd, params.worktree.trim()), cwd, listed, run, bounds.refReadMs);
2913
+ };
2914
+ const alreadyCleaned = async (receipt, receiptPath) => {
2915
+ const target = receipt.worktree.path;
2916
+ const cleaned = receipt.worktree.removed;
2917
+ if (!cleaned && pathAbsence(target) !== "absent")
2918
+ return null;
2919
+ const listed = await readWorktrees(cwd, run, bounds.refReadMs);
2920
+ const disk = pathAbsence(target);
2921
+ const record = Array.isArray(listed) ? registeredRecord(listed, target) : null;
2922
+ const registration = !Array.isArray(listed) ? "unknown" : record === null ? "absent" : "present";
2923
+ const state = targetAbsence(disk, registration);
2924
+ let note = null;
2925
+ if (state === "absent") {
2926
+ note = cleaned ? `worktree ${target} was already cleaned by an earlier call` : `worktree ${target} is already gone (neither on disk nor registered); nothing was removed and the landing receipt is unchanged`;
2927
+ } else if (!cleaned) {
2928
+ return null;
2929
+ } else if (state === "present") {
2930
+ return {
2931
+ ok: false,
2932
+ reason: `worktree.path: ${target} was cleaned by an earlier call but a ${record !== null ? "registered worktree" : "directory"} exists there now (HEAD ${record?.head ?? "unknown, not a registered worktree"}); it was not removed, so inspect it and run delivery_cleanup against a new landing receipt if it should go`
2933
+ };
2934
+ } else {
2935
+ const why = Array.isArray(listed) ? `the filesystem read of ${target} failed` : `the worktree list could not be read (${listed.reason})`;
2936
+ return {
2937
+ ok: false,
2938
+ reason: `worktree.path: ${target} was cleaned by an earlier call, but ${why}, so its absence is unproven; nothing was removed`
2939
+ };
2940
+ }
2941
+ return {
2942
+ ok: true,
2943
+ receipt,
2944
+ path: receiptPath,
2945
+ remoteBranchAbsence: receipt.branch.deletedRemote ? "absent" : "unknown",
2946
+ alreadyCleaned: true,
2947
+ partlyRemoved: false,
2948
+ localRefDeleted: false,
2949
+ report: { removed: [], skipped: [note] }
2950
+ };
2951
+ };
2952
+ const resolution = await resolveReceipt(params, cwd, env, bounds.refReadMs, git, await worktreeHead());
2953
+ if (resolution.tag === "refused")
2954
+ return await foreignWorktree() ? foreignRepository() : resolution.failure;
2955
+ const receipt = resolution.receipt;
2956
+ const argsFailure = verifyArguments(params, receipt);
2957
+ if (argsFailure !== null)
2958
+ return await foreignWorktree() ? foreignRepository() : argsFailure;
2959
+ const gone = await alreadyCleaned(receipt, resolution.path);
2960
+ if (gone !== null)
2961
+ return gone;
2962
+ if (typeof receipt.pr.mergeCommitOid !== "string" || receipt.pr.mergeCommitOid.trim() === "") {
2963
+ return refuse2("pr.mergeCommitOid", receipt.pr.mergeCommitOid, "a non-empty merge commit oid before cleanup");
2964
+ }
2965
+ if (invocationInsideTarget(cwd, receipt.worktree.path)) {
2966
+ return refuse2("worktree.invocationCwd", cwd, `a directory outside the worktree this call would remove (${receipt.worktree.path}, resolved to ${physicalPath(receipt.worktree.path)})`);
2967
+ }
2968
+ const path = receipt.worktree.path;
2969
+ const settle = async (failure) => {
2970
+ const taken = await alreadyCleaned(receipt, resolution.path);
2971
+ return taken?.ok === true ? taken : failure;
2972
+ };
2973
+ const proveTarget = async () => {
2974
+ const identity = await verifyTargetIdentity(receipt, cwd, run, bounds.refReadMs, git);
2975
+ if (isFailure(identity))
2976
+ return identity;
2977
+ const observed = await observePullRequest(receipt, run, identity.cwd, env, bounds.refReadMs, identity.pin);
2978
+ if (isFailure(observed))
2979
+ return observed;
2980
+ const observedFailure = verifyObservation(receipt, observed.pr);
2981
+ if (observedFailure !== null)
2982
+ return observedFailure;
2983
+ const dirty = await verifyCleanTarget(identity.cwd, run, bounds.treeScanMs, identity.pin, stashBranches(receipt.branch.name, identity.target));
2984
+ if (dirty !== null)
2985
+ return dirty;
2986
+ const pushed = await verifyPushed(identity.cwd, run, bounds.refReadMs, identity.pin);
2987
+ if (isFailure(pushed))
2988
+ return pushed;
2989
+ return { identity, observed, pushed };
2990
+ };
2991
+ const unlocked = await proveTarget();
2992
+ const proofs = !isFailure(unlocked) || deps.proofSection === undefined ? unlocked : await deps.proofSection(path, proveTarget);
2993
+ if (isFailure(proofs))
2994
+ return settle(proofs);
2995
+ const { identity, observed, pushed } = proofs;
2996
+ const ledger = await verifyLedger(receipt, cwd, resolution.path, run, bounds.bdShowMs, bounds.refReadMs, git, env);
2997
+ if (ledger !== null)
2998
+ return ledger;
2999
+ await deps.authorize?.({ worktree: path, branch: receipt.branch.name, pr: receipt.pr.number });
3000
+ let absenceProven = false;
3001
+ const removeSection = async () => {
3002
+ const localRef = await verifyLocalRef(receipt, cwd, run, bounds.refReadMs);
3003
+ if (isFailure(localRef))
3004
+ return localRef;
3005
+ const boundary = await revalidateBoundary(receipt, cwd, run, bounds, git);
3006
+ if (isFailure(boundary))
3007
+ return boundary;
3008
+ const executionCwd = safeExecutionCwd(receipt, boundary.records, cwd);
3009
+ if (executionCwd === null)
3010
+ return refuse2("worktree.executionCwd", null, "a different listed worktree for the same repository");
3011
+ const executionDir = physicalPath(executionCwd);
3012
+ const executionVerdict = executionDir === null ? { state: "absent" } : verifyCheckout(executionDir, boundary.common);
3013
+ if (executionDir === null || executionVerdict.state !== "same")
3014
+ return refuse2("worktree.executionCwd", `${executionCwd} (.git ${executionVerdict.state})`, "a verified worktree of this repository");
3015
+ const executionPin = executionVerdict.pin;
3016
+ const targetPath = boundary.target.path;
3017
+ const removeArgv = ["worktree", "remove", targetPath];
3018
+ let route = "git";
3019
+ if (deps.host !== undefined) {
3020
+ try {
3021
+ route = removalRoute(await deps.host.list(targetPath), targetPath);
3022
+ } catch (error) {
3023
+ const message = error instanceof Error ? error.message : String(error);
3024
+ return refuse2("worktree.owner", `host worktree.list failed (${message.trim().slice(0, 400)})`, "a readable OpenCode worktree registry; nothing was removed, so retry delivery_cleanup once the host responds");
3025
+ }
3026
+ }
3027
+ if (signal?.aborted === true)
3028
+ return refuse2("signal", "an abort", "no interrupt before the worktree removal; nothing was removed");
3029
+ const held = await deps.finalCheck?.(targetPath);
3030
+ if (held !== undefined) {
3031
+ return refuse2("worktree.held", held, "no owner, hold, denial or competing remover at the moment of removal; nothing was removed");
3032
+ }
3033
+ if (signal?.aborted === true)
3034
+ return refuse2("signal", "an abort", "no interrupt before the worktree removal; nothing was removed");
3035
+ const rebound = markersStillBound(boundary, executionDir, executionPin);
3036
+ if (rebound !== null)
3037
+ return rebound;
3038
+ let failure = null;
3039
+ let stopped = false;
3040
+ let refusedClean = false;
3041
+ if (route === "host" && deps.host !== undefined) {
3042
+ try {
3043
+ await deps.host.remove(targetPath);
3044
+ } catch (error) {
3045
+ const message = error instanceof Error ? error.message : String(error);
3046
+ failure = refuse2("worktree.removed", `host worktree.remove ${JSON.stringify(targetPath)} (error ${gitMessage(message)})`, "host removal");
3047
+ }
3048
+ } else {
3049
+ const removed = await runGit(commit, executionDir, removeArgv, bounds.mutationMs, executionPin, MUTATION_ENV);
3050
+ if (!completed(removed)) {
3051
+ failure = mutationFailure("worktree.removed", ["git", ...removeArgv], removed);
3052
+ stopped = removed.exitCode === null;
3053
+ refusedClean = !stopped && removed.exitCode === 128 && CLEAN_CHECK_REFUSAL.test(removed.stderr);
3054
+ }
3055
+ }
3056
+ const registration = await registrationAbsence(executionDir, targetPath, commit, bounds.refReadMs, executionPin);
3057
+ const pathGone = pathAbsence(targetPath);
3058
+ const left = failure !== null && pathGone !== "absent" ? await treeStatus(boundary, commit, bounds.treeScanMs) : null;
3059
+ const untouched = refusedClean || left !== null && !left.some(isDeletion) && markersStillBound(boundary, executionDir, executionPin) === null;
3060
+ if (failure !== null && !stopped && registration !== "absent" && pathGone !== "absent" && untouched) {
3061
+ if (left === null || left.length === 0)
3062
+ return failure;
3063
+ const why = left.every((line) => line.startsWith(" D ")) ? removalElsewhere(path) : changedAfterProof(left);
3064
+ return { ok: false, reason: `${failure.reason}; ${why}` };
3065
+ }
3066
+ const unfinished = [];
3067
+ const branch = receipt.branch.name;
3068
+ if (registration !== "absent" || pathGone !== "absent") {
3069
+ unfinished.push(failure === null ? `worktree ${path} is there again after its removal (registration ${registration}, directory ${pathGone}) and was left alone; absence unverified; no continuation receipt; ${inspectAdvice(path, left)}` : `worktree ${path}: removal attempted and stopped part-way (${failure.reason}); registration ${registration}, directory ${pathGone}; absence unverified; no continuation receipt; ${inspectAdvice(path, left)}`, `local branch ${branch} kept: the worktree's absence is not proven`);
3070
+ return { ok: true, worktreeRemoved: failure === null, registration, pathGone, localAbsence: "unknown", localRefPlan: localRef, localRefDeleted: false, executionDir, unfinished };
3071
+ }
3072
+ if (failure !== null)
3073
+ unfinished.push(`the worktree removal reported a failure, yet the worktree is gone: ${failure.reason}`);
3074
+ absenceProven = true;
3075
+ const refAfterWorktree = await verifyLocalRef(receipt, executionDir, commit, bounds.refReadMs, executionPin);
3076
+ const localRefPlan = isFailure(refAfterWorktree) ? localRef : refAfterWorktree;
3077
+ let deleted = false;
3078
+ if (isFailure(refAfterWorktree)) {
3079
+ unfinished.push(`local branch ${branch} kept: ${refAfterWorktree.reason}`);
3080
+ } else if (localRef === "delete" && refAfterWorktree === "moved") {
3081
+ unfinished.push(`local branch ${branch} kept: it moved off ${receipt.pr.headRefOid} during the removal`);
3082
+ } else if (refAfterWorktree === "delete") {
3083
+ const deleteArgv = branchDeleteArgs(branch);
3084
+ const result = await runGit(commit, executionDir, deleteArgv, bounds.mutationMs, executionPin, MUTATION_ENV);
3085
+ if (completed(result))
3086
+ deleted = true;
3087
+ else
3088
+ unfinished.push(`local branch ${branch} kept: ${mutationFailure("worktree.localRefDeleted", ["git", ...deleteArgv], result).reason}`);
3089
+ }
3090
+ const localAbsence = await localRefAbsence(executionDir, branch, commit, bounds.refReadMs, executionPin);
3091
+ const expected = deleted || localRefPlan === "absent" ? "absent" : "present";
3092
+ if (localAbsence !== expected)
3093
+ unfinished.push(`local branch ${branch}: observed ${localAbsence} afterwards, expected ${expected}`);
3094
+ return {
3095
+ ok: true,
3096
+ worktreeRemoved: true,
3097
+ registration,
3098
+ pathGone,
3099
+ localAbsence,
3100
+ localRefPlan,
3101
+ localRefDeleted: deleted && localAbsence === "absent",
3102
+ executionDir,
3103
+ unfinished
3104
+ };
3105
+ };
3106
+ const section = deps.removalSection === undefined ? await removeSection() : await deps.removalSection(path, removeSection);
3107
+ let afterNotes = [];
3108
+ if (absenceProven) {
3109
+ try {
3110
+ afterNotes = await deps.afterRemoval?.(path) ?? [];
3111
+ } catch (error) {
3112
+ afterNotes = [`work after the removal failed: ${error instanceof Error ? error.message : String(error)}`];
3113
+ }
3114
+ }
3115
+ if (isFailure(section))
3116
+ return settle(section);
3117
+ const { registration, pathGone, localAbsence, executionDir } = section;
3118
+ const report = withNotes(removalReport(receipt, path, identity.target, section), afterNotes);
3119
+ const withoutContinuation = (remoteBranchAbsence, notes) => ({
3120
+ ok: true,
3121
+ receipt,
3122
+ path: resolution.path,
3123
+ remoteBranchAbsence,
3124
+ alreadyCleaned: false,
3125
+ partlyRemoved: !section.worktreeRemoved,
3126
+ localRefDeleted: section.localRefDeleted,
3127
+ report: withNotes(report, notes)
3128
+ });
3129
+ if (!absenceProven)
3130
+ return withoutContinuation(receipt.branch.deletedRemote ? "absent" : "unknown", []);
3131
+ const remoteAbsence = observed.identity.forge === "github" ? (await observeGithubBranch(observed.identity.nameWithOwner, receipt.branch.name, commit, env)).verdict : await remoteBranchAbsent(observed.identity.remoteUrl, receipt.branch.name, executionDir, commit);
3132
+ const issuedAt = nextReceiptEpoch(receipt, now);
3133
+ const verifiedAt = new Date(issuedAt).toISOString();
3134
+ const continued = buildReceipt({
3135
+ now: issuedAt,
3136
+ continues: receipt,
3137
+ emitter: { plugin: package_default.name, version: package_default.version, tool: "delivery_cleanup" },
3138
+ repo: receipt.repo,
3139
+ pr: {
3140
+ number: observed.pr.number,
3141
+ url: observed.pr.url,
3142
+ state: observed.pr.state,
3143
+ baseRefName: observed.pr.baseRefName,
3144
+ headRefName: observed.pr.headRefName,
3145
+ headRefOid: observed.pr.headRefOid,
3146
+ mergeCommitOid: observed.pr.mergeCommitOid,
3147
+ mergedAt: observed.pr.mergedAt
3148
+ },
3149
+ branch: {
3150
+ name: receipt.branch.name,
3151
+ deletedRemote: remoteAbsence === "absent",
3152
+ remoteAbsenceVerifiedAt: remoteAbsence === "absent" ? verifiedAt : null,
3153
+ autoDeleteSetting: receipt.branch.autoDeleteSetting
3154
+ },
3155
+ worktree: {
3156
+ path,
3157
+ removed: true,
3158
+ localRefDeleted: localAbsence === "absent",
3159
+ absenceVerifiedAt: verifiedAt
3160
+ },
3161
+ beads: receipt.beads,
3162
+ proof: {
3163
+ method: observed.pr.method,
3164
+ observedAt: verifiedAt,
3165
+ evidence: {
3166
+ worktreeRegistration: registration,
3167
+ worktreePath: pathGone,
3168
+ localRef: localAbsence,
3169
+ remoteBranch: remoteAbsence,
3170
+ pushed
3171
+ }
3172
+ },
3173
+ outcome: "cleaned",
3174
+ notes: remoteAbsence === "absent" ? undefined : `remote branch absence observed ${remoteAbsence}`
3175
+ });
3176
+ const validation = validateReceipt(continued);
3177
+ if (!validation.ok)
3178
+ return withoutContinuation(remoteAbsence, [`no continuation receipt written: ${validation.reason}`]);
3179
+ let written;
3180
+ try {
3181
+ written = writeReceipt(continued, dirname4(resolution.path));
3182
+ } catch (error) {
3183
+ return withoutContinuation(remoteAbsence, [`no continuation receipt written: ${error instanceof Error ? error.message : String(error)}`]);
3184
+ }
3185
+ return {
3186
+ ok: true,
3187
+ receipt: continued,
3188
+ path: written,
3189
+ remoteBranchAbsence: remoteAbsence,
3190
+ alreadyCleaned: false,
3191
+ partlyRemoved: false,
3192
+ localRefDeleted: section.localRefDeleted,
3193
+ report
3194
+ };
3195
+ }
3196
+
3197
+ // plugins/delivery/opencode/src/cleanup-tool.ts
3198
+ var CLEANUP_ACTION = "delivery_cleanup";
3199
+ var CLEANUP_INPUT = {
3200
+ type: "object",
3201
+ properties: {
3202
+ receipt: {
3203
+ type: "string",
3204
+ minLength: 1,
3205
+ description: "Path to a canonical landing receipt; omit to select the newest for this repository"
3206
+ },
3207
+ pr: { type: "integer", minimum: 1, description: "PR number, which must equal the selected receipt" },
3208
+ branch: { type: "string", minLength: 1, description: "Branch, which must equal the selected receipt" },
3209
+ worktree: { type: "string", minLength: 1, description: "Worktree path, which must equal the selected receipt" },
3210
+ remote: { type: "string", minLength: 1, description: "Remote name, which must equal the selected receipt" },
3211
+ repo: { type: "string", minLength: 1, description: `"<owner>/<name>", which must equal the selected receipt's repo; another repository needs repoPath or worktree` },
3212
+ repoPath: { type: "string", minLength: 1, description: "Checkout of repo on this machine; cleanup then runs in that clone" }
3213
+ },
3214
+ additionalProperties: false
3215
+ };
3216
+ var CLEANUP_OUTPUT = {
3217
+ type: "object",
3218
+ properties: {
3219
+ ok: { type: "boolean" },
3220
+ receiptPath: { type: "string" },
3221
+ branch: { type: "string" },
3222
+ worktree: { type: "string" },
3223
+ remoteBranchAbsence: { type: "string", enum: ["absent", "present", "unknown"] },
3224
+ alreadyCleaned: { type: "boolean" },
3225
+ partlyRemoved: { type: "boolean" },
3226
+ removed: { type: "array", items: { type: "string" } },
3227
+ skipped: { type: "array", items: { type: "string" } },
3228
+ reason: { type: "string" },
3229
+ deferred: { type: "string" },
3230
+ receipt: { type: "object" }
3231
+ },
3232
+ required: ["ok"]
3233
+ };
3234
+
3235
+ class CleanupDeferred extends Error {
3236
+ deferred;
3237
+ constructor(deferred) {
3238
+ super(deferred);
3239
+ this.deferred = deferred;
3240
+ this.name = "CleanupDeferred";
3241
+ }
3242
+ }
3243
+ function explicitDeferral(ownership) {
3244
+ const why = ownershipDeferral(ownership);
3245
+ if (why === undefined)
3246
+ return;
3247
+ return ownership.owner === "lane" ? `${why}; removed by its owner once finished` : `${why}; not removed until it can be read`;
3248
+ }
3249
+ function metadataOf(output) {
3250
+ const { receipt: _receipt, ...rest } = output;
3251
+ return rest;
3252
+ }
3253
+ function cleanupOutput(result) {
3254
+ if (!result.ok)
3255
+ return { ok: false, reason: result.reason };
3256
+ return {
3257
+ ok: true,
3258
+ receiptPath: result.path,
3259
+ branch: result.receipt.branch.name,
3260
+ worktree: result.receipt.worktree.path ?? "",
3261
+ remoteBranchAbsence: result.remoteBranchAbsence,
3262
+ alreadyCleaned: result.alreadyCleaned,
3263
+ partlyRemoved: result.partlyRemoved,
3264
+ removed: result.report.removed,
3265
+ skipped: result.report.skipped,
3266
+ receipt: result.receipt
3267
+ };
3268
+ }
3269
+ function cleanupText(result) {
3270
+ if (!result.ok)
3271
+ return `delivery_cleanup refused: ${result.reason}`;
3272
+ const skipped = result.report.skipped.length > 0 ? `; skipped: ${result.report.skipped.join("; ")}` : "";
3273
+ const receipt = `
3274
+ receipt: ${result.path}`;
3275
+ if (result.alreadyCleaned)
3276
+ return `delivery_cleanup: nothing to remove. ${result.report.skipped.join("; ")}.${receipt}`;
3277
+ if (result.partlyRemoved) {
3278
+ return `delivery_cleanup: removal attempted, partly removed, unverified: ${result.receipt.worktree.path ?? ""}${skipped}.${receipt}`;
3279
+ }
3280
+ return `delivery_cleanup removed ${result.report.removed.join(", ")}${skipped}; remote branch ${result.remoteBranchAbsence}.${receipt}`;
3281
+ }
3282
+ function cleanupToolResult(result) {
3283
+ const output = cleanupOutput(result);
3284
+ return { output, content: cleanupText(result), metadata: metadataOf(output) };
3285
+ }
3286
+ function deferredToolResult(deferred) {
3287
+ const output = { ok: true, deferred };
3288
+ return { output, content: `delivery_cleanup deferred: ${deferred}`, metadata: metadataOf(output) };
3289
+ }
3290
+
3291
+ // plugins/delivery/pi-src/delivery-cleanup.ts
3292
+ var LOCK_OWNER = "delivery (pi)";
3293
+ var UNRESOLVED_COMMON = "worktree.held: observed the git common directory could not be resolved, expected a coordination store; nothing was removed";
3294
+ function otherRepositoryReason(root) {
3295
+ return `repo: observed ${JSON.stringify(root)}, a checkout of a repository other than this session's; the pi delivery_cleanup removes only worktrees of the session's own repository, so run it from a session in that repository; nothing was removed`;
3296
+ }
3297
+ var DESCRIPTION = `Remove a landed PR's worktree and local branch in this repository after proving its landing receipt.
3298
+ ` + "Explicit calls only: no retry and no background cleanup. Recomputes the ledger classification at the canonical root, " + "proves the PR merged at the recorded head from the receipt's own remote, checks every receipt bead is closed with metadata.merge_sha equal to the merge (read-only bd show), " + "and refuses the worktree it runs from, a dirty tree or unpushed commits, a worktree a lane claims or background work holds, and a receipt or worktree of another repository. " + "Under the worktree lock every delivery remover takes, it then removes the worktree (git worktree remove, no force), runs git branch -d, verifies four absences and writes a continuation receipt. It asks nothing.";
3299
+ function removalBlock(common, worktree, now) {
3300
+ return ownershipDeferral(ownershipOf(readClaim(common, worktree))) ?? holdsState(common, worktree, now);
3301
+ }
3302
+ function sessionCoordination(cwd, deps = {}) {
3303
+ const now = deps.now ?? Date.now;
3304
+ const lock = { sessionID: LOCK_OWNER, now, ...deps.lock };
3305
+ const common = async () => (await repositoryContext(cwd, deps.observe))?.commonDir ?? null;
3306
+ return {
3307
+ proofSection: async (worktree, read) => {
3308
+ const dir = await common();
3309
+ if (dir === null)
3310
+ return { ok: false, reason: UNRESOLVED_COMMON };
3311
+ const outcome = await lockedWorktreeRead(dir, worktree, lock, read);
3312
+ if (outcome.locked)
3313
+ return outcome.value;
3314
+ return { ok: false, reason: `worktree.held: observed ${outcome.reason}, expected no competing remover; nothing was removed` };
3315
+ },
3316
+ removalSection: async (worktree, run) => {
3317
+ const dir = await common();
3318
+ if (dir === null)
3319
+ return { ok: false, reason: UNRESOLVED_COMMON };
3320
+ const outcome = await lockedWorktreeRemoval(dir, worktree, lock, {
3321
+ recheck: async () => removalBlock(dir, worktree, now()),
3322
+ remove: run
3323
+ });
3324
+ if (outcome.removed)
3325
+ return outcome.value;
3326
+ return { ok: false, reason: `worktree.held: observed ${outcome.reason}, expected no owner, hold or competing remover; nothing was removed` };
3327
+ },
3328
+ authorize: async ({ worktree }) => {
3329
+ const dir = await common();
3330
+ const deferred = dir === null ? undefined : explicitDeferral(ownershipOf(readClaim(dir, worktree)));
3331
+ if (deferred !== undefined)
3332
+ throw new CleanupDeferred(deferred);
3333
+ },
3334
+ coordinate: async ({ root }) => ({ ok: false, reason: otherRepositoryReason(root) })
3335
+ };
3336
+ }
3337
+ async function runCleanup(params, cwd, signal, deps = {}) {
3338
+ try {
3339
+ const result = await cleanupDelivery(params, cwd, { ...deps.cleanup, signal, ...sessionCoordination(cwd, deps) });
3340
+ return cleanupToolResult(result);
3341
+ } catch (error) {
3342
+ if (error instanceof CleanupDeferred)
3343
+ return deferredToolResult(error.deferred);
3344
+ throw error;
3345
+ }
3346
+ }
3347
+ function toToolResult(result) {
3348
+ return {
3349
+ content: [{ type: "text", text: result.content }],
3350
+ details: result.metadata,
3351
+ structuredContent: result.output
3352
+ };
3353
+ }
3354
+ var schema = (value) => value;
3355
+ function cleanupTool(deps = {}) {
3356
+ return {
3357
+ name: CLEANUP_ACTION,
3358
+ label: "Delivery: clean up a landed PR",
3359
+ description: DESCRIPTION,
3360
+ parameters: schema(CLEANUP_INPUT),
3361
+ outputSchema: schema(CLEANUP_OUTPUT),
3362
+ approval: "exec",
3363
+ execute: async (_id, params, signal, _onUpdate, ctx) => toToolResult(await runCleanup(params, ctx.cwd, signal, deps))
3364
+ };
3365
+ }
3366
+ function delivery(pi) {
3367
+ pi.registerTool(cleanupTool());
3368
+ }
3369
+ export {
3370
+ DESCRIPTION,
3371
+ UNRESOLVED_COMMON,
3372
+ cleanupTool,
3373
+ delivery as default,
3374
+ otherRepositoryReason,
3375
+ removalBlock,
3376
+ runCleanup,
3377
+ sessionCoordination,
3378
+ toToolResult
3379
+ };