@evident-ai/runner-cdk 0.1.1-dev.0fe02fb → 0.1.1-dev.25e01b7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +64 -16
  2. package/dist/controller-lambda/handler.js +50523 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +14 -1
  5. package/dist/microvm/constants.d.ts +7 -0
  6. package/dist/microvm/constants.js +35 -0
  7. package/dist/microvm/construct.d.ts +73 -0
  8. package/dist/microvm/construct.js +245 -0
  9. package/dist/microvm/controller/doorbell.d.ts +73 -0
  10. package/dist/microvm/controller/doorbell.js +107 -0
  11. package/dist/microvm/controller/handle-doorbell.d.ts +27 -0
  12. package/dist/microvm/controller/handle-doorbell.js +480 -0
  13. package/dist/microvm/controller/microvm-client.d.ts +75 -0
  14. package/dist/microvm/controller/microvm-client.js +7 -0
  15. package/dist/microvm/controller/shape-catalogue.d.ts +64 -0
  16. package/dist/microvm/controller/shape-catalogue.js +108 -0
  17. package/dist/microvm/controller/throttle-retry.d.ts +11 -0
  18. package/dist/microvm/controller/throttle-retry.js +27 -0
  19. package/dist/microvm/image/stage-context.d.ts +33 -0
  20. package/dist/microvm/image/stage-context.js +148 -0
  21. package/dist/microvm/shapes.d.ts +72 -0
  22. package/dist/microvm/shapes.js +93 -0
  23. package/dist/microvm-image-context/Dockerfile +224 -0
  24. package/dist/microvm-image-context/hook-server.js +290 -0
  25. package/dist/microvm-image-context/hooks/common.sh +1255 -0
  26. package/dist/microvm-image-context/hooks/resume +79 -0
  27. package/dist/microvm-image-context/hooks/run +111 -0
  28. package/dist/microvm-image-context/hooks/suspend +19 -0
  29. package/dist/microvm-image-context/hooks/terminate +34 -0
  30. package/package.json +11 -4
@@ -0,0 +1,1255 @@
1
+ #!/usr/bin/env bash
2
+ # Sourced by every hook script. Nothing here runs at image build time.
3
+ #
4
+ # These hooks are the SECOND shell speaking the runner-synchroniser CLI contract
5
+ # (packages/runner-image/entrypoint.sh is the first), so both are held to it by
6
+ # packages/runner-synchroniser/src/shell-contract.test.ts — which derives what
7
+ # `run_synchroniser` below must handle from the subcommands this shell calls.
8
+
9
+ # Installed from npm by the image (docker/Dockerfile's ARG
10
+ # RUNNER_SYNCHRONISER_VERSION) and resolved off PATH here. The Dockerfile's
11
+ # required-binary assertion is the loud failure if it is missing.
12
+ SYNCHRONISER="runner-synchroniser"
13
+ OPENCODE_PORT="${OPENCODE_PORT:-4096}"
14
+
15
+ # A hook script keeps no memory between invocations, but /resume must re-dial
16
+ # with the runner key /run was given, so /run leaves it here. Deliberate, on two
17
+ # axes: tmpfs means it never reaches the block device, and the SHARED image
18
+ # snapshot is taken at build time — long before /run — so the key cannot enter
19
+ # the artefact every VM boots from. And at 0600 owned by uid 10001 it is
20
+ # readable by nobody who could not already read it out of the tunnel process's
21
+ # /proc/<pid>/environ, which runs as that same uid. /terminate removes it.
22
+ # shellcheck disable=SC2034 # read by the scripts that source this file
23
+ CONTEXT_FILE="/dev/shm/evident-run-context"
24
+ TUNNEL_PID_FILE="/dev/shm/evident-tunnel.pid"
25
+ OPENCODE_PID_FILE="/dev/shm/evident-opencode.pid"
26
+ LITESTREAM_PID_FILE="/dev/shm/evident-litestream.pid"
27
+
28
+ # Where the runner's credential store lives inside the durable-state bucket.
29
+ # The BUCKET is the same for every VM from an image version, so the stack bakes
30
+ # it into the image environment; the PREFIX selects one runner's store, so it is
31
+ # per-VM and can only arrive in the /run payload. /run leaves it here for the
32
+ # hooks that flush back to it. A file of its own rather than a line of
33
+ # CONTEXT_FILE: it is not a secret, so /suspend never has to read the runner key
34
+ # to find out where to write.
35
+ STATE_PREFIX_FILE="/dev/shm/evident-state-prefix"
36
+
37
+ # The generated litestream.yml (#812). tmpfs for the same two reasons as the
38
+ # files above: it must never reach the block device (Q6, `docs`), and it
39
+ # survives suspend/resume, which is what lets `/resume` start litestream again
40
+ # with no regeneration cost. Regenerated only when absent or empty
41
+ # (`ensure_litestream_config`, below).
42
+ LITESTREAM_CONFIG_FILE="/dev/shm/evident-litestream.yml"
43
+
44
+ # Set when a `session-db-classify` answer of 31 (replica unusable), or a
45
+ # restore this hook gave up on for its own reasons (a truncated `timeout`, a
46
+ # broken tool), means this boot must NOT start `litestream replicate` — doing
47
+ # so would let a partial/fresh local DB overwrite a replica this boot never
48
+ # proved is safe to write over. Cleared at the top of every `restore_session_db`
49
+ # call (i.e. every `/run`) before any other decision, so a marker left by an
50
+ # earlier boot cannot silently disable replication for the VM's whole life.
51
+ SESSION_DB_NO_REPLICATE_MARKER="/dev/shm/evident-session-db-no-replicate"
52
+
53
+ log() { echo "[hook:$(basename "$0")] $*"; }
54
+ warn() { echo "[hook:$(basename "$0")] $*" >&2; }
55
+ error() { echo "[hook:$(basename "$0")] ERROR: $*" >&2; }
56
+
57
+ # Returns the CLI's own exit code. Domain outcomes (nothing persisted yet, a
58
+ # corrupt object) are LOGGED and exit 0, the predicates answer "no" with 10, and
59
+ # `session-db-classify`'s three typed answers are 30 (fatal)/31 (replica
60
+ # unusable)/32 (retry) — see `packages/runner-synchroniser/src/cli.ts`'s own
61
+ # comment for what each means, not restated here. Any OTHER non-zero status
62
+ # means the tool itself broke, which is the only case worth an ERROR here —
63
+ # EXCEPT 124/137 (a `timeout` deadline/SIGKILL) when the caller asked for one:
64
+ # that is an intentional bound firing, not a broken tool, so the caller
65
+ # classifies it instead (restore_credentials, #930). A trailing
66
+ # `--evident-deadline=N` (stripped below before forwarding to the CLI, and
67
+ # never produced by anything but timed_synchroniser) is how a caller opts in;
68
+ # every other caller — sync_credentials, restore_session_db's `env` /
69
+ # `litestream-config` / `session-db-classify`, and this file's own contract
70
+ # test — passes none, so 124/137 there still means a genuine external SIGKILL
71
+ # (e.g. an OOM kill) and must keep producing the ERROR below.
72
+ run_synchroniser() {
73
+ local -a call_args=("$@")
74
+ local deadline=""
75
+ local last=$(( ${#call_args[@]} - 1 ))
76
+ if [ "${last}" -ge 0 ] && [[ "${call_args[last]}" == --evident-deadline=* ]]; then
77
+ deadline="${call_args[last]#--evident-deadline=}"
78
+ call_args=("${call_args[@]:0:${last}}")
79
+ fi
80
+
81
+ local rc=0
82
+ local -a launcher=()
83
+ [ -n "${deadline}" ] && launcher=(timeout -k "${CREDENTIAL_RESTORE_KILL_GRACE_SECONDS}" "${deadline}")
84
+ "${launcher[@]}" "${SYNCHRONISER}" "${call_args[@]}" || rc=$?
85
+ case "${rc}" in
86
+ 0 | 10 | 30 | 31 | 32) ;;
87
+ 124 | 137)
88
+ [ -n "${deadline}" ] || error "synchroniser '${call_args[*]}' exited ${rc}; the '${SYNCHRONISER}' command is missing from PATH, corrupt, or it threw"
89
+ ;;
90
+ *) error "synchroniser '${call_args[*]}' exited ${rc}; the '${SYNCHRONISER}' command is missing from PATH, corrupt, or it threw" ;;
91
+ esac
92
+ return "${rc}"
93
+ }
94
+
95
+ # Wall-clock milliseconds. ${EPOCHREALTIME} is a bash 5 builtin (the image is
96
+ # node:22-bookworm-slim → bash 5.2) rather than `date +%s%3N`, which has to
97
+ # exec /bin/date inside the caller's command substitution: measured on a loaded
98
+ # box, that exec put ~190ms of its own cost INSIDE the window being measured,
99
+ # against ~23ms for this — overhead charged to the very number this exists to
100
+ # learn. The remaining ~23ms is the command substitution's subshell, kept
101
+ # because removing it means an out-parameter global, and ~2% of a ~1.2s call
102
+ # biases the reading generous, which is the safe direction for sizing a
103
+ # deadline.
104
+ #
105
+ # The `[.,]` is not paranoia: ${EPOCHREALTIME} renders its decimal separator
106
+ # from LC_NUMERIC, so a comma locale would otherwise silently produce garbage
107
+ # here. Stripping either turns it into whole microseconds, which /1000 makes
108
+ # milliseconds.
109
+ #
110
+ # Never fails its caller: a timing line is diagnostics, and hardening a
111
+ # currently-working path is worse than the gap it closes (#931). The `date`
112
+ # fallback covers a pre-5.0 bash; a 0 means "could not read the clock", which
113
+ # timed_synchroniser turns into `elapsed_ms=unknown` rather than aborting /run
114
+ # under `set -e` — and rather than a 0 that would read as a fast healthy call.
115
+ now_ms() {
116
+ local now="${EPOCHREALTIME:-}"
117
+ if [ -n "${now}" ]; then
118
+ now="${now/[.,]/}"
119
+ echo "$((now / 1000))"
120
+ return 0
121
+ fi
122
+ date +%s%3N 2>/dev/null || echo 0
123
+ }
124
+
125
+ # Reports what one step COST, in a deliberately machine-greppable line (`op=`,
126
+ # `elapsed_ms=`, `rc=`) so "how long does this actually take in the fleet?" is a
127
+ # log query rather than another spike. `at_s` is where the step landed on the
128
+ # hook's own SECONDS clock, which is what the pre-opencode budget in
129
+ # hook-scripts.test.ts is derived against.
130
+ #
131
+ # Callable directly, not only through timed_synchroniser below, because the
132
+ # steps that dominate the pre-opencode window CANNOT be wrapped: their stdout is
133
+ # captured (`x="$(run_synchroniser env)"`, later `eval`'d), so a `log` line
134
+ # emitted inside the substitution would be evaluated as configuration.
135
+ #
136
+ # `unknown`, never a number, when either end failed to read the clock (now_ms's
137
+ # 0). Subtracting them would report `elapsed_ms=0` — indistinguishable from a
138
+ # very fast healthy call, which would quietly bias the fleet-wide sizing data
139
+ # this line exists to produce, in the DANGEROUS direction (a deadline sized too
140
+ # tight). A non-numeric value drops out of an aggregate instead of poisoning it.
141
+ log_elapsed_since() {
142
+ local op="$1" started_ms="$2" rc="$3"
143
+
144
+ local finished_ms elapsed_ms="unknown"
145
+ finished_ms="$(now_ms)"
146
+ if [ "${started_ms}" -gt 0 ] && [ "${finished_ms}" -gt 0 ]; then
147
+ elapsed_ms="$((finished_ms - started_ms))"
148
+ fi
149
+
150
+ log "SYNCHRONISER-TIMING op=${op} elapsed_ms=${elapsed_ms} rc=${rc} at_s=${SECONDS}"
151
+ }
152
+
153
+ # Runs ONE synchroniser call and reports what it COST, without changing what it
154
+ # MEANS: the call's own status is returned untouched, so every caller's
155
+ # `|| return 1` / `|| status=$?` keeps working exactly as before.
156
+ #
157
+ # `deadline` is an explicit parameter, forwarded to run_synchroniser as a
158
+ # trailing `--evident-deadline=N` (never a global or dynamically-scoped
159
+ # variable, #930) — every current caller (restore_credentials) always has a
160
+ # positive remaining-budget value by the time it calls this, having already
161
+ # decided to skip the call entirely otherwise.
162
+ timed_synchroniser() {
163
+ local op="$1" deadline="$2"
164
+ shift 2
165
+
166
+ local started_ms rc=0
167
+ started_ms="$(now_ms)"
168
+ run_synchroniser "$@" "--evident-deadline=${deadline}" || rc=$?
169
+ log_elapsed_since "${op}" "${started_ms}" "${rc}"
170
+ return "${rc}"
171
+ }
172
+
173
+ # Exports what `runner-synchroniser` resolves its object-store location from
174
+ # (packages/runner-synchroniser/src/config.ts). It treats either being empty as
175
+ # "persistence disabled" and then reports every restore as a WARNING it still
176
+ # exits 0 for — so an unset value has to be caught HERE, where it can still be
177
+ # told apart from "the store is simply empty".
178
+ load_state_config() {
179
+ if [ -z "${LITESTREAM_BUCKET:-}" ]; then
180
+ error "LITESTREAM_BUCKET is unset; the image is missing the durable-state bucket the stack bakes in"
181
+ return 1
182
+ fi
183
+
184
+ LITESTREAM_PREFIX="$(cat "${STATE_PREFIX_FILE}" 2>/dev/null || true)"
185
+ if [ -z "${LITESTREAM_PREFIX}" ]; then
186
+ error "no durable-state prefix at ${STATE_PREFIX_FILE}; /run records the payload's state_prefix there before anything can be restored or flushed"
187
+ return 1
188
+ fi
189
+
190
+ export LITESTREAM_BUCKET LITESTREAM_PREFIX
191
+
192
+ # Mirrors runner-synchroniser's own persistenceEnabled predicate (config.ts):
193
+ # both non-empty, already checked above, so by this point PERSISTENCE_BUCKET
194
+ # is just LITESTREAM_BUCKET. start_litestream and flush_session_db (#812
195
+ # WI-3/WI-4) read ONLY this var, never LITESTREAM_BUCKET/LITESTREAM_PREFIX
196
+ # directly, so every entry point agrees on one predicate regardless of which
197
+ # earlier step in THIS hook process set it: restore_session_db's
198
+ # `eval "$(run_synchroniser env)"` on /run, or this function on /resume,
199
+ # /suspend and /terminate, none of which ever call the synchroniser before
200
+ # needing the answer.
201
+ export PERSISTENCE_BUCKET="${LITESTREAM_BUCKET}"
202
+ }
203
+
204
+ # /run starts no LLM task — it restores state, starts opencode and dials the
205
+ # tunnel, none of which needs a model credential. Which credential a turn needs
206
+ # depends on the model that turn's message asks for, so that question has no
207
+ # single boot-time answer; it is answered per message, not here. What IS still
208
+ # fatal is credential persistence being unavailable at all (an unset bucket/
209
+ # prefix, or a broken synchroniser bundle) — that would silently drop refreshed
210
+ # tokens on every suspend, so those two restores stay `|| return 1`.
211
+ # `model-auth-ready` therefore stays a boot-time diagnostic: its only output is
212
+ # a log line, since the runtime forwards no hook stderr to the doorbell caller.
213
+
214
+ # How long restore_credentials' shared step budget is, covering all THREE of
215
+ # its synchroniser calls (restore claude, restore opencode, model-auth-ready)
216
+ # as one window rather than a timeout apiece — a fixed per-call cap at the same
217
+ # total would false-fire on the ordinary case of one slow call (a slow S3 GET),
218
+ # which is precisely the boot this exists to keep healthy. From #930's 3-boot
219
+ # sample: the step measured ~3-5s total (~1.2s per call, three node cold
220
+ # starts of a 1.8 MB bundle) — a WEAK estimate this file's own
221
+ # SYNCHRONISER-TIMING lines are what will sharpen for real. Too tight and a
222
+ # routine slow call boots this VM with no model credentials until an operator
223
+ # reconnects it; too loose and a hung call burns more of the hook's own
224
+ # SIGTERM budget before the VM is destroyed mid-boot anyway. The env override
225
+ # is for tests only, so they need not burn wall clock.
226
+ CREDENTIAL_RESTORE_DEADLINE_SECONDS="${EVIDENT_CREDENTIAL_RESTORE_DEADLINE_SECONDS:-8}"
227
+ # The SIGKILL backstop `timeout -k` applies after its own SIGTERM, exactly like
228
+ # SESSION_DB_RESTORE_KILL_GRACE_SECONDS above (a bare `timeout` only SIGTERMs,
229
+ # and a call that ignored it would be unbounded again). Hard ceiling on the
230
+ # step: DEADLINE + this = 10s, once — not per call.
231
+ CREDENTIAL_RESTORE_KILL_GRACE_SECONDS=2
232
+
233
+ # What is left of the shared step budget, in whole seconds, `step_started_s`
234
+ # seconds after it began. `SECONDS` (a bash builtin with no failure mode,
235
+ # unlike `now_ms`) truncates, so a step that began at true time `s0` can read
236
+ # less elapsed time than actually passed — the `- 1` restores the invariant
237
+ # that no call is granted more than DEADLINE + GRACE from step start.
238
+ remaining_credential_budget() {
239
+ local step_started_s="$1"
240
+ echo $(( CREDENTIAL_RESTORE_DEADLINE_SECONDS - (SECONDS - step_started_s) - 1 ))
241
+ }
242
+
243
+ # Runs one of the step's bounded calls: skips it with a named warn if the
244
+ # shared budget is already exhausted, treats a timeout (124/137) as the
245
+ # non-fatal warn-and-continue D1 approved, and keeps every other non-zero
246
+ # fatal exactly as restore_credentials always has (`|| return 1` aborts /run
247
+ # before opencode and the tunnel start).
248
+ bounded_restore_call() {
249
+ local op="$1" step_started_s="$2"
250
+ shift 2
251
+
252
+ local remaining
253
+ remaining="$(remaining_credential_budget "${step_started_s}")"
254
+ if [ "${remaining}" -lt 1 ]; then
255
+ warn "CREDENTIAL-RESTORE-SKIPPED: ${op} skipped; the ${CREDENTIAL_RESTORE_DEADLINE_SECONDS}s credential-restore budget is exhausted"
256
+ return 0
257
+ fi
258
+
259
+ local rc=0
260
+ timed_synchroniser "${op}" "${remaining}" "$@" || rc=$?
261
+ case "${rc}" in
262
+ 0) ;;
263
+ 124 | 137)
264
+ warn "CREDENTIAL-RESTORE-TIMEOUT: ${op} did not finish within its ${remaining}s share of the ${CREDENTIAL_RESTORE_DEADLINE_SECONDS}s credential-restore deadline; continuing without it"
265
+ ;;
266
+ *) return 1 ;;
267
+ esac
268
+ return 0
269
+ }
270
+
271
+ restore_credentials() {
272
+ local step_started_ms step_started_s
273
+ step_started_ms="$(now_ms)"
274
+ step_started_s="${SECONDS}"
275
+
276
+ load_state_config || return 1
277
+ bounded_restore_call restore-claude "${step_started_s}" restore claude || return 1
278
+ bounded_restore_call restore-opencode "${step_started_s}" restore opencode || return 1
279
+
280
+ # `restore` exits 0 whether it restored, found nothing, or discarded a corrupt
281
+ # object, so the synchroniser's own predicate is the only reliable answer to
282
+ # "can this VM authenticate a model right now". Its status is captured, not
283
+ # used as a condition, so it can never become this function's return status —
284
+ # `run` calls this bare (no `||`) under `set -euo pipefail`, and any
285
+ # non-zero return here would abort the hook before opencode and the tunnel
286
+ # ever start.
287
+ local auth_status=0 auth_remaining
288
+ auth_remaining="$(remaining_credential_budget "${step_started_s}")"
289
+ if [ "${auth_remaining}" -lt 1 ]; then
290
+ warn "CREDENTIAL-RESTORE-SKIPPED: model-auth-ready skipped; the ${CREDENTIAL_RESTORE_DEADLINE_SECONDS}s credential-restore budget is exhausted"
291
+ else
292
+ timed_synchroniser model-auth-ready "${auth_remaining}" model-auth-ready || auth_status=$?
293
+ case "${auth_status}" in
294
+ 0) ;; # some model auth is configured; the two restores above already logged what they found
295
+ 10)
296
+ warn "no model credentials under s3://${LITESTREAM_BUCKET}/${LITESTREAM_PREFIX}/ \
297
+ (neither claude/credentials.json nor opencode/auth.json yielded valid JSON) and neither \
298
+ ANTHROPIC_API_KEY nor OPENAI_API_KEY is set. This VM boots and connects; a turn that needs \
299
+ a model provider fails until one is connected. See 'Seeding a credential store' in \
300
+ infrastructure/evident-microvm/README.md."
301
+ ;;
302
+ 124 | 137)
303
+ warn "CREDENTIAL-RESTORE-TIMEOUT: model-auth-ready did not finish within its ${auth_remaining}s share of the ${CREDENTIAL_RESTORE_DEADLINE_SECONDS}s credential-restore deadline; continuing without it"
304
+ ;;
305
+ *)
306
+ # run_synchroniser has already `error`ed the tool-broke line for a
307
+ # broken tool; any other unrecognised code lands here too. Do not
308
+ # claim there are no credentials — absent evidence is not contrary
309
+ # evidence (development-workflow.mdc).
310
+ warn "could not determine whether this VM has model credentials"
311
+ ;;
312
+ esac
313
+ fi
314
+ # The step total, in the SAME greppable shape as the per-call lines above, so
315
+ # one query answers both "what does credential restore cost?" and "which of
316
+ # its three calls cost it". Bounded now by CREDENTIAL_RESTORE_DEADLINE_SECONDS
317
+ # + CREDENTIAL_RESTORE_KILL_GRACE_SECONDS as one shared window (see the
318
+ # comment above that constant) rather than per call. `rc=0` is deliberate
319
+ # here, not an absence of failure modes: a timed-out call already warned by
320
+ # name above and is non-fatal by design (D1); every failure that DOES abort
321
+ # this step has already returned 1 above.
322
+ log_elapsed_since credential-restore-step "${step_started_ms}" 0
323
+ return 0
324
+ }
325
+
326
+ # Best-effort by design: /suspend must still drop the tunnel and /terminate must
327
+ # still clean up, so a flush that cannot happen is loud but never fatal.
328
+ sync_credentials() {
329
+ load_state_config || return 0
330
+ run_synchroniser sync-once claude || true
331
+ run_synchroniser sync-once opencode || true
332
+ }
333
+
334
+ # --- Session DB restore (#812 WI-2) ----------------------------------------
335
+ #
336
+ # Restores opencode.db from S3 before opencode opens it — the read half only.
337
+ # Writes NOTHING to S3 itself; replication back to S3 is started separately by
338
+ # `start_litestream` (below) from the `run`/`resume` hooks. `ensure_litestream_config`/
339
+ # `restore_session_db` are the MicroVM side of the same contract
340
+ # packages/runner-image/entrypoint.sh's inlined restore already speaks, going
341
+ # through the SAME runner-synchroniser CLI.
342
+
343
+ # Reads the ~30 MB litestream binary into the page cache, in the background, so
344
+ # the FIRST exec of it does not pay that read on the critical path.
345
+ #
346
+ # Why it is on the critical path at all: restore_session_db must finish before
347
+ # start_opencode, and HOOK_SIGTERM_SECONDS is a POINT on the hook's SECONDS
348
+ # clock, so a second spent here is a second taken from the rest of /run — and a
349
+ # /run that overruns is SIGTERMed mid-boot and its VM destroyed. (Until #1172
350
+ # the binding point was the tighter in-hook opencode readiness deadline; that
351
+ # deadline is gone, the hook's own SIGTERM is not.)
352
+ # Boot measurements put ~6.6-7.3s between the credential restore and the
353
+ # litestream version line, of which only ~0.2s is accounted for by the two node
354
+ # calls in between — the remainder is INFERRED to be this read, never measured.
355
+ # The `litestream-prewarm` and `litestream-version` timings are what settle it
356
+ # on the next boot.
357
+ #
358
+ # Nothing waits on it and nothing reads its output, so if that inference is
359
+ # wrong this costs one backgrounded `cat`. Deleting the `litestream version`
360
+ # diagnostic instead would save nothing: `litestream restore` two calls later
361
+ # pays the identical read.
362
+ prewarm_litestream() {
363
+ local binary
364
+ binary="$(command -v litestream 2>/dev/null || true)"
365
+ if [ -z "${binary}" ]; then
366
+ warn "litestream is not on PATH; skipping the boot pre-warm"
367
+ return 0
368
+ fi
369
+
370
+ # `cat` rather than a throwaway `litestream version`: a sequential read gets
371
+ # the whole file with readahead, where an exec demand-pages it.
372
+ (
373
+ local started_ms rc=0
374
+ started_ms="$(now_ms)"
375
+ cat "${binary}" >/dev/null 2>&1 || rc=$?
376
+ log_elapsed_since litestream-prewarm "${started_ms}" "${rc}"
377
+ ) &
378
+ log "pre-warming ${binary} in the background"
379
+ }
380
+
381
+ # Generates ${LITESTREAM_CONFIG_FILE} from runner-synchroniser's own renderer
382
+ # — the SAME config module the credential restore/sync already goes through,
383
+ # so there is no second copy of the bucket/prefix/path logic to drift
384
+ # (litestream-config.ts's own header makes the same point). Only when absent
385
+ # or empty, so `/resume` (WI-4) restarting litestream after a suspend/resume
386
+ # snapshot — /dev/shm intact — pays nothing to regenerate it.
387
+ #
388
+ # Returns 1 on failure — fatal to the CALLER, never to the hook: every caller
389
+ # (restore_session_db here, start_litestream in WI-3) must still let opencode
390
+ # and the tunnel start regardless.
391
+ ensure_litestream_config() {
392
+ if [ -s "${LITESTREAM_CONFIG_FILE}" ]; then
393
+ return 0
394
+ fi
395
+
396
+ # Timed OUTSIDE the substitution, not with timed_synchroniser: this call's
397
+ # stdout IS the config, so a timing line emitted inside `$(...)` would land in
398
+ # litestream.yml.
399
+ local rendered config_started_ms config_rc=0
400
+ config_started_ms="$(now_ms)"
401
+ rendered="$(run_synchroniser litestream-config)" || config_rc=$?
402
+ log_elapsed_since litestream-config "${config_started_ms}" "${config_rc}"
403
+ if [ "${config_rc}" -ne 0 ]; then
404
+ error "could not generate ${LITESTREAM_CONFIG_FILE}: runner-synchroniser litestream-config failed (see the error above)"
405
+ return 1
406
+ fi
407
+ printf '%s\n' "${rendered}" >"${LITESTREAM_CONFIG_FILE}" || {
408
+ error "could not write ${LITESTREAM_CONFIG_FILE}"
409
+ return 1
410
+ }
411
+
412
+ # Q7's diagnostic, for whoever can read this VM's CloudWatch log: which way
413
+ # litestream resolved its AWS region, and whether it can even see the
414
+ # names it would need to (never the VALUES of any OTHER AWS_* variable —
415
+ # AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN may be present here).
416
+ local region_empty="yes"
417
+ if printf '%s\n' "${rendered}" | grep -Eq '^ *region: *[^[:space:]]'; then
418
+ region_empty="no"
419
+ fi
420
+ # Hoisted out of the log line below so it can be timed: this is the FIRST exec
421
+ # of the litestream binary on the boot, and the pre-warm /run fires (see
422
+ # prewarm_litestream) is aimed squarely at what this number measures.
423
+ local version_started_ms litestream_version
424
+ version_started_ms="$(now_ms)"
425
+ litestream_version="$(litestream version 2>/dev/null || echo 'unknown')"
426
+ log_elapsed_since litestream-version "${version_started_ms}" 0
427
+ log "litestream ${litestream_version}; AWS_REGION=${AWS_REGION:-<unset>} AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-<unset>}; rendered litestream.yml region empty: ${region_empty}"
428
+ }
429
+
430
+ # Writes the marker AND names the reason, in one call, so the marker can never
431
+ # appear silently. Every give-up path in restore_session_db calls this EXCEPT
432
+ # the classifier's 31 (#1106 — see that branch), and no success path ever does.
433
+ # It is what a later `/resume`/`start_litestream` (WI-3) reads to skip
434
+ # replicating this boot: a local DB that is only PARTIALLY restored must never
435
+ # be allowed to overwrite a replica this boot never proved safe to write over.
436
+ # A merely FRESH local DB is not that danger — litestream continues the txid
437
+ # chain — which is precisely why 31 no longer belongs here.
438
+ mark_no_replicate() {
439
+ : >"${SESSION_DB_NO_REPLICATE_MARKER}"
440
+ warn "SESSION-DB-NO-REPLICATE: $1"
441
+ }
442
+
443
+ # Removes local session-DB debris a give-up path leaves behind. Called on
444
+ # EVERY give-up path and NO success path: skipping it on a give-up is a real
445
+ # bug (a truncated file left in place makes opencode fail to open a malformed
446
+ # database, which fails /run outright — worse than the history loss this
447
+ # discards); calling it on a success path would delete a good restore. One
448
+ # `rm -f` per path, not a single command, so a failure removing one does not
449
+ # skip the other two.
450
+ discard_session_db_debris() {
451
+ rm -f "${OPENCODE_DB_PATH}" "${OPENCODE_DB_PATH}-wal" "${OPENCODE_DB_PATH}-shm"
452
+ }
453
+
454
+ # How long restore_session_db waits for ONE `litestream restore` before giving
455
+ # up. From M4 (see the plan's §2): ~50 MB/s extrapolated from the x86_64 ECS
456
+ # container's own live replica, so 7s covers roughly 300-350 MB — an
457
+ # EXTRAPOLATION, not a MicroVM measurement (different arch, network path and
458
+ # credential source); the boot line ensure_litestream_config logs, plus the
459
+ # ${SECONDS} stamps in /run, are how it gets measured here for real.
460
+ #
461
+ # 7 rather than the 8 it was: hook-scripts.test.ts's pre-opencode ladder held an
462
+ # allowance of 4s for the rest of this step, which live boots measured at
463
+ # 6.7-7.4s, so the ladder passed while real boots blew the deadline. Correcting
464
+ # that allowance is what takes this second — the remedy the ladder's own failure
465
+ # message prescribes, and the one that leaves the SIGTERM worst case untouched.
466
+ # The cost is real and unmeasured on this platform: ~50 MB less restorable
467
+ # replica before a truncation that silently loses history. A fresh
468
+ # state_prefix starts at zero, so this is generous for a long time, but
469
+ # RoutingStrategy is 'per_user' only (routing-strategy.ts) and every prefix is
470
+ # deterministic and permanent per (pool, routing key) — so a long-lived
471
+ # runner's opencode.db grows monotonically across VM generations, exactly
472
+ # like the ~1 GB ECS one M4 measured, and will eventually hit this ceiling.
473
+ # Past it the restore is truncated (SESSION-DB-RESTORE-TRUNCATED, below) and
474
+ # this boot skips replication — silent, permanent history loss for that
475
+ # runner unless somebody reads the log. Not solved here (WI-0 Task 0.2).
476
+ # The env override is for tests only, so they need not burn 7s of wall clock.
477
+ SESSION_DB_RESTORE_DEADLINE_SECONDS="${EVIDENT_SESSION_DB_RESTORE_DEADLINE_SECONDS:-7}"
478
+ # The SIGKILL backstop `timeout -k` applies after its own SIGTERM: `timeout`
479
+ # alone only SIGTERMs, and a litestream that ignored it would be unbounded
480
+ # again. Hard ceiling on this step: DEADLINE + this = 9s.
481
+ SESSION_DB_RESTORE_KILL_GRACE_SECONDS=2
482
+
483
+ # The one bounded restore attempt, run before start_opencode (opencode opens
484
+ # the DB the moment it starts, so this is the only place it can happen).
485
+ # Every branch returns 0 — /run calls this bare under `set -euo pipefail`,
486
+ # exactly like restore_credentials, and nothing about the session DB may ever
487
+ # fail /run (Q3): a /run that exits 1 fails the whole lifecycle transition
488
+ # and the user gets NO runner at all, which is worse than losing history.
489
+ restore_session_db() {
490
+ # Cleanup, not a decision, and unconditionally first: /dev/shm survives
491
+ # suspend/resume and a /run retry, so a marker left by an earlier boot must
492
+ # never silently disable replication for the rest of this VM's life.
493
+ rm -f "${SESSION_DB_NO_REPLICATE_MARKER}"
494
+
495
+ # Config resolved ONCE here, in the synchroniser (config.ts owns
496
+ # OPENCODE_DB_PATH; no second copy of that path here), exactly as
497
+ # entrypoint.sh's own line does. Unlike ECS's `|| die`, a failure here must
498
+ # not abort the hook — `x="$(cmd)"` under `set -e` WOULD abort the whole
499
+ # shell on a failing substitution, which is exactly why it is caught
500
+ # explicitly rather than left to `set -e`.
501
+ # Timed OUTSIDE the substitution for the same reason ensure_litestream_config
502
+ # is: this call's stdout is `eval`'d, so a timing line emitted inside `$(...)`
503
+ # would be evaluated as configuration.
504
+ local synchroniser_env env_started_ms env_rc=0
505
+ env_started_ms="$(now_ms)"
506
+ synchroniser_env="$(run_synchroniser env)" || env_rc=$?
507
+ log_elapsed_since session-db-env "${env_started_ms}" "${env_rc}"
508
+ if [ "${env_rc}" -ne 0 ]; then
509
+ mark_no_replicate "could not resolve the runner-synchroniser configuration (see the ERROR above)"
510
+ return 0
511
+ fi
512
+ # Guarded for the SAME reason as the substitution above, which is easy to miss:
513
+ # `eval` returns the status of what it ran, so a malformed line from a skewed
514
+ # bundle would abort /run right here under `set -e` — before start_opencode,
515
+ # so the user gets NO runner at all. entrypoint.sh:110 leaves the identical
516
+ # line bare because on ECS the blast radius is a crash-loop-and-replace; here
517
+ # it is the whole lifecycle transition, so Q3 makes it a give-up instead.
518
+ eval "${synchroniser_env}" || {
519
+ mark_no_replicate "the runner-synchroniser configuration could not be evaluated; the installed bundle likely does not match this hook"
520
+ return 0
521
+ }
522
+
523
+ # #931's exact lesson, one shell over (packages/runner-image/entrypoint.sh):
524
+ # the `|| { ... }` above only catches a non-zero EXIT — an `env` that exits
525
+ # 0 with an INCOMPLETE contract (a runner-synchroniser version/build skew)
526
+ # would otherwise abort right here under `set -u` the moment
527
+ # `${OPENCODE_DB_PATH}` is dereferenced below. entrypoint.sh may `die` on
528
+ # this (ECS just crash-loops and replaces the task); this hook cannot —
529
+ # Q3 says nothing about the session DB may ever fail /run — so a missing
530
+ # OPENCODE_DB_PATH is a give-up, not a silent default (a guessed path would
531
+ # be actively wrong, not merely absent).
532
+ if [ -z "${OPENCODE_DB_PATH+x}" ]; then
533
+ mark_no_replicate "run_synchroniser env did not define OPENCODE_DB_PATH; the installed runner-synchroniser build likely does not match this hook"
534
+ return 0
535
+ fi
536
+
537
+ # #770's arm, checked FIRST of the decisions and with its OWN message —
538
+ # never the SESSION-DB-REPLICA-UNUSABLE one below (#764's finding: an
539
+ # operator grepping that marker must not hit the disabled case).
540
+ # PERSISTENCE_BUCKET is empty exactly when LITESTREAM_BUCKET or
541
+ # LITESTREAM_PREFIX is unset (config.ts's persistenceEnabled) — the
542
+ # IDENTICAL predicate ECS's own litestream-launch gate uses
543
+ # (entrypoint.sh), so the two images agree on what "disabled" means.
544
+ if [ -z "${PERSISTENCE_BUCKET:-}" ]; then
545
+ warn "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; opencode starts with a fresh session DB and nothing is replicated."
546
+ return 0
547
+ fi
548
+
549
+ if ! ensure_litestream_config; then
550
+ mark_no_replicate "could not generate ${LITESTREAM_CONFIG_FILE} (see the error above)"
551
+ return 0
552
+ fi
553
+
554
+ local restore_rc=0 restore_started_ms
555
+ restore_started_ms="$(now_ms)"
556
+ timeout -k "${SESSION_DB_RESTORE_KILL_GRACE_SECONDS}" "${SESSION_DB_RESTORE_DEADLINE_SECONDS}" \
557
+ litestream restore -config "${LITESTREAM_CONFIG_FILE}" \
558
+ -if-db-not-exists -if-replica-exists "${OPENCODE_DB_PATH}" || restore_rc=$?
559
+ log_elapsed_since session-db-restore "${restore_started_ms}" "${restore_rc}"
560
+
561
+ # `timeout`'s OWN codes, handled BEFORE classifying: 124/137 are a
562
+ # TRUNCATED restore, not a corrupt replica — handing them to
563
+ # session-db-classify would mislabel a slow/large replica as one. 125-127
564
+ # mean `timeout` (or litestream itself) is broken, not the replica.
565
+ case "${restore_rc}" in
566
+ 124 | 137)
567
+ discard_session_db_debris
568
+ mark_no_replicate "SESSION-DB-RESTORE-TRUNCATED: litestream restore did not finish within the ${SESSION_DB_RESTORE_DEADLINE_SECONDS}s deadline (+${SESSION_DB_RESTORE_KILL_GRACE_SECONDS}s kill grace), ${SECONDS}s into the hook; opencode starts with a fresh session DB and nothing is replicated this boot"
569
+ return 0
570
+ ;;
571
+ 125 | 126 | 127)
572
+ error "litestream restore could not even run (timeout exited ${restore_rc})"
573
+ discard_session_db_debris
574
+ mark_no_replicate "restore tool is broken (timeout exited ${restore_rc}); opencode starts with a fresh session DB and nothing is replicated this boot"
575
+ return 0
576
+ ;;
577
+ esac
578
+
579
+ local classify_rc=0
580
+ run_synchroniser session-db-classify "${restore_rc}" 1 --on-unusable-replica=leave || classify_rc=$?
581
+ case "${classify_rc}" in
582
+ 0) ;; # restored, or no replica yet — the CLI already logged which
583
+ 31)
584
+ # The classifier already discarded the local debris (session-db.ts) — and
585
+ # that is exactly why this is the ONE give-up path that does NOT
586
+ # mark_no_replicate (#1106). Every other give-up here may be sitting on a
587
+ # half-restored DB, so the marker stays; a 31 is structurally guaranteed
588
+ # to be a FRESH one, and replicating it starts a new backup chain instead
589
+ # of leaving this boot with a zero-width backup window. Same reasoning,
590
+ # and same one-line change, as packages/runner-image/entrypoint.sh's `31)`.
591
+ warn "SESSION-DB-REPLICA-UNUSABLE: booting with a fresh opencode.db and starting a fresh backup chain this boot (see the WARNING above)"
592
+ ;;
593
+ 32)
594
+ # The CLI's own contract for 32 is "re-run litestream restore and ask
595
+ # again", but this hook has budget for exactly ONE attempt (Q4) — name
596
+ # the deviation so nobody reads this as a bug.
597
+ discard_session_db_debris
598
+ mark_no_replicate "session-db-classify asked for another restore attempt (32), but this hook has budget for only one; treating it as a give-up rather than retrying"
599
+ ;;
600
+ 30)
601
+ # The CLI already logged its own FATAL line above; Q3 still says boot
602
+ # fresh rather than fail /run.
603
+ discard_session_db_debris
604
+ mark_no_replicate "session-db-classify returned fatal (30); see the FATAL message above"
605
+ ;;
606
+ *)
607
+ # run_synchroniser already logged the "tool broke" ERROR for this.
608
+ discard_session_db_debris
609
+ mark_no_replicate "session-db-classify exited ${classify_rc}, which is none of its documented answers"
610
+ ;;
611
+ esac
612
+
613
+ return 0
614
+ }
615
+ # --- Session DB restore (end) -----------------------------------------------
616
+
617
+ # `kill -0` answers "does this pid exist", which is not the question any caller
618
+ # here is asking. A process that has exited but has not been reaped — a zombie —
619
+ # still exists, so `kill -0` reports a corpse as ALIVE. That condition is the
620
+ # normal case for everything these hooks start: `start_tunnel`/`start_opencode`
621
+ # background a process that outlives the hook, the hook shell must return so AWS
622
+ # gets its 200, and PID 1 in this image is a bare node hook server with no init
623
+ # (Dockerfile) — so nothing ever wait()s for the orphan. It stayed a zombie for
624
+ # the rest of the VM's life, which made `stop_tunnel` burn its whole budget
625
+ # SIGKILLing a corpse and made a stale pid file suppress the next
626
+ # `start_tunnel`, leaving a resumed VM permanently offline (#718).
627
+ #
628
+ # This is zombie-safe, NOT identity-safe: a recycled pid reads R/S and is still
629
+ # called alive, so the SIGKILL backstop could in principle hit an unrelated
630
+ # process. Pre-existing limitation of the pid-file approach, out of scope here —
631
+ # named so nobody over-trusts the helper (src/image/hook-scripts.test.ts).
632
+ #
633
+ # Also sets PROC_DEAD_REASON on every return path — "gone" for a `kill -0`
634
+ # miss, "zombie" for an unreaped `Z`, reset to empty on the alive path so a
635
+ # stale value from a previous call can never be read — for the caller that
636
+ # needs to say WHICH death it was (stop_tunnel's outcome line), never for this
637
+ # function itself: see the silence note below. File-scope init (below) is what
638
+ # keeps a read of it safe under `set -u` before this has ever run.
639
+ PROC_DEAD_REASON=""
640
+
641
+ process_is_alive() {
642
+ if ! kill -0 "$1" 2>/dev/null; then
643
+ PROC_DEAD_REASON="gone"
644
+ return 1
645
+ fi
646
+
647
+ # `/proc/<pid>/status` rather than `/proc/<pid>/stat`, whose fields cannot be
648
+ # split safely when a comm contains a space or a paren. If the state cannot be
649
+ # read at all, keep the `kill -0` answer: absent evidence is not "dead", and
650
+ # reading it as dead would SIGTERM-and-forget a live, still-draining CLI.
651
+ # Three fields, not two: `read` hands the whole remainder to its LAST variable,
652
+ # so a trailing `_` is what keeps the state letter out of `Z (zombie)`.
653
+ #
654
+ # That deferral is silent HERE on purpose: `stop_tunnel` polls this 10x/s, so a
655
+ # warning inside it would bury the log. The flag lets `is_running` say it once
656
+ # per guard instead — absent evidence must warn as well as defer
657
+ # (development-workflow.mdc).
658
+ PROC_STATE_UNREADABLE=0
659
+ local state
660
+ read -r _ state _ < <(grep -m1 '^State:' "/proc/$1/status" 2>/dev/null) || {
661
+ PROC_STATE_UNREADABLE=1
662
+ PROC_DEAD_REASON="" # unreadable /proc still means "alive" below, not a dead reason
663
+ return 0
664
+ }
665
+
666
+ if [ "${state}" = "Z" ]; then
667
+ PROC_DEAD_REASON="zombie"
668
+ return 1
669
+ fi
670
+
671
+ PROC_DEAD_REASON=""
672
+ return 0
673
+ }
674
+
675
+ is_running() {
676
+ [ -s "$1" ] || return 1
677
+
678
+ local pid
679
+ pid="$(cat "$1")"
680
+ process_is_alive "${pid}" || return 1
681
+
682
+ # The one state in which this whole helper is back to being a bare `kill -0`
683
+ # (a `hidepid=` mount, a `/proc` that is not mounted): every liveness answer
684
+ # silently reverts to #718 — a corpse reads as alive, so suspend SIGKILLs it
685
+ # after the full wait and the next start is suppressed for the VM's life.
686
+ [ "${PROC_STATE_UNREADABLE}" = 0 ] \
687
+ || warn "could not read /proc/${pid}/status; falling back to 'kill -0', which reports an exited-but-unreaped process as alive (#718)"
688
+
689
+ return 0
690
+ }
691
+
692
+ # The snapshot bakes one machine id into every VM launched from this image
693
+ # version, so /run replaces it. Best-effort per file: the hook runs as uid 10001
694
+ # and these live in root-owned directories, so a VM that kept the snapshot's id
695
+ # must still boot — but it says so, because it is a state worth being able to see.
696
+ regenerate_machine_id() {
697
+ local machine_id
698
+ machine_id="$(tr -d '-' </proc/sys/kernel/random/uuid)"
699
+
700
+ for path in /etc/machine-id /var/lib/dbus/machine-id; do
701
+ printf '%s\n' "${machine_id}" >"${path}" 2>/dev/null \
702
+ || warn "could not rewrite ${path}; this VM keeps the snapshot's machine id"
703
+ done
704
+ }
705
+
706
+ tunnel_is_running() { is_running "${TUNNEL_PID_FILE}"; }
707
+ opencode_is_running() { is_running "${OPENCODE_PID_FILE}"; }
708
+ litestream_is_running() { is_running "${LITESTREAM_PID_FILE}"; }
709
+
710
+ # `jq -e` alone is not enough: its exit status reflects the LAST OUTPUT VALUE,
711
+ # and an interpolation of a missing field is still a non-empty string, so a
712
+ # payload with no runner_key would sail through as the literal "null".
713
+ payload_is_complete() {
714
+ jq -e '
715
+ (.runner_key | type == "string" and length > 0)
716
+ and (.endpoints.api | type == "string" and length > 0)
717
+ and (.endpoints.tunnel | type == "string" and length > 0)
718
+ and (.state_prefix | type == "string" and length > 0)
719
+ ' >/dev/null 2>&1
720
+ }
721
+
722
+ # `setsid` so opencode outlives this hook: the script must return so AWS gets its
723
+ # 200, while opencode keeps serving. The guard makes /run idempotent — a retry
724
+ # after a killed hook must not put a second instance on the same port.
725
+ start_opencode() {
726
+ if opencode_is_running; then
727
+ warn "opencode already running (pid $(cat "${OPENCODE_PID_FILE}")); reusing it"
728
+ return 0
729
+ fi
730
+
731
+ setsid opencode serve \
732
+ --hostname 127.0.0.1 \
733
+ --port "${OPENCODE_PORT}" \
734
+ --print-logs &
735
+
736
+ echo $! >"${OPENCODE_PID_FILE}"
737
+ log "opencode starting (pid $(cat "${OPENCODE_PID_FILE}"))"
738
+ }
739
+
740
+ stop_opencode() {
741
+ if ! opencode_is_running; then
742
+ # Clear the file here too, for the same reason stop_tunnel does: opencode
743
+ # has exit paths that never reach this function (a crash, an OOM kill), so
744
+ # the pid file routinely outlives the process it names, and leaving it is
745
+ # #718 again the moment anything starts reaping orphans and the pid is
746
+ # recycled.
747
+ rm -f "${OPENCODE_PID_FILE}"
748
+ log "no opencode to stop"
749
+ return 0
750
+ fi
751
+
752
+ kill -TERM "$(cat "${OPENCODE_PID_FILE}")" 2>/dev/null || true
753
+ rm -f "${OPENCODE_PID_FILE}"
754
+ log "opencode stopped"
755
+ }
756
+
757
+ # The ceiling stop_opencode_and_wait (below) waits before its SIGKILL backstop.
758
+ # /terminate can afford a real drain — the VM is being torn down either way —
759
+ # unlike /run's cleanup, which cannot (stop_opencode's own cheapness above is
760
+ # load-bearing for that budget, §4, and must not grow a wait).
761
+ OPENCODE_STOP_WAIT_SECONDS="${EVIDENT_OPENCODE_STOP_WAIT_SECONDS:-5}"
762
+
763
+ # The graceful stop /terminate needs (#812 WI-4): SIGTERM, poll for exit,
764
+ # SIGKILL backstop, clear the pid file. A NEW function rather than growing
765
+ # stop_opencode itself, for the reason above — mirrors stop_tunnel's and
766
+ # stop_litestream's shape, including PROC_DEAD_REASON's one deciding read
767
+ # after the poll loop (never inside it, which would bury the log at 10x/s).
768
+ # This is half of the ordered-shutdown invariant (plan §6): /terminate must
769
+ # stop opencode BEFORE flush_session_db's final sync, or litestream could
770
+ # snapshot while opencode is still writing its WAL and the last session
771
+ # writes would be missing from S3.
772
+ stop_opencode_and_wait() {
773
+ if ! opencode_is_running; then
774
+ rm -f "${OPENCODE_PID_FILE}"
775
+ log "no opencode to stop"
776
+ return 0
777
+ fi
778
+
779
+ local pid
780
+ pid="$(cat "${OPENCODE_PID_FILE}")"
781
+ kill -TERM "${pid}" 2>/dev/null || true
782
+
783
+ local tenths=0
784
+ local deadline_tenths=$(( OPENCODE_STOP_WAIT_SECONDS * 10 ))
785
+ while [ "${tenths}" -lt "${deadline_tenths}" ]; do
786
+ process_is_alive "${pid}" || break
787
+ sleep 0.1
788
+ tenths=$(( tenths + 1 ))
789
+ done
790
+
791
+ local outcome
792
+ if process_is_alive "${pid}"; then
793
+ warn "opencode ${pid} ignored SIGTERM; killing"
794
+ kill -KILL "${pid}" 2>/dev/null || true
795
+ outcome="after SIGKILL (ignored SIGTERM for ${OPENCODE_STOP_WAIT_SECONDS}s)"
796
+ else
797
+ outcome="cleanly in $(( tenths / 10 )).$(( tenths % 10 ))s (${PROC_DEAD_REASON})"
798
+ fi
799
+
800
+ rm -f "${OPENCODE_PID_FILE}"
801
+ log "opencode stopped ${outcome}"
802
+ }
803
+
804
+ # --- litestream replicate (#812 WI-3) ---------------------------------------
805
+ #
806
+ # The write half of session-DB persistence. restore_session_db (above) is the
807
+ # read half only and never starts this. Q8 chose one backgrounded, unsupervised
808
+ # `litestream replicate` over a periodic flush or a `replicate -exec` wrapper
809
+ # around opencode: SIGTERM is `replicate`'s own final-sync trigger, so
810
+ # stop_litestream (below) doubles as the checked flush /suspend and /terminate
811
+ # need, and there is no supervisor in this image to hand the process to (no
812
+ # init, no `wait -n` shell that could stay alive after the hook returns).
813
+
814
+ # The graceful wait before the SIGKILL backstop in stop_litestream, below.
815
+ # litestream's own sync is normally sub-second, so 10s is generous headroom —
816
+ # chosen the same way TUNNEL_STOP_WAIT_SECONDS was, not a measured worst case.
817
+ LITESTREAM_STOP_WAIT_SECONDS="${EVIDENT_LITESTREAM_STOP_WAIT_SECONDS:-10}"
818
+
819
+ # Guards, in this exact order and no other — reordering any of them re-arms the
820
+ # invariant it exists to protect:
821
+ #
822
+ # 1. persistence disabled (#770) — bucket AND prefix both non-empty — is its
823
+ # OWN arm with its OWN message, checked FIRST, and must never log
824
+ # SESSION-DB-REPLICA-UNUSABLE: an operator grepping that marker must not
825
+ # hit the disabled case (#764).
826
+ # 2. the no-replicate marker (restore_session_db above) — set when this boot's
827
+ # local DB may be only PARTIALLY restored, so starting replicate here would
828
+ # let it overwrite a replica this boot never proved safe to write over.
829
+ # A classifier 31 no longer sets it (#1106): that DB is guaranteed fresh,
830
+ # and skipping replicate for it was what made the history loss unbounded.
831
+ # 3. no usable config — ensure_litestream_config (restore_session_db, above)
832
+ # already logged why it is missing; this is not a place to retry it.
833
+ # 4. already running — idempotence, mirroring start_tunnel's own guard.
834
+ #
835
+ # Only past all four does it actually spawn, backgrounded with `setsid` for the
836
+ # same reason start_opencode/start_tunnel are: the hook must return so AWS gets
837
+ # its 200, while replicate keeps running. litestream's OWN stderr is left to
838
+ # reach CloudWatch — never redirected — because there is no supervisor in this
839
+ # image, so that is the only channel that can say why a replicator died.
840
+ start_litestream() {
841
+ if [ -z "${PERSISTENCE_BUCKET:-}" ]; then
842
+ warn "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; nothing is replicated."
843
+ return 0
844
+ fi
845
+
846
+ if [ -e "${SESSION_DB_NO_REPLICATE_MARKER}" ]; then
847
+ log "skipping litestream replicate: this boot's session DB was not proven safe to replicate (see the SESSION-DB-* warning above)"
848
+ return 0
849
+ fi
850
+
851
+ if [ ! -s "${LITESTREAM_CONFIG_FILE}" ]; then
852
+ error "no usable ${LITESTREAM_CONFIG_FILE}; not starting litestream replicate"
853
+ return 0
854
+ fi
855
+
856
+ if litestream_is_running; then
857
+ warn "litestream already running (pid $(cat "${LITESTREAM_PID_FILE}")); reusing it"
858
+ return 0
859
+ fi
860
+
861
+ setsid litestream replicate -config "${LITESTREAM_CONFIG_FILE}" &
862
+
863
+ echo $! >"${LITESTREAM_PID_FILE}"
864
+ log "litestream replicate starting (pid $(cat "${LITESTREAM_PID_FILE}"))"
865
+ }
866
+
867
+ # The graceful stop: mirrors stop_tunnel exactly, including PROC_DEAD_REASON's
868
+ # one deciding read AFTER the poll loop (never inside it, which polls 10x/s and
869
+ # would bury the log) — gone / zombie / SIGKILLed are the three outcomes an
870
+ # operator needs told apart, not a flatter clean/killed binary. /suspend and
871
+ # /terminate call this: the SIGTERM it sends IS the checked flush they need.
872
+ stop_litestream() {
873
+ if ! litestream_is_running; then
874
+ rm -f "${LITESTREAM_PID_FILE}"
875
+ log "no litestream to stop"
876
+ return 0
877
+ fi
878
+
879
+ local pid
880
+ pid="$(cat "${LITESTREAM_PID_FILE}")"
881
+ kill -TERM "${pid}" 2>/dev/null || true
882
+
883
+ local tenths=0
884
+ local deadline_tenths=$(( LITESTREAM_STOP_WAIT_SECONDS * 10 ))
885
+ while [ "${tenths}" -lt "${deadline_tenths}" ]; do
886
+ process_is_alive "${pid}" || break
887
+ sleep 0.1
888
+ tenths=$(( tenths + 1 ))
889
+ done
890
+
891
+ local outcome
892
+ if process_is_alive "${pid}"; then
893
+ warn "litestream ${pid} ignored SIGTERM; killing"
894
+ kill -KILL "${pid}" 2>/dev/null || true
895
+ outcome="after SIGKILL (ignored SIGTERM for ${LITESTREAM_STOP_WAIT_SECONDS}s)"
896
+ else
897
+ outcome="cleanly in $(( tenths / 10 )).$(( tenths % 10 ))s (${PROC_DEAD_REASON})"
898
+ fi
899
+
900
+ rm -f "${LITESTREAM_PID_FILE}"
901
+ log "litestream stopped ${outcome}"
902
+ }
903
+
904
+ # The cheap stop: one SIGTERM, one rm, one log line, NO poll loop — `/run`'s
905
+ # own cleanup calls this, never stop_litestream, because that path only runs
906
+ # after /run has already FAILED: no session happened yet, so a graceful final
907
+ # sync is worth nothing against a SIGTERM budget that cannot afford another
908
+ # wait on top of stop_tunnel's own. A distinct function rather than a mode
909
+ # argument on stop_litestream:
910
+ # stop_tunnel's own comment argues against an argument a future caller can get
911
+ # wrong. litestream_is_running is the same O(1) check stop_litestream's own
912
+ # no-op branch uses, not a poll — /run's cleanup trap fires this before
913
+ # start_litestream is ever reached whenever an earlier step failed, and an
914
+ # operator reading that log must not be told a stop signal went to a process
915
+ # that never started.
916
+ kill_litestream() {
917
+ if ! litestream_is_running; then
918
+ rm -f "${LITESTREAM_PID_FILE}"
919
+ log "no litestream to stop"
920
+ return 0
921
+ fi
922
+
923
+ kill -TERM "$(cat "${LITESTREAM_PID_FILE}")" 2>/dev/null || true
924
+ rm -f "${LITESTREAM_PID_FILE}"
925
+ log "litestream stop signalled (no wait)"
926
+ }
927
+ # --- litestream replicate (end) ----------------------------------------------
928
+
929
+ # --- flush_session_db (#812 WI-4) -------------------------------------------
930
+ #
931
+ # The checked, synchronous flush /suspend and /terminate need before they
932
+ # finish tearing down. Never fatal, for the same reason every session-DB
933
+ # function in this file is: /suspend and /terminate must complete their own
934
+ # teardown regardless of whether S3 could be reached.
935
+
936
+ # Ceiling for the one-shot `litestream replicate -once` flush below. litestream's
937
+ # own sync is normally sub-second (M5, the plan's grounding); 10s is generous
938
+ # headroom, chosen the same way LITESTREAM_STOP_WAIT_SECONDS was above — not a
939
+ # measured worst case. The SIGKILL backstop below reuses
940
+ # SESSION_DB_RESTORE_KILL_GRACE_SECONDS rather than its own literal: it is the
941
+ # identical concept (bare `timeout` only SIGTERMs, and a litestream that
942
+ # ignored it would be unbounded again), and there is no reason for the restore
943
+ # and flush paths to ever drift on how long a SIGTERM gets to land.
944
+ SESSION_DB_FLUSH_DEADLINE_SECONDS="${EVIDENT_SESSION_DB_FLUSH_DEADLINE_SECONDS:-10}"
945
+
946
+ # Guards mirror start_litestream's first three exactly (disabled -> marker ->
947
+ # config) — a flush must never attempt work those guards would have refused
948
+ # to start in the first place. PERSISTENCE_BUCKET is the SAME variable
949
+ # start_litestream reads, so both agree regardless of which earlier step in
950
+ # THIS process set it (load_state_config, above, or restore_session_db's
951
+ # eval, on /run).
952
+ #
953
+ # Then: stop the daemon FIRST — its SIGTERM IS litestream's own final-sync
954
+ # trigger — and only once it is confirmed stopped does the synchronous -once
955
+ # flush run, as a second, checked pass. Running -once while the daemon is
956
+ # still alive would put two writers on one prefix, the single-writer
957
+ # invariant this whole feature exists to protect (Q8) — this ordering is not
958
+ # negotiable.
959
+ #
960
+ # If the daemon has already died (a missing or stale pid file), that IS the
961
+ # detection this needs: SESSION-DB-REPLICATOR-DIED names it loudly instead of
962
+ # silently skipping straight to the flush (development-workflow.mdc: every
963
+ # recovery branch emits a server-visible signal). The flush still runs either
964
+ # way — it is what actually gets any unreplicated writes to S3 before the
965
+ # caller's next step.
966
+ flush_session_db() {
967
+ if [ -z "${PERSISTENCE_BUCKET:-}" ]; then
968
+ warn "SESSION-DB-PERSISTENCE-DISABLED: LITESTREAM_BUCKET/LITESTREAM_PREFIX are not both set; nothing to flush."
969
+ return 0
970
+ fi
971
+
972
+ if [ -e "${SESSION_DB_NO_REPLICATE_MARKER}" ]; then
973
+ log "skipping session-DB flush: this boot's session DB was not proven safe to replicate (see the SESSION-DB-* warning above)"
974
+ return 0
975
+ fi
976
+
977
+ if [ ! -s "${LITESTREAM_CONFIG_FILE}" ]; then
978
+ error "no usable ${LITESTREAM_CONFIG_FILE}; cannot flush the session DB"
979
+ return 0
980
+ fi
981
+
982
+ if litestream_is_running; then
983
+ stop_litestream
984
+ else
985
+ warn "SESSION-DB-REPLICATOR-DIED: no live litestream at ${LITESTREAM_PID_FILE}; flushing one-shot anyway"
986
+ fi
987
+
988
+ # Only reached with the daemon confirmed stopped, or never running — never
989
+ # concurrently with it (see above).
990
+ local flush_rc=0
991
+ timeout -k "${SESSION_DB_RESTORE_KILL_GRACE_SECONDS}" "${SESSION_DB_FLUSH_DEADLINE_SECONDS}" \
992
+ litestream replicate -once -config "${LITESTREAM_CONFIG_FILE}" || flush_rc=$?
993
+
994
+ if [ "${flush_rc}" -eq 0 ]; then
995
+ log "SESSION-DB-FINAL-FLUSH: succeeded, ${SECONDS}s into the hook"
996
+ else
997
+ warn "SESSION-DB-FINAL-FLUSH: litestream replicate -once exited ${flush_rc}, ${SECONDS}s into the hook; some writes since the last sync may not have reached S3"
998
+ fi
999
+ }
1000
+ # --- flush_session_db (end) --------------------------------------------------
1001
+
1002
+ # How long the guest CLI runs with no activity before it exits itself
1003
+ # (`evident run --idle-timeout`, apps/cli/src/commands/run.ts), which is what
1004
+ # turns a truly-abandoned VM into the clean-offline POST that lets Evident
1005
+ # suspend it (#732). Sized from the measured cost of guessing wrong rather than
1006
+ # the saving: suspend reaches SUSPENDED in ~7 s and a resume is RUNNING in
1007
+ # ~0.6 s with the tunnel back ~2 s later (README, "Measured, end to end"), so
1008
+ # napping a VM whose user comes straight back costs ~10 s — against ~$0.30/h
1009
+ # that is cheap enough that the balance sits far nearer the floor than the
1010
+ # ceiling. Not AT the floor, though: the CLI's idle detector needs 2 clear poll
1011
+ # cycles (`run.ts`'s `idlePolls >= 2`, ≥4 s of real time), so a value near that
1012
+ # would spend more time suspending/resuming than idle.
1013
+ # ECS's waker uses 900 s instead only because *its* cold start is far slower
1014
+ # than this VM's ~2 s resume — not evidence this default should match it.
1015
+ #
1016
+ # NOT part of the hook's own teardown budget (TUNNEL_STOP_WAIT_SECONDS et al.,
1017
+ # below): it governs the CLI's lifetime long after the hook has already
1018
+ # returned its 200, so it is deliberately outside that arithmetic.
1019
+ #
1020
+ # EVIDENT_IDLE_TIMEOUT_SECONDS, deliberately the SAME env var name
1021
+ # packages/runner-image/entrypoint.sh uses for the ECS runner's own
1022
+ # idle-timeout flag, so an operator who knows one knows the other. A
1023
+ # non-numeric override must never silently DROP the flag — that degrades to
1024
+ # an always-on VM burning ~$2.40/day, exactly the bug this closes — so it
1025
+ # warns and falls back to the default instead.
1026
+ #
1027
+ # Deliberately NOT in the /run payload yet: doing so would touch the doorbell
1028
+ # contract in four coordinated places for no capability today. #716 shipped
1029
+ # the swarm/per-user provisioner but explicitly scoped control-plane
1030
+ # idle/suspend policy OUT (its own "Phase 3" — see the issue's "Out of
1031
+ # Scope"), so a per-pool idle policy is still a clean follow-up, not
1032
+ # something #716 already provides a home for.
1033
+ IDLE_TIMEOUT_SECONDS=120
1034
+ if [ -n "${EVIDENT_IDLE_TIMEOUT_SECONDS:-}" ]; then
1035
+ if [[ "${EVIDENT_IDLE_TIMEOUT_SECONDS}" =~ ^[0-9]+$ ]]; then
1036
+ IDLE_TIMEOUT_SECONDS="${EVIDENT_IDLE_TIMEOUT_SECONDS}"
1037
+ else
1038
+ warn "EVIDENT_IDLE_TIMEOUT_SECONDS='${EVIDENT_IDLE_TIMEOUT_SECONDS}' is not numeric; using the default ${IDLE_TIMEOUT_SECONDS}s instead of leaving the VM always-on"
1039
+ fi
1040
+ fi
1041
+
1042
+ # `setsid` so the tunnel outlives this hook: the script must return so AWS gets
1043
+ # its 200, while the tunnel keeps serving.
1044
+ start_tunnel() {
1045
+ local runner_key="$1" api_url="$2" tunnel_url="$3"
1046
+
1047
+ if tunnel_is_running; then
1048
+ warn "tunnel already running (pid $(cat "${TUNNEL_PID_FILE}")); not starting a second one"
1049
+ return 0
1050
+ fi
1051
+
1052
+ # The key travels in the child's environment ONLY: argv is world-readable
1053
+ # through /proc.
1054
+ # --enable-file-sync-to is what makes the UI's "connect a provider account"
1055
+ # flow reach this VM: without it the CLI declines every queued file and the
1056
+ # page can only say "this runner isn't accepting files". There is no shell
1057
+ # into a MicroVM, so it is the ONLY way to seed model credentials on a runner
1058
+ # that is already up — the S3 credential store is read at /run and /resume,
1059
+ # never mid-life. The allow-list stays a single directory, as on ECS
1060
+ # (packages/runner-image/entrypoint.sh): the flag is repeatable, but every
1061
+ # extra entry widens what Evident can write into a VM that executes agent
1062
+ # code. ${HOME} is set by the image (ENV HOME=/home/runner) and `set -u` makes
1063
+ # an unset one abort rather than silently allow-list "/.claude".
1064
+ EVIDENT_RUNNER_KEY="${runner_key}" setsid evident run \
1065
+ --port "${OPENCODE_PORT}" \
1066
+ --endpoint "${api_url}" \
1067
+ --tunnel "${tunnel_url}" \
1068
+ --idle-timeout "${IDLE_TIMEOUT_SECONDS}" \
1069
+ --enable-file-sync-to "${HOME}/.claude" &
1070
+
1071
+ echo $! >"${TUNNEL_PID_FILE}"
1072
+ log "tunnel started (pid $(cat "${TUNNEL_PID_FILE}"))"
1073
+ }
1074
+
1075
+ # The worst case `evident run` can take to shut down gracefully on SIGTERM, in
1076
+ # whole seconds: 25 s in-flight drain (SHUTDOWN_DRAIN_TIMEOUT_MS,
1077
+ # apps/cli/src/commands/run.ts) + 2 s offline POST (notifyAgentDisconnected,
1078
+ # apps/cli/src/commands/agent-lookup.ts) + 5 s telemetry flush
1079
+ # (TELEMETRY_SHUTDOWN_TIMEOUT_MS, run.ts). Each of the three is bounded there, so
1080
+ # this is a ceiling rather than a typical cost — an idle suspend finishes in a
1081
+ # couple of seconds. This is the ONE place the budget is written down; the CLI
1082
+ # only points back here, because restating it in three places produced #657.
1083
+ #
1084
+ # DOCUMENTATION ONLY — nothing is derived from this any more. The wait below
1085
+ # used to be pinned above it, which is the reasoning that talked #699 into 40 s;
1086
+ # since #718 an exited CLI is noticed on the first poll, so the wait is a
1087
+ # backstop chosen on its own merits and the two numbers are unrelated. Nothing
1088
+ # cross-checks the 32 against apps/cli either: it is a hand-maintained sum of the
1089
+ # three bounds cited above, so if one of them moves, update it here.
1090
+ # shellcheck disable=SC2034 # documentation; deliberately read by nothing
1091
+ CLI_SHUTDOWN_CEILING_SECONDS=32
1092
+
1093
+ # How long stop_tunnel waits for that shutdown before the SIGKILL backstop.
1094
+ # Since #718 this binds ONLY for a CLI that is still draining: one that has
1095
+ # already exited is detected on the first 0.1 s poll whatever this says, because
1096
+ # process_is_alive no longer mistakes its unreaped corpse for a live process.
1097
+ # That is what takes a routine suspend from ~41 s back to the ~2 s it measures.
1098
+ #
1099
+ # So 10 is chosen, not derived, and it sits in the middle of a real range. The
1100
+ # measured shutdown was 1255 ms of drain inside a 2322 ms total (#697): 5 s is
1101
+ # only ~2.2x that and re-arms #657's complaint of a kill landing mid-drain,
1102
+ # while 30 s never truncates a legitimate drain but rebuilds the headroom
1103
+ # problem #699 created — 41 s against a 60 s lifecycleTimeout leaves 19 s for
1104
+ # everything else in the hook. 10 s is ~4x the measured shutdown and gives a
1105
+ # provable worst case of 10 + the 10 s `suspend` spends in sync_credentials
1106
+ # before us = 20 s, inside the ~55 s the in-VM server allows this script
1107
+ # (DEFAULT_TIMEOUT_SECONDS, packages/lambda-microvm-runtime/src/runtime.ts),
1108
+ # itself inside AWS's 60 s (HOOK_TIMEOUT_SECONDS, src/constants.ts) —
1109
+ # overrunning that fails the whole lifecycle transition, which is worse than the
1110
+ # kill this replaces. The residual cost is a drain longer than 10 s being
1111
+ # truncated; that work stays `processing` server-side and is re-adopted on the
1112
+ # next start (ADR-0046).
1113
+ #
1114
+ # src/image/hook-scripts.test.ts holds both that this stays small and that it
1115
+ # fits the hook timeout, and times a real SIGKILL against the override to prove
1116
+ # the loop HONOURS it rather than a hardcoded deadline. The env override is for
1117
+ # tests only, so they need not burn 10 s of wall clock.
1118
+ TUNNEL_STOP_WAIT_SECONDS="${EVIDENT_TUNNEL_STOP_WAIT_SECONDS:-10}"
1119
+
1120
+ stop_tunnel() {
1121
+ if ! tunnel_is_running; then
1122
+ # Clear the file here too, not only on the path below: `evident run` has
1123
+ # self-exit paths that never reach this function (auth expired, idle
1124
+ # timeout, a crash), so the pid file routinely outlives the process it
1125
+ # names. Leaving it means every later guard re-reads a dead pid — harmless
1126
+ # while process_is_alive agrees it is dead, and #718 again the moment
1127
+ # anything starts reaping orphans and the pid gets recycled.
1128
+ rm -f "${TUNNEL_PID_FILE}"
1129
+ log "no tunnel to stop"
1130
+ return 0
1131
+ fi
1132
+
1133
+ local pid
1134
+ pid="$(cat "${TUNNEL_PID_FILE}")"
1135
+ # One drain length for every caller: /suspend and /terminate always run over
1136
+ # a connected tunnel, and /run's and /resume's own cleanup traps only reach a
1137
+ # live tunnel here when it was never started (the cheap no-op branch above) —
1138
+ # there is no path left where a just-spawned, not-yet-connected tunnel is the
1139
+ # one being stopped, so there is nothing left to special-case.
1140
+ kill -TERM "${pid}" 2>/dev/null || true
1141
+
1142
+ local tenths=0
1143
+ local deadline_tenths=$(( TUNNEL_STOP_WAIT_SECONDS * 10 ))
1144
+ while [ "${tenths}" -lt "${deadline_tenths}" ]; do
1145
+ process_is_alive "${pid}" || break
1146
+ sleep 0.1
1147
+ tenths=$(( tenths + 1 ))
1148
+ done
1149
+
1150
+ # This call, not the loop's, is the deciding read: it is what the `if` below
1151
+ # branches on, so PROC_DEAD_REASON is fresh by construction. A corpse can
1152
+ # still be reaped between the loop's last poll and this call, so the reason
1153
+ # named below is what THIS call saw, not necessarily what the loop saw.
1154
+ local outcome
1155
+ if process_is_alive "${pid}"; then
1156
+ warn "tunnel ${pid} ignored SIGTERM; killing"
1157
+ kill -KILL "${pid}" 2>/dev/null || true
1158
+ outcome="after SIGKILL (ignored SIGTERM for ${TUNNEL_STOP_WAIT_SECONDS}s)"
1159
+ else
1160
+ outcome="cleanly in $(( tenths / 10 )).$(( tenths % 10 ))s (${PROC_DEAD_REASON})"
1161
+ fi
1162
+
1163
+ rm -f "${TUNNEL_PID_FILE}"
1164
+ log "tunnel stopped ${outcome}"
1165
+ }
1166
+
1167
+ # --- check_runner_key (#1172) ------------------------------------------------
1168
+ #
1169
+ # Answers exactly one question before opencode/the tunnel start spending this
1170
+ # boot's SIGTERM budget on a key that cannot work: "does the runner key in this
1171
+ # payload authenticate against Evident?" Delegates entirely to the CLI's own
1172
+ # `evident status --json` (apps/cli/src/commands/status.ts) rather than
1173
+ # reimplementing its auth logic here — that command's `reason` field is the
1174
+ # published contract this function reads, and its own header states the
1175
+ # absent-vs-contrary distinction this function must honour.
1176
+ #
1177
+ # Keyed on the JSON `reason`, NEVER on the exit code: an older CLI without a
1178
+ # `status` subcommand exits 1 from Commander's own "unknown command" handling,
1179
+ # which under an exit-code mapping would read as "the key was rejected" and
1180
+ # destroy every VM on a hook/CLI version skew — precisely the hazard this
1181
+ # image's README's "version skew" section flags. So no parseable JSON line
1182
+ # means no verdict, whatever the exit code says.
1183
+ #
1184
+ # Returns 0 for positive AND absent evidence (network/timeout/5xx/404/old-CLI/
1185
+ # crash) — the caller continues either way — and 1 ONLY for contrary evidence
1186
+ # (401, another 4xx, or no credentials resolved at all): the key is actually
1187
+ # wrong, not merely untested (development-workflow.mdc's "never fail a gate on
1188
+ # absent evidence"). Every branch logs a named, greppable RUNNER-KEY-* signal
1189
+ # so a caller that treats the return value as fatal (or doesn't) still leaves
1190
+ # a trace of which branch fired.
1191
+ #
1192
+ # A 404 is deliberately NOT contrary: it means the endpoint has no /me route,
1193
+ # so the key was never tested. Treating it as a rejection destroyed every VM
1194
+ # for a day when the run payload shipped a bare origin instead of the CLI's
1195
+ # /v1-prefixed one.
1196
+ check_runner_key() {
1197
+ local runner_key="$1" api_url="$2"
1198
+
1199
+ # status.ts's own exit-code contract (its header comment) means this exits
1200
+ # non-zero on EVERY branch except `ok` — guarded exactly like
1201
+ # ensure_litestream_config's `run_synchroniser litestream-config` call,
1202
+ # above, so that expected non-zero does not abort this function under the
1203
+ # caller's `set -e` before the case below ever runs. Only stdout is
1204
+ # captured: status.ts's own contract is one parseable JSON line and nothing
1205
+ # else there, and — like litestream's stderr elsewhere in this file — its
1206
+ # stderr is left to reach CloudWatch directly rather than being folded in,
1207
+ # since a stray stderr line ahead of the JSON would otherwise break `jq`.
1208
+ local response rc=0
1209
+ response="$(EVIDENT_API_URL="${api_url}" EVIDENT_RUNNER_KEY="${runner_key}" evident status --json)" || rc=$?
1210
+
1211
+ # `-z` as well as jq's own exit code, and not as belt-and-braces: on EMPTY
1212
+ # input jq has no value to report on, so `jq -e` exits 0 with empty output
1213
+ # rather than its documented 4 (verified on jq 1.6, the image's). Empty
1214
+ # stdout is exactly the old-CLI-skew and missing-binary shape this branch
1215
+ # exists for, so keying only on the exit code sent precisely those cases to
1216
+ # the unrecognised-reason arm below — same safe return, but a log line
1217
+ # blaming the API for an odd answer instead of naming the CLI skew, which is
1218
+ # the one thing an operator needs told here.
1219
+ local reason
1220
+ reason="$(printf '%s' "${response}" | jq -er '.reason' 2>/dev/null)" || reason=""
1221
+ if [ -z "${reason}" ]; then
1222
+ warn "RUNNER-KEY-UNVERIFIABLE: 'evident status --json' exited ${rc} with no parseable JSON on stdout (an old CLI without this subcommand, a missing binary, or a crash — see its stderr above, if any); the key was NOT validated, continuing anyway"
1223
+ return 0
1224
+ fi
1225
+ local detail
1226
+ detail="$(printf '%s' "${response}" | jq -er '.error // empty' 2>/dev/null)" || detail=""
1227
+
1228
+ case "${reason}" in
1229
+ ok)
1230
+ log "RUNNER-KEY-OK: evident status confirmed the runner key against ${api_url}"
1231
+ return 0
1232
+ ;;
1233
+ unauthorized | no_credentials | http_error)
1234
+ error "RUNNER-KEY-REJECTED: evident status reason=${reason} against ${api_url}${detail:+: ${detail}}"
1235
+ return 1
1236
+ ;;
1237
+ unreachable)
1238
+ warn "RUNNER-KEY-UNREACHABLE: could not reach ${api_url} to validate the runner key; the key was NOT validated, continuing anyway"
1239
+ return 0
1240
+ ;;
1241
+ endpoint_not_found)
1242
+ # Absent evidence, NOT contrary: a 404 means this endpoint has no /me
1243
+ # route (typically a bare origin where the CLI wants the /v1-prefixed
1244
+ # one), which says nothing about the key. Loud, because the runner will
1245
+ # keep failing every API call until the endpoint is fixed.
1246
+ warn "RUNNER-KEY-ENDPOINT-NOT-FOUND: ${api_url} has no /me route${detail:+: ${detail}}; the key was NOT validated, continuing anyway"
1247
+ return 0
1248
+ ;;
1249
+ *)
1250
+ warn "RUNNER-KEY-UNKNOWN-REASON: evident status returned an unrecognised reason='${reason}'; the key was NOT validated, continuing anyway"
1251
+ return 0
1252
+ ;;
1253
+ esac
1254
+ }
1255
+ # --- check_runner_key (end) ---------------------------------------------------