harn-stdlib 0.10.125

Embedded Harn standard library source catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/**
 * std/bump/runtime — the pure, provider-agnostic state machine that bumps a
 * Harn package repository onto a newer pinned Harn runtime.
 *
 * The orchestration logic here performs NO I/O. Every side effect (release
 * lookup, working-tree mutation, validation, branch/PR leases, signed commit
 * creation, PR refresh, auto-merge) is reached through the injected
 * [`BumpAdapter`] capability record. `std/bump/live` owns local filesystem,
 * command, and git effects while a package supplies the remote provider
 * capability; the in-process fixtures inject fakes. That seam is what lets
 * the whole state machine be exercised with `harn test` — no network, no
 * clock, no sleeps.
 *
 * The single entry point is [`run_bump`]. It returns a typed [`BumpReceipt`]
 * that is both the machine-readable receipt the workflow surfaces and the
 * value the fixtures assert against.
 */
import { compare_release, strip_v } from "std/semver"

/** Everything the caller controls about one bump attempt. */
pub type BumpOptions = {
  tag: string,
  repo: string,
  branch: string,
  base: string,
  enable_auto_merge: bool,
  publish_failure_for_repair: bool,
  merge_method: string,
}

/** Normalized readiness verdict for a target release. */
pub type ReleaseReadiness = {
  ready: bool,
  detail: string,
  attempts: int,
  attempt_lines: list<string>,
}

/** Outcome of writing the new pin and regenerating derived sources. */
pub type BumpApplyOutcome = {ok: bool, changed: bool, refreshed: list<string>, detail: string}

/** One declared validation lane (fmt/check/lint/test/package…) and its verdict. */
pub type BumpValidationStep = {name: string, ok: bool, detail: string}

/** Aggregate verdict over the caller's single declared validation entrypoint. */
pub type BumpValidation = {ok: bool, steps: list<BumpValidationStep>, detail: string}

/** The working-tree delta a signed commit would carry. */
pub type BumpChangeSet = {additions: list<string>, deletions: list<string>}

/** Current remote identity of the declared base branch. */
pub type BumpBaseHead = {available: bool, oid: string?, detail: string}

/** Machine-readable recovery requested after a non-ready bump attempt. */
pub type BumpRecovery = {kind: "none" | "fresh_base_retry", base_oid: string?}

/**
 * One request to adopt an advanced base branch head into the local checkout.
 *
 * `refreshed` is the path set this bump's refresh has already authored, so the
 * adapter can refuse an adoption whose incoming commits touch the same files
 * instead of silently deciding which writer wins.
 */
pub type BumpBaseAdoptionRequest = {
  base: string,
  from_oid: string?,
  to_oid: string,
  refreshed: list<string>,
  attempt: int,
}

/** Verdict of adopting an advanced base. `conflicts` names the contested paths. */
pub type BumpBaseAdoption = {
  ok: bool,
  adopted_oid: string?,
  conflicts: list<string>,
  detail: string,
}

/** Observed state of an already-open bump PR, or nil when none exists. */
pub type BumpPrState = {
  number: int,
  head_oid: string,
  base_ref: string,
  base_oid: string,
  auto_merge_enabled: bool,
  auto_merge_method: string?,
  url: string,
  state: string,
}

/** Inputs to one atomic provider-owned branch + signed-commit publication. */
pub type BumpCommitRequest = {branch: string, base_sha: string, headline: string}

/** Result of atomically publishing the bump branch and signed commit. */
pub type BumpCommitResult = {oid: string, url: string, branch_action: string}

/** Result of a create-or-refresh PR upsert. */
pub type BumpPrUpsert = {number: int, head_oid: string, url: string, created: bool}

/** Result of arming auto-merge. */
pub type BumpAutoMerge = {enabled: bool, state: string, detail: string}

/** How the consumer's current pin compares with the requested release. */
pub type BumpVersionRelation = "behind" | "equal" | "ahead"

/**
 * The injected capability surface. Each field is a function the orchestrator
 * calls at a well-defined phase; swapping the record swaps live I/O for
 * fixtures without touching a line of the state machine.
 */
pub type BumpAdapter = {
  resolve_target_tag: fn(string) -> string,
  release_ready: fn(string) -> ReleaseReadiness,
  read_current_version: fn() -> string,
  base_sha: fn() -> string,
  apply_version: fn(string) -> BumpApplyOutcome,
  run_validation: fn() -> BumpValidation,
  working_changes: fn() -> BumpChangeSet,
  remote_base_head: fn() -> BumpBaseHead,
  adopt_base: fn(BumpBaseAdoptionRequest) -> BumpBaseAdoption,
  find_bump_pr: fn() -> BumpPrState?,
  disable_auto_merge: fn(BumpPrState, string) -> bool,
  publish_commit: fn(BumpCommitRequest) -> BumpCommitResult,
  branch_matches_base: fn() -> bool,
  upsert_pr: fn(BumpPrState?, string) -> BumpPrUpsert,
  close_pr: fn(int, string) -> bool,
  enable_auto_merge: fn(int, string) -> BumpAutoMerge,
}

/**
 * Terminal outcome of a bump attempt. Every early-exit is a first-class,
 * idempotent-safe state, not an error.
 */
pub type BumpOutcome = "not_ready" \
  | "already_current" \
  | "refresh_failed" \
  | "no_changes" \
  | "validation_failed" \
  | "base_advanced" \
  | "base_conflict" \
  | "closed_noop" \
  | "committed"

/** What happened to the PR head during this attempt. */
pub type BumpPrAction = "none" | "created" | "refreshed" | "closed"

/** The machine-readable receipt every attempt emits. */
pub type BumpReceipt = {
  schema: "harn-bump-runtime-v1",
  outcome: BumpOutcome,
  ok: bool,
  repo: string,
  branch: string,
  target_tag: string,
  previous_version: string,
  version_relation: BumpVersionRelation,
  ready: bool,
  readiness_detail: string,
  changed: bool,
  refreshed: list<string>,
  refresh_ok: bool,
  refresh_detail: string,
  validation: BumpValidation,
  changeset: BumpChangeSet,
  expected_base_oid: string?,
  observed_base_oid: string?,
  base_current: bool?,
  base_check_phase: "before_refresh" | "before_publication" | "before_arming" | nil,
  recovery: BumpRecovery,
  base_adoptions: int,
  lease_recovered: bool,
  commit_oid: string?,
  pr_action: BumpPrAction,
  pr_number: int?,
  pr_url: string?,
  auto_merge: BumpAutoMerge?,
  notes: list<string>,
}

fn __bump_default_validation() -> BumpValidation {
  return {ok: true, steps: [], detail: ""}
}

fn __bump_empty_changeset() -> BumpChangeSet {
  return {additions: [], deletions: []}
}

/**
 * Merge caller-supplied options over the canonical defaults. The bump branch,
 * base, and squash auto-merge mirror the shell workflow this replaces.
 *
 * @effects: []
 * @errors: []
 */
pub fn bump_options(overrides: dict = {}) -> BumpOptions {
  const o = overrides ?? {}
  return {
    tag: to_string(o.tag ?? ""),
    repo: to_string(o.repo ?? ""),
    branch: to_string(o.branch ?? "automation/bump-harn-runtime"),
    base: to_string(o.base ?? "main"),
    enable_auto_merge: o.enable_auto_merge ?? true,
    publish_failure_for_repair: o.publish_failure_for_repair ?? false,
    merge_method: to_string(o.merge_method ?? "squash"),
  }
}

/**
 * True when the pinned version already matches the target, module a leading
 * `v`. The pin file and the resolved tag are compared on their bare semver so
 * `v0.10.30` and `0.10.30` are the same pin.
 *
 * @effects: []
 * @errors: []
 */
pub fn bump_is_current(previous: string, target: string) -> bool {
  return strip_v(trim(previous ?? "")) == strip_v(trim(target ?? ""))
    && strip_v(trim(target ?? ""))
      != ""
}

/**
 * Compare a consumer pin with the requested release. Both inputs accept the
 * optional `v` used by release tags. Invalid versions fail closed through the
 * canonical SemVer parser instead of making a potentially unsafe mutation.
 *
 * @effects: []
 * @errors: ["std/semver: left/right version is not release semver"]
 */
pub fn bump_version_relation(previous: string, target: string) -> BumpVersionRelation {
  const order = compare_release(strip_v(trim(previous)), strip_v(trim(target)))
  if order < 0 {
    return "behind"
  }
  if order > 0 {
    return "ahead"
  }
  return "equal"
}

/**
 * True when a changeset carries nothing a commit could include.
 *
 * @effects: []
 * @errors: []
 */
pub fn bump_changeset_empty(changeset: BumpChangeSet) -> bool {
  return len(changeset.additions) == 0 && len(changeset.deletions) == 0
}

fn __bump_receipt_base(
  options: BumpOptions,
  target: string,
  previous: string,
  relation: BumpVersionRelation,
  readiness: ReleaseReadiness,
) -> BumpReceipt {
  return {
    schema: "harn-bump-runtime-v1",
    outcome: "not_ready",
    ok: false,
    repo: options.repo,
    branch: options.branch,
    target_tag: target,
    previous_version: previous,
    version_relation: relation,
    ready: readiness.ready,
    readiness_detail: readiness.detail,
    changed: false,
    refreshed: [],
    refresh_ok: true,
    refresh_detail: "",
    validation: __bump_default_validation(),
    changeset: __bump_empty_changeset(),
    expected_base_oid: nil,
    observed_base_oid: nil,
    base_current: nil,
    base_check_phase: nil,
    recovery: {kind: "none", base_oid: nil},
    base_adoptions: 0,
    lease_recovered: false,
    commit_oid: nil,
    pr_action: "none",
    pr_number: nil,
    pr_url: nil,
    auto_merge: nil,
    notes: [],
  }
}

type BumpBaseCheckPhase = "before_refresh" | "before_publication" | "before_arming"

type BumpBaseReconciliation = {current: bool, receipt: BumpReceipt, detail: string}

fn __observe_base_lease(
  adapter: BumpAdapter,
  receipt: BumpReceipt,
  phase: BumpBaseCheckPhase,
) -> BumpBaseReconciliation {
  const expected_oid = trim(receipt.expected_base_oid ?? adapter.base_sha())
  const observed = adapter.remote_base_head()
  const observed_value = trim(observed.oid ?? "")
  const observed_oid = if observed.available && observed_value != "" {
    observed_value
  } else {
    nil
  }
  const current = expected_oid != "" && observed_oid != nil && observed_oid == expected_oid
  const next_receipt = receipt
    + {
      expected_base_oid: if expected_oid == "" {
        nil
      } else {
        expected_oid
      },
      observed_base_oid: observed_oid,
      base_current: current,
      base_check_phase: phase,
    }
  if current {
    return {current: true, receipt: next_receipt, detail: ""}
  }
  const detail = if expected_oid == "" {
    "local base identity unavailable"
  } else if observed_oid == nil {
    "remote base identity unavailable: ${observed.detail}"
  } else {
    "remote base advanced from ${expected_oid} to ${observed_oid}"
  }
  return {current: false, receipt: next_receipt, detail: detail}
}

/**
 * Bounded number of advanced-base adoptions one attempt may make before it
 * hands the race back to the controller. Each adoption costs a full refresh
 * and validation, so the ceiling is small and the lease is held throughout.
 */
const BUMP_MAX_BASE_ADOPTIONS = 3

fn __base_advanced_receipt(
  options: BumpOptions,
  base: BumpBaseReconciliation,
  adoptions: int,
  extra: list<string> = [],
) -> BumpReceipt {
  const exhausted = if adoptions >= BUMP_MAX_BASE_ADOPTIONS {
    ["exhausted ${BUMP_MAX_BASE_ADOPTIONS} base adoptions without a stable ${options.base}"]
  } else {
    []
  }
  return base.receipt
    + {
      outcome: "base_advanced",
      ok: false,
      base_adoptions: adoptions,
      recovery: {kind: "fresh_base_retry", base_oid: base.receipt.observed_base_oid},
      notes: base.receipt.notes
        + [base.detail]
        + extra
        + exhausted
        + ["retry the bump from a fresh checkout of ${options.base}"],
    }
}

/**
 * The one abort a fresh retry cannot fix: the advanced base changed a path this
 * bump's refresh also authors, so adopting it would decide a contest between
 * two writers of the same artifact. Name the paths and stop.
 */
fn __base_conflict_receipt(
  options: BumpOptions,
  base: BumpBaseReconciliation,
  adoption: BumpBaseAdoption,
) -> BumpReceipt {
  const contested = if len(adoption.conflicts) > 0 {
    ["the advanced ${options.base} changed refreshed paths: ${join(adoption.conflicts, ", ")}"]
  } else {
    []
  }
  return base.receipt
    + {
      outcome: "base_conflict",
      ok: false,
      recovery: {kind: "none", base_oid: base.receipt.observed_base_oid},
      notes: base.receipt.notes
        + [base.detail, "cannot adopt the advanced ${options.base}: ${adoption.detail}"]
        + contested,
    }
}

type BumpBasePreparation = {existing: BumpPrState?, base: BumpBaseReconciliation}

fn __prepare_base_lease(adapter: BumpAdapter, receipt: BumpReceipt) -> BumpBasePreparation {
  const existing = adapter.find_bump_pr()
  let next_receipt = receipt
  if existing != nil && existing.auto_merge_enabled {
    if !adapter.disable_auto_merge(existing, existing.base_oid) {
      throw "std/bump/runtime: failed to disable stale auto-merge on #${existing.number}"
    }
    next_receipt = receipt
      + {
        lease_recovered: true,
        notes: receipt.notes
          + ["disarmed stale auto-merge on #${existing.number} before refresh"],
      }
  }
  return {existing: existing, base: __observe_base_lease(adapter, next_receipt, "before_refresh")}
}

/**
 * Run the full bump state machine against an injected adapter and return its
 * receipt. Pure with respect to this process: all effects flow through
 * `adapter`. The phase order is fixed and every early return leaves the repo
 * in a safe, re-runnable state.
 *
 * @effects: []
 * @errors: []
 */
pub fn run_bump(options: BumpOptions, adapter: BumpAdapter) -> BumpReceipt {
  const target = adapter.resolve_target_tag(options.tag)
  const readiness = adapter.release_ready(target)
  const previous = trim(adapter.read_current_version())
  const relation = bump_version_relation(previous, target)
  let receipt = __bump_receipt_base(options, target, previous, relation, readiness)
  // Phase 1 — release readiness gate. A target that is still publishing its
  // assets is not an error; the scheduled rerun will pick it up.
  if !readiness.ready {
    return receipt
      + {outcome: "not_ready", ok: true, notes: ["target release is not fully published yet"]}
  }
  // Phase 2 — idempotent no-op. Concurrent/scheduled reruns land here once the
  // pin already matches, so the common steady state does zero mutation.
  if relation == "equal" {
    return receipt
      + {outcome: "already_current", ok: true, notes: ["pin already matches ${target}"]}
  }
  // A bump is monotonic. A stale explicit target can race with a newer release
  // landing on the base branch; treat the newer pin as satisfied and never
  // turn that race into a downgrade PR.
  if relation == "ahead" {
    return receipt
      + {
        outcome: "already_current",
        ok: true,
        notes: ["pin ${previous} is newer than requested target ${target}; no downgrade applied"],
      }
  }
  // Any previously armed bump must stop before the long refresh begins. It
  // could otherwise merge while this attempt is validating a replacement.
  const preparation = __prepare_base_lease(adapter, receipt)
  const existing = preparation.existing
  let base = preparation.base
  receipt = base.receipt
  let adoptions = 0
  let repair_outcome: BumpOutcome? = nil
  let repair_detail = ""
  // Refresh and validation run long enough for the base branch to move under
  // them. The refreshed content is a pure function of (base content, target),
  // so a moved base is re-derivable rather than fatal: adopt the observed head
  // into the checkout and re-enter the mutation phases against it, under the
  // same auto-merge disarm lease. The loop is bounded and leaves only on a base
  // the adapter has proved is the local checkout's own head.
  while true {
    if !base.current {
      const observed = base.receipt.observed_base_oid
      // An unreadable remote head is not an identity that can be adopted, and
      // absence must never read as "still current".
      if observed == nil || adoptions >= BUMP_MAX_BASE_ADOPTIONS {
        return __base_advanced_receipt(options, base, adoptions)
      }
      const adoption = adapter.adopt_base(
        {
          base: options.base,
          from_oid: base.receipt.expected_base_oid,
          to_oid: observed,
          refreshed: receipt.refreshed,
          attempt: adoptions + 1,
        },
      )
      if !adoption.ok {
        // Contested paths need a human. Everything else — an unreachable oid,
        // a failed fetch — stays a retryable race for the controller.
        if len(adoption.conflicts) > 0 {
          return __base_conflict_receipt(options, base, adoption)
        }
        return __base_advanced_receipt(
          options,
          base,
          adoptions,
          ["could not adopt the advanced ${options.base}: ${adoption.detail}"],
        )
      }
      adoptions = adoptions + 1
      receipt = receipt
        + {
          base_adoptions: adoptions,
          expected_base_oid: adoption.adopted_oid,
          notes: receipt.notes
            + [
              "adopted advanced base ${observed} for re-application "
                + "(adoption ${adoptions} of ${BUMP_MAX_BASE_ADOPTIONS})",
            ],
        }
      // The adoption itself can lose the race again; re-read before spending.
      base = __observe_base_lease(adapter, receipt, "before_refresh")
      receipt = base.receipt
      continue
    }
    // Phase 3 — write the pin and regenerate derived sources (lockfile, codegen).
    const apply = adapter.apply_version(target)
    receipt = receipt
      + {
        changed: apply.changed,
        refreshed: apply.refreshed,
        refresh_ok: apply.ok,
        refresh_detail: apply.detail,
      }
    if !apply.ok && (!options.publish_failure_for_repair || !apply.changed) {
      return receipt
        + {
          outcome: "refresh_failed",
          ok: false,
          notes: receipt.notes + ["refresh failed: ${apply.detail}"],
        }
    }
    if !apply.changed {
      return receipt
        + {
          outcome: "already_current",
          ok: true,
          notes: receipt.notes + ["writing ${target} produced no change"],
        }
    }
    // Phase 4 — the caller's single declared validation entrypoint. By default,
    // any failed mutation stops before publication. Fleet controllers may opt
    // into a leased repair PR for either a refresh or validation failure; that
    // path preserves the exact failed outcome and can never arm auto-merge.
    // Validation is skipped after a failed refresh because its preconditions no
    // longer hold; the bounded repair lane must rerun the complete bump gate.
    repair_outcome = nil
    repair_detail = ""
    if !apply.ok {
      repair_outcome = "refresh_failed"
      repair_detail = apply.detail
    } else {
      const validation = adapter.run_validation()
      receipt = receipt + {validation: validation}
      if !validation.ok && !options.publish_failure_for_repair {
        return receipt
          + {
            outcome: "validation_failed",
            ok: false,
            notes: receipt.notes + ["validation failed: ${validation.detail}"],
          }
      }
      if !validation.ok {
        repair_outcome = "validation_failed"
        repair_detail = validation.detail
      }
    }
    // Phase 5 — nothing to commit? Never manufacture an empty PR. A failed
    // mutation remains failed even when it produced no file delta.
    const changeset = adapter.working_changes()
    receipt = receipt + {changeset: changeset}
    if bump_changeset_empty(changeset) {
      if repair_outcome != nil {
        return receipt
          + {
            outcome: repair_outcome ?? "validation_failed",
            ok: false,
            notes: receipt.notes
              + [
                "${repair_outcome ?? "validation_failed"} without a repairable file delta: "
                  + repair_detail,
              ],
          }
      }
      return receipt
        + {
          outcome: "no_changes",
          ok: true,
          notes: receipt.notes + ["no file changes after refresh"],
        }
    }
    // Phase 6 — re-read the base immediately before publication. The connector
    // derives its payload against the local HEAD, so a tree proved against an
    // older base can never be published as-is; the loop head decides whether
    // this attempt adopts the new base or hands the race back.
    base = __observe_base_lease(adapter, receipt, "before_publication")
    receipt = base.receipt
    if base.current {
      break
    }
  }
  const repair_publication = repair_outcome != nil
  const repair_failure: BumpOutcome = repair_outcome ?? "validation_failed"
  const base_sha = receipt.expected_base_oid ?? ""
  let notes = receipt.notes
  // Phase 7 — atomically create/reset the branch and publish one signed commit
  // under the observed base lease. The provider adapter owns the worktree
  // encoding and branch mutation as one deep operation.
  const commit = adapter.publish_commit(
    {branch: options.branch, base_sha: base_sha, headline: "chore: bump Harn runtime to ${target}"},
  )
  receipt = receipt + {commit_oid: commit.oid}
  // Phase 8 — if the refreshed branch tree already matches base, the bump is a
  // true no-op: close any stale PR instead of opening an empty one.
  if adapter.branch_matches_base() {
    if existing != nil {
      adapter.close_pr(
        existing.number,
        "Closing: the refreshed Harn bump already matches ${options.base}.",
      )
      if repair_publication {
        return receipt
          + {
            outcome: repair_failure,
            ok: false,
            pr_action: "closed",
            pr_number: existing.number,
            notes: notes
              + [
                "${repair_failure} and the published tree matched ${options.base}; closed #${existing.number}",
              ],
          }
      }
      return receipt
        + {
          outcome: "closed_noop",
          ok: true,
          pr_action: "closed",
          pr_number: existing.number,
          notes: notes + ["branch tree matches ${options.base}; closed #${existing.number}"],
        }
    }
    if repair_publication {
      return receipt
        + {
          outcome: repair_failure,
          ok: false,
          notes: notes
            + ["${repair_failure} and the published tree matched ${options.base}; no PR needed"],
        }
    }
    return receipt
      + {
        outcome: "no_changes",
        ok: true,
        notes: notes + ["branch tree matches ${options.base}; no PR needed"],
      }
  }
  // Phase 9 — create or refresh the PR.
  const upsert = adapter.upsert_pr(existing, commit.oid)
  const pr_action = if upsert.created {
    "created"
  } else {
    "refreshed"
  }
  receipt = receipt + {pr_action: pr_action, pr_number: upsert.number, pr_url: upsert.url}
  if repair_publication {
    return receipt
      + {
        outcome: repair_failure,
        ok: false,
        notes: notes
          + [
            "${repair_failure}: ${repair_detail}",
            "published #${upsert.number} for bounded repair with auto-merge disabled",
          ],
      }
  }
  // PR creation can itself race the base branch. Re-read immediately before
  // arming so any stale publication remains visible but cannot enter the
  // merge queue. The controller retries from a fresh base checkout.
  const arm_base = __observe_base_lease(adapter, receipt, "before_arming")
  receipt = arm_base.receipt
  if !arm_base.current {
    return __base_advanced_receipt(options, arm_base, adoptions)
  }
  // Phase 10 — arm auto-merge so the merge queue owns the final landing.
  let auto_merge = nil
  if options.enable_auto_merge {
    auto_merge = adapter.enable_auto_merge(upsert.number, upsert.head_oid)
    notes = notes
      + [
        if auto_merge.enabled {
          "auto-merge armed on #${upsert.number}"
        } else {
          "auto-merge not enabled: ${auto_merge.detail}"
        },
      ]
  }
  return receipt + {outcome: "committed", ok: true, auto_merge: auto_merge, notes: notes}
}