harn-stdlib 0.10.82

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

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

/**
 * 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,
  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" \
  | "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,
  ready: bool,
  readiness_detail: string,
  changed: bool,
  refreshed: list<string>,
  refresh_ok: bool,
  refresh_detail: string,
  validation: BumpValidation,
  changeset: BumpChangeSet,
  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 ?? ""))
    != ""
}

/**
 * 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, target, previous, readiness) -> BumpReceipt {
  return {
    schema: "harn-bump-runtime-v1",
    outcome: "not_ready",
    ok: false,
    repo: options.repo,
    branch: options.branch,
    target_tag: target,
    previous_version: previous,
    ready: readiness.ready,
    readiness_detail: readiness.detail,
    changed: false,
    refreshed: [],
    refresh_ok: true,
    refresh_detail: "",
    validation: __bump_default_validation(),
    changeset: __bump_empty_changeset(),
    lease_recovered: false,
    commit_oid: nil,
    pr_action: "none",
    pr_number: nil,
    pr_url: nil,
    auto_merge: nil,
    notes: [],
  }
}

/**
 * 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())
  let receipt = __bump_receipt_base(options, target, previous, 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 bump_is_current(previous, target) {
    return receipt
      + {outcome: "already_current", ok: true, notes: ["pin already matches ${target}"]}
  }
  // 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: ["refresh failed: ${apply.detail}"]}
  }
  if !apply.changed {
    return receipt
      + {
      outcome: "already_current",
      ok: true,
      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: ["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: ["${repair_failure} without a repairable file delta: ${repair_detail}"],
      }
    }
    return receipt
      + {outcome: "no_changes", ok: true, notes: ["no file changes after refresh"]}
  }
  // Phase 6 — branch/PR lease reconciliation. Observe base before touching
  // remote state, then disarm a stale PR under exact head + base leases. This
  // prevents a stale actor from disabling or replacing a newer publication.
  const existing = adapter.find_bump_pr()
  const base_sha = trim(adapter.base_sha())
  let notes = []
  let lease_recovered = false
  if existing != nil && existing.auto_merge_enabled {
    if !adapter.disable_auto_merge(existing, base_sha) {
      throw "std/bump/runtime: failed to disable stale auto-merge on #${existing.number}"
    }
    lease_recovered = true
    notes = notes + ["disarmed stale auto-merge on #${existing.number} before refresh"]
  }
  receipt = receipt + {lease_recovered: lease_recovered}
  // 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",
      ],
    }
  }
  // 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}
}