harn-stdlib 0.10.120

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
/**
 * 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?}

/** 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,
  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" \
  | "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,
  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},
    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}
}

fn __base_advanced_receipt(options: BumpOptions, base: BumpBaseReconciliation) -> BumpReceipt {
  return base.receipt
    + {
      outcome: "base_advanced",
      ok: false,
      recovery: {kind: "fresh_base_retry", base_oid: base.receipt.observed_base_oid},
      notes: base.receipt.notes
        + [base.detail, "retry the bump from a fresh checkout of ${options.base}"],
    }
}

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
  // Refuse a stale checkout before spending on refresh and validation. The
  // later checks close the races introduced by those long-running phases.
  const initial_base = preparation.base
  receipt = initial_base.receipt
  if !initial_base.current {
    return __base_advanced_receipt(options, initial_base)
  }
  // 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.
  let repair_outcome: BumpOutcome? = nil
  let 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
    }
  }
  const repair_publication = repair_outcome != nil
  const repair_failure: BumpOutcome = repair_outcome ?? "validation_failed"
  // 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_publication {
      return receipt
        + {
          outcome: repair_failure,
          ok: false,
          notes: receipt.notes
            + ["${repair_failure} without a repairable file delta: ${repair_detail}"],
        }
    }
    return receipt
      + {outcome: "no_changes", ok: true, notes: receipt.notes + ["no file changes after refresh"]}
  }
  // Phase 6 — refresh and validation can take long enough for the remote base
  // to advance. Refuse publication of a tree proved against an older base.
  const base = __observe_base_lease(adapter, receipt, "before_publication")
  receipt = base.receipt
  if !base.current {
    return __base_advanced_receipt(options, base)
  }
  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)
  }
  // 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}
}