# Hosted runners 1a, Task 17b: live plan for sections 7 and 8 (for Paul's approval)

**Revision:** 1 (2026-11-30), derived from the Task 17 plan revision 5
(`docs/superpowers/plans/2026-11-23-hosted-1a-task17-live-plan.md`, `52a771ad`), which attempt 4
ran to completion on 2026-11-28 with sections 7 and 8 skipped by a plan defect (evidence
`f0e0b525`). **Status:** draft for approval. No AWS command or SDK call of any kind was made while
writing it. This plan is self-contained: the executor runs it alone, block by block, and never
needs revision 5.

## What Paul approves

One run in account `640012953448` (profile `kass`), region `eu-west-1`, every call behind the
account and region guard; IAM is the one global-endpoint exception (R37) and there is no billing
call (R33). Nothing touches account `149757027610` (equipo-hosted): the guard aborts on any other
account, and any ARN naming `149757027610` is a hard stop. The run builds only what sections 7 and
8 need (network, connector, one Small image version, SNS topic, keys and config), re-runs one live
contract subtest (`ChangedSpecConflicts`, expected to pass now), then runs the controller on docs-t1:
the driver sequence (launch, drain, quiescent, suspend, resume, stop with proof), the crash between
the provider call and transaction 2 with Replay claiming the one VM, and a planted orphan the reaper
must stop. Then it tears everything down and verifies it gone. Every Lambda MicroVMs and Lambda core
call goes through `livectl`, the pinned Go SDK tool (R40), which refuses any other account, region
or name outside the run; EC2, IAM, S3, SNS, CloudWatch Logs and STS stay on the CLI. Every taggable
resource carries `purpose=equipo-hosted-dev` and `run=<RUN>`; MicroVMs (no tag field) and the
connector's Lambda-managed interfaces are recorded by ID and proven gone (R34). The code is the
exact revision `PIN_SHA` `bf29344a` (R35), and the controller's reaper sees only this run's image
(R32). The run stops hard only for safety: the wrong account or region, spend (the run's own
estimate reaching $5; $10 is the approval ceiling), a MicroVM alive outside its step (the orphan
alive past P+15:00 included), or anything not in the ledger. It also stops when a step that later
steps need cannot complete (a resource that cannot be created or deleted). Everything else that
differs from expectation becomes a `FINDING:` line in the journal and the run goes on where it
safely can; the report lists every FINDING. Paul also pre-approves these fallbacks: the operator
role uses the AWS-managed connector policy plus a subnet-scoped delete from the start; 3.7 and 3.8
step down one base image version once; and 10.2 drops the delete policy's managed-operator condition
once if the connector cannot be deleted. Expected spend is about $0.20, worst case about $5.55,
retained image storage after an early stop about $0.24 to $6.53 a month. Guarded, run-scoped,
read-only calls on this run's own resources are pre-approved even where this plan does not print
them; a failed observation read is a FINDING. Reads needed for identity, ownership, settlement,
deletion or a named later step stay fatal. Any other change to a command, or any other AWS call,
comes back to Paul first.

## Changes from revision 5

1. **Scope.** Only revision 5's sections 7 and 8, plus the setup and teardown they need: 0, 1, 2,
   3 (Small only), 4, 5, one contract subtest (6), 7, 8, 10, S, 11 and 12. Section 9 (facts) is
   dropped: attempt 4 settled it. The full contract run is dropped; 6.1 re-runs only
   `ChangedSpecConflicts`, expected to PASS with the client-token fix (`5f6e3e65`). A failure is a
   FINDING, and every VM it made is settled before section 7.
2. **Code pin.** `PIN_SHA` is `bf29344a` (`bf29344a8b6832dff425aafc1337d4883f6a894f`): the
   ErrConflict fix `5f6e3e65` with its two review test rows, on the origin/main merge `2d6d2345`.
   0.1 checks that HEAD contains it, that it contains `a36861a0` (livectl), `bdf85fb7` (livectl
   final), `f95575c6` (R32) and `5f6e3e65` (client-token ErrConflict), and that nothing outside
   `docs/` changed since it; it runs livectl's offline tests and the awsjob package's offline
   tests. The SHA is written once, in 0.1; 0.2 reads it from the file 0.1 leaves, so a re-pin is a
   one-line change.
3. **The 5.6 defect is fixed.** Revision 5 required a `network_audit_passed` audit row, which the
   controller writes only when an audit passes again after failing
   (`internal/hostedctl/reaper.go:739-747`); a clean first pass writes none, so attempt 4 set
   `AUDIT_OK=no` and skipped 7 and 8. 5.6 now requires what a clean start does produce: readiness
   (`equipo_hosted_network_audit_passing 1` and `equipo_hosted_reap_last_error 0`,
   `internal/hostedctl/metrics.go:118-131`), captured while the controller runs; exactly one
   `provider_bound` row naming `aws:640012953448:eu-west-1` (`internal/hostedctl/store.go:366-372`);
   the `provider_binding` namespace; no `network_audit_failed` row and no
   `hosted controller: network audit failed` log line (`internal/hostedctl/logs.go:35`). A
   `network_audit_passed` row is recorded as a fact only.
4. **MicroVM ID pattern.** Live IDs are `microvm-<uuid>` (44 characters, attempt 4). `harvest` and
   7.3's crash-log grep now use `VMID_RE`,
   `microvm-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`, not `mvm-...`. The
   adapter's own check (`isolatedjob.Ref.Valid`, `internal/isolatedjob/isolatedjob.go:41-53`,
   R36) is letters, digits and `-` up to the maximum length, which is too loose to pick IDs out of
   a log, so `harvest` also reports any other `microvm-...` token (other than `microvm-image...`)
   as a FINDING; the image-scoped scans stay the inventory.
5. **Log and metric checks re-read against the code.** Every grep, metric line and audit action
   was checked at `bf29344a`: `launches enabled: <bool>` (`cmd/equipo-hosted-controller/main.go:120`),
   the crash point's `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1` and `crash point: the provider launched <vm>
   for <attempt>` lines (`crashpoint.go:35,46`), `hosted controller: orphan VM stopped` and
   `... left running for a dispatched launch intent` (`logs.go:18,29`), `restart stop requested,
   elapsed time unknown` (`logs.go:44`), the job-state and alert metric lines
   (`metrics.go:104-153,213-227`), and the audit actions in `launch.go:58-70`, `pause.go:35-49`,
   `resume.go:32-39`, `stop.go:44-52` and `reaper.go:48-56`. Controller log checks now read only the
   lines written since the latest start (`ctl_log`), so one start's lines never satisfy or fail
   another start's check. 7.2 and 7.4 check the named audit actions; each missing one is a FINDING.
6. **No Large version.** The adapter needs at least one version per image
   (`internal/isolatedjob/awsjob/runner.go:141-151`), and every launch in 6, 7 and 8 is Small
   (`internal/hostedclient/driver_test.go:45`, the contract's `SizeSmall`, livectl's
   `-version $VER_SMALL`). Revision 5's 3.9 is gone; its image read moves into 3.8; both configs
   list `small` only. One build and one stored version less.
7. **SNS topic kept.** `sns_topic_arn` is required (`cmd/equipo-hosted-controller/config.go:122-127`;
   the SNS alerter is wired at `main.go:104`), and 8.2 counts the `orphan_stopped` alert as sent
   through it. Revision 5 said 5.6 "proves the SNS topic takes startup alerts"; it does not: startup
   alerts are queued only after a wall-clock rollback (`internal/hostedctl/store.go:226-235`), so
   8.2's alert is the first publish.
8. **The sequence attempt ID is set by the plan** (`EQUIPO_HOSTED_LIVE_ATTEMPT`, read by
   `TestLiveControllerSequence`), not parsed from the test log.
9. **Metric reads in 7 and 8 are observations.** A metrics read that fails is a FINDING (`mread`),
   not a hard stop; the listener check stays a hard stop.
10. **Blocks and the controller run as systemd user units (R44), and blocks never overlap.**
    Attempt 4 started 7.2, 7.3 and 7.4 back to back. Every long block now runs as the transient
    user unit `t17b-<RUN>-<block>.service` and every controller start as
    `t17b-<RUN>-ctl-<label>.service` (`systemd-run --user --collect`, `KillMode=control-group`,
    `TimeoutStopSec=45`), so systemd tracks each one's processes by its cgroup and reaps them.
    Every start, stop and state read goes by unit name; there are no PID files, PID signals or
    environment markers. A unit is proved stopped only when it is inactive or failed and gone, or
    its cgroup is empty; anything unknown is `unresolved`. The long-block start refuses while a block
    unit is running or unresolved, and `env.sh` refuses to load while a block unit other than its own
    is. A block past its bound is stopped with `systemctl --user stop`. S.0, a local emergency stop
    run before `env.sh`, stops every unit of the run and proves each one done before S.1 to S.3; if
    it cannot, that is a hard stop that prints the unit names for Paul. 0.2 proves the mechanism
    with a probe unit before any AWS call. Helpers: `unitctl.sh` and `bin/exitpost.sh` (0.2).
11. **Fresh scratch and names.** Scratch is `$TMPDIR/equipo-t17b` (and `$TMPDIR/equipo-t17b-pre` for
    0.1 and 0.2); revision 5's 0.1a (attempt 1's scratch) is gone. The run ID is
    `<mmdd>-b<6 hex>`, so every name is run-unique, with the same collision checks (R39). The base
    name keeps livectl's fixed prefix `equipo-hosted-dev-t17-<RUN>`.
12. **Spend.** Expected about $0.20; worst case about $5.55; self-stop at the run's own estimate of
    $5; ceiling $10. 11.2's estimator is updated for this run (one version, two counted pause
    cycles, launch snapshot reads per VM).
13. **Section 12** is re-run: what attempt 4 settled is moved to "settled"; new items are listed.
14. **Unit environment and ownership (R45, applied after Astra's round 3).**
    - Every unit's command is `/usr/bin/env -i <allowlisted NAME=value...> <program> <args>`
      (`--expand-environment=no`), so the argument list is the program's whole environment and
      nothing from the user manager's environment reaches it. The allowlist keeps PATH, HOME, the
      Go settings and the AWS profile and region; `start_ctl` adds explicit controller defaults
      (`AWS_PROFILE=kass`, `AWS_REGION` and `AWS_DEFAULT_REGION` `eu-west-1`) and the
      `EQUIPO_HOSTED_*` settings it is given. `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH` is set only in 7.3's
      unit. 7.4 reads the restarted unit's `ExecStart` and checks its `env -i` argument list has no
      crash switch; a failed or unreadable read fails the block (`soft_fail`). 0.2's probe unit
      records its environment and must show only allowlisted names.
    - 0.2 reserves the run ID atomically (`mkdir "$HOME/.cache/t17b-runs/<RUN>"`, a new ID if it
      exists), then requires `systemctl --user list-units --all 't17b-<RUN>-*'` to be empty, before
      any unit or AWS call. Every unit name is journalled (`UNIT <name>`) before its `systemd-run`,
      and every stop, S.0's included, acts only on journalled names; the glob is a cross-check, and
      a matching unit that was not journalled is reported for Paul and never stopped. 10.9 removes
      exactly the reservation directory, and its parent only if empty (`rmdir`).
    - S.0 stops and proves the block units first, then re-reads the journal and stops and proves
      the controller units, then takes a final inventory of the journalled units plus the glob
      cross-check before it prints done.

## Order of execution

| Run order | Section | Roughly |
| --- | --- | --- |
| 1 | 0. Guard rails, code pin, collision checks | 10 min |
| 2 | 1. Network | 5 to 10 min |
| 3 | 2. Connector | 10 to 15 min |
| 4 | 3. Image, Small version only | 10 to 30 min |
| 5 | 4. SNS topic | 2 min |
| 6 | 5. Keys, config, builds, and the audit-only controller run | 10 min |
| 7 | 6. Live contract subtest `ChangedSpecConflicts`, every VM settled | 5 to 10 min |
| 8 | 7. Controller sequence, crash and Replay | 30 to 45 min |
| 9 | 8. Orphan | 20 to 25 min |
| 10 | 10. Teardown and verification | 20 to 45 min (up to 130 with 10.2's fallback) |

About 2 to 3 hours in all. 11.2 (the spend estimate) runs at the end of every section. The SDK-side
network audit (5.6) runs before any VM is launched, so the connector's `VersionArn` and Elastic IP
setting are checked by the controller's own code before the first launch.

## Rules for every block

- **Every block runs with the agent sandbox off.** Attempt 1 showed the sandbox proxy blocks AWS
  (its allowlist has no `*.amazonaws.com`, and `allowed_domains` is ignored in this session), and
  `$TMPDIR` is a different path inside and outside the sandbox. Running every block the same way
  keeps `$TMPDIR/equipo-t17b` one directory and lets AWS calls through.
- **Every block runs as its own script, `bash <file>`.** The agent writes each block's text,
  exactly as printed (only the `<T17 printed by 0.2>` path filled in), to `$T17/blocks/<block>.sh`
  and runs `bash "$T17/blocks/<block>.sh"` in the foreground, or detached for the long blocks below.
  0.1 and 0.2 run before the scratch exists, so they go to `$TMPDIR/equipo-t17b-pre/` instead
  (the executor creates that directory, mode 700, for them), which 10.9 removes.
  It never pastes a block into the tool's shell: the plan writer found on 2026-11-28 that a tool's
  wrapper can run commands in a context where `set -e` is ignored, which would let a failed command
  pass silently. Run as a script, `set -e` is in force, and every hard stop also reaches the parent
  through `die`'s FATAL marker.
- **One block, one Bash tool call, run by bash.** Every block begins with
  `set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"` and, if it calls AWS, `guard`. The
  environment file (0.2) defines every helper the blocks use; nothing is pasted by hand.
- **One block at a time.** A block starts only after the previous one has finished: a foreground
  block has returned, and a long block's wait call has printed its exit status. The start call for
  a long block refuses while any block unit of the run is running or unresolved, and `env.sh`
  refuses to load (exit 1) while a block unit other than the one loading it is, so an overlap stops
  at once. Unresolved means its state cannot be established, or its status is `unresolved`; the
  proof is described under the long-block mechanism. After an abort, S.0 stops every unit of the
  run before anything sources `env.sh` again. (Attempt 4 started 7.2, 7.3 and
  7.4 back to back; with section 7 skipped it did no harm, but it would have with the controller
  running.)
- **Two kinds of stop (Paul, 2026-11-28).** `die` is kept for the hard stops: the wrong account or
  region (`guard`, livectl's own guard), spend (11.2's $5 rule; $10 is the approval ceiling), a
  MicroVM alive outside its step (`settle_all`, `vm_end`, the orphan bound), anything not in the
  ledger (collision checks, unknown resources, unresolved creations), and a step later steps need
  that cannot complete (a create or delete that fails, the connector's qualified ARN, the image).
  Everything else that differs from expectation is a `finding`: a `FINDING` line in the journal,
  printed with `FINDING:`, and the block goes on. The report lists every FINDING.
- **The read-only envelope.** Guarded (`guard`, livectl's own guard), run-scoped, read-only calls
  on this run's own resources are pre-approved, including ones this plan does not print. A read
  that only observes, and errors or answers differently, is a FINDING (`fact_eq`, `fact_json`,
  `fact_lv`, `eni_snapshot soft`). A read needed for identity, ownership, settlement, deletion or a
  named later step stays fatal: the VM scans and `vm_end`, the collision checks, the connector's
  qualified ARN, the base image list, the default-resource lookups, the interface list before the
  connector delete, and every deletion check.
- **Failure is loud.** A failed command that is not handled ends the block. Calls that are expected
  to fail run under `try` or `lv` and pass only through an explicit branch that names the accepted
  error codes. Every poll fails when its bound runs out.
- **livectl (R40).** Every Lambda MicroVMs and Lambda core call goes through `lv`, which runs
  `$T17/bin/livectl -run <RUN>` (built in 0.2 from the pinned code). livectl takes only static keys
  (R41), and `kass` resolves through a `credential_process`, so each call first runs
  `aws configure export-credentials --profile kass --format process` and starts livectl in a
  subshell holding only `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and, if one was issued,
  `AWS_SESSION_TOKEN`, with `AWS_PROFILE`, `AWS_CONFIG_FILE` and `AWS_SHARED_CREDENTIALS_FILE` unset
  (R42). The keys live only in that subshell's environment: never on disk, in the journal, in an
  argument list or in output. A failed or incomplete export is a hard stop (as livectl's exit 4). Its replies are the SDK's
  output structs with Go field names (`State`, `VersionArn`, `MicrovmId`) and unions under
  `.Value`; its errors are one JSON line whose `code` `lv` puts in `ECODE` and whose `aws_message`
  it puts in `LV_MSG`. Client tokens start with the run prefix, as livectl requires. Exit codes, as
  livectl defines them at `PIN_SHA`:
  - **4** (guard: account, region, run prefix, missing `-run`, or credentials that are not static
    keys) and **3** (usage) are hard stops, inside `lv` itself.
  - **2** (an SDK call failed; livectl makes one attempt per call, so a throttle, a 5xx or no answer
    within its 60 s cutoff, `"error":"transport"`, all come back as 2). On a read, `lvr` tries a
    transient failure up to 3 times, 5 s apart; what is left is a FINDING, except where a hard stop
    depends on the read (the VM scans, `vm_end`, the collision checks, the connector's qualified
    ARN, the base image list). On a change it follows the block's own branches; only idempotent
    deletes and terminates use `lvr`.
  - **5** (a wait's bound passed, including an answer that came after it) and **6** (a failed
    state) are handled by each block against its bound. `lv_wait` gives each wait one overall bound
    and carries on through a transient exit 2 inside it, as a FINDING.
- **A hard stop means the safe stop (section S, starting with S.0), then ask Paul.** Nothing else
  runs after it.
- **Ledger.** Before each create call the block writes an `INTENT` line (kind, run-specific name or
  token); after the call it records the confirmed ID with `rec` (checked writes, ARN checks). Every
  MicroVM ID that appears anywhere is added to the VM ledger with `vmrec`. A deletion is recorded
  with `deleted` only after a direct read shows it gone. Teardown and the safe stop work only from
  these records; nothing is ever adopted or deleted because its name looks right.
- **Skip-never-created rule.** Teardown (section 10) and the safe stop act only on resources with
  a confirmed creation record, that is, a ledger variable set by `rec` (`VPC`, `CONN_ARN`,
  `IMAGE_ARN`, `BUCKET_CREATED` and so on; the names in `run.env` alone do not count). `have` sees
  three states. Confirmed: act. Never attempted, or the last attempt followed by a `NOTCREATED`
  record (from S.2 or a refused create): journal `SKIP <variable>` and skip. Unresolved (an
  `INTENT` with neither): never skipped; the block aborts, so teardown cannot complete, S.3 cannot
  report "never created", and 10.9 cannot remove the scratch until S.2 reconciles it.
- **Long blocks, one mechanism.** These blocks can run past the Bash tool's 10-minute limit for one
  call: 2.1, 2.3, 3.8, 6.1, 7.2, 7.3, 7.4, 8.2, 10.1 and 10.2 (bounds below). Each is written to a
  script file and run as a transient systemd user unit, started from a sandbox-off shell (R44); its
  exit status is read from a status file the unit's `ExecStopPost` writes. Every one of them starts
  with the sandbox-off header (`T17=` set explicitly). The agent never uses another background
  mechanism.
  1. Write the block's text, exactly as printed here with only the `<T17 printed by 0.2>` path filled
     in, to `$T17/blocks/<block>.sh` (for example `$T17/blocks/6.1.sh`), as for every block.
  2. Start it (one sandbox-off call). It runs as the transient systemd user unit
     `t17b-<RUN>-<block>.service` (R44). A refused start changes nothing and is not an abort: wait
     for the unfinished block with its wait call, then start again. (After an abort, the safe stop
     begins with S.0, which stops any unit of the run.)

     ```sh
     set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'
     . "$T17/run.env"; . "$T17/unitctl.sh"; d="$T17/blocks"
     [ -s "$d/$B.sh" ] || { echo "ABORT: no $d/$B.sh"; exit 1; }
     [ ! -e "$d/$B.status" ] && [ ! -e "$d/$B.unit" ] || { echo "ABORT: block $B was already started"; exit 1; }
     if busy=$(blocks_busy); then echo "REFUSED: a block is not finished: $busy"; exit 1; fi
     bash -n "$d/$B.sh"
     u="${UNIT_PREFIX}$B.service"; printf '%s\n' "$u" > "$d/$B.unit"; date +%s > "$d/$B.start"
     unit_start "$u" "$d/$B.out" "$d/$B.status" -E "T17_BLOCK=$B" -- bash "$d/$B.sh" || { echo "ABORT: systemd-run could not start $u; run S.0"; exit 1; }
     echo "block $B started as unit $u"
     ```

  3. Wait (repeat this sandbox-off call until it prints an exit status, `ABORT` or `UNRESOLVED`;
     `MAXMIN` is the block's bound from the table). Each call has one deadline, 540 s after it
     starts, that covers every read and the stop: it waits only while at least 135 s are left, each
     wait step (a 5 s sleep and one `systemctl` read bounded at 10 s) takes at most 15 s, and a stop
     takes at most 75 s plus 15 s of reads that never pass the deadline. So a call ends within about
     9 minutes, under the tool's 10-minute limit.

     ```sh
     set -euo pipefail; T17='<T17 printed by 0.2>'; B='<block>'; MAXMIN='<bound>'
     DL=$(( $(date +%s) + 540 ))
     . "$T17/run.env"; . "$T17/unitctl.sh"; d="$T17/blocks"
     [ -s "$d/$B.unit" ] && [ -s "$d/$B.start" ] || { echo "ABORT: block $B was not started"; exit 1; }
     u=$(cat "$d/$B.unit")
     over() { [ $(( ($(date +%s) - $(cat "$d/$B.start")) / 60 )) -ge "$MAXMIN" ]; }
     while :; do
       s=$(unit_state "$u")
       [ "$s" = running ] && ! over && [ "$(date +%s)" -le $(( DL - 135 )) ] || break
       sleep 5
     done
     tail -n 60 "$d/$B.out" 2>/dev/null || true
     case "$s" in
       done)
         st=$(cat "$d/$B.status" 2>/dev/null || echo unknown)
         echo "block $B finished: unit $u is inactive or gone with an empty cgroup; exit status $st"
         [ "$st" = 0 ] || exit 1; exit 0;;
       unresolved) echo "UNRESOLVED: the state of unit $u cannot be established; this is an abort: run S.0"; exit 1;;
     esac
     if over; then
       if unit_stop "$u" "$(( DL - 5 ))"; then
         printf 'killed\n' > "$d/$B.status"
         echo "ABORT: block $B ran past its $MAXMIN-minute bound; systemd stopped unit $u (TERM, then KILL) and it is inactive or gone with an empty cgroup"; exit 1
       fi
       printf 'unresolved\n' > "$d/$B.status"
       echo "UNRESOLVED: block $B ran past its $MAXMIN-minute bound and unit $u was not proved stopped within this call; run S.0 in a fresh call"; exit 1
     fi
     echo "block $B still running after $(( ($(date +%s) - $(cat "$d/$B.start")) / 60 )) minutes; call again"
     ```

  An exit status other than 0, `killed`, `unresolved` or the bound passing is an abort (safe stop,
  from S.0). How "stopped" is proved (R44): systemd keeps a unit's processes, and everything they
  start, in the unit's own cgroup, whatever they do to their environment or process group, and it
  reaps them. A stop is `systemctl --user stop <unit>`: TERM to every process in the cgroup, KILL
  after `TimeoutStopSec=45`. `unit_state` reads `done` only when `ActiveState` is inactive or failed
  and the unit is gone (collected, which systemd does only once the cgroup is empty) or its
  `cgroup.procs` is absent or empty; anything unknown or unreadable is `unresolved`, which every
  guard treats as unfinished until S.0 proves the unit done. Starts, stops and reads go by unit name
  only; nothing is signalled by PID. The exit status comes from the unit's `ExecStopPost`
  (`bin/exitpost.sh`), which records the main process's status, or `signal:<name>`, however the unit
  ends. The unit's command is `/usr/bin/env -i <allowlist> bash <block file>`, so the block sees
  only the allowlisted environment (R45). Every unit name is journalled before its `systemd-run`,
  and stops act only on journalled names. 0.2 proves the mechanism once with a probe unit before any
  AWS call. Bounds in minutes:
  2.1: 10; 2.3: 20; 3.8: 50; 6.1: 40; 7.2: 40; 7.3: 15; 7.4: 25; 8.2: 25; 10.1: 30; 10.2: 130 (its
  shared budget is 120).
- **The controller, as a unit (R37, R44).** Every block that starts, checks or stops the
  controller runs with the agent's sandbox OFF: 5.6, 6.1, 7.1, 7.2, 7.3, 7.4, 8.1, 8.2, 10.1, 10.9,
  S.0, S.1 and S.3, plus the other long blocks (2.1, 2.3, 3.8, 10.2). Those blocks set `T17`
  explicitly to the path 0.2 printed; their first line reads
  `set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"`, and that path is the only text
  the agent fills in. `start_ctl` starts each controller run as its own transient user unit,
  `t17b-<RUN>-ctl-<label>.service` (labels `audit-only`, `sequence`, `crash`, `recover`, `orphan`),
  never as a child of the block that starts it. The controller is the unit's main process; its
  output goes to `controller.log` and its exit status (137 for 7.3's crash point) to
  `controller.exit`, written by the unit's `ExecStopPost`. The unit's command is
  `/usr/bin/env -i <NAME=value...> <controller> -config ...`, so that argument list is the
  controller's whole environment (R45): `unitctl.sh`'s allowlist (PATH, HOME and the rest, so the
  kass `credential_process` works), then `AWS_PROFILE=kass`, `AWS_REGION` and `AWS_DEFAULT_REGION`
  `eu-west-1`, then the `EQUIPO_HOSTED_*` settings `start_ctl` is given
  (`EQUIPO_HOSTED_CRASH_AFTER_LAUNCH` only in 7.3). Nothing from the user manager's environment
  reaches it.
  `ctl_alive` reads the unit's state; `stop_ctl` stops the unit by name and proves it done. If the
  controller is gone when a block expects it, or a port stays open after its unit is done, that is
  an abort.
- **docs-t1.** The controller listens on `127.0.0.1:18443` (API) and `127.0.0.1:18444` (metrics)
  only, checked after every start. The hook server in the image listens on port 9000 inside the
  MicroVM, not on docs-t1. Scratch is `$TMPDIR/equipo-t17b`, removed in 10.9. Go caches stay at
  their defaults; every Go command runs with `CGO_ENABLED=0`. No sudo.
- **Records.** After each section, append its results to
  `docs/superpowers/plans/HOSTED-SLICE1-PROGRESS.md` under a new heading at the end of the file,
  `## Task 17b live run (attempt 5)`, and commit that file locally at the end (subject under 80
  characters). Never push. The report lists every `FINDING` line (10.9 prints them all).
- **Spend after every section.** Run 11.2 at the end of every section; its exit status 3 is the
  spend hard stop.

---

## 0. Guard rails

### 0.1 Code pin and local tools (no AWS call)

`PIN_SHA` is `bf29344a` (`bf29344a8b6832dff425aafc1337d4883f6a894f`): the client-token ErrConflict fix
`5f6e3e65` plus the two test rows from its review, on top of the origin/main merge `2d6d2345`. It
contains livectl's first commit `a36861a0`, livectl's final commit `bdf85fb7`, R32 (`f95575c6`)
and the fix `5f6e3e65`. **This block is the only place the SHA is written.** It saves the checked
SHA to `$TMPDIR/equipo-t17b-pre/pin`, and 0.2 reads it from there; a re-pin changes the
`PIN_SHA=` line below and nothing else. The block also runs livectl's offline tests and the
awsjob package's offline tests (the client-token mapping included).

```sh
set -euo pipefail
PIN_SHA='bf29344a8b6832dff425aafc1337d4883f6a894f'
: "${TMPDIR:?TMPDIR is unset}"
P="$TMPDIR/equipo-t17b-pre"; [ -d "$P" ] || { echo "ABORT: $P does not exist (it holds this block)"; exit 1; }
[[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "ABORT: PIN_SHA is not a full commit SHA"; exit 1; }
cd /home/paulca/amadan.net/oficina/equipo-hosted-1a
git rev-parse --verify "$PIN_SHA^{commit}"
for c in a36861a0 bdf85fb7 f95575c6 5f6e3e65; do
  git merge-base --is-ancestor "$c" "$PIN_SHA" || { echo "ABORT: $PIN_SHA does not contain $c"; exit 1; }
done
git merge-base --is-ancestor "$PIN_SHA" HEAD || { echo "ABORT: HEAD does not contain $PIN_SHA"; exit 1; }
d=$(git diff "$PIN_SHA" HEAD -- . ':!docs'); [ -z "$d" ] || { echo "ABORT: code differs from $PIN_SHA outside docs/"; exit 1; }
s=$(git status --porcelain --untracked-files=all -- . ':!docs'); [ -z "$s" ] || { echo "ABORT: uncommitted changes outside docs/:"; echo "$s"; exit 1; }
git log --oneline -1
aws --version
go version
for t in jq openssl sha256sum curl ss python3 systemd-run systemctl timeout; do command -v "$t" >/dev/null || { echo "ABORT: missing $t"; exit 1; }; done
CGO_ENABLED=0 go test -tags hostedlive ./internal/isolatedjob/awsjob/livectl -count=1
CGO_ENABLED=0 go test ./internal/isolatedjob/awsjob -count=1
printf '%s\n' "$PIN_SHA" > "$P/pin"
echo "code pin ok: $PIN_SHA"
```

- Expected: both test packages `ok`; `code pin ok`; `aws-cli/2.36.x`; `go1.26.x`.
- Abort if: any check fails.
- A re-pin: if the coordinator relays a new SHA (another review round on the fix), only the
  `PIN_SHA=` line above changes, plus the prose in "What Paul approves" and this paragraph's
  first line. The new SHA must still contain the four commits checked here.

### 0.2 Scratch, the environment file and the run names (no AWS call)

```sh
set -euo pipefail
: "${TMPDIR:?TMPDIR is unset}"
PIN_SHA=$(cat "$TMPDIR/equipo-t17b-pre/pin") || { echo "ABORT: 0.1 has not passed (no pin file)"; exit 1; }
[[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "ABORT: the pin file does not hold a full SHA"; exit 1; }
(cd /home/paulca/amadan.net/oficina/equipo-hosted-1a && git merge-base --is-ancestor "$PIN_SHA" HEAD \
  && [ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ]) || { echo "ABORT: HEAD moved away from $PIN_SHA since 0.1"; exit 1; }
[ ! -e "$TMPDIR/equipo-t17b" ] || { echo "ABORT: $TMPDIR/equipo-t17b already exists"; exit 1; }
case "$TMPDIR/equipo-t17b" in *[!A-Za-z0-9/._-]*) echo "ABORT: the scratch path has characters a systemd command line could misread"; exit 1;; esac
mkdir -m 700 "$TMPDIR/equipo-t17b"
mkdir -m 700 "$TMPDIR/equipo-t17b"/{out,image,iam,keys,bin,blocks}
cat > "$TMPDIR/equipo-t17b/unitctl.sh" <<'BCEOF'
# unitctl.sh: systemd user units for Task 17b (ruling R44). Functions only; no AWS call. Sourced by
# env.sh, by the long-block start and wait calls, and by S.0, which runs before env.sh.
# Every detached block and every controller start is a transient user service:
# t17b-<RUN>-<block>.service or t17b-<RUN>-ctl-<label>.service. systemd keeps the service's
# processes, and everything they start, in the unit's own cgroup, whatever they do to their
# environment or process group, and reaps them. Every start, stop and state read goes by unit name;
# nothing is ever signalled by PID (R44).
# Ownership (R45): 0.2 reserves the run ID atomically (mkdir $HOME/.cache/t17b-runs/<RUN>) and
# proves no t17b-<RUN>-* unit exists. unit_start journals every unit name (a "UNIT <name>" line)
# before its systemd-run, and unit_stop acts only on names this run journalled. The unit-name glob
# is a cross-check only: a matching unit that was not journalled is never stopped.
# Environment (R45): a unit's command is /usr/bin/env -i <allowlisted NAME=value...> <program>, so
# nothing from the user manager's environment reaches the program; the argv is its whole environment.
: "${T17:?T17 is unset}"; : "${RUN:?RUN is unset}"
UNIT_PREFIX="t17b-$RUN-"
# The allowlist: variables copied into a unit's env -i argv when set in the caller. env.sh unsets
# every AWS key, and no key, token or config-path variable is listed here, so no credential can
# reach a unit. HOME and PATH keep the kass profile's credential_process working.
UNIT_ENV_VARS="PATH HOME USER LOGNAME LANG LANGUAGE LC_ALL TZ TMPDIR XDG_RUNTIME_DIR XDG_CACHE_HOME XDG_CONFIG_HOME
  DBUS_SESSION_BUS_ADDRESS GOPATH GOMODCACHE GOCACHE GOCACHEPROG GOFLAGS GOPROXY GOSUMDB GONOSUMDB GOPRIVATE GONOPROXY
  GOTOOLCHAIN GOENV SSL_CERT_FILE SSL_CERT_DIR HTTP_PROXY HTTPS_PROXY NO_PROXY http_proxy https_proxy no_proxy
  AWS_PROFILE AWS_REGION AWS_DEFAULT_REGION AWS_PAGER AWS_STS_REGIONAL_ENDPOINTS AWS_RETRY_MODE AWS_MAX_ATTEMPTS CGO_ENABLED"
# _sc ARGS...: systemctl --user, bounded at 10 s.
_sc() { timeout 10 systemctl --user "$@"; }
# unit_state UNIT: prints running, done or unresolved.
#   running:    ActiveState active, activating, deactivating, reloading or refreshing.
#   done:       ActiveState inactive or failed, and the unit is gone (LoadState not-found: --collect
#               removed it, which systemd does only after its cgroup is empty), or it is loaded and
#               its cgroup no longer exists or lists no process.
#   unresolved: anything else: a systemctl call that fails or times out, any other state, or a
#               cgroup that cannot be read or still lists a process.
unit_state() { local o load act cg f procs
  o=$(_sc show -p LoadState -p ActiveState -p ControlGroup -- "$1" 2>/dev/null) || { echo unresolved; return 0; }
  load=$(sed -n 's/^LoadState=//p' <<<"$o"); act=$(sed -n 's/^ActiveState=//p' <<<"$o"); cg=$(sed -n 's/^ControlGroup=//p' <<<"$o")
  case "$act" in
    active|activating|deactivating|reloading|refreshing) echo running; return 0;;
    inactive|failed) ;;
    *) echo unresolved; return 0;;
  esac
  if [ "$load" = not-found ]; then echo done; return 0; fi
  [ "$load" = loaded ] || { echo unresolved; return 0; }
  if [ -n "$cg" ]; then
    f="/sys/fs/cgroup$cg/cgroup.procs"
    if [ -e "$f" ]; then
      procs=$(cat "$f" 2>/dev/null) || { echo unresolved; return 0; }
      [ -z "$procs" ] || { echo unresolved; return 0; }
    fi
  fi
  echo done; }
# run_units: the names of every unit of this run that systemd has loaded; status 1 if systemctl fails.
run_units() { local o; o=$(_sc list-units --all --plain --no-legend --full -- "${UNIT_PREFIX}*") || return 1
  awk '{for (i = 1; i <= NF; i++) if ($i ~ /\.service$/) {print $i; break}}' <<<"$o"; }
# journal_units: every unit name this run journalled (UNIT lines in journal.tsv, this run's prefix
# only), one per line; status non-zero if the journal cannot be read.
journal_units() { local o
  o=$(awk -F'\t' -v p="$UNIT_PREFIX" '$2 ~ /^UNIT / {u = substr($2, 6); if (index(u, p) == 1 && u ~ /\.service$/) print u}' "$T17/journal.tsv") || return 1
  [ -z "$o" ] || sort -u <<<"$o"; }
# unit_recorded UNIT: 0 if this run journalled UNIT.
unit_recorded() { local o; o=$(journal_units) || return 1; grep -qxF -- "$1" <<<"$o"; }
# unit_stop UNIT [DEADLINE]: only for a unit this run journalled (anything else: status 1, nothing
# stopped). systemctl --user stop, bounded at 75 s (systemd sends TERM to every process in the unit's
# cgroup, KILL after TimeoutStopSec=45, and reaps them); then reads unit_state for up to 15 s, never
# past DEADLINE (epoch seconds) when one is given. Status 0 only on done.
unit_stop() { local end
  unit_recorded "$1" || { echo "unit_stop: $1 was not journalled by this run; it is not stopped" >&2; return 1; }
  timeout 75 systemctl --user stop -- "$1" >/dev/null 2>&1 || true
  end=$(( $(date +%s) + 15 )); if [ -n "${2:-}" ] && [ "$2" -lt "$end" ]; then end=$2; fi
  while :; do
    [ "$(unit_state "$1")" = done ] && return 0
    [ "$(date +%s)" -lt "$end" ] || return 1
    sleep 1
  done; }
# unit_start UNIT OUT STATUS [-E NAME=VALUE]... -- CMD...: journal "UNIT <UNIT>", then run
# /usr/bin/env -i <allowlist> <-E pairs> CMD as a transient user service in its own cgroup, with
# KillMode=control-group and TimeoutStopSec=45; stdout and stderr appended to OUT; working directory
# $T17; and, however it ends, bin/exitpost.sh writes its exit status (or signal:<name>) to STATUS.
# --collect removes the unit once it has ended; --expand-environment=no keeps every argument literal.
# The -E pairs come after the allowlist, so they win. UNIT must carry this run's prefix.
unit_start() { local u=$1 out=$2 st=$3 v; shift 3
  local envv=()
  case "$u" in "$UNIT_PREFIX"*.service) ;; *) echo "unit_start: $u is not a unit name of this run" >&2; return 3;; esac
  for v in $UNIT_ENV_VARS; do [ -z "${!v+x}" ] || envv+=("$v=${!v}"); done
  while [ "$#" -gt 0 ] && [ "$1" != -- ]; do
    [ "$1" = -E ] && [ "$#" -ge 2 ] && [[ "$2" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || { echo "unit_start: bad arguments" >&2; return 3; }
    envv+=("$2"); shift 2
  done
  [ "${1:-}" = -- ] && [ "$#" -ge 2 ] || { echo "unit_start: no command" >&2; return 3; }
  shift
  printf '%s\tUNIT %s\n' "$(date -u +%FT%T.%3NZ)" "$u" >> "$T17/journal.tsv" || { echo "unit_start: journal write failed" >&2; return 3; }
  timeout 30 systemd-run --user --quiet --collect --expand-environment=no "--unit=$u" -p KillMode=control-group \
    -p TimeoutStopSec=45 -p "WorkingDirectory=$T17" -p StandardInput=null -p "StandardOutput=append:$out" \
    -p "StandardError=append:$out" -p "ExecStopPost=$T17/bin/exitpost.sh $st" -- /usr/bin/env -i "${envv[@]}" "$@"; }
# blocks_busy [EXCEPT]: print "<block or unit> <state>" for each detached block of this run, other
# than EXCEPT, that is running or unresolved (status "unresolved" counts), and for each listed block
# unit of this run that is not done; status 0 if there is any, 1 if none. A failed listing counts.
blocks_busy() { local f b s r=1 u units
  for f in "$T17"/blocks/*.unit; do
    [ -e "$f" ] || continue; b=$(basename "${f%.unit}"); [ "$b" != "${1:-}" ] || continue
    s=$(unit_state "$(cat "$f")")
    if [ "$s" = done ] && [ "$(cat "$T17/blocks/$b.status" 2>/dev/null || true)" = unresolved ]; then s=unresolved; fi
    [ "$s" = done ] || { echo "$b $s"; r=0; }
  done
  if ! units=$(run_units); then echo "units unresolved: systemctl list-units failed"; return 0; fi
  for u in $units; do
    case "$u" in "${UNIT_PREFIX}ctl-"*|"${UNIT_PREFIX}probe.service"|"${UNIT_PREFIX}${1:-}.service") continue;; esac
    s=$(unit_state "$u"); [ "$s" = done ] || { echo "$u $s"; r=0; }
  done
  return "$r"; }
# unit_probe: start t17b-<RUN>-probe.service (it records its environment, then runs sleep 60), see it
# running with a process in its cgroup, check that its environment holds only allowlisted names
# (plus PWD, SHLVL and _, which bash sets), stop it, and prove it done with exit status
# signal:TERM. 0.2 aborts unless this passes.
unit_probe() { local u="${UNIT_PREFIX}probe.service" i cg procs n
  [ "$(unit_state "$u")" = done ] || return 1
  rm -f "$T17/out/probe.status" "$T17/out/probe.env"
  unit_start "$u" "$T17/out/probe.out" "$T17/out/probe.status" -- /bin/bash -c 'env > "$0"; exec sleep 60' "$T17/out/probe.env" || return 1
  for i in $(seq 1 20); do [ "$(unit_state "$u")" = running ] && break; sleep 0.25; done
  [ "$(unit_state "$u")" = running ] || { unit_stop "$u"; return 1; }
  cg=$(_sc show -p ControlGroup --value -- "$u") || { unit_stop "$u"; return 1; }
  procs=$(cat "/sys/fs/cgroup$cg/cgroup.procs" 2>/dev/null) || procs=""
  [ -n "$cg" ] && [ -n "$procs" ] || { unit_stop "$u"; return 1; }
  for i in $(seq 1 20); do [ -s "$T17/out/probe.env" ] && break; sleep 0.25; done
  [ -s "$T17/out/probe.env" ] || { unit_stop "$u"; return 1; }
  for n in $(sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' "$T17/out/probe.env"); do
    case " $(echo $UNIT_ENV_VARS) PWD SHLVL _ " in *" $n "*) ;; *) echo "unit_probe: $n reached the unit" >&2; unit_stop "$u"; return 1;; esac
  done
  unit_stop "$u" || return 1
  [ "$(cat "$T17/out/probe.status" 2>/dev/null || true)" = signal:TERM ]; }
BCEOF
cat > "$TMPDIR/equipo-t17b/bin/exitpost.sh" <<'EPEOF'
#!/bin/sh
# ExecStopPost for Task 17b units: record how the unit's main process ended, in the file named by $1.
# systemd sets EXIT_CODE (exited, killed or dumped) and EXIT_STATUS (a number or a signal name).
case "${EXIT_CODE:-}" in
  exited) printf '%s\n' "${EXIT_STATUS:-unknown}";;
  "") printf 'unknown\n';;
  *) printf 'signal:%s\n' "${EXIT_STATUS:-unknown}";;
esac > "$1"
EPEOF
chmod 755 "$TMPDIR/equipo-t17b/bin/exitpost.sh"
cat > "$TMPDIR/equipo-t17b/env.sh" <<'ENVEOF'
# env.sh: sourced by every block, after `set -euo pipefail`. Task 17b only.
: "${TMPDIR:?TMPDIR is unset}"
# T17 may be set by a sandbox-off block (R37); otherwise it is $TMPDIR/equipo-t17b.
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_SECURITY_TOKEN AWS_DEFAULT_PROFILE \
  AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_ROLE_ARN AWS_ROLE_SESSION_NAME AWS_WEB_IDENTITY_TOKEN_FILE \
  AWS_CA_BUNDLE AWS_ENDPOINT_URL AWS_USE_FIPS_ENDPOINT AWS_USE_DUALSTACK_ENDPOINT
for _v in $(env | sed -n 's/^\(AWS_ENDPOINT_URL_[A-Z0-9_]*\)=.*/\1/p'); do unset "$_v"; done
export AWS_PROFILE=kass AWS_REGION=eu-west-1 AWS_DEFAULT_REGION=eu-west-1 AWS_PAGER="" \
  AWS_STS_REGIONAL_ENDPOINTS=regional AWS_RETRY_MODE=standard AWS_MAX_ATTEMPTS=3
export CGO_ENABLED=0
if [ -z "${T17:-}" ]; then T17="$TMPDIR/equipo-t17b"; fi
export T17 REPO=/home/paulca/amadan.net/oficina/equipo-hosted-1a
export LIVECTL="$T17/bin/livectl"
export ACCOUNT=640012953448 TAGV=equipo-hosted-dev
export LEDGER="$T17/ledger.env" JOURNAL="$T17/journal.tsv" VMS="$T17/vms.tsv"
export NO_INGRESS=arn:aws:lambda:eu-west-1:aws:network-connector:aws-network-connector:NO_INGRESS
export API=127.0.0.1:18443 METRICS=127.0.0.1:18444
# A live MicroVM ID: "microvm-" and a lower-case UUID, 44 characters (attempt 4).
export VMID_RE='microvm-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
[ -d "$T17" ] || { echo "ABORT: $T17 does not exist; was TMPDIR changed?" >&2; exit 1; }
[ -f "$T17/run.env" ] && . "$T17/run.env"
[ -f "$LEDGER" ] && . "$LEDGER"
# One block at a time (R44): refuse to load while a block unit other than this one (T17_BLOCK, set by
# the long-block start call) is running or unresolved. S.0 does not load env.sh.
[ -f "$T17/unitctl.sh" ] || { echo "ABORT: $T17/unitctl.sh is missing" >&2; exit 1; }
. "$T17/unitctl.sh"
if _busy=$(blocks_busy "${T17_BLOCK:-}"); then
  echo "ABORT: a block unit is unfinished: $_busy. Wait for it with its wait call; after an abort, run S.0 first." >&2; exit 1
fi

# die: a hard stop. It also appends to $T17/FATAL, so a hard stop inside a subshell, a poll or a
# command substitution reaches the parent: finding and fatal_check re-raise it, so it can never
# become a FINDING. Exit status 99.
die() { echo "ABORT: $*" >&2; jw "ABORT $*" 2>/dev/null || true; printf '%s\n' "$*" >> "$T17/FATAL" 2>/dev/null || true; exit 99; }
# soft_fail: an ordinary failure (a poll's bound or an unexpected state) that ends the current
# (sub)shell with status 1 without a hard stop; at a block's top level it still ends the block.
soft_fail() { echo "FAILED: $*" >&2; jw "FAILED $*" 2>/dev/null || true; exit 1; }
_fatal_count() { if [ -f "$T17/FATAL" ]; then wc -l < "$T17/FATAL"; else echo 0; fi; }
_FATAL0=$(_fatal_count)
# fatal_check: re-raise any hard stop that happened in a subshell since this block began.
fatal_check() { [ "$(_fatal_count)" -le "$_FATAL0" ] || die "a hard stop happened inside a subshell: $(tail -n 1 "$T17/FATAL")"; }
# need VAR...: each must be set, non-empty, and not None or null.
need() { local v; for v; do [ -n "${!v:-}" ] && [ "${!v}" != None ] && [ "${!v}" != null ] || die "$v is unset"; done; }
# arn_ok ARN: in this account and eu-west-1 (IAM and S3 ARNs have no region).
arn_ok() {
  case "$1" in
    *149757027610*) die "ARN $1 names account 149757027610";;
    arn:aws:*:eu-west-1:640012953448:*|arn:aws:iam::640012953448:role/*|arn:aws:s3:::*) ;;
    *) die "ARN $1 is not in 640012953448 and eu-west-1";;
  esac
}
# jw TEXT: one journal line; a failed write is an abort.
jw() { local t="$*"; t=${t//$'\r'/}; t=${t//$'\n'/ | }; t=${t//$'\t'/ }
  printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "$t" >> "$JOURNAL" || { echo "ABORT: journal write failed" >&2; exit 1; }; }
# _kind VAR: sets K_I and K_N, the journal patterns for VAR's INTENT and NOTCREATED records ("" when
# VAR has no creation of its own: the VPC defaults exist only with the VPC, and image versions only
# with the image, which livectl deletes whole).
_kind() { case "$1" in
  VPC) K_I='^INTENT vpc( |$)'; K_N='^NOTCREATED vpc( |$)';;
  SUBNET) K_I='^INTENT subnet( |$)'; K_N='^NOTCREATED subnet( |$)';;
  RTB) K_I='^INTENT route-table( |$)'; K_N='^NOTCREATED route-table( |$)';;
  RTB_ASSOC) K_I='^INTENT route-table-association( |$)'; K_N='^NOTCREATED route-table-association( |$)';;
  SG) K_I='^INTENT security-group( |$)'; K_N='^NOTCREATED security-group( |$)';;
  OPERATOR_ROLE_ARN) K_I="^INTENT iam-role $OPERATOR_ROLE( |\$)"; K_N="^NOTCREATED iam-role $OPERATOR_ROLE( |\$)";;
  BUILD_ROLE_ARN) K_I="^INTENT iam-role $BUILD_ROLE( |\$)"; K_N="^NOTCREATED iam-role $BUILD_ROLE( |\$)";;
  CONN_ARN) K_I='^INTENT connector( |$)'; K_N='^NOTCREATED connector( |$)';;
  BUCKET_CREATED) K_I='^INTENT s3-bucket( |$)'; K_N='^NOTCREATED s3-bucket( |$)';;
  LOG_GROUP_CREATED) K_I='^INTENT log-group( |$)'; K_N='^NOTCREATED log-group( |$)';;
  ARTIFACT) K_I='^INTENT s3-object( |$)'; K_N='^NOTCREATED s3-object( |$)';;
  IMAGE_ARN) K_I='^INTENT microvm-image( |$)'; K_N='^NOTCREATED (microvm-image|image attempt)( |$)';;
  TOPIC_ARN) K_I='^INTENT sns-topic( |$)'; K_N='^NOTCREATED sns-topic( |$)';;
  *) K_I=''; K_N='';;
esac; }
# creation_state VAR: sets CST to confirmed (VAR is set), none (never attempted), absent (the last
# attempt is followed by a NOTCREATED record) or unresolved (attempted, neither confirmed nor shown absent).
creation_state() {
  if [ -n "${!1:-}" ]; then CST=confirmed; return 0; fi
  _kind "$1"; if [ -z "$K_I" ]; then CST=none; return 0; fi
  CST=$(awk -F'\t' -v ri="$K_I" -v rn="$K_N" '$2 ~ ri {li = NR} $2 ~ rn {ln = NR} END {if (!li) print "none"; else if (ln > li) print "absent"; else print "unresolved"}' "$JOURNAL") || die "journal unreadable"
}
# have VAR: 0 to act on a confirmed creation; 1, with a journalled SKIP, for one never attempted or
# shown absent. An unresolved creation is never skipped: it aborts, so teardown cannot complete and
# scratch cannot be removed until S.2 reconciles it (the skip-never-created rule).
have() {
  creation_state "$1"
  case "$CST" in
    confirmed) return 0;;
    none|absent) jw "SKIP $1 $CST"; echo "skip: $1 ($CST: never created)"; return 1;;
    *) jw "UNRESOLVED-TEARDOWN $1"; die "$1: a creation was attempted but is neither confirmed nor shown absent; reconcile it (S.2) first";;
  esac
}
# no_unresolved: abort if any resource is still unresolved.
no_unresolved() { local v; for v in VPC SUBNET RTB RTB_ASSOC SG OPERATOR_ROLE_ARN BUILD_ROLE_ARN CONN_ARN BUCKET_CREATED LOG_GROUP_CREATED ARTIFACT IMAGE_ARN TOPIC_ARN; do
  creation_state "$v"; [ "$CST" != unresolved ] || die "$v is unresolved; reconcile it (S.2) before finishing"; done; }
# gone0 WHAT CMD...: a list read that must succeed and count 0 (no error code is guessed).
gone0() { local w=$1; shift; get _g "$@"; [ "$_g" = 0 ] || die "$w is still listed ($_g)"; }
# intent KIND KEY DETAIL...: written BEFORE a create call.
intent() { jw "INTENT $*"; }
# rec VAR VALUE: written AFTER a create call returned the ID; checked; exported.
rec() {
  [ $# = 2 ] || die "rec needs a name and a value"
  case "$2" in ""|None|null) die "rec $1: empty value";; *149757027610*) die "rec $1=$2 names account 149757027610";; esac
  printf 'export %s=%q\n' "$1" "$2" >> "$LEDGER" || die "ledger write failed"
  jw "CONFIRMED $1 $2"
  export "$1=$2"
}
# deleted KIND ID HOW: written after a deletion is confirmed by a direct read.
deleted() { jw "DELETED $*"; }
# try CMD...: run CMD; never exits; sets OUT, ERR, RC and ECODE (the AWS error code, if any).
try() {
  local had=0 e; case $- in *e*) had=1;; esac
  e=$(mktemp "$T17/err.XXXXXX") || { echo "ABORT: mktemp" >&2; exit 1; }
  set +e; OUT=$("$@" 2>"$e"); RC=$?; [ "$had" = 1 ] && set -e
  ERR=$(cat "$e"); rm -f "$e"
  ECODE=$(printf '%s' "$ERR" | sed -n 's/.*An error occurred (\([A-Za-z0-9.]*\)).*/\1/p' | head -n 1)
  return 0
}
# must: after try, the call must have succeeded.
must() { [ "$RC" = 0 ] || die "call failed (rc $RC, ${ECODE:-no code}): $ERR"; }
# get VAR CMD...: run a read; abort unless it succeeded; only then store its output in VAR.
get() { local __v=$1; shift; try "$@"; must; printf -v "$__v" '%s' "$OUT"; }
# _creds: export kass's credentials through the CLI's own resolution (its credential_process),
# into shell variables of the calling (sub)shell only (R42). Never written to disk, the journal or
# any argument list, and never printed. AccessKeyId and SecretAccessKey are required; a
# SessionToken, if present, needs an Expiration. Static IAM user keys have neither.
_creds() {
  local j rc had=0; case $- in *e*) had=1;; esac
  set +e; j=$(timeout 30 aws configure export-credentials --profile kass --format process 2>/dev/null); rc=$?; [ "$had" = 1 ] && set -e
  [ "$rc" = 0 ] || return 1
  _AK=$(jq -r '.AccessKeyId // empty' <<<"$j" 2>/dev/null || true)
  _SK=$(jq -r '.SecretAccessKey // empty' <<<"$j" 2>/dev/null || true)
  _ST=$(jq -r '.SessionToken // empty' <<<"$j" 2>/dev/null || true)
  _EXP=$(jq -r '.Expiration // empty' <<<"$j" 2>/dev/null || true)
  j=""
  [ -n "$_AK" ] && [ -n "$_SK" ] || return 1
  [ -z "$_ST" ] || [ -n "$_EXP" ] || return 1
}
# _lvx ARGS...: livectl in a subshell whose environment holds exactly the exported static keys:
# AWS_PROFILE, AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE are unset for it, so livectl sees only
# static environment keys. A failed export is livectl's guard exit (4): a hard stop in lv.
_lvx() (
  if ! _creds; then echo '{"error":"guard","message":"kass credentials could not be exported as static keys (R42)"}' >&2; exit 4; fi
  unset AWS_PROFILE AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE AWS_SESSION_TOKEN
  export AWS_ACCESS_KEY_ID="$_AK" AWS_SECRET_ACCESS_KEY="$_SK"
  [ -z "$_ST" ] || export AWS_SESSION_TOKEN="$_ST"
  unset _AK _SK _ST
  exec "$LIVECTL" -run "$RUN" "$@"
)
# cred_left: seconds until the exported credentials expire, or "none" for static keys without an
# Expiration. Prints nothing secret.
cred_left() ( _creds || exit 4; unset _AK _SK _ST
  if [ -z "$_EXP" ]; then echo none; else echo $(( $(date -d "$_EXP" +%s) - $(date +%s) )); fi )
# lv ARGS...: one livectl call (every Lambda MicroVMs and Lambda core call, R40). Sets OUT, ERR, RC,
# ECODE (the smithy error code), LV_KIND (api, transport, usage, guard, timeout, failed_state, other)
# and LV_MSG (the service's own text). A guard refusal (4) or usage error (3) is a hard stop.
lv() {
  [ -x "$LIVECTL" ] || die "livectl is not built at $LIVECTL"
  need RUN
  try _lvx "$@"
  ECODE=""; LV_KIND=""; LV_MSG=""; LV_HTTP=""
  if [ "$RC" != 0 ]; then
    local e; e=$(tail -n 1 <<<"$ERR")
    ECODE=$(jq -r '.code // empty' <<<"$e" 2>/dev/null || true)
    LV_KIND=$(jq -r '.error // empty' <<<"$e" 2>/dev/null || true)
    LV_MSG=$(jq -r '.aws_message // empty' <<<"$e" 2>/dev/null || true)
    LV_HTTP=$(jq -r '.http_status // empty' <<<"$e" 2>/dev/null || true)
  fi
  [ "$RC" != 4 ] || die "livectl guard refusal (account, region, run prefix or -run): $ERR"
  [ "$RC" != 3 ] || die "livectl usage error (a plan defect): $ERR"
  return 0
}
# _transient: after lv, 0 if the failure is worth trying again: livectl makes one attempt per call,
# so a throttle, a server error or no answer within its 60 s cutoff comes back as exit 2.
_transient() { [ "$RC" = 2 ] || return 1; [ "$LV_KIND" = transport ] && return 0
  case "$ECODE" in ThrottlingException|TooManyRequestsException|InternalServerException|ServiceException|ServiceUnavailableException) return 0;; esac; return 1; }
# lvr ARGS...: lv with up to 3 tries, 5 s apart, on a transient failure. For reads and idempotent
# deletes and terminates only; creates and other changes use lv once.
lvr() { local i; for i in 1 2 3; do lv "$@"; _transient || return 0; [ "$i" = 3 ] || { echo "transient (${ECODE:-$LV_KIND}); trying again"; sleep 5; }; done; return 0; }
# lv_wait SECONDS ARGS...: a livectl wait with one outer deadline, SECONDS from now, covering the
# credential export (bounded at 30 s), livectl's start and account check (its 60 s cutoff) and the
# waiting itself: 90 s of each call is kept for the first two. A chunk is never longer than what is
# left; when the exported credentials expire sooner (less a 120 s margin) the wait is split into
# shorter calls, each with fresh credentials. A transient exit 2 is a FINDING and the wait goes on.
# A success that comes back after the deadline counts as a timeout. Leaves RC 0, 5 (the deadline
# passed), 6 (a failed state) or 2 (any other error). A guard failure stays a hard stop.
lv_wait() { local end=$(( $(date +%s) + $1 )) left cl chunk; shift
  while :; do
    left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
    cl=$(cred_left) || die "kass credentials could not be exported (R42)"
    left=$(( end - $(date +%s) - 90 )); if [ "$left" -le 0 ]; then RC=5; return 0; fi
    chunk=$left
    if [ "$cl" != none ] && [ $(( cl - 120 )) -lt "$chunk" ]; then
      chunk=$(( cl - 120 )); if [ "$chunk" -lt 15 ]; then chunk=$(( left < 15 ? left : 15 )); fi
    fi
    lv "$@" -timeout "${chunk}s"
    if [ "$RC" = 0 ] && [ "$(date +%s)" -gt "$end" ]; then finding "a wait answered after its deadline; counted as a timeout"; RC=5; return 0; fi
    if _transient; then finding "transient error inside a wait (${ECODE:-$LV_KIND}); waiting on"; sleep 5; continue; fi
    if [ "$RC" = 5 ] && [ "$chunk" -lt "$left" ]; then echo "wait split at the credentials' expiry; going on with fresh credentials"; continue; fi
    return 0
  done; }
# finding TEXT: a FINDING line in the journal; the run goes on (Paul's rule 1).
finding() { fatal_check; jw "FINDING $*"; echo "FINDING: $*"; }
# fact_eq WHAT WANT CMD...: a read of the run's own resource; a failed read or another value is a FINDING.
fact_eq() { local w=$1 want=$2; shift 2; try "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; elif [ "$OUT" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$OUT], want [$want]"; fi; }
# fact_json WHAT WANT CMD...: as fact_eq, comparing compacted JSON.
fact_json() { local w=$1 want=$2 got; shift 2; try "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
  got=$(jq -c . <<<"$OUT" 2>/dev/null) || { finding "$w: reply is not JSON"; return 0; }
  if [ "$got" = "$(jq -c . <<<"$want")" ]; then echo "ok: $w"; else finding "$w: got $got, want $want"; fi; }
# fact_lv WHAT WANT JQ ARGS...: a livectl read; jq -r JQ of the reply must equal WANT, else a FINDING.
fact_lv() { local w=$1 want=$2 q=$3 got; shift 3; lvr "$@"
  if [ "$RC" != 0 ]; then finding "$w: read failed (${ECODE:-rc$RC})"; return 0; fi
  got=$(jq -r "$q" <<<"$OUT" 2>/dev/null) || { finding "$w: reply unreadable"; return 0; }
  if [ "$got" = "$want" ]; then echo "ok: $w"; else finding "$w: got [$got], want [$want]"; fi; }
# code_in CODE...: after try, 0 if the call failed with one of CODE.
code_in() { local c; [ "$RC" != 0 ] || return 1; for c; do [ "$ECODE" = "$c" ] && return 0; done; return 1; }
# expect_err CODE...: after try, the call must have failed with one of CODE (an expected-failure branch).
expect_err() { code_in "$@" || die "expected one of [$*], got rc $RC ${ECODE:-no code}: ${ERR:-$OUT}"; }
guard() {
  [ "$AWS_PROFILE" = kass ] && [ "$AWS_REGION" = eu-west-1 ] && [ "$AWS_DEFAULT_REGION" = eu-west-1 ] || die "profile or region changed"
  [ -z "${AWS_ACCESS_KEY_ID:-}" ] || die "AWS_ACCESS_KEY_ID is set"
  try aws sts get-caller-identity --query Account --output text; must
  [ "$OUT" = "$ACCOUNT" ] || die "account is $OUT, not $ACCOUNT"
}
# poll SECONDS INTERVAL WHAT FN ARGS...: FN returns 0 done, 1 not yet, anything else an ordinary
# failure (soft_fail). A hard stop inside FN (die) stays a hard stop.
poll() {
  local secs=$1 iv=$2 what=$3 rc had=0 end; end=$(( $(date +%s) + secs )); shift 3
  case $- in *e*) had=1;; esac
  while :; do
    set +e; "$@"; rc=$?; [ "$had" = 1 ] && set -e
    [ "$rc" = 0 ] && return 0
    fatal_check
    [ "$rc" = 1 ] || soft_fail "$what: unexpected state (rc $rc)"
    [ "$(date +%s)" -lt "$end" ] || soft_fail "$what: not done within $secs s"
    sleep "$iv"
  done
}

# --- MicroVMs: recorded by ID (they have no tags), found by the image-scoped List ---
# vmrec ID SOURCE START: one VM ledger line per (ID, source, start). START is the provider's
# startedAt, or "phase:<time>" (the start of the phase that found it) when only that is known.
vmrec() {
  [ $# = 3 ] && [ -n "$3" ] && [ "$3" != phase: ] || die "vmrec $1: no start time"
  [ -f "$VMS" ] || die "no VM ledger"
  local key; printf -v key '%s\t%s\t%s\t' "$1" "$2" "$3"
  grep -qF "$key" "$VMS" && return 0
  printf '%s%s\n' "$key" "$(date -u +%FT%T.%3NZ)" >> "$VMS" || die "VM ledger write failed"
  jw "VM $1 $2 $3"
}
# vm_ids: sets VIDS to every recorded VM ID.
vm_ids() { [ -f "$VMS" ] || die "no VM ledger"; VIDS=$(cut -f1 "$VMS" | sort -u) || die "VM ledger unreadable"; }
# list_items: validate a livectl list reply in OUT: a JSON object with an explicit Items key whose
# value is null or an array. On success ITEMS holds that array, with null read as []. Anything else
# (not JSON, not an object, no Items key, Items of another type) returns 1, and the caller fails per
# its own rules: a hard stop where the result drives a safety decision (collision, settled, deleted,
# reconciliation), a FINDING for an observation.
list_items() {
  ITEMS=$(jq -ce 'if type == "object" and has("Items") and (.Items == null or (.Items | type) == "array") then (.Items // []) else error("malformed") end' <<<"$OUT" 2>/dev/null) || { ITEMS=""; return 1; }
}
# scan: one image-scoped List, every page, every state; records every ID; writes last_scan.tsv.
scan() {
  need IMAGE_ARN
  lvr vm list -image "$IMAGE_ARN"; must
  list_items || die "malformed VM list reply: $(head -c 200 <<<"$OUT")"
  jq -e --arg a "$IMAGE_ARN" 'all(.[]; .ImageArn == $a)' <<<"$ITEMS" >/dev/null || die "list returned a VM of another image"
  jq -r '.[] | [.MicrovmId, .State, .StartedAt] | @tsv' <<<"$ITEMS" > "$T17/last_scan.tsv" || die "VM list items unreadable"
  local id st started
  while IFS=$'\t' read -r id st started; do [ -n "$id" ] && vmrec "$id" scan "$started"; done < "$T17/last_scan.tsv"
  LIVE=$(awk -F'\t' '$2 != "TERMINATED" {print $1}' "$T17/last_scan.tsv") || die "scan output unreadable"
  cat "$T17/last_scan.tsv"
}
# After scan, LIVE holds the IDs of this image's VMs that are not TERMINATED.
# vm_get ID: sets VST to the state, NOTFOUND, or ERROR:<code>.
vm_get() {
  lvr vm get -id "$1"
  if [ "$RC" = 0 ]; then VST=$(jq -r '.State // empty' <<<"$OUT"); [ -n "$VST" ] || VST="ERROR:no-state"; elif [ "$ECODE" = ResourceNotFoundException ]; then VST=NOTFOUND; else VST="ERROR:${ECODE:-${LV_KIND:-rc$RC}}"; fi
}
_vm_check() { vm_get "$1"; echo "$(date -u +%T) $1 $VST"; [ "$VST" = "$2" ] && return 0; case " $3 ThrottlingException transport " in *" ${VST#ERROR:} "*) return 1;; esac; return 2; }
# vm_wait ID TARGET SECONDS ALLOWED...: wait for TARGET; a state outside ALLOWED is fatal.
vm_wait() { local id=$1 t=$2 s=$3; shift 3; poll "$s" 5 "VM $id to $t" _vm_check "$id" "$t" "$*"; }
# vm_end ID: terminate and confirm: TERMINATED, or not found twice at least 60 s apart.
vm_end() {
  lvr vm terminate -id "$1"
  [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "terminate $1: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"
  local nf=0 end=$(( $(date +%s) + 600 ))
  while :; do
    vm_get "$1"; echo "$(date -u +%T) $1 $VST"
    case "$VST" in
      TERMINATED) jw "VMGONE $1 TERMINATED"; return 0;;
      NOTFOUND) [ "$nf" = 0 ] && nf=$(date +%s); [ $(( $(date +%s) - nf )) -ge 60 ] && { jw "VMGONE $1 NOTFOUND-TWICE"; return 0; };;
      PENDING|RUNNING|SUSPENDING|SUSPENDED|TERMINATING|ERROR:ThrottlingException|ERROR:transport) nf=0;;
      *) die "VM $1: $VST";;
    esac
    [ "$(date +%s)" -lt "$end" ] || die "VM $1 has not ended after 10 min"
    sleep 10
  done
}
# settle_all: end every recorded and every listed live VM; done only after three scans 30 s apart show none live.
settle_all() {
  need IMAGE_ARN; local round i clean id
  for round in 1 2 3; do
    scan >/dev/null
    for id in $LIVE; do vm_end "$id"; done
    vm_ids
    for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || vm_end "$id"; done
    clean=0
    for i in 1 2 3; do
      scan >/dev/null
      [ -n "$LIVE" ] && break
      clean=$((clean + 1)); [ "$i" -lt 3 ] && sleep 30
    done
    vm_ids
    [ "$clean" = 3 ] && { jw "SETTLED $(wc -w <<<"$VIDS") recorded"; echo "settled: $(wc -w <<<"$VIDS") VMs recorded, none live in three scans"; return 0; }
  done
  die "VMs still live after three settle rounds"
}
# launch LABEL TOKEN MAXSECONDS PAYLOADFILE: one livectl vm run (Small, NO_INGRESS, the connector);
# records any VM it returns. TOKEN must start with the run prefix. Sets L_OUTCOME:
#   created    the reply names a VM (recorded);
#   rejected   a confirmed refusal: an api error with a 4xx status, so AWS did not run it;
#   settled    the outcome was uncertain (no answer, a 5xx, an unreadable error): the identical
#              request was replayed up to twice under the same client token; if no replay named a
#              VM, settle_all ended every live VM of this image (bounded image-scoped scans), which
#              proves nothing launched is left. If that cannot be proved, settle_all is a hard stop.
_launch_once() {
  lv vm run -image "$IMAGE_ARN" -version "$VER_SMALL" -connector "$CONN_QARN" -max-seconds "$3" \
    -client-token "$2" -payload-file "$4"
  printf '%s\n' "$OUT" > "$T17/out/launch-$1.json"; printf '%s\n' "$ERR" > "$T17/out/launch-$1.err"
  L_RC=$RC; L_CODE=$ECODE; L_MSG=$LV_MSG; L_ID=""
  if [ "$RC" = 0 ]; then
    L_ID=$(printf '%s' "$OUT" | jq -r '.MicrovmId // empty')
    [ -n "$L_ID" ] || die "launch $1 succeeded with no MicrovmId"
    local st; st=$(printf '%s' "$OUT" | jq -r '.StartedAt // empty')
    vmrec "$L_ID" "$1" "${st:-phase:$L_T0}"; L_OUTCOME=created
  elif [ "$LV_KIND" = api ] && [ -n "$LV_HTTP" ] && [ "$LV_HTTP" -ge 400 ] && [ "$LV_HTTP" -lt 500 ]; then L_OUTCOME=rejected
  else L_OUTCOME=uncertain; fi
}
launch() {
  need IMAGE_ARN VER_SMALL CONN_QARN; [ -f "$4" ] || die "no payload file $4"
  intent vm "$1" "token=$2" "max=$3"
  L_T0=$(date -u +%FT%T.%3NZ)
  _launch_once "$@"
  local k
  for k in 1 2; do
    [ "$L_OUTCOME" = uncertain ] || break
    jw "UNCERTAIN vm $1 token=$2 (${L_CODE:-${LV_KIND:-rc$L_RC}}): replay $k with the same client token"; sleep 5
    _launch_once "$1-replay$k" "$2" "$3" "$4"
  done
  if [ "$L_OUTCOME" = uncertain ] || { [ "$L_OUTCOME" = rejected ] && grep -q $'\tUNCERTAIN vm '"$1"' ' "$JOURNAL"; }; then
    finding "launch $1 has an uncertain outcome (${L_CODE:-${LV_KIND:-rc$L_RC}}); settling every VM of the image"
    settle_all; L_OUTCOME=settled; L_ID=""; jw "RESOLVED vm $1 by settlement"
  fi
  echo "launch $1: $L_OUTCOME rc=$L_RC code=${L_CODE:-none} id=${L_ID:-none}"
}
# eni_snapshot MODE WHEN: list the VPC's interfaces. Any outside this run's subnet is not in the ledger:
# a hard stop, before anything is recorded. Each one inside is recorded once as SERVICE-ENI, so 10.2
# can prove each ID gone. MODE strict makes a failed list a hard stop (10.2 needs it); soft makes it a
# FINDING (observations during the VM phases).
eni_snapshot() {
  need VPC SUBNET
  try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --output json
  if [ "$RC" != 0 ]; then
    [ "$1" = strict ] && die "interface list failed (${ECODE:-rc$RC}); 10.2 needs it"
    finding "interface list failed ($2): ${ECODE:-rc$RC}"; return 0
  fi
  printf '%s' "$OUT" | jq -e '.NetworkInterfaces | type == "array"' >/dev/null || die "interface list unreadable ($2)"
  printf '%s' "$OUT" | jq -e --arg s "$SUBNET" 'all(.NetworkInterfaces[]; .SubnetId == $s)' >/dev/null \
    || die "an interface outside this run's subnet is in the run's VPC ($2): not in the ledger"
  local e n=0
  for e in $(printf '%s' "$OUT" | jq -r '.NetworkInterfaces[].NetworkInterfaceId'); do
    n=$((n + 1)); grep -qF "SERVICE-ENI $e" "$JOURNAL" || jw "SERVICE-ENI $e"
  done
  jw "FACT interfaces in the VPC ($2): $n"; echo "interfaces in the VPC ($2): $n"
}
# harvest LOG SOURCE PHASESTART: record every MicroVM ID (VMID_RE) a log names, with the phase start
# as its conservative start (scans add the provider's startedAt later). Any other "microvm-..." token
# that is not an image name is a FINDING: the ID form may have changed, and the image-scoped scans
# (which record every VM whatever its form) are then the only inventory.
harvest() {
  [ -f "$1" ] && [ -n "${3:-}" ] || die "harvest: no log $1 or no phase start"
  local ids id odd
  ids=$(grep -oE "$VMID_RE" "$1" | sort -u || true)
  for id in $ids; do vmrec "$id" "$2" "phase:$3"; done
  odd=$(grep -oE 'microvm-[0-9A-Za-z][0-9A-Za-z-]*' "$1" | grep -vxE "$VMID_RE|microvm-image.*" | sort -u | head -n 5 | tr '\n' ' ' || true)
  [ -z "$odd" ] || finding "$(basename "$1") names MicroVM-like tokens outside the known ID form: $odd"
}
# ctl_log: the controller log's lines written since the latest start_ctl.
ctl_log() { local n; n=$(cat "$T17/controller.logstart") || die "no controller log start"; tail -n +"$((n + 1))" "$T17/controller.log"; }
# harvest_ctl: save the log lines since the latest start to a slice file (its path in CTL_SLICE),
# then harvest it.
harvest_ctl() { local t; t=$(cat "$T17/controller.start") || die "no controller start time"
  CTL_SLICE="$T17/out/controller-$(date -u +%H%M%S).log"; ctl_log > "$CTL_SLICE" || die "controller log unreadable"
  harvest "$CTL_SLICE" controller "$t"; }

# --- the controller: one transient user unit per start, t17b-<RUN>-ctl-<label>.service (R44) ---
# ctl_unit: the unit of the latest start (status 1 if none was started).
ctl_unit() { [ -s "$T17/controller.unit" ] && cat "$T17/controller.unit"; }
# ctl_alive: 0 if the latest controller unit is running; 1 if it is done or none was started; a state
# that cannot be established is a hard stop. A process systemd has not yet reaped still counts as
# running, and once systemd has reaped it the unit is done, so there is no zombie case.
ctl_alive() { local u s; u=$(ctl_unit) || return 1; s=$(unit_state "$u")
  case "$s" in running) return 0;; done) return 1;; *) die "controller unit $u: state cannot be established ($s)";; esac; }
# listeners: sets LST to the addresses listening on 18443 or 18444 (empty if none); aborts if ss fails.
listeners() { local o; o=$(ss -ltnH '( sport = :18443 or sport = :18444 )') || die "ss failed"; LST=$(printf '%s\n' "$o" | awk 'NF {print $4}' | sort -u | tr '\n' ' '); }
# start_ctl BINARY LABEL [EQUIPO_HOSTED_X=VALUE...]: start the controller as its own unit (never a
# child of the block that starts it). Its whole environment is the unit's env -i argv: unitctl.sh's
# allowlist, then these explicit defaults (AWS_PROFILE=kass, eu-west-1), then the EQUIPO_HOSTED_
# settings given (EQUIPO_HOSTED_CRASH_AFTER_LAUNCH only in 7.3), nothing else. Its exit status goes
# to controller.exit (exitpost.sh).
start_ctl() {
  local bin=$1 label=$2 u a i ev=(-E AWS_PROFILE=kass -E AWS_REGION=eu-west-1 -E AWS_DEFAULT_REGION=eu-west-1); shift 2
  [ -x "$bin" ] || die "no binary $bin"
  ! ctl_alive || die "a controller is already running"
  listeners; [ -z "$LST" ] || die "ports 18443 or 18444 are in use: $LST"
  u="${UNIT_PREFIX}ctl-$label.service"
  [ "$(unit_state "$u")" = done ] || die "unit $u already exists"
  for a; do case "$a" in EQUIPO_HOSTED_*=*) ev+=(-E "$a");; *) die "start_ctl: $a is not an EQUIPO_HOSTED_ setting";; esac; done
  rm -f "$T17/controller.exit"
  [ -f "$T17/controller.log" ] || : > "$T17/controller.log"
  wc -l < "$T17/controller.log" > "$T17/controller.logstart" || die "cannot write controller.logstart"
  date -u +%FT%T.%3NZ > "$T17/controller.start" || die "cannot write controller.start"
  printf '%s\n' "$u" > "$T17/controller.unit" || die "cannot write controller.unit"
  jw "CONTROLLER start $label $u $bin $*"
  unit_start "$u" "$T17/controller.log" "$T17/controller.exit" "${ev[@]}" -- "$bin" -config "$T17/controller.json" || die "systemd-run could not start $u"
  for i in $(seq 1 20); do [ "$(unit_state "$u")" = running ] && break; [ -s "$T17/controller.exit" ] && break; sleep 0.25; done
  ctl_alive || die "the controller did not start (see controller.log)"
  echo "controller $label started as unit $u"
}
_ctl_ready() {
  [ -s "$T17/controller.exit" ] && return 2
  local m; m=$(curl -fsS "http://$METRICS/metrics" 2>/dev/null) || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 0$' && return 3
  printf '%s\n' "$m" | grep -q '^equipo_hosted_network_audit_passing 1$' || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_age_seconds ' || return 1
  printf '%s\n' "$m" | grep -q '^equipo_hosted_reap_last_error 0$' || return 4
  return 0
}
# ctl_ready: within 240 s the audit has passed and a reaper pass has finished cleanly (else soft_fail);
# listeners are 127.0.0.1 only (else a hard stop: docs-t1's binding rule).
ctl_ready() {
  poll 240 5 "controller ready" _ctl_ready
  listeners; [ "$LST" = "127.0.0.1:18443 127.0.0.1:18444 " ] || die "listeners are [$LST], want 127.0.0.1:18443 and :18444 only"
  local m; m=$(curl -fsS "http://$METRICS/metrics") || soft_fail "metrics unreadable"
  echo "controller ready:"; printf '%s\n' "$m" | grep -E '^equipo_hosted_(network_audit_passing|reap_last_error|reap_last_age_seconds|store_readable) ' || soft_fail "readiness metrics missing"
}
# stop_ctl: stop the latest controller unit (systemd: TERM, KILL after 45 s, reaped) and prove it
# done; its ports must close.
stop_ctl() {
  local u s i
  if u=$(ctl_unit); then
    s=$(unit_state "$u")
    if [ "$s" != done ]; then
      jw "CONTROLLER stop $u ($s)"
      unit_stop "$u" || die "controller unit $u could not be proved stopped: $(unit_state "$u")"
    fi
  fi
  for i in $(seq 1 10); do [ -s "$T17/controller.exit" ] && break; sleep 1; done
  listeners; [ -z "$LST" ] || die "a listener is still open: $LST"
  jw "CONTROLLER exited $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
  echo "controller stopped; exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown)"
}
metrics() { curl -fsS "http://$METRICS/metrics" | grep -E '^equipo_hosted_' || die "metrics unreadable"; }
# mread: an observation read of the metrics into MTXT; 1 (and a FINDING) if it fails.
mread() { MTXT=$(curl -fsS --max-time 10 "http://$METRICS/metrics" 2>/dev/null) && MTXT=$(grep -E '^equipo_hosted_' <<<"$MTXT") && return 0
  MTXT=""; finding "metrics unreadable"; return 1; }
# audit_has ATTEMPT ACTION...: with the controller stopped, each ACTION must have an audit row for
# ATTEMPT; each missing one is a FINDING. The actions are hostedctl's constants.
audit_has() { local a=$1 x n; shift
  for x; do n=$(dbread "select count(*) from audit where attempt_id='$a' and action='$x'") || { finding "database copy unreadable"; return 0; }
    [ "${n:-0}" -ge 1 ] || finding "no $x audit row for $a"; done; }
# dbread SQL: read a copy of the stopped controller's database.
dbread() {
  ! ctl_alive || die "stop the controller before reading its database"
  rm -rf "$T17/dbcopy"; mkdir "$T17/dbcopy"; cp "$T17"/controller.db* "$T17/dbcopy/"
  python3 -I -c 'import sqlite3,sys
con = sqlite3.connect(sys.argv[1])
for r in con.execute(sys.argv[2]): print("\t".join("" if c is None else str(c) for c in r))' "$T17/dbcopy/controller.db" "$1"
}
# gotest LOG ARGS...: run go test with output to LOG; record VM IDs it names; return its status.
gotest() {
  local log=$1 rc had=0 t0; shift; case $- in *e*) had=1;; esac
  t0=$(date -u +%FT%T.%3NZ); jw "PHASE $(basename "$log") start $t0"
  set +e; (cd "$REPO" && CGO_ENABLED=0 go test "$@") > "$log" 2>&1; rc=$?; [ "$had" = 1 ] && set -e
  jw "PHASE $(basename "$log") end rc=$rc"
  harvest "$log" "$(basename "$log")" "$t0"
  grep -E '^(=== RUN|--- (PASS|FAIL|SKIP)|PASS|FAIL|ok|panic)' "$log" | tail -n 40 || true
  return "$rc"
}
true
ENVEOF
# Reserve the run ID atomically (R45): the leaf mkdir fails if the directory exists, so a run ID
# another agent of this user holds is never taken; then no unit of it may exist yet.
mkdir -p "$HOME/.cache/t17b-runs"
RUN=""
for _i in 1 2 3 4 5; do
  _r=$(date -u +%m%d)-b$(openssl rand -hex 3)
  if mkdir "$HOME/.cache/t17b-runs/$_r" 2>/dev/null; then RUN=$_r; break; fi
done
[ -n "$RUN" ] || { echo "ABORT: could not reserve a run ID under $HOME/.cache/t17b-runs"; exit 1; }
_u=$(timeout 10 systemctl --user list-units --all --plain --no-legend --full -- "t17b-$RUN-*") || { echo "ABORT: systemctl --user cannot list t17b-$RUN-*"; exit 1; }
[ -z "$_u" ] || { echo "ABORT: units named t17b-$RUN-* already exist (not this run's; never touched): $_u"; exit 1; }
NAME=equipo-hosted-dev-t17-$RUN
cat > "$TMPDIR/equipo-t17b/run.env" <<RUNEOF
export PIN_SHA='$PIN_SHA'
export RUN=$RUN NAME=$NAME RUN_RESERVATION=$HOME/.cache/t17b-runs/$RUN
export OPERATOR_ROLE=$NAME-conn-op BUILD_ROLE=$NAME-build CONN_NAME=$NAME-egress IMAGE_NAME=$NAME
export BUCKET=$NAME-640012953448 LOG_GROUP=/aws/lambda-microvms/$NAME TOPIC_NAME=$NAME-alerts SG_NAME=$NAME-vm
export TAGS_EC2="Key=purpose,Value=equipo-hosted-dev Key=run,Value=$RUN"
RUNEOF
touch "$TMPDIR/equipo-t17b/ledger.env" "$TMPDIR/equipo-t17b/journal.tsv" "$TMPDIR/equipo-t17b/vms.tsv"
. "$TMPDIR/equipo-t17b/env.sh"
unit_probe || die "the systemd user-unit probe (${UNIT_PREFIX}probe.service) failed: detached blocks and the controller could not be tracked (R44); no AWS call has been made"
[[ "$PIN_SHA" =~ ^[0-9a-f]{40}$ ]] || die "PIN_SHA in run.env is not a full SHA"
jw "RUN $RUN start pin=$PIN_SHA"
(cd "$REPO" && CGO_ENABLED=0 go build -tags hostedlive -o "$LIVECTL" ./internal/isolatedjob/awsjob/livectl)
[ -x "$LIVECTL" ] || die "livectl did not build"
echo "T17=$T17 RUN=$RUN NAME=$NAME LIVECTL=$LIVECTL"
```

- `PIN_SHA` comes from the file 0.1 wrote after its checks passed; `run.env` carries it for 5.4's
  re-check. livectl is built from the checked-out code, which 0.1 proved is the pinned revision.
- The run ID is `<mmdd>-b<6 hex>` (the `b` marks Task 17b). Every name below contains it, so every
  name is new to the account; 0.4 still proves each one absent (R39). The base name keeps
  livectl's fixed run prefix `equipo-hosted-dev-t17-<RUN>`.
- Expected: one line with the scratch path, the run ID and the base name. Record the `T17=` path:
  sandboxed blocks find it through `$TMPDIR`, and the sandbox-off blocks (R37) set it from this line.
  The environment file refuses to load if the directory is not there.
- Abort if: the scratch directory already exists.

### 0.3 First AWS call: who am I

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
aws sts get-caller-identity --query '[Account,Arn]' --output text
lvr caller; must
[ "$(jq -r '"\(.Account) \(.Region)"' <<<"$OUT")" = "640012953448 eu-west-1" ] || die "livectl sees $(jq -c . <<<"$OUT")"
```

- Expected: `640012953448` and an ARN in that account, from the CLI and from livectl.
- Abort if: anything else. Nothing else runs.

### 0.4 Observations and collision checks

Every name below contains the random run ID, so a collision is not expected; each check still reads
the exact name and must get the "does not exist" answer.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need RUN NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME
try aws resourcegroupstaggingapi get-resources --tag-filters Key=purpose,Values=$TAGV --query 'ResourceTagMappingList[].ResourceARN' --output text; must
echo "observation: resources already tagged purpose=$TAGV (not ours, never touched): [$OUT]"
try aws ec2 describe-vpcs --filters Name=tag:run,Values=$RUN --query 'Vpcs[].VpcId' --output text; must; [ -z "$OUT" ] || die "a VPC already has run=$RUN"
for r in "$OPERATOR_ROLE" "$BUILD_ROLE"; do try aws iam get-role --role-name "$r"; expect_err NoSuchEntity; done
lvr connector get -id "$CONN_NAME"; { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; } || die "connector name $CONN_NAME: rc $RC ${ECODE:-} (it exists, or the check could not run)"
lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply (collision check)"
[ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "image name $IMAGE_NAME exists"
get _v aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$_v" = 0 ] || die "bucket $BUCKET exists in this account"
try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text; must; [ -z "$OUT" ] || die "log group exists: $OUT"
get _v aws sns list-topics --query "length(Topics[?TopicArn=='arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME'])" --output json; [ "$_v" = 0 ] || die "topic $TOPIC_NAME exists"
jw "COLLISION-CHECKS clean"; echo "collision checks clean"
```

- Expected: one observation line; `collision checks clean`. A collision is "anything not in the
  ledger", a hard stop.
- Abort if: any name exists, or a lookup fails. The image, bucket and topic checks list and match
  the exact name (the CLI reads every page), so they need no error code. A bucket name held by
  another account is not listed here; `create-bucket` in 3.1 then fails before anything is created,
  which is an abort.

---

## 1. Network

### 1.1 VPC, DNS off, and its default resources tagged

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need RUN NAME TAGS_EC2
intent vpc "tag:run=$RUN"
try aws ec2 create-vpc --cidr-block 10.177.0.0/16 \
  --tag-specifications "ResourceType=vpc,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.1-vpc.json"
rec VPC "$(jq -r .Vpc.VpcId "$T17/out/1.1-vpc.json")"
aws ec2 wait vpc-available --vpc-ids "$VPC"
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-hostnames '{"Value":false}'
aws ec2 modify-vpc-attribute --vpc-id "$VPC" --enable-dns-support '{"Value":false}'
fact_eq "VPC enableDnsSupport" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsSupport --query EnableDnsSupport.Value --output text
fact_eq "VPC enableDnsHostnames" False aws ec2 describe-vpc-attribute --vpc-id "$VPC" --attribute enableDnsHostnames --query EnableDnsHostnames.Value --output text
get DEF aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "default groups: [$DEF]"; rec DEF_SG "$DEF"
get DEF aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "main route tables: [$DEF]"; rec MAIN_RTB "$DEF"
get DEF aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text
[ "$(wc -w <<<"$DEF")" = 1 ] || die "default network ACLs: [$DEF]"; rec DEF_ACL "$DEF"
get DEF aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
[ -n "$DEF" ] || die "the default group has no rules to tag"; rec DEF_SG_RULES "$DEF"
aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
try aws ec2 describe-tags --filters Name=resource-id,Values="$VPC,$DEF_SG,$MAIN_RTB,$DEF_ACL,$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" Name=key,Values=purpose --query 'length(Tags)' --output json
if [ "$RC" != 0 ]; then finding "purpose tag read failed: ${ECODE:-rc$RC}"
elif [ "$OUT" != $(( 4 + $(wc -w <<<"$DEF_SG_RULES") )) ]; then finding "purpose tag read back on $OUT resources"; fi
echo "VPC $VPC: DNS support and hostnames off; defaults tagged: $DEF_SG $MAIN_RTB $DEF_ACL $DEF_SG_RULES"
```

- Expected: the last line. The defaults go with the VPC in 10.3 and are verified gone in 10.8.
- Abort if: the create, a default-resource lookup or the tagging fails. A differing or failed
  readback (DNS attributes, tag count) is a FINDING.

### 1.2 One VM subnet

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need VPC RUN NAME
intent subnet "tag:run=$RUN"
try aws ec2 create-subnet --vpc-id "$VPC" --cidr-block 10.177.1.0/24 --availability-zone eu-west-1a \
  --tag-specifications "ResourceType=subnet,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.2-subnet.json"
rec SUBNET "$(jq -r .Subnet.SubnetId "$T17/out/1.2-subnet.json")"
aws ec2 wait subnet-available --subnet-ids "$SUBNET"
fact_eq "subnet readback" "$VPC	10.177.1.0/24	eu-west-1a	False" aws ec2 describe-subnets --subnet-ids "$SUBNET" --query 'Subnets[0].[VpcId,CidrBlock,AvailabilityZone,MapPublicIpOnLaunch]' --output text
echo "subnet $SUBNET ok"
```

- Abort if: creation fails (an unsupported zone would be a stop; U10 is settled). A readback that
  differs or fails is a FINDING.

### 1.3 The subnet's own route table, local route only

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need VPC SUBNET RUN NAME
intent route-table "tag:run=$RUN"
try aws ec2 create-route-table --vpc-id "$VPC" \
  --tag-specifications "ResourceType=route-table,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$NAME-vm}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.3-rtb.json"
rec RTB "$(jq -r .RouteTable.RouteTableId "$T17/out/1.3-rtb.json")"
intent route-table-association "" "$RTB/$SUBNET"
try aws ec2 associate-route-table --route-table-id "$RTB" --subnet-id "$SUBNET" --query AssociationId --output text; must
rec RTB_ASSOC "$OUT"
fact_eq "routes" "10.177.0.0/16	local	active" aws ec2 describe-route-tables --route-table-ids "$RTB" --query 'RouteTables[0].Routes[].[DestinationCidrBlock,GatewayId,State]' --output text
fact_eq "the subnet's route table" "$RTB" aws ec2 describe-route-tables --filters Name=association.subnet-id,Values="$SUBNET" --query 'RouteTables[].RouteTableId' --output text
echo "route table $RTB: local route only, associated"
```

### 1.4 Security group with no rules

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need VPC RUN SG_NAME
intent security-group "$SG_NAME"
try aws ec2 create-security-group --group-name "$SG_NAME" --description "Task 17 VM group, no rules" --vpc-id "$VPC" \
  --tag-specifications "ResourceType=security-group,Tags=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN},{Key=Name,Value=$SG_NAME}]" --output json; must
printf '%s\n' "$OUT" > "$T17/out/1.4-sg.json"
rec SG "$(jq -r .GroupId "$T17/out/1.4-sg.json")"
aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --output json > "$T17/out/1.4-rules.json"
jq -e '[.SecurityGroupRules[] | select(.IsEgress)] | length == 1' "$T17/out/1.4-rules.json" >/dev/null || finding "not exactly one default egress rule: $(jq -c . "$T17/out/1.4-rules.json")"
jq -e '[.SecurityGroupRules[] | select(.IsEgress | not)] | length == 0' "$T17/out/1.4-rules.json" >/dev/null || finding "the new group has inbound rules"
rules=$(jq -r '.SecurityGroupRules[] | select(.IsEgress) | .SecurityGroupRuleId' "$T17/out/1.4-rules.json")
[ -z "$rules" ] || [ "$(aws ec2 revoke-security-group-egress --group-id "$SG" --security-group-rule-ids $rules --query Return --output text)" = True ] || die "revoking the default egress rules failed"
get got aws ec2 describe-security-groups --group-ids "$SG" --query 'SecurityGroups[0].[length(IpPermissions),length(IpPermissionsEgress)]' --output text
[ "$got" = "0	0" ] || finding "rules left: [$got]"
fact_eq "VM group rule count" 0 aws ec2 describe-security-group-rules --filters Name=group-id,Values="$SG" --query 'length(SecurityGroupRules)' --output text
echo "security group $SG: no rules"
```

---

## 2. Connector

### 2.1 The connector's network-interface role

The trust policy is the one AWS documents for the connector operator role (Lambda Web Functions
networking guide: `lambda.amazonaws.com`, `sts:AssumeRole`), plus `sts:TagSession`, which only lets
Lambda tag the session it assumes. Attempts 2 and 3 showed a narrow, scoped policy is refused when
the connector is created, even 3.3 minutes later, while the AWS-managed
`AWSLambdaNetworkConnectorOperatorPolicy` plus an inline delete was accepted. So, for this
throwaway dev run (Paul, 2026-11-25 and 2026-11-28), the role gets the managed policy from the
start, plus an inline `ec2:DeleteNetworkInterface` (the managed policy has none). The delete is
scoped as narrowly as EC2 allows before the interfaces exist: this account and region,
network-interface resources only, only interfaces whose `ec2:ManagedResourceOperator` is the
Lambda connector service, and only interfaces in this run's subnet. The block then waits 120 s
for IAM propagation, the wait that preceded attempt 3's accepted call.

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need SUBNET OPERATOR_ROLE RUN
cat > "$T17/iam/lambda-trust.json" <<'TEOF'
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":["sts:AssumeRole","sts:TagSession"]}]}
TEOF
A=arn:aws:ec2:eu-west-1:640012953448
cat > "$T17/iam/operator-delete.json" <<TEOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"DeleteLambdaConnectorEniOnly","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
  "Condition":{"StringEquals":{"ec2:ManagedResourceOperator":"network-connectors.lambda.amazonaws.com"},
   "ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
TEOF
jq -e . "$T17/iam/operator-delete.json" >/dev/null
intent iam-role "$OPERATOR_ROLE"
try aws iam create-role --role-name "$OPERATOR_ROLE" --description "Task 17 connector network interfaces, run $RUN" \
  --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
  --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
arn_ok "$OUT"; rec OPERATOR_ROLE_ARN "$OUT"
aws iam attach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
rec OPERATOR_MANAGED_POLICY arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy
aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete.json"
rec OPERATOR_INLINE_POLICY t17-connector-eni-delete
aws iam wait role-exists --role-name "$OPERATOR_ROLE"
fact_json "operator inline policies" '["t17-connector-eni-delete"]' aws iam list-role-policies --role-name "$OPERATOR_ROLE" --query 'PolicyNames' --output json
fact_json "operator managed policies" '["AWSLambdaNetworkConnectorOperatorPolicy"]' aws iam list-attached-role-policies --role-name "$OPERATOR_ROLE" --query 'AttachedPolicies[].PolicyName' --output json
echo "waiting 120 s for IAM propagation before Lambda assumes the operator role"; sleep 120
echo "operator role $OPERATOR_ROLE_ARN ready"
```

- Abort if: a create, attach or put call fails (2.2 needs the role).
- The two readbacks are facts: `fact_json` compares the compacted JSON, and a difference is a
  FINDING.

### 2.2 Create the VPC_EGRESS connector for MicroVMs (once)

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need SUBNET SG OPERATOR_ROLE_ARN CONN_NAME RUN
intent connector "$CONN_NAME" "token=$CONN_NAME-1"
lv connector create -name "$CONN_NAME" -role "$OPERATOR_ROLE_ARN" -subnet "$SUBNET" -sg "$SG" \
  -client-token "$CONN_NAME-1" -tag purpose=$TAGV -tag run=$RUN
if [ "$RC" != 0 ]; then
  if [ "$ECODE" = InvalidParameterValueException ] && grep -qF 'invalid ConnectorOperatorRole permissions' <<<"$LV_MSG"; then
    msg=$LV_MSG
    lvr connector get -id "$CONN_NAME"
    if [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; then jw "NOTCREATED connector attempt 1"; fi
    die "the connector was refused with the managed operator policy ($msg); 2.3 onwards needs it"
  fi
  die "connector create: rc $RC ${ECODE:-} ${LV_MSG:-$ERR} (uncertain: S.2 reconciles it)"
fi
printf '%s\n' "$OUT" > "$T17/out/2.2-connector.json"
arn_ok "$(jq -r .Arn "$T17/out/2.2-connector.json")"
rec CONN_ARN "$(jq -r .Arn "$T17/out/2.2-connector.json")"; rec CONN_ID "$(jq -r .Id "$T17/out/2.2-connector.json")"
[ "$CONN_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:network-connector:$CONN_ID" ] || die "connector ARN has an unexpected form: $CONN_ARN"
rec CONN_OPERATOR_POLICY "managed AWSLambdaNetworkConnectorOperatorPolicy plus inline delete"
jw "FACT connector create reply: $(jq -c '{State,Version,VersionArn,LatestVersion,LatestVersionArn}' "$T17/out/2.2-connector.json")"
jq -c '{Arn,Id,State,Version,VersionArn}' "$T17/out/2.2-connector.json"
```

- Expected: state `PENDING`. livectl sends no `ElasticIpConfiguration`, so the connector gets none;
  2.4 and 5.6 confirm it.
- Abort if: the create fails. A refusal leaves no connector (attempt 2's evidence); anything else
  is uncertain and S.2 reconciles it by name.

### 2.3 Wait for ACTIVE (spike, attempts 3 and 4: about 4.3 to 4.5 min; bound 15 min)

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need CONN_ARN
lv_wait 900 connector wait-active -id "$CONN_ARN" -interval 15s
printf '%s\n' "$OUT" > "$T17/out/2.3-active.json"
jq -c '{State,StateReason,StateReasonCode}' "$T17/out/2.3-active.json" 2>/dev/null || true
[ "$RC" = 0 ] || die "connector not ACTIVE (rc $RC, ${ECODE:-no code}); 2.4 onwards needs it"
jw "TIMING connector-active"
```

- Abort if: a failed state (exit 6, the reply shows `StateReason`) or the bound runs out (exit 5).

### 2.4 The version-1 qualified ARN, facts about versions, and the interfaces

A new connector starts at version 1 (pinned SDK, `CreateNetworkConnector`). Attempt 3's discovery
read `<arn>:1` and got `Version` 1, ACTIVE; the unqualified read carries only `LatestVersion` and
`LatestVersionArn`. The launches and the 5.6 audit need the qualified ARN, so that read is a
requirement; the rest are facts.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need CONN_ARN CONN_ID SUBNET SG VPC
lvr connector get -id "$CONN_ARN:1"; must
printf '%s\n' "$OUT" > "$T17/out/2.4-qualified.json"
jq -e --arg q "$CONN_ARN:1" --arg s "$SUBNET" --arg g "$SG" '.Version == 1 and .VersionArn == $q and .State == "ACTIVE"
  and .Configuration.Value.SubnetIds == [$s] and .Configuration.Value.SecurityGroupIds == [$g]
  and .Configuration.Value.AssociatedComputeResourceTypes == ["MicroVm"]' "$T17/out/2.4-qualified.json" >/dev/null \
  || die "the version-1 read does not show this run's ACTIVE connector: $(jq -c '{Version,VersionArn,State,Configuration}' "$T17/out/2.4-qualified.json")"
rec CONN_VERSION 1; rec CONN_QARN "$CONN_ARN:1"
fact_lv "connector Elastic IP configuration" "null" '.Configuration.Value.ElasticIpConfiguration' connector get -id "$CONN_QARN"
lvr connector get -id "$CONN_ARN"
if [ "$RC" = 0 ]; then
  jw "FACT unqualified read: $(jq -c '{Version,VersionArn,LatestVersion,LatestVersionArn,ServerTime:.ResultMetadata.ServerTime}' <<<"$OUT")"
  [ "$(jq -r .LatestVersionArn <<<"$OUT")" = "$CONN_QARN" ] || finding "unqualified read: LatestVersionArn is $(jq -r .LatestVersionArn <<<"$OUT"), not $CONN_QARN"
else finding "unqualified connector read failed: ${ECODE:-rc$RC}"; fi
lvr connector list-versions -id "$CONN_ARN"
if [ "$RC" = 0 ] && list_items; then jw "FACT connector versions: $(jq -c '[.[] | {Version,VersionArn,State}]' <<<"$ITEMS")"
elif [ "$RC" = 0 ]; then finding "connector version list reply is malformed"
else finding "connector version list failed: ${ECODE:-rc$RC}"; fi
eni_snapshot soft "2.4, connector ACTIVE"
echo "qualified connector ARN: $CONN_QARN"
```

- Expected: the version-1 read is this run's ACTIVE connector, in this subnet with this group. No
  Elastic IP configuration. Attempt 3 saw no interfaces while ACTIVE, which is recorded as a fact.
  Interfaces Lambda creates later are recorded by ID by `eni_snapshot` in 6.1, 7.2 and 8.1 (while
  VMs run) and in 10.2 just before the connector is deleted; 10.2 then proves each recorded ID gone.
  Attempt 4 saw none in the run's VPC at any snapshot, VMs running included. An interface outside
  this run's subnet is a hard stop.
- Abort if: the version-1 read fails or shows another connector; everything after needs it.

---

## 3. Image

The API builds an image from a zip in S3 holding a `Dockerfile` and its files, on a Lambda-managed
base image, with a build role that can read the zip and write build logs. Memory, x86_64 and the
`ALL` capability are set per image version. This run builds only the Small version (2048 MiB): the
adapter needs at least one version per image, and every VM in sections 6, 7 and 8 is Small. The
image is a static Go binary that answers 200 on every hook path on port 9000 inside the VM; the run
hook must answer, because the adapter always sends a run hook payload. Attempt 4 built this exact
image from base version 4 in about 1.8 minutes.

### 3.1 S3 bucket

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need BUCKET RUN
intent s3-bucket "$BUCKET"
try aws s3api create-bucket --bucket "$BUCKET" --create-bucket-configuration LocationConstraint=eu-west-1 --output json; must
rec BUCKET_CREATED "$BUCKET"
aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
fact_eq "bucket run tag" "$RUN" aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
echo "bucket $BUCKET ok"
```

### 3.2 Log group for the build

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need LOG_GROUP RUN
intent log-group "$LOG_GROUP"
try aws logs create-log-group --log-group-name "$LOG_GROUP" --tags purpose=$TAGV,run=$RUN; must
rec LOG_GROUP_CREATED "$LOG_GROUP"
aws logs put-retention-policy --log-group-name "$LOG_GROUP" --retention-in-days 1
fact_eq "log group and retention" "$LOG_GROUP	1" aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].[logGroupName,retentionInDays]' --output text
```

### 3.3 Build role (least privilege)

Same trust policy as 2.1. The current getting-started page prints `sts:AssumeRole` only; Astra's
review cites a version with `sts:TagSession`. Granting both satisfies either. Permissions are the
guide's, narrowed to the one S3 key and the one log group. It is a build role only: no VM ever gets
an execution role (spec §3, §15).

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need BUILD_ROLE BUCKET LOG_GROUP RUN
L="arn:aws:logs:eu-west-1:640012953448:log-group:$LOG_GROUP"
cat > "$T17/iam/build.json" <<EOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"ReadTheCodeArtifact","Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::$BUCKET/t17/app.zip"},
 {"Sid":"WriteBuildLogsToThisGroup","Effect":"Allow","Action":["logs:CreateLogGroup","logs:CreateLogStream","logs:PutLogEvents"],"Resource":["$L","$L:*"]}]}
EOF
jq -e . "$T17/iam/build.json" >/dev/null
intent iam-role "$BUILD_ROLE"
try aws iam create-role --role-name "$BUILD_ROLE" --description "Task 17 MicroVM image build, run $RUN" \
  --assume-role-policy-document "file://$T17/iam/lambda-trust.json" \
  --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query Role.Arn --output text; must
arn_ok "$OUT"; rec BUILD_ROLE_ARN "$OUT"
aws iam put-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build --policy-document "file://$T17/iam/build.json"
aws iam wait role-exists --role-name "$BUILD_ROLE"
fact_eq "build role inline policy" t17-build aws iam list-role-policies --role-name "$BUILD_ROLE" --query 'PolicyNames' --output text
echo "waiting 60 s for IAM propagation before Lambda assumes the build role"; sleep 60
```

### 3.4 Hook binary, Dockerfile, hooks and zip (no AWS call)

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
cd "$T17/image"
cat > hookd.go <<'EOF'
// hookd answers every Lambda MicroVM lifecycle hook with 200. Task 17 only.
package main

import (
	"io"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/aws/lambda-microvms/runtime/v1/", func(w http.ResponseWriter, r *http.Request) {
		n, _ := io.Copy(io.Discard, r.Body)
		log.Printf("hook %s %d bytes", r.URL.Path, n)
		w.WriteHeader(http.StatusOK)
	})
	log.Fatal(http.ListenAndServe(":9000", nil))
}
EOF
cat > Dockerfile <<'EOF'
FROM public.ecr.aws/lambda/microvms:al2023-minimal
COPY hookd /usr/local/bin/hookd
CMD ["/usr/local/bin/hookd"]
EOF
cat > hooks.json <<'EOF'
{"port":9000,
 "microvmHooks":{"run":"ENABLED","runTimeoutInSeconds":10,"resume":"ENABLED","resumeTimeoutInSeconds":10,
   "suspend":"ENABLED","suspendTimeoutInSeconds":10,"terminate":"ENABLED","terminateTimeoutInSeconds":10},
 "microvmImageHooks":{"ready":"ENABLED","readyTimeoutInSeconds":120,"validate":"DISABLED"}}
EOF
jq -e . hooks.json >/dev/null
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags=-s -o hookd hookd.go
chmod 0755 hookd
[ "$(head -c 4 hookd | od -An -c | tr -d ' ')" = '177ELF' ] || die "hookd is not an ELF binary"
python3 -I -m zipfile -c app.zip Dockerfile hookd
[ "$(python3 -I -c 'import zipfile;print(" ".join(sorted(zipfile.ZipFile("app.zip").namelist())))')" = "Dockerfile hookd" ] || die "zip contents differ"
sha256sum app.zip
```

### 3.5 Digest, and the upload that proves it (object tagged)

AWS has no content digest for a MicroVM image, so the controller's allowlist key (`sha256:` and 64
lower-case hex digits) is the SHA-256 of the exact zip the image is built from. S3 rejects the
upload if the bytes do not match the checksum sent; the read-back shows S3 holds that checksum;
3.8 shows each version names this object.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need BUCKET RUN
cd "$T17/image"
rec DIGEST "sha256:$(sha256sum app.zip | cut -d' ' -f1)"
B64=$(openssl dgst -sha256 -binary app.zip | base64)
rec ARTIFACT_B64 "$B64"
intent s3-object "s3://$BUCKET/t17/app.zip"
try aws s3api put-object --bucket "$BUCKET" --key t17/app.zip --body app.zip --checksum-algorithm SHA256 \
  --checksum-sha256 "$B64" --tagging "purpose=$TAGV&run=$RUN" --query ChecksumSHA256 --output text; must
[ "$OUT" = "$B64" ] || finding "put-object checksum [$OUT]"
rec ARTIFACT "s3://$BUCKET/t17/app.zip"
fact_eq "S3 object checksum" "$B64" aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text
fact_eq "S3 object run tag" "$RUN" aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
echo "artifact $ARTIFACT digest $DIGEST"
```

### 3.6 Managed base image and version

livectl reads each base version's `Status` and `SupportedCpuConfigurations` (the CLI dropped them).
The block picks the newest `AVAILABLE` version that supports x86_64, and records the next one down
for the pre-approved step down in 3.7 and 3.8.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
lvr image base-versions; must
printf '%s\n' "$OUT" > "$T17/out/3.6-base.json"
list_items || die "malformed base version list reply; the image needs a base version"
jq -r '.[] | [.ImageVersion, .Status, ([.SupportedCpuConfigurations[]?.Architecture] | join(","))] | @tsv' <<<"$ITEMS"
rec BASE_ARN "$(jq -r '.BaseImage' "$T17/out/3.6-base.json")"
[ "$BASE_ARN" = arn:aws:lambda:eu-west-1:aws:microvm-image:al2023-1 ] || finding "base image ARN is $BASE_ARN"
vs=$(jq -r '[.[] | select(.Status == "AVAILABLE" and any(.SupportedCpuConfigurations[]?; .Architecture == "X86_64"))] | .[0:2][] | .ImageVersion' <<<"$ITEMS")
v1=$(sed -n 1p <<<"$vs"); v2=$(sed -n 2p <<<"$vs")
[ -n "$v1" ] || die "no AVAILABLE base version supports x86_64; the image needs one"
rec BASE_VER "$v1"
if [ -n "$v2" ]; then rec BASE_VER_DOWN "$v2"; else finding "only one AVAILABLE x86_64 base version ($v1): no step down available"; fi
```

- Expected: the newest `AVAILABLE` x86_64 version, and one below it.
- Abort if: the list fails, or no version is both `AVAILABLE` and x86_64.

### 3.7 Create the image: Small version

Two pre-approved retries, each at most once:

- **A refusal about the build role**, which was created in 3.3, gets the propagation treatment:
  confirm no image exists, wait 120 s, retry with the same base version. It counts only if the
  code is `ValidationException`, `AccessDeniedException` or `InvalidParameterValueException`; the
  service's message names the build role (its name or ARN) or Lambda assuming it ("build role",
  "assume role"); and it is not a denial of the caller ("is not authorized to perform").
- **Any other refusal that leaves no image** steps down once to `BASE_VER_DOWN` (Paul,
  2026-11-28).

Anything else, or a third refusal, is a stop: the image is needed.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need IMAGE_NAME ARTIFACT BASE_ARN BASE_VER BUILD_ROLE_ARN BUILD_ROLE LOG_GROUP RUN
# create_image BASEVERSION N: one attempt with client token $IMAGE_NAME-create-N. IMG_RC=0 created;
# 1 a build-role refusal; 2 another refusal; both with no image left. Anything uncertain aborts.
create_image() {
  intent microvm-image "$IMAGE_NAME" "token=$IMAGE_NAME-create-$2" "base=$1"
  lv image create -name "$IMAGE_NAME" -description "Task 17 minimal hook image, small, run $RUN" \
    -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$1" -build-role "$BUILD_ROLE_ARN" \
    -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 \
    -client-token "$IMAGE_NAME-create-$2" -tag purpose=$TAGV -tag run=$RUN
  if [ "$RC" = 0 ]; then IMG_RC=0; return 0; fi
  [ "$LV_KIND" = api ] || die "image create attempt $2: ${LV_KIND:-rc$RC} (no answer: S.2 reconciles it)"
  IMG_CODE=$ECODE; IMG_MSG=$LV_MSG
  jw "REFUSED image attempt $2 (base $1): ${IMG_CODE} ${IMG_MSG}"
  lvr image list -name "$IMAGE_NAME"; must; list_items || die "malformed image list reply after a refused create"
  [ "$(jq --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n)] | length' <<<"$ITEMS")" = 0 ] || die "a refused create left an image named $IMAGE_NAME"
  jw "NOTCREATED image attempt $2"
  case "$IMG_CODE" in ValidationException|AccessDeniedException|InvalidParameterValueException) role_code=yes;; *) role_code=no;; esac
  if [ "$role_code" = yes ] \
     && { grep -qF -e "$BUILD_ROLE_ARN" -e "$BUILD_ROLE" <<<"$IMG_MSG" || grep -qiE 'build role|assume (the )?(build )?role' <<<"$IMG_MSG"; } \
     && ! grep -qi 'is not authorized to perform' <<<"$IMG_MSG"; then IMG_RC=1; else IMG_RC=2; fi
}
ver=$BASE_VER; n=1; waited=no; stepped=no
while :; do
  create_image "$ver" "$n"
  [ "$IMG_RC" = 0 ] && break
  if [ "$IMG_RC" = 1 ] && [ "$waited" = no ]; then waited=yes; echo "build-role refusal: waiting 120 s, then the same version"; sleep 120
  elif [ "$IMG_RC" = 2 ] && [ "$stepped" = no ] && [ -n "${BASE_VER_DOWN:-}" ]; then
    stepped=yes; finding "image create from base $ver refused (${IMG_CODE}: ${IMG_MSG}); stepping down to $BASE_VER_DOWN"; ver=$BASE_VER_DOWN
  else die "image create refused (attempt $n, ${IMG_CODE}: ${IMG_MSG}); no pre-approved retry is left"; fi
  n=$((n + 1))
done
printf '%s\n' "$OUT" > "$T17/out/3.7-image.json"
arn_ok "$(jq -r .ImageArn "$T17/out/3.7-image.json")"
rec IMAGE_ARN "$(jq -r .ImageArn "$T17/out/3.7-image.json")"; rec VER_SMALL "$(jq -r .ImageVersion "$T17/out/3.7-image.json")"
rec BASE_VER_USED "$ver"; [ "$stepped" = no ] || rec BASE_STEPPED_DOWN yes
[ "$IMAGE_ARN" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$IMAGE_ARN]"
```

- livectl always sends x86_64 and the `ALL` capability, and no egress connectors, so the build pulls
  its container base image over the default build path; running VMs get only the connector.

### 3.8 Wait for the Small version and check it (bound 50 min with the step down)

If the Small build fails and 3.7 has not stepped down, the block builds a new Small version from
`BASE_VER_DOWN` by one update (pre-approved, once), and waits again.

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need IMAGE_ARN IMAGE_NAME VER_SMALL ARTIFACT BASE_ARN BUILD_ROLE_ARN LOG_GROUP RUN
lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
if [ "$RC" = 6 ] && [ -z "${BASE_STEPPED_DOWN:-}" ] && [ -n "${BASE_VER_DOWN:-}" ]; then
  finding "Small version $VER_SMALL failed to build from base ${BASE_VER_USED}: $(jq -r '.StateReason // empty' <<<"$OUT"); stepping down to $BASE_VER_DOWN"
  try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20
  rec VER_SMALL_FAILED "$VER_SMALL"
  intent microvm-image-version "$IMAGE_NAME" "token=$IMAGE_NAME-update-small-2" "base=$BASE_VER_DOWN"
  lv image update -id "$IMAGE_ARN" -description "Task 17 minimal hook image, small, run $RUN, base $BASE_VER_DOWN" \
    -artifact "$ARTIFACT" -base "$BASE_ARN" -base-version "$BASE_VER_DOWN" -build-role "$BUILD_ROLE_ARN" \
    -hooks "$T17/image/hooks.json" -log-group "$LOG_GROUP" -memory 2048 -client-token "$IMAGE_NAME-update-small-2"; must
  rec VER_SMALL "$(jq -r .ImageVersion <<<"$OUT")"; rec BASE_VER_USED "$BASE_VER_DOWN"; rec BASE_STEPPED_DOWN yes
  lv_wait 1200 image wait-version -id "$IMAGE_ARN" -version "$VER_SMALL" -interval 15s
fi
if [ "$RC" != 0 ]; then
  try aws logs filter-log-events --log-group-name "$LOG_GROUP" --limit 50 --query 'events[].message' --output text; [ "$RC" = 0 ] && printf '%s\n' "$OUT" | tail -n 20
  die "the Small version did not build; the image is needed"
fi
lvr image get-version -id "$IMAGE_ARN" -version "$VER_SMALL"
if [ "$RC" = 0 ]; then
  printf '%s\n' "$OUT" > "$T17/out/3.8-small.json"
  jq -e --arg a "$ARTIFACT" '([.CpuConfigurations[].Architecture] == ["X86_64"]) and ([.Resources[].MinimumMemoryInMiB] == [2048])
    and (.AdditionalOsCapabilities == ["ALL"]) and (.CodeArtifact.Value == $a) and (.Hooks.Port == 9000)' "$T17/out/3.8-small.json" >/dev/null \
    || finding "the Small version differs from what the adapter checks: $(jq -c '{CpuConfigurations,Resources,AdditionalOsCapabilities,CodeArtifact,Hooks}' "$T17/out/3.8-small.json")"
  jw "FACT Small version: $(jq -c '{ImageVersion,State,Status,Tags}' "$T17/out/3.8-small.json")"
else finding "Small version read failed: ${ECODE:-rc$RC}"; fi
lvr image get -id "$IMAGE_ARN"
if [ "$RC" = 0 ]; then
  case "$(jq -r .State <<<"$OUT")" in CREATED|UPDATED) ;; *) finding "image state $(jq -r .State <<<"$OUT")";; esac
  [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" = "$RUN" ] || finding "image tags: $(jq -c .Tags <<<"$OUT")"
else finding "image read failed: ${ECODE:-rc$RC}"; fi
jw "TIMING image-small-built"
```

- Expected: `SUCCESSFUL ACTIVE`; the fields the adapter's image check reads (`checkImageVersion`)
  match, or each difference is a FINDING (the adapter then refuses the version, and the contract
  shows it).
- Abort if: no Small version builds, after the one step down.
- There is no Large version in this run (revision 5's 3.9 is gone).

---

## 4. SNS topic

The controller refuses a config without `sns_topic_arn` (`cmd/equipo-hosted-controller/config.go:122-127`)
and wires its alerter to it (`main.go:104`). It stops at a startup alert it cannot deliver
(`internal/hostedctl/controller.go:105`), but startup alerts are queued only after a wall-clock
rollback (`store.go:226-235`), so a clean start publishes nothing. The first publish this run
expects is 8.2's `orphan_stopped` alert, counted by the controller as sent or failed. The topic
exists from here to 10.7.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need TOPIC_NAME RUN
intent sns-topic "$TOPIC_NAME"
try aws sns create-topic --name "$TOPIC_NAME" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN --query TopicArn --output text; must
[ "$OUT" = "arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME" ] || die "topic ARN [$OUT]"
rec TOPIC_ARN "$OUT"
fact_eq "topic run tag" "$RUN" aws sns list-tags-for-resource --resource-arn "$TOPIC_ARN" --query "Tags[?Key=='run'].Value" --output text
fact_eq "topic subscription count" 0 aws sns list-subscriptions-by-topic --topic-arn "$TOPIC_ARN" --query 'length(Subscriptions)' --output text
```

- 0.4 proved the name did not exist, so `create-topic`'s idempotent return cannot be someone else's
  topic. No subscription is made: alerts are read from the controller's metrics and database.

---

## 5. Keys, config, builds, and the audit before any launch

### 5.1 Keys and the self-signed certificate (pre-flight helper, no AWS call)

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
cd "$REPO" && EQUIPO_HOSTED_KEYGEN_DIR="$T17/keys" CGO_ENABLED=0 go test -tags hostedlive ./cmd/equipo-hosted-controller -run 'TestLiveKeygen$' -count=1 -v
for f in controller.key instance.key operator.key tls.key; do [ "$(stat -c %a "$T17/keys/$f")" = 600 ] || die "$f is not mode 600"; done
for f in controller.pub verify_keys.json tls.crt; do [ -s "$T17/keys/$f" ] || die "$f missing"; done
openssl x509 -in "$T17/keys/tls.crt" -noout -ext subjectAltName | grep -q 'IP Address:127.0.0.1' || die "certificate SAN is not 127.0.0.1"
jq -r '.[] | [.id, .role] | @tsv' "$T17/keys/verify_keys.json"
```

- Expected: `task17-instance instance` and `task17-operator operator`.

### 5.2 Ports free

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
listeners; [ -z "$LST" ] || die "in use: $LST"; echo "ports 18443 and 18444 free"
```

### 5.3 Controller config and live contract config

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
need DIGEST IMAGE_ARN VER_SMALL VPC SUBNET SG CONN_QARN TOPIC_ARN
jq -n --slurpfile vk "$T17/keys/verify_keys.json" --arg api "$API" --arg met "$METRICS" --arg d "$T17" \
  --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" \
  --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" --arg topic "$TOPIC_ARN" '{
  listen: $api, metrics_listen: $met,
  tls_cert_file: ($d + "/keys/tls.crt"), tls_key_file: ($d + "/keys/tls.key"),
  database: ($d + "/controller.db"), signing_key_file: ($d + "/keys/controller.key"),
  verify_keys: $vk[0],
  images: [{digest: $digest, arn: $arn, versions: {small: $small}}],
  region: "eu-west-1", vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
  connector_arn: $conn, egress: [], sns_topic_arn: $topic}' > "$T17/controller.json"
jq -n --arg digest "$DIGEST" --arg arn "$IMAGE_ARN" --arg small "$VER_SMALL" \
  --arg vpc "$VPC" --arg subnet "$SUBNET" --arg sg "$SG" --arg conn "$CONN_QARN" '{
  region: "eu-west-1", connector_id: $conn, vpc_id: $vpc, vm_subnet_id: $subnet, vm_security_group_id: $sg,
  image: $digest, image_arn: $arn, versions: {small: $small}, egress: []}' > "$T17/live.json"
jq -e '[.. | strings] | all(. != "" and . != "null")' "$T17/controller.json" "$T17/live.json" >/dev/null || die "an empty value in a config"
jq -e '.egress == []' "$T17/controller.json" "$T17/live.json" >/dev/null || die "egress is not empty (R30)"
cat "$T17/controller.json" "$T17/live.json"
```

Filled in, `controller.json` reads (angle brackets are ledger values):

```json
{
  "listen": "127.0.0.1:18443",
  "metrics_listen": "127.0.0.1:18444",
  "tls_cert_file": "<T17>/keys/tls.crt",
  "tls_key_file": "<T17>/keys/tls.key",
  "database": "<T17>/controller.db",
  "signing_key_file": "<T17>/keys/controller.key",
  "verify_keys": [
    {"id": "task17-instance", "role": "instance", "public_key": "<base64>"},
    {"id": "task17-operator", "role": "operator", "public_key": "<base64>"}
  ],
  "images": [{"digest": "<DIGEST>", "arn": "<IMAGE_ARN>", "versions": {"small": "<VER_SMALL>"}}],
  "region": "eu-west-1",
  "vpc_id": "<VPC>",
  "vm_subnet_id": "<SUBNET>",
  "vm_security_group_id": "<SG>",
  "connector_arn": "<CONN_ARN>:<CONN_VERSION>",
  "egress": [],
  "sns_topic_arn": "<TOPIC_ARN>"
}
```

### 5.4 Build the two controller binaries (no AWS call)

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
cd "$REPO"
[ -z "$(git diff "$PIN_SHA" HEAD -- . ':!docs')" ] && [ -z "$(git status --porcelain --untracked-files=all -- . ':!docs')" ] || die "code changed since 0.1"
CGO_ENABLED=0 go build -o "$T17/bin/controller" ./cmd/equipo-hosted-controller
CGO_ENABLED=0 go build -tags hostedlive -o "$T17/bin/controller-crash" ./cmd/equipo-hosted-controller
ls -l "$T17/bin"
```

- `controller` is the normal build (no crash point); `controller-crash` is used only in 7.3.

### 5.5 Driver environment file (no AWS call)

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
need DIGEST
cat > "$T17/driver.env" <<EOF
export EQUIPO_HOSTED_LIVE_URL=https://$API
export EQUIPO_HOSTED_LIVE_CA_FILE=$T17/keys/tls.crt
export EQUIPO_HOSTED_LIVE_KEY_ID=task17-instance
export EQUIPO_HOSTED_LIVE_KEY_FILE=$T17/keys/instance.key
export EQUIPO_HOSTED_LIVE_CONTROLLER_KEY_FILE=$T17/keys/controller.pub
export EQUIPO_HOSTED_LIVE_IMAGE=$DIGEST
EOF
cat "$T17/driver.env"
```

### 5.6 Audit-only controller run: the SDK checks the network before any VM exists

Launches stay off (no `EQUIPO_HOSTED_ENABLED`). The reaper's first passes run the network audit
through the SDK: VPC DNS both off, the subnet's table local-only, the group with no rules, and the
connector read by its qualified ARN with `VersionArn` equal to it, `ACTIVE`, `MicroVm` only, this
subnet and group only, and no service-managed Elastic IPs (`internal/isolatedjob/awsjob/network.go`).
This also binds the database to `aws:640012953448:eu-west-1` (R28).

What a clean start writes, read from the code at the pin (this is the revision 5 defect: it asked
for a `network_audit_passed` row, which `reaperAudit` writes only when an audit passes again after
a failing run, `internal/hostedctl/reaper.go:739-747`):

- **Metrics, while it runs** (`internal/hostedctl/metrics.go:118-131`):
  `equipo_hosted_network_audit_passing 1` (the last audit passed and is fresh enough for
  launches; absent before the first audit), `equipo_hosted_reap_last_error 0` and
  `equipo_hosted_reap_last_age_seconds` (absent before the first pass). `ctl_ready` waits for
  exactly these.
- **Audit rows:** one `provider_bound` row, reason `database bound to provider namespace
  aws:640012953448:eu-west-1`, written once, on the database's first start
  (`internal/hostedctl/store.go:366-372`); no `network_audit_failed` row (written when a run of
  failed audits begins, `reaper.go:748-754`); normally no `network_audit_passed` row.
- **The binding:** `provider_binding.namespace` is `aws:640012953448:eu-west-1`.
- **Log:** `equipo-hosted-controller: API on 127.0.0.1:18443, metrics on 127.0.0.1:18444, launches
  enabled: false` (`cmd/equipo-hosted-controller/main.go:120`), and no
  `hosted controller: network audit failed; launches refused` line (`internal/hostedctl/logs.go:35`).

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
ok=yes
start_ctl "$T17/bin/controller" audit-only
if (ctl_ready); then
  if mread; then
    printf '%s\n' "$MTXT" > "$T17/out/5.6-metrics.txt"
    grep -qx 'equipo_hosted_network_audit_passing 1' <<<"$MTXT" || { finding "audit metric is not 1 after ready"; ok=no; }
    grep -qx 'equipo_hosted_reap_last_error 0' <<<"$MTXT" || { finding "the last reaper pass failed after ready"; ok=no; }
    jw "FACT 5.6 metrics: $(grep -E '^equipo_hosted_(network_audit_passing|reap_last_error|reap_last_age_seconds|store_readable) ' <<<"$MTXT" | tr '\n' ' ')"
  else ok=no; fi
  ctl_log | grep -F 'launches enabled: false' || finding "the controller did not report launches off"
  if ctl_log | grep -F 'hosted controller: network audit failed'; then finding "the log shows a failed network audit"; ok=no; fi
else finding "the audit-only controller did not become ready with the audit passing (see controller.log)"; ok=no; fi
stop_ctl
[ "$(cat "$T17/controller.exit" 2>/dev/null || true)" = 0 ] || finding "audit-only controller exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown), want 0"
dbread "select id, action, reason from audit where action in ('provider_bound','network_audit_passed','network_audit_failed') order by id"
n=$(dbread "select count(*) from audit where action='network_audit_failed'"); [ "$n" = 0 ] || { finding "$n network_audit_failed rows"; ok=no; }
n=$(dbread "select count(*) from audit where action='provider_bound' and reason='database bound to provider namespace aws:$ACCOUNT:eu-west-1'")
[ "$n" = 1 ] || { finding "$n provider_bound rows naming aws:$ACCOUNT:eu-west-1, want 1"; ok=no; }
ns=$(dbread "select namespace from provider_binding")
[ "$ns" = "aws:$ACCOUNT:eu-west-1" ] || { finding "database bound to [$ns], not aws:$ACCOUNT:eu-west-1"; ok=no; }
n=$(dbread "select count(*) from audit where action='network_audit_passed'"); jw "FACT network_audit_passed rows after a clean start: $n (0 expected)"
rec AUDIT_OK "$ok"
if [ "$ok" = yes ]; then jw "AUDIT passed before any launch"; echo "audit passed: sections 7 and 8 will run"
else echo "the audit did not pass: sections 7 and 8 will be skipped (each failed check is a FINDING above)"; fi
```

- Expected: ready within 4 minutes; the metrics above (attempt 4 saw them at once); the
  launches-off line and no audit-failed line; one `provider_bound` row naming this account and
  region, no failure rows, the binding as above; exit status 0 after the stop; `audit passed`.
- If any of those checks fails, each is a FINDING and `AUDIT_OK` is `no`: sections 7 and 8, which
  need a ready controller with a passing audit, are skipped as FINDINGs; 6 does not use the
  controller and still runs. A `network_audit_passed` row is only a fact: it appears only after a
  failed audit, which the failure-row check already reports.

---

## 6. Live contract: `ChangedSpecConflicts` only

Attempt 4 ran the whole contract: 8 of 9 subtests passed, and `ChangedSpecConflicts` failed because
the adapter mapped RunMicrovm's `ValidationException` "The provided clientToken was used with
different request parameters." to `ErrInvalid`. `5f6e3e65` maps exactly that refusal on `run` to
`ErrConflict` (`internal/isolatedjob/awsjob/errors.go`), and `bf29344a` adds two test rows. This
section re-runs only that subtest against AWS. It is expected to PASS. A failure is a FINDING, not
a stop. The subtest launches one Small VM (15-minute maximum), asks again with the same attempt and
a new bootstrap, and stops the first VM in its cleanup
(`internal/isolatedjob/isolatedjobtest/contract.go:172-184`); if AWS ever answered the changed
request with a second VM, the cleanup would not stop it, so `settle_all` ends every VM of the image
before section 7, whatever the result.

### 6.1 Run it, then settle every VM it made (long block, bound 40 min)

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
need IMAGE_ARN
! ctl_alive || die "the controller is running"
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image before the contract: $LIVE"
export EQUIPO_HOSTED_LIVE_CONFIG="$T17/live.json"
J="$T17/out/6-contract.json"
if gotest "$J" -tags hostedlive ./internal/isolatedjob/awsjob -run '^TestLiveContract$/^ChangedSpecConflicts$' -count=1 -v -json -timeout 20m; then rc=0; else rc=$?; fi
eni_snapshot soft "6.1, after the contract subtest"
settle_all
[ -s "$J" ] || { finding "the contract wrote no test output (rc $rc)"; exit 0; }
jq -R -r 'fromjson? | select(.Action == "output") | .Output' "$J" > "$T17/out/6-contract.log"
if grep -E "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/6-contract.log"; then finding "the adapter refused a MicroVM ID as malformed (R36)"; fi
grep -E 'visibility: Get showed new VM ' "$T17/out/6-contract.log" || finding "the contract logged no visibility line"
T=TestLiveContract/ChangedSpecConflicts
sub=$(jq -R -r --arg t "$T" 'fromjson? | select(.Test == $t and (.Action == "pass" or .Action == "fail" or .Action == "skip")) | .Action' "$J" | tail -n 1)
top=$(jq -R -r 'fromjson? | select(.Test == "TestLiveContract" and (.Action == "pass" or .Action == "fail" or .Action == "skip")) | .Action' "$J" | tail -n 1)
if [ "$rc" = 0 ] && [ "$sub" = pass ] && [ "$top" = pass ]; then rec CONTRACT_CSC pass; jw "CONTRACT ChangedSpecConflicts pass"; echo "ChangedSpecConflicts PASS"; exit 0; fi
msgs=$(jq -R -r --arg t "$T" 'fromjson? | select(.Test == $t and .Action == "output") | .Output' "$J" | grep -E '^\s+contract\.go:[0-9]+: ' | grep -vE 'contract\.go:[0-9]+: visibility: ' || true)
label=other
if grep -qE 'Launch with the same attempt and a new bootstrap = \("", .*ValidationException.*clientToken was used with different request parameters.*\), want ErrConflict$' <<<"$msgs"; then
  label="the old failure: the fix did not take effect"
elif grep -qE 'Launch with the same attempt and a new bootstrap = \(".+", <nil>\), want ErrConflict$' <<<"$msgs"; then
  label="AWS returned a VM for the changed request"
elif grep -qE 'Launch with the same attempt and a new bootstrap = ' <<<"$msgs"; then
  label="another refusal, not mapped to ErrConflict"
fi
rec CONTRACT_CSC "fail:$label"
finding "contract $T: rc $rc, subtest [${sub:-did not run}], top [${top:-none}] ($label): $(tr '\n' ' ' <<<"$msgs")"
echo "ChangedSpecConflicts did not pass; recorded as a FINDING; every VM of the image is settled"
```

- Expected: `ChangedSpecConflicts PASS`, a `visibility: Get showed new VM ...` line, and
  `settled: N VMs recorded, none live in three scans` (N is 1).
- A failure, a skip, or a subtest that did not run is a FINDING with its messages, labelled from
  the subtest's own output. The run goes on to section 7 either way, because `settle_all` has
  proved no VM of the image is live.
- Hard stop only if: a VM it made cannot be settled.

---

## 7. Controller on docs-t1

Every block here reads the controller's log only through `ctl_log` (the lines since the latest
start) or the slice `harvest_ctl` saves (`CTL_SLICE`), so one start's lines never pass or fail
another start's check. The log lines checked, at the pin:

| Check | Text | Source |
| --- | --- | --- |
| launches on | `launches enabled: true` | `cmd/equipo-hosted-controller/main.go:120` |
| crash switch on | `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the process exits after the next provider launch that returns a VM` | `crashpoint.go:35` |
| crash point | `crash point: the provider launched <vm> for <attempt>; exiting before the Ref is saved` | `crashpoint.go:46` |
| no elapsed-unknown stop | `hosted controller: restart stop requested, elapsed time unknown` | `internal/hostedctl/logs.go:44` |
| malformed ID refused | `microvm id is missing or malformed` | `internal/isolatedjob/awsjob/runner.go:260,328` |

### 7.1 Start with launches on, check readiness

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ "${AUDIT_OK:-}" != yes ]; then finding "section 7 skipped: the 5.6 audit did not pass"; rec SKIP_7 yes; exit 0; fi
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
start_ctl "$T17/bin/controller" sequence EQUIPO_HOSTED_ENABLED=1
if ! (ctl_ready); then finding "the controller did not become ready; section 7 skipped"; stop_ctl; rec SKIP_7 yes; exit 0; fi
ctl_log | grep -F 'launches enabled: true' || finding "the controller did not report launches enabled"
```

- Expected: `controller ready:` with `equipo_hosted_network_audit_passing 1` and
  `equipo_hosted_reap_last_error 0`, then the launches-on line.

### 7.2 Driver sequence: launch Small, drain, quiescent, suspend, resume, stop with proof (long block, bound 40 min)

The plan names the attempt (`EQUIPO_HOSTED_LIVE_ATTEMPT`, which `TestLiveControllerSequence` uses
when set, `internal/hostedclient/live_test.go:122-131`). The driver launches one Small VM with a
1-hour lifetime (`live_test.go:82`), waits for running, drains, acknowledges quiescence, suspends,
resumes, and stops until it holds proof, logging each step (`driver_test.go:136-211`).

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
. "$T17/driver.env"
ctl_alive || die "the controller is not running"
[ -n "${SEQ_ATTEMPT:-}" ] || rec SEQ_ATTEMPT "task17-seq-$(openssl rand -hex 4)"
export EQUIPO_HOSTED_LIVE_ATTEMPT="$SEQ_ATTEMPT"
if gotest "$T17/out/7.2-sequence.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveControllerSequence$' -count=1 -v -timeout 30m; then rc=0; else rc=$?; fi
grep -E 'attempt |launch:|running:|pause:|suspended:|resume:|stop:|timings:' "$T17/out/7.2-sequence.log" || true
eni_snapshot soft "7.2, after the sequence"
stop_ctl
harvest_ctl
settle_all
if grep -hE "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/7.2-sequence.log" "$CTL_SLICE"; then finding "a MicroVM ID was refused as malformed (R36)"; fi
[ "$rc" = 0 ] || finding "TestLiveControllerSequence failed (rc $rc); see 7.2-sequence.log"
grep -qF "attempt $SEQ_ATTEMPT, image " "$T17/out/7.2-sequence.log" || finding "the sequence log does not name attempt $SEQ_ATTEMPT"
t=$(grep -oE 'timings: .*' "$T17/out/7.2-sequence.log" | tail -n 1 || true)
if [ -n "$t" ]; then jw "FACT sequence $t"; else finding "the sequence logged no timings line"; fi
ep=$(grep -oE 'resume: epoch [0-9]+ \(was [0-9]+\)' "$T17/out/7.2-sequence.log" | tail -n 1 || true)
if [[ "$ep" =~ ^resume:\ epoch\ ([0-9]+)\ \(was\ ([0-9]+)\)$ ]]; then
  jw "FACT sequence epoch ${BASH_REMATCH[2]} -> ${BASH_REMATCH[1]}"
  [ "${BASH_REMATCH[1]}" = "$(( BASH_REMATCH[2] + 1 ))" ] || finding "resume epoch ${BASH_REMATCH[1]}, want one above ${BASH_REMATCH[2]}"
else finding "the sequence logged no resume epoch"; fi
dbread "select attempt_id, state, vm_ref, epoch, pause_generation, stop_proof_json from jobs where attempt_id='$SEQ_ATTEMPT'"
dbread "select action, reason from audit where attempt_id='$SEQ_ATTEMPT' order by id"
st=$(dbread "select state from jobs where attempt_id='$SEQ_ATTEMPT'"); [ "$st" = stopped ] || finding "sequence job state [$st], want stopped"
audit_has "$SEQ_ATTEMPT" launch_intent launch_started drain quiescent suspend_requested resume_prepared resume_committed stop_requested stop_proven
```

- Expected: PASS and the `timings:` line (launch call a few seconds; `to_running` up to about a
  minute, since states are read once per 60 s pass; suspend about 2 s and resume about 4 s, as
  attempt 4 measured directly; `stop_to_proof` about 2 to 3 minutes, R17). The resume epoch is one
  above the launch epoch. The job row is `stopped` with stop proof. Its audit rows include, in
  order, `launch_intent`, `launch_started`, `drain`, `quiescent`, `suspend_requested`,
  `resume_prepared`, `resume_committed`, `stop_requested` and `stop_proven` (the constants in
  `internal/hostedctl/launch.go:58-70`, `pause.go:35-49`, `resume.go:32-39` and `stop.go:44-52`).
- A FAIL, a missing line or row, or odd evidence is a FINDING; the controller is stopped and every
  VM settled either way.

### 7.3 Crash between the provider call and transaction 2: the launch step (long block, bound 15 min)

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ]; then echo "section 7 skipped"; exit 0; fi
. "$T17/driver.env"
rec CRASH_ATTEMPT "task17-crash-$(openssl rand -hex 4)"
rec CRASH_START "$(date -u +%FT%T)"
start_ctl "$T17/bin/controller-crash" crash EQUIPO_HOSTED_ENABLED=1 EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1
if ! (ctl_ready); then finding "the crash-build controller did not become ready; 7.3 and 7.4 skipped"; stop_ctl; rec SKIP_74 yes; exit 0; fi
ctl_log | grep -F 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=1: the process exits' || finding "the crash switch is not reported on"
export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=launch
if gotest "$T17/out/7.3-launch.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveCrashRecovery$' -count=1 -v -timeout 10m; then rc=0; else rc=$?; fi
[ "$rc" = 0 ] || finding "the launch step failed (rc $rc); see 7.3-launch.log"
_exited() { [ -s "$T17/controller.exit" ] && return 0; return 1; }
if ! (poll 60 2 "crash-build controller exit" _exited); then finding "the crash-build controller did not exit after the launch"; fi
stop_ctl
[ "$(cat "$T17/controller.exit" 2>/dev/null || true)" = 137 ] || finding "crash-build exit status $(cat "$T17/controller.exit" 2>/dev/null || echo unknown), want 137"
harvest_ctl
vm=$(grep -oE "provider launched $VMID_RE for $CRASH_ATTEMPT;" "$CTL_SLICE" | tail -n 1 | cut -d' ' -f3 || true)
if [ -z "$vm" ]; then finding "the crash log names no launched VM; 7.4 skipped"; rec SKIP_74 yes; settle_all; exit 0; fi
rec CRASH_VM "$vm"
vm_get "$CRASH_VM"; echo "crash VM $CRASH_VM: $VST"
case "$VST" in PENDING|RUNNING) ;; *) finding "crash VM state $VST";; esac
row=$(dbread "select state, ifnull(vm_ref, '-') from jobs where attempt_id='$CRASH_ATTEMPT'")
[ "$row" = "waiting	-" ] || finding "crash job row [$row], want waiting with no VM ref (the Ref must not be saved)"
audit_has "$CRASH_ATTEMPT" launch_intent
jw "CRASH controller exited after launching $CRASH_VM"
```

- Expected: the launch fails in transport (the test passes: `launch: the controller went away ...`);
  exit status 137; the log line `crash point: the provider launched <vm> for <attempt>; exiting
  before the Ref is saved`, with `<vm>` matching `VMID_RE`; the VM `PENDING` or `RUNNING`; the job
  row `waiting` with no VM ref, and a `launch_intent` audit row.
- The controller answering the launch, another exit status, or no launched VM is a FINDING; 7.4
  is then skipped if there is no VM to recover. Every VM is settled. A launch refused because no
  audit has passed recently is a FINDING, like any other failed launch step.

### 7.4 Restart without the crash switch; Replay claims the one VM (long block, bound 25 min)

The controller unit's `env -i` argument list is its whole environment (R45), and only 7.3's unit
gets `EQUIPO_HOSTED_CRASH_AFTER_LAUNCH`. The block reads the restarted unit's `ExecStart` and checks
that argument list has no crash switch (pre-flight concern 3); a read that fails or cannot be parsed
fails the block (`soft_fail`), never counts as "absent". The readiness check comes before the recovery driver; Replay runs on the
second reaper pass, about 60 s after start (pre-flight concern 2). The replay re-sends the stored
spec with the attempt ID as the client token (`internal/hostedctl/launch.go:233,310`,
`internal/isolatedjob/awsjob/runner.go:248`), so AWS answers with the crash VM: attempt 4 showed a
repeated request under a used token returns the same VM, even 7 minutes on and after the VM ended.

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_7:-}" ] || [ -n "${SKIP_74:-}" ]; then echo "7.4 skipped"; settle_all; exit 0; fi
. "$T17/driver.env"
need CRASH_ATTEMPT CRASH_VM CRASH_START
start_ctl "$T17/bin/controller" recover EQUIPO_HOSTED_ENABLED=1
if ! (ctl_ready); then finding "the restarted controller did not become ready; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi
_x=$(_sc show -p ExecStart --value -- "$(ctl_unit)") || soft_fail "cannot read the restarted controller unit's ExecStart"
_a=$(sed -n 's/.*argv\[\]=\(.*\) ; ignore_errors=.*/\1/p' <<<"$_x")
[[ "$_a" == "/usr/bin/env -i "* ]] || soft_fail "the restarted controller unit's ExecStart argv is unreadable or not an env -i list: [$_x]"
if grep -qF 'EQUIPO_HOSTED_CRASH_AFTER_LAUNCH=' <<<"$_a"; then finding "the crash switch is in the restarted controller's env -i argv; 7.4 skipped"; stop_ctl; settle_all; exit 0; fi
export EQUIPO_HOSTED_LIVE_ATTEMPT="$CRASH_ATTEMPT" EQUIPO_HOSTED_LIVE_CRASH_STEP=recover \
  EQUIPO_HOSTED_LIVE_OPERATOR_KEY_ID=task17-operator EQUIPO_HOSTED_LIVE_OPERATOR_KEY_FILE="$T17/keys/operator.key"
if gotest "$T17/out/7.4-recover.log" -tags hostedlive ./internal/hostedclient -run '^TestLiveCrashRecovery$' -count=1 -v -timeout 15m; then rc=0; else rc=$?; fi
grep -E 'recover:|listed vm|stop:' "$T17/out/7.4-recover.log" || true
stop_ctl
harvest_ctl
settle_all
[ "$rc" = 0 ] || finding "the recover step failed (rc $rc); see 7.4-recover.log"
grep -qF "recover: job $CRASH_ATTEMPT holds vm $CRASH_VM " "$T17/out/7.4-recover.log" || finding "the job does not hold $CRASH_VM"
if grep -F 'restart stop requested, elapsed time unknown' "$CTL_SLICE"; then finding "the restart stopped a job for unknown elapsed time"; fi
if grep -hE "microvm id is missing or malformed|microvm id is malformed|empty or malformed ref" "$T17/out/7.4-recover.log" "$CTL_SLICE"; then finding "a MicroVM ID was refused as malformed (R36)"; fi
scan >/dev/null
n=$(awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv" | wc -l)
awk -F'\t' -v t="$CRASH_START" '$3 >= t' "$T17/last_scan.tsv"
[ "$n" = 1 ] || finding "$n VMs of this image started since the crash launch, want 1"
dbread "select attempt_id, state, vm_ref, stop_proof_json from jobs where attempt_id='$CRASH_ATTEMPT'"
dbread "select action, reason from audit where attempt_id='$CRASH_ATTEMPT' order by id"
row=$(dbread "select state, vm_ref from jobs where attempt_id='$CRASH_ATTEMPT'")
[ "$row" = "stopped	$CRASH_VM" ] || finding "crash job row [$row], want stopped holding $CRASH_VM"
audit_has "$CRASH_ATTEMPT" launch_intent replay_started stop_requested stop_proven
```

- Expected: PASS; the job holds `$CRASH_VM`, the same ID the crashed controller launched; the
  operator list shows one VM for the attempt and no unowned live VM; stop with proof; no
  `restart stop requested, elapsed time unknown` line; exactly one VM of this image started since
  7.3 began; the job row `stopped` holding `$CRASH_VM`; audit rows `launch_intent`,
  `replay_started` (`launch.go:602-604`: a replay that gains a VM writes `replay_started`, not
  `launch_started`), `stop_requested` and `stop_proven`.
- Each failed check is a FINDING; the controller is stopped and every VM settled.

---

## 8. Orphan

### 8.1 Start the controller (launches off: reaping works regardless) and plant a VM

R22 defers orphans while a dispatched launch intent is still waiting, so the block first reads
`equipo_hosted_jobs{state="waiting"} 0` (`internal/hostedctl/metrics.go:104-115`). After section 7
both jobs are `stopped`.

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ "${AUDIT_OK:-}" != yes ]; then finding "section 8 skipped: the 5.6 audit did not pass"; rec SKIP_8 yes; exit 0; fi
scan >/dev/null; [ -z "$LIVE" ] || die "live VMs of this image: $LIVE"
start_ctl "$T17/bin/controller" orphan
if ! (ctl_ready); then finding "the controller did not become ready; section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0; fi
if ! mread || ! grep -qx 'equipo_hosted_jobs{state="waiting"} 0' <<<"$MTXT"; then
  finding "no proof that no launch intent is waiting (R22 could defer the orphan); section 8 skipped"; stop_ctl; rec SKIP_8 yes; exit 0
fi
printf 'orphan' > "$T17/out/payload-orphan"
rec ORPHAN_TOKEN "$NAME-orphan"
rec ORPHAN_PLANTED "$(date -u +%FT%TZ)"
launch orphan "$ORPHAN_TOKEN" 1800 "$T17/out/payload-orphan"
if [ "$L_OUTCOME" != created ]; then finding "the orphan launch was $L_OUTCOME (${L_CODE:-rc$L_RC} ${L_MSG}); section 8 skipped"; stop_ctl; settle_all; rec SKIP_8 yes; exit 0; fi
rec ORPHAN_VM "$L_ID"
[[ "$ORPHAN_VM" =~ ^$VMID_RE$ ]] || finding "orphan VM ID [$ORPHAN_VM] is outside the known form"
eni_snapshot soft "8.1, orphan planted"
```

- Expected: a VM ID of the form `VMID_RE`; no job or intent names its token; its 1800 s maximum
  duration is AWS's backstop.

### 8.2 Watch the reaper stop it (long block, bound 25 min)

Expected timeline from the plant time P: the reaper lists every 60 s (`ReapInterval`,
`internal/hostedctl/reaper.go:16`), so it first sees the VM by about P+1:30; it stops an orphan on
the first pass at least 10 minutes (`OrphanGrace`, `reaper.go:22`) after the first sighting, after
rechecking ownership; so the stop lands between about P+11:00 and P+12:30, and the VM ends within a
minute or two after that. The stop raises one `orphan_stopped` alert, published to the run's SNS
topic: the first SNS publish of the whole task.

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if [ -n "${SKIP_8:-}" ]; then echo "section 8 skipped"; exit 0; fi
need ORPHAN_VM ORPHAN_PLANTED
P=$(date -d "$ORPHAN_PLANTED" +%s)
while :; do
  now=$(date +%s)
  if [ $(( now - P )) -ge 900 ]; then stop_ctl; vm_end "$ORPHAN_VM"; die "the orphan was not stopped by P+15:00 (last state ${VST:-none}): a VM alive outside its step"; fi
  ctl_alive || { finding "the controller stopped while watching the orphan"; vm_end "$ORPHAN_VM"; settle_all; exit 0; }
  vm_get "$ORPHAN_VM"
  echo "P+$(( (now - P) / 60 )):$(printf %02d $(( (now - P) % 60 ))) $VST"
  case "$VST" in
    TERMINATING|TERMINATED|NOTFOUND) break;;
    PENDING|RUNNING) ;;
    *) finding "orphan read: $VST";;
  esac
  sleep 20
done
[ $(( now - P )) -ge 600 ] || finding "the orphan was stopped before the 10-minute grace (P+$(( now - P ))s)"
jw "ORPHAN stopped by the reaper at P+$(( now - P ))s"
for i in 1 2 3 4 5 6; do mread || break; grep -q '^equipo_hosted_alerts_total{kind="orphan_stopped"' <<<"$MTXT" && break; sleep 10; done
if [ -n "${MTXT:-}" ]; then
  grep -E 'orphan' <<<"$MTXT" || true
  grep -qx 'equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1' <<<"$MTXT" || finding "no orphan_stopped alert counted as sent"
  if grep -q '^equipo_hosted_alerts_total{kind="orphan_stopped",result="failed"}' <<<"$MTXT"; then finding "the orphan_stopped alert failed to publish to SNS"; fi
fi
stop_ctl
harvest_ctl
grep -F 'hosted controller: orphan VM stopped' "$CTL_SLICE" | grep -F "vm_ref=$ORPHAN_VM" || finding "no orphan-stopped log line for $ORPHAN_VM"
if grep -F 'hosted controller: orphan VM left running for a dispatched launch intent' "$CTL_SLICE" | grep -qF "vm_ref=$ORPHAN_VM"; then finding "the orphan was deferred (R22)"; fi
vm_end "$ORPHAN_VM"
settle_all
dbread "select action, reason from audit where action like 'orphan%' order by id"
n=$(dbread "select count(*) from audit where action='orphan_seen' and reason like 'VM $ORPHAN_VM %'"); [ "$n" = 1 ] || finding "$n orphan_seen audit rows for $ORPHAN_VM, want 1"
n=$(dbread "select count(*) from audit where action='orphan_stopped' and reason like 'VM $ORPHAN_VM %'"); [ "$n" = 1 ] || finding "$n orphan_stopped audit rows for $ORPHAN_VM, want 1"
```

- Expected: `RUNNING` until about P+11:00 to P+12:30; then
  `equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1`; the operator log record
  `msg="hosted controller: orphan VM stopped" vm_ref=<orphan>` (slog text,
  `internal/hostedctl/logs.go:18`) and no deferral record (`logs.go:29`); one `orphan_seen`
  (`reaper.go:559-560`) and one `orphan_stopped` audit row for it, each reason starting
  `VM <orphan> `; the VM ends.
- Hard stop: no stop seen by P+15:00, whatever the reads returned (the deadline is checked first on
  every iteration); the block stops the controller and ends the VM first. A stop before P+10:00,
  a failed SNS publish and any missing evidence are FINDINGs.

**Task 17b record** (one line each in the progress file, section 11.3 lists them): the
`ChangedSpecConflicts` result; the sequence's `timings:` line and its epochs; the crash VM, the
crash exit status and the recover result; the orphan's plant time, its stop time relative to P,
and the alert result.

---

## 10. Teardown and verification

Runs after section 8, or on Paul's word after a safe stop. Dependency order. Each deletion is confirmed by
a direct read before the next dependency is touched, and recorded with `deleted`.

### 10.1 No controller, no VM, then the image (all its versions)

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
stop_ctl
if have IMAGE_ARN; then
settle_all
lvr image delete -id "$IMAGE_ARN"
[ "$RC" = 0 ] || die "image delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR} (a ConflictException is a stop: U8)"
_img() { lvr image list -name "$IMAGE_NAME"; [ "$RC" = 0 ] || return 1
  list_items || die "malformed image list reply while proving the image deleted"
  OUT=$(jq -r --arg a "$IMAGE_ARN" '[.[] | select(.ImageArn == $a) | .State] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
  echo "$(date -u +%T) listed state: [${OUT}]"; case "$OUT" in ""|DELETED) return 0;; DELETING) return 1;; esac; return 2; }
poll 900 15 "image deleted" _img
deleted microvm-image "$IMAGE_ARN"
for vv in VER_SMALL_FAILED VER_SMALL; do
  [ -n "${!vv:-}" ] || continue; v=${!vv}
  lvr image get-version -id "$IMAGE_ARN" -version "$v"
  if { [ "$RC" = 0 ] && [ "$(jq -r .State <<<"$OUT")" = DELETED ]; } || { [ "$RC" != 0 ] && [ "$ECODE" = ResourceNotFoundException ]; }; then
    deleted microvm-image-version "$IMAGE_ARN:$v"
  else finding "version $v after the image delete: rc $RC ${ECODE:-} $(jq -r '.State // empty' <<<"$OUT" 2>/dev/null || true)"; fi
done
fi
```

### 10.2 Connector, then its network interfaces

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if have CONN_ARN; then
need VPC SUBNET OPERATOR_ROLE
eni_snapshot strict "10.2, before the connector delete"
B_END=$(( $(date +%s) + 7200 ))
# budget N: N seconds, or what is left of 10.2's shared 120-minute budget if that is less.
budget() { local r=$(( B_END - $(date +%s) )); [ "$r" -gt 0 ] || die "10.2's shared 120-minute budget is spent: hard stop"; echo $(( r < $1 ? r : $1 )); }
conn_delete() { lvr connector delete -id "$CONN_ARN"
  [ "$RC" = 0 ] || [ "$ECODE" = ResourceNotFoundException ] || die "connector delete: ${ECODE:-rc$RC} ${LV_MSG:-$ERR}"; }
conn_gone() { local b; b=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; lv_wait "$b" connector wait-gone -id "$CONN_ARN" -interval 15s; CG_RC=$RC; CG_CODE=$ECODE
  echo "wait-gone: rc $CG_RC ${CG_CODE:-} $(jq -c '{State,StateReason}' <<<"$OUT" 2>/dev/null || true)"; }
# enis_gone SECONDS: 0 when no interface is left in the VPC within SECONDS; 1 when some are left at the bound.
enis_gone() { local end=$(( $(date +%s) + $1 ))
  while :; do
    try aws ec2 describe-network-interfaces --filters Name=vpc-id,Values="$VPC" --query 'length(NetworkInterfaces)' --output json
    [ "$RC" = 0 ] || die "interface count unreadable: ${ECODE:-rc$RC}"
    echo "$(date -u +%T) interfaces in VPC: $OUT"; [ "$OUT" = 0 ] && return 0
    [ "$(date +%s)" -lt "$end" ] || return 1
    sleep 30
  done; }
conn_delete; conn_gone; ok=no
if [ "$CG_RC" = 0 ]; then deleted connector "$CONN_ARN"; eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" && ok=yes
elif [ "$CG_RC" = 6 ] && [ "$CG_CODE" = DELETE_FAILED ]; then :
else die "connector wait-gone: rc $CG_RC ${CG_CODE:-}"; fi
if [ "$ok" = no ]; then
  finding "connector teardown needs the pre-approved fallback (wait-gone rc $CG_RC ${CG_CODE:-}, or interfaces left after 40 min)"
  have OPERATOR_ROLE_ARN || die "no operator role to change"
  A=arn:aws:ec2:eu-west-1:640012953448
  cat > "$T17/iam/operator-delete-subnet.json" <<TEOF
{"Version":"2012-10-17","Statement":[
 {"Sid":"DeleteEniInThisSubnet","Effect":"Allow","Action":"ec2:DeleteNetworkInterface","Resource":"$A:network-interface/*",
  "Condition":{"ArnEquals":{"ec2:Subnet":"$A:subnet/$SUBNET"}}}]}
TEOF
  jq -e . "$T17/iam/operator-delete-subnet.json" >/dev/null
  aws iam put-role-policy --role-name "$OPERATOR_ROLE" --policy-name t17-connector-eni-delete --policy-document "file://$T17/iam/operator-delete-subnet.json"
  rec OPERATOR_DELETE_FALLBACK "subnet condition only (Paul, 2026-11-28)"
  echo "waiting 120 s for IAM propagation, then one more connector delete"; sleep 120
  conn_delete; conn_gone
  [ "$CG_RC" = 0 ] || die "the connector delete failed again after the fallback (rc $CG_RC ${CG_CODE:-}): hard stop"
  grep -q $'\tDELETED connector '"$CONN_ARN"'$' "$JOURNAL" || deleted connector "$CONN_ARN"
  eb=$(budget 2400) || die "10.2's shared budget is spent: hard stop"; enis_gone "$eb" || die "interfaces are still in the VPC after the fallback: hard stop"
fi
for e in $(awk -F'\t' '$2 ~ /^SERVICE-ENI / {split($2, a, " "); print a[2]}' "$JOURNAL"); do
  gone0 "interface $e" aws ec2 describe-network-interfaces --filters Name=network-interface-id,Values="$e" --query 'length(NetworkInterfaces)' --output json
  deleted service-eni "$e"
done
fi
```

- Pre-approved fallback (Paul, 2026-11-28): on `DELETE_FAILED`, or interfaces left after 40
  minutes, the inline delete policy loses its `ec2:ManagedResourceOperator` condition (the subnet
  condition stays), and after 120 s the connector delete is retried once. A second failure, or
  interfaces still left, is a hard stop. Lambda's interfaces are never deleted by hand.
- One shared budget of 120 minutes covers the attempt and its fallback: each wait takes at most its
  own 40-minute bound and never more than what is left of the 120 minutes; when it is spent, that is
  a hard stop. The detached-block limit for 10.2 alone is 130 minutes, so the wrapper never cuts the
  pre-approved fallback short.

### 10.3 Network

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
if have SG; then
  get _v aws ec2 delete-security-group --group-id "$SG" --query Return --output text; [ "$_v" = True ] || die "delete group"
  gone0 "group $SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$SG" --query 'length(SecurityGroups)' --output json; deleted security-group "$SG"
fi
if have RTB_ASSOC; then aws ec2 disassociate-route-table --association-id "$RTB_ASSOC"; deleted route-table-association "$RTB_ASSOC"; fi
if have RTB; then
  aws ec2 delete-route-table --route-table-id "$RTB"
  gone0 "route table $RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$RTB" --query 'length(RouteTables)' --output json; deleted route-table "$RTB"
fi
if have SUBNET; then
  aws ec2 delete-subnet --subnet-id "$SUBNET"
  gone0 "subnet $SUBNET" aws ec2 describe-subnets --filters Name=subnet-id,Values="$SUBNET" --query 'length(Subnets)' --output json; deleted subnet "$SUBNET"
fi
if have VPC; then
  aws ec2 delete-vpc --vpc-id "$VPC"
  gone0 "VPC $VPC" aws ec2 describe-vpcs --filters Name=vpc-id,Values="$VPC" --query 'length(Vpcs)' --output json; deleted vpc "$VPC"
  if have DEF_SG_RULES; then gone0 "default group rules $DEF_SG_RULES" aws ec2 describe-security-group-rules --filters Name=security-group-rule-id,Values="$(tr '\t ' ',,' <<<"$DEF_SG_RULES")" --query 'length(SecurityGroupRules)' --output json; deleted vpc-default-security-group-rules "$DEF_SG_RULES"; fi
  if have DEF_SG; then gone0 "default group $DEF_SG" aws ec2 describe-security-groups --filters Name=group-id,Values="$DEF_SG" --query 'length(SecurityGroups)' --output json; deleted vpc-default-security-group "$DEF_SG"; fi
  if have MAIN_RTB; then gone0 "main route table $MAIN_RTB" aws ec2 describe-route-tables --filters Name=route-table-id,Values="$MAIN_RTB" --query 'length(RouteTables)' --output json; deleted vpc-main-route-table "$MAIN_RTB"; fi
  if have DEF_ACL; then gone0 "default network ACL $DEF_ACL" aws ec2 describe-network-acls --filters Name=network-acl-id,Values="$DEF_ACL" --query 'length(NetworkAcls)' --output json; deleted vpc-default-network-acl "$DEF_ACL"; fi
fi
```

- Abort if: a `DependencyViolation`, a failed read, or a filtered `describe` that still lists the
  resource.

### 10.4 IAM roles

The operator role holds the managed attachment and the inline delete policy (2.1; 10.2's fallback
rewrites the same policy name). The old narrow policy name is still tried, so a role left by an
earlier revision is cleaned too. Each is removed if present; `NoSuchEntity` means it was never
added.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need OPERATOR_ROLE BUILD_ROLE
if have OPERATOR_ROLE_ARN; then
  for pn in t17-connector-eni t17-connector-eni-delete; do
    try aws iam delete-role-policy --role-name "$OPERATOR_ROLE" --policy-name "$pn"; [ "$RC" = 0 ] || expect_err NoSuchEntity
  done
  try aws iam detach-role-policy --role-name "$OPERATOR_ROLE" --policy-arn arn:aws:iam::aws:policy/AWSLambdaNetworkConnectorOperatorPolicy; [ "$RC" = 0 ] || expect_err NoSuchEntity
  aws iam delete-role --role-name "$OPERATOR_ROLE"
  try aws iam get-role --role-name "$OPERATOR_ROLE"; expect_err NoSuchEntity; deleted iam-role "$OPERATOR_ROLE_ARN"
  if [ -n "${OPERATOR_INLINE_POLICY:-}" ]; then deleted iam-inline-policy "$OPERATOR_INLINE_POLICY"; fi
  if [ -n "${OPERATOR_MANAGED_POLICY:-}" ]; then deleted iam-managed-attachment "$OPERATOR_MANAGED_POLICY"; fi
fi
if have BUILD_ROLE_ARN; then
  try aws iam delete-role-policy --role-name "$BUILD_ROLE" --policy-name t17-build; [ "$RC" = 0 ] || expect_err NoSuchEntity
  aws iam delete-role --role-name "$BUILD_ROLE"
  try aws iam get-role --role-name "$BUILD_ROLE"; expect_err NoSuchEntity; deleted iam-role "$BUILD_ROLE_ARN"
fi
```

### 10.5 S3

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need BUCKET
if have BUCKET_CREATED; then
if have ARTIFACT; then
aws s3api delete-object --bucket "$BUCKET" --key t17/app.zip
gone0 "object t17/app.zip" aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json; deleted s3-object "s3://$BUCKET/t17/app.zip"
fi
get _v aws s3api list-object-versions --bucket "$BUCKET" --output json
[ "$(jq '((.Versions // []) + (.DeleteMarkers // [])) | length' <<<"$_v")" = 0 ] || die "objects left in the bucket"
aws s3api delete-bucket --bucket "$BUCKET"
_bucket() { try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; }
poll 300 10 "bucket gone from the list" _bucket; deleted s3-bucket "$BUCKET"
fi
```

### 10.6 Log group

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need LOG_GROUP
if have LOG_GROUP_CREATED; then
get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
[ "$got" = "$LOG_GROUP" ] || die "log groups under the prefix: [$got]; any group the run did not create goes to Paul"
aws logs delete-log-group --log-group-name "$LOG_GROUP"
get got aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
[ -z "$got" ] || die "log group still listed: [$got]"
deleted log-group "$LOG_GROUP"
fi
```

### 10.7 SNS topic

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
if have TOPIC_ARN; then
aws sns delete-topic --topic-arn "$TOPIC_ARN"
_topic() { try aws sns list-topics --query "length(Topics[?TopicArn=='$TOPIC_ARN'])" --output json; [ "$RC" = 0 ] || return 3; echo "$(date -u +%T) listed: $OUT"; [ "$OUT" = 0 ] && return 0; return 1; }
poll 300 10 "topic gone from the list" _topic; deleted sns-topic "$TOPIC_ARN"
fi
```

### 10.8 Verify: every record classified, then the tag index as a cross-check

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need RUN
echo "== confirmed creations without a confirmed deletion:"
awk -F'\t' '
  $2 ~ /^DELETED / {split($2, a, " "); d[substr($2, length("DELETED " a[2] " ") + 1)] = 1}
  $2 ~ /^CONFIRMED / {split($2, a, " "); c[substr($2, length("CONFIRMED " a[2] " ") + 1)] = a[2]}
  END {for (k in c) if (!(k in d)) print c[k], k}' "$JOURNAL" | sort
echo "== VMs: recorded, and how each ended:"
vm_ids
for id in $VIDS; do grep -q "VMGONE $id " "$JOURNAL" || die "VM $id has no confirmed end"; done
echo "$(wc -w <<<"$VIDS") VMs recorded, every one confirmed ended"
echo "== intents without a confirmation:"
awk -F'\t' '$2 ~ /^INTENT /' "$JOURNAL"
echo "== tag index (lags; direct reads above decide):"
for k in run purpose; do v=$([ "$k" = run ] && echo "$RUN" || echo "$TAGV")
  aws resourcegroupstaggingapi get-resources --tag-filters Key=$k,Values=$v --query 'ResourceTagMappingList[].ResourceARN' --output text | tr '\t' '\n'; done
```

- Expected: the first list holds only values that are not resources (the run's settings: `DIGEST`,
  `VER_*`, `CONN_VERSION`, `CONN_QARN`, `BASE_*`, tokens, times, results); every resource ID has a
  `DELETED` line. Every recorded VM has a confirmed end. Each intent has its confirmation (or, for
  `vm` intents, a VM ID or a recorded refusal). The tag index lists nothing with `run=<RUN>`, or
  only ARNs already confirmed deleted above ("index lag"); with `purpose`, only what 0.4 already
  observed. An ARN that is neither goes to Paul untouched.

### 10.9 Evidence into the progress file, then remove scratch

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
! ctl_alive || die "the controller is running"; listeners; [ -z "$LST" ] || die "listeners open: $LST"
_u=$(run_units) || die "systemctl cannot list the run's units"
for _x in $_u; do [ "$(unit_state "$_x")" = done ] || die "unit $_x is not done; run S.0"; done
no_unresolved
cut -f2- "$JOURNAL" | grep -vE '^(INTENT|CONTROLLER) ' > "$T17/journal-for-progress.txt"
wc -l "$T17/journal-for-progress.txt" "$VMS"
echo "== every FINDING (the report lists each one):"
awk -F'\t' '$2 ~ /^FINDING / {print $1, substr($2, 9)}' "$JOURNAL" | tee "$T17/findings.txt"
```

Paste `journal-for-progress.txt`, `vms.tsv`, the Task 17b record lines (section 11.3) and section
11.2's estimate into
`HOSTED-SLICE1-PROGRESS.md` (they hold IDs, times and results only, no keys), then:

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; no_unresolved; need RUN RUN_RESERVATION
[ "$RUN_RESERVATION" = "$HOME/.cache/t17b-runs/$RUN" ] || die "unexpected reservation path [$RUN_RESERVATION]"
rmdir -- "$RUN_RESERVATION"; rmdir -- "$HOME/.cache/t17b-runs" 2>/dev/null || true
rm -rf "$TMPDIR/equipo-t17b" "$TMPDIR/equipo-t17b-pre"; [ ! -e "$TMPDIR/equipo-t17b" ] && echo "reservation and scratch removed"
```

---

## S. Safe stop

Run in this order after any abort: S.0, S.1, S.2, S.3, S.4. Each part is safe to run whatever
phase the run reached.

**S.0 Emergency stop of the run's units (local only, no AWS call; always first).**
`env.sh` refuses to load while a block unit is unfinished, so after an abort the safe stop cannot
start from it. S.0 runs before `env.sh`, using only `run.env`, `unitctl.sh` and the journal (no AWS
call). It acts only on unit names this run journalled (`UNIT` lines, written before each
`systemd-run`; R45), in this order: first the block units (and the probe), stopped and proved done;
then, from a fresh read of the journal (a block may have started a controller meanwhile), the
controller units, stopped and proved done; then a final inventory of every journalled unit plus a
cross-check of `systemctl --user list-units --all 't17b-<RUN>-*'`. A stop is `systemctl --user stop`
(TERM, then KILL after 45 s, reaped by systemd); done means inactive or gone with an empty cgroup.
A unit that matches the glob but was not journalled is reported for Paul and never stopped. Each
outcome is an `EMERGENCY` journal line. S.0 marks a stopped block `emergency-stopped`, so `env.sh`
loads again, and only then may S.1 to S.3 run. If it cannot read the journal, prove a unit done, list
the units, or finds an unjournalled match, it prints `HARD STOP` with the unit names: stop there and
report them to Paul. Nothing is signalled by PID.

```sh
set -euo pipefail
T17='<T17 printed by 0.2>'
[ -f "$T17/run.env" ] && [ -f "$T17/unitctl.sh" ] && [ -f "$T17/journal.tsv" ] || { echo "HARD STOP: $T17/run.env, unitctl.sh or journal.tsv is missing; nothing was stopped. Tell Paul."; exit 1; }
. "$T17/run.env"; . "$T17/unitctl.sh"
ej() { printf '%s\t%s\n' "$(date -u +%FT%T.%3NZ)" "EMERGENCY $*" >> "$T17/journal.tsv" || echo "WARNING: journal write failed"; echo "$*"; }
bad=""
# stop_set KIND UNIT...: stop and prove done each journalled unit that is not already done.
stop_set() { local kind=$1 u s; shift
  for u; do
    s=$(unit_state "$u"); [ "$s" != done ] || continue
    ej "$kind unit $u is $s: stopping it"
    if unit_stop "$u"; then ej "$kind unit $u: inactive or gone, with an empty cgroup"
    else s=$(unit_state "$u"); ej "$kind unit $u could not be proved stopped: $s"; bad="$bad $u($s)"; fi
  done; }
rec=$(journal_units) || { echo "HARD STOP: the journal's unit records cannot be read; nothing was stopped. Tell Paul."; exit 1; }
# 1. Block units (and the probe): every journalled unit that is not a controller unit.
stop_set block $(grep -v -- "^${UNIT_PREFIX}ctl-" <<<"$rec" || true)
# 2. Controller units, from a fresh read of the journal.
rec=$(journal_units) || { echo "HARD STOP: the journal's unit records cannot be read after the block stops. Tell Paul."; exit 1; }
stop_set controller $(grep -- "^${UNIT_PREFIX}ctl-" <<<"$rec" || true)
for f in "$T17"/blocks/*.unit; do
  [ -e "$f" ] || continue; b=$(basename "${f%.unit}")
  st=$(cat "$T17/blocks/$b.status" 2>/dev/null || true)
  if { [ -z "$st" ] || [ "$st" = unresolved ]; } && [ "$(unit_state "$(cat "$f")")" = done ]; then
    printf 'emergency-stopped\n' > "$T17/blocks/$b.status"; ej "block $b: marked emergency-stopped"
  fi
done
# 3. Final inventory: every journalled unit done; the glob is a cross-check only.
if rec=$(journal_units); then
  for u in $rec; do s=$(unit_state "$u"); [ "$s" = done ] || { ej "inventory: $u is $s"; bad="$bad $u($s)"; }; done
else ej "inventory: the journal's unit records cannot be read"; bad="$bad journal-unreadable"; rec=""; fi
if listed=$(run_units); then
  for u in $listed; do
    grep -qxF -- "$u" <<<"$rec" && continue
    ej "inventory: $u matches ${UNIT_PREFIX}* but this run never journalled it: not stopped, for Paul"; bad="$bad $u(not-journalled)"
  done
else ej "inventory: systemctl cannot list ${UNIT_PREFIX}*"; bad="$bad unit-listing-failed"; fi
if [ -n "$bad" ]; then echo "HARD STOP:$bad. Report these unit names to Paul; do not run S.1 to S.3."; exit 1; fi
ej "S.0 done: every journalled unit of this run is inactive or gone with an empty cgroup, and no other unit matches ${UNIT_PREFIX}*"
echo "S.0 done; run S.1 to S.3"
```

**S.1 Controller.**

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"
stop_ctl
```

If `stop_ctl` aborts because the controller's unit cannot be proved done, or a port stays open
after it is, stop here and ask Paul. Nothing is signalled by PID.

**S.2 Reconcile uncertain creations (R39).** For each creation whose `INTENT` has no `CONFIRMED`
record, one direct, guarded read decides. A resource created with a run-unique name (the run ID,
proved absent by 0.4) and found by that exact name is ours: it is recorded, tagged if a separate
tagging call never ran, and torn down. The unnamed EC2 resources carried their tags in the create
call (`TagSpecifications`) and are found by a direct `describe` filtered on the `run` tag and their
`Name` tag, never through the tag index. Each read has exactly three outcomes: success (record),
an empty list or an approved not-found code (`NOTCREATED`), or anything else (`UNRESOLVED`: that resource's
reconciliation stops and it goes to Paul with its cost in S.4). The MicroVM intents are reconciled
by S.3.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"; guard
need RUN NAME SG_NAME OPERATOR_ROLE BUILD_ROLE CONN_NAME IMAGE_NAME BUCKET LOG_GROUP TOPIC_NAME TAGS_EC2
UNRES=""
unresolved() { jw "UNRESOLVED $*"; UNRES="$UNRES|$*"; echo "UNRESOLVED: $*"; }
absent() { jw "NOTCREATED $*"; echo "not created: $*"; }
pending() { awk -F'\t' -v k="INTENT $1 $2" 'index($2, k) == 1 {f = 1} END {exit !f}' "$JOURNAL" && [ -z "${!3:-}" ]; }
# one_ec2 KIND VAR CMD...: a describe that must list 0 or 1 IDs.
one_ec2() { local kind=$1 var=$2; shift 2; try "$@"
  if [ "$RC" != 0 ]; then unresolved "$kind lookup failed: ${ECODE:-rc$RC}"; return; fi
  case "$(wc -w <<<"$OUT")" in 0) absent "$kind";; 1) rec "$var" "$OUT";; *) unresolved "$kind: several match: $OUT";; esac; }
# one_def KIND VAR CMD...: a VPC default resource; it exists whenever the VPC does, so only exactly one is an answer.
one_def() { local kind=$1 var=$2; shift 2; try "$@"
  if [ "$RC" = 0 ] && [ "$(wc -w <<<"$OUT")" = 1 ]; then rec "$var" "$OUT"; else unresolved "$kind: rc $RC ${ECODE:-} [$OUT]"; fi; }

if pending vpc "tag:run=$RUN" VPC; then one_ec2 vpc VPC aws ec2 describe-vpcs --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME" --query 'Vpcs[].VpcId' --output text; fi
if [ -n "${VPC:-}" ] && [ -z "${DEF_SG_RULES:-}" ]; then
  [ -n "${DEF_SG:-}" ] || one_def vpc-default-security-group DEF_SG aws ec2 describe-security-groups --filters Name=vpc-id,Values="$VPC" Name=group-name,Values=default --query 'SecurityGroups[].GroupId' --output text
  [ -n "${MAIN_RTB:-}" ] || one_def vpc-main-route-table MAIN_RTB aws ec2 describe-route-tables --filters Name=vpc-id,Values="$VPC" Name=association.main,Values=true --query 'RouteTables[].RouteTableId' --output text
  [ -n "${DEF_ACL:-}" ] || one_def vpc-default-network-acl DEF_ACL aws ec2 describe-network-acls --filters Name=vpc-id,Values="$VPC" Name=default,Values=true --query 'NetworkAcls[].NetworkAclId' --output text
  if [ -n "${DEF_SG:-}" ] && [ -n "${MAIN_RTB:-}" ] && [ -n "${DEF_ACL:-}" ]; then
    try aws ec2 describe-security-group-rules --filters Name=group-id,Values="$DEF_SG" --query 'SecurityGroupRules[].SecurityGroupRuleId' --output text
    if [ "$RC" = 0 ] && [ -n "$OUT" ]; then rec DEF_SG_RULES "$OUT"
      try aws ec2 create-tags --resources "$DEF_SG" "$MAIN_RTB" "$DEF_ACL" $DEF_SG_RULES --tags $TAGS_EC2
      [ "$RC" = 0 ] || unresolved "vpc defaults: tagging failed: ${ECODE:-rc$RC}"
    else unresolved "vpc default security group rules: ${ECODE:-rc$RC}"; fi
  fi
fi
if pending subnet "tag:run=$RUN" SUBNET; then one_ec2 subnet SUBNET aws ec2 describe-subnets --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'Subnets[].SubnetId' --output text; fi
if pending route-table "tag:run=$RUN" RTB; then one_ec2 route-table RTB aws ec2 describe-route-tables --filters Name=tag:run,Values="$RUN" Name=tag:Name,Values="$NAME-vm" --query 'RouteTables[].RouteTableId' --output text; fi
if pending route-table-association "" RTB_ASSOC && [ -n "${RTB:-}" ] && [ -n "${SUBNET:-}" ]; then
  one_ec2 route-table-association RTB_ASSOC aws ec2 describe-route-tables --route-table-ids "$RTB" --query "RouteTables[0].Associations[?SubnetId=='$SUBNET'].RouteTableAssociationId" --output text; fi
if pending security-group "$SG_NAME" SG; then one_ec2 security-group SG aws ec2 describe-security-groups --filters Name=tag:run,Values="$RUN" Name=group-name,Values="$SG_NAME" --query 'SecurityGroups[].GroupId' --output text; fi
for pair in "$OPERATOR_ROLE:OPERATOR_ROLE_ARN" "$BUILD_ROLE:BUILD_ROLE_ARN"; do
  r=${pair%%:*}; v=${pair#*:}
  pending iam-role "$r" "$v" || continue
  try aws iam get-role --role-name "$r" --output json
  if [ "$RC" = 0 ]; then arn=$(jq -r .Role.Arn <<<"$OUT"); arn_ok "$arn"; rec "$v" "$arn"
    if ! jq -e --arg r "$RUN" 'any(.Role.Tags[]?; .Key == "run" and .Value == $r)' <<<"$OUT" >/dev/null; then
      try aws iam tag-role --role-name "$r" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "iam-role $r: tagging failed: ${ECODE:-rc$RC}"; fi
  elif code_in NoSuchEntity; then absent "iam-role $r"
  else unresolved "iam-role $r: ${ECODE:-rc$RC}"; fi
done
if pending connector "$CONN_NAME" CONN_ARN; then
  lvr connector get -id "$CONN_NAME"
  if [ "$RC" = 0 ] && [ "$(jq -r .Name <<<"$OUT")" = "$CONN_NAME" ]; then arn=$(jq -r .Arn <<<"$OUT"); arn_ok "$arn"; rec CONN_ARN "$arn"; rec CONN_ID "$(jq -r .Id <<<"$OUT")"
  elif code_in ResourceNotFoundException; then absent "connector $CONN_NAME"
  else unresolved "connector $CONN_NAME: ${ECODE:-rc$RC}"; fi
fi
if pending s3-bucket "$BUCKET" BUCKET_CREATED; then
  try aws s3api list-buckets --prefix "$BUCKET" --query "length(Buckets[?Name=='$BUCKET'])" --output json
  if [ "$RC" != 0 ]; then unresolved "s3-bucket $BUCKET: list failed: ${ECODE:-rc$RC}"
  elif [ "$OUT" = 1 ]; then rec BUCKET_CREATED "$BUCKET"
    try aws s3api get-bucket-tagging --bucket "$BUCKET" --query "TagSet[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" = "$RUN" ]; then :
    elif [ "$RC" = 0 ] || code_in NoSuchTagSet; then
      try aws s3api put-public-access-block --bucket "$BUCKET" --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
      [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: public access block failed: ${ECODE:-rc$RC}"
      try aws s3api put-bucket-tagging --bucket "$BUCKET" --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
      [ "$RC" = 0 ] || unresolved "s3-bucket $BUCKET: tagging failed: ${ECODE:-rc$RC}"
    else unresolved "s3-bucket $BUCKET: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$OUT" = 0 ]; then absent "s3-bucket $BUCKET"
  else unresolved "s3-bucket $BUCKET: listed $OUT times"; fi
fi
if pending log-group "$LOG_GROUP" LOG_GROUP_CREATED; then
  try aws logs describe-log-groups --log-group-name-prefix "$LOG_GROUP" --query 'logGroups[].logGroupName' --output text
  if [ "$RC" != 0 ]; then unresolved "log-group: ${ECODE:-rc$RC}"
  elif [ "$OUT" = "$LOG_GROUP" ]; then rec LOG_GROUP_CREATED "$LOG_GROUP"
  elif [ -z "$OUT" ]; then absent "log-group $LOG_GROUP"
  else unresolved "log-group: unexpected groups [$OUT]"; fi
fi
if pending s3-object "s3://$BUCKET/t17/app.zip" ARTIFACT; then
  need ARTIFACT_B64
  if [ -z "${BUCKET_CREATED:-}" ]; then absent "s3-object (no bucket)"; OBJ=absent; RC=0; OUT=""
  else try aws s3api list-objects-v2 --bucket "$BUCKET" --prefix t17/app.zip --query 'length((Contents || `[]`)[?Key==`t17/app.zip`])' --output json
  if [ "$RC" != 0 ]; then unresolved "s3-object: list failed: ${ECODE:-rc$RC}"; OBJ=unknown
  elif [ "$OUT" = 0 ]; then absent "s3-object"; OBJ=absent
  else OBJ=listed; try aws s3api head-object --bucket "$BUCKET" --key t17/app.zip --checksum-mode ENABLED --query ChecksumSHA256 --output text; fi
  fi
  if [ "$OBJ" != listed ]; then :
  elif [ "$RC" = 0 ] && [ "$OUT" = "$ARTIFACT_B64" ]; then rec ARTIFACT "s3://$BUCKET/t17/app.zip"
    try aws s3api get-object-tagging --bucket "$BUCKET" --key t17/app.zip --query "TagSet[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
      try aws s3api put-object-tagging --bucket "$BUCKET" --key t17/app.zip --tagging "TagSet=[{Key=purpose,Value=$TAGV},{Key=run,Value=$RUN}]"
      [ "$RC" = 0 ] || unresolved "s3-object: tagging failed: ${ECODE:-rc$RC}"
    elif [ "$RC" != 0 ]; then unresolved "s3-object: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$RC" = 0 ]; then unresolved "s3-object: checksum $OUT is not $ARTIFACT_B64"
  else unresolved "s3-object: head failed: ${ECODE:-rc$RC}"; fi
fi
if pending microvm-image "$IMAGE_NAME" IMAGE_ARN; then
  lvr image list -name "$IMAGE_NAME"
  if [ "$RC" = 0 ]; then
    list_items || die "malformed image list reply in reconciliation"
    OUT=$(jq -r --arg n "$IMAGE_NAME" '[.[] | select(.Name == $n) | .ImageArn] | join(" ")' <<<"$ITEMS") || die "image list items unreadable"
  fi
  if [ "$RC" != 0 ]; then unresolved "microvm-image $IMAGE_NAME: list failed: ${ECODE:-rc$RC}"
  elif [ -z "$OUT" ]; then absent "microvm-image $IMAGE_NAME"
  elif [ "$(wc -w <<<"$OUT")" != 1 ]; then unresolved "microvm-image $IMAGE_NAME: listed several: $OUT"
  else arn=$OUT
    [ "$arn" = "arn:aws:lambda:eu-west-1:$ACCOUNT:microvm-image:$IMAGE_NAME" ] || die "image ARN [$arn]"
    rec IMAGE_ARN "$arn"
    lvr image get -id "$IMAGE_ARN"
    if [ "$RC" = 0 ] && [ "$(jq -r '.Tags.run // empty' <<<"$OUT")" != "$RUN" ]; then
      finding "microvm-image: tags missing ($(jq -c .Tags <<<"$OUT")); livectl tags only at create"
    elif [ "$RC" != 0 ]; then finding "microvm-image: tags unreadable: ${ECODE:-rc$RC}"; fi
  fi
fi
if pending sns-topic "$TOPIC_NAME" TOPIC_ARN; then
  t="arn:aws:sns:eu-west-1:$ACCOUNT:$TOPIC_NAME"
  try aws sns list-topics --query "length(Topics[?TopicArn=='$t'])" --output json
  if [ "$RC" != 0 ]; then unresolved "sns-topic: list failed: ${ECODE:-rc$RC}"
  elif [ "$OUT" = 1 ]; then rec TOPIC_ARN "$t"
    try aws sns list-tags-for-resource --resource-arn "$t" --query "Tags[?Key=='run'].Value" --output text
    if [ "$RC" = 0 ] && [ "$OUT" != "$RUN" ]; then
      try aws sns tag-resource --resource-arn "$t" --tags Key=purpose,Value=$TAGV Key=run,Value=$RUN; [ "$RC" = 0 ] || unresolved "sns-topic: tagging failed: ${ECODE:-rc$RC}"
    elif [ "$RC" != 0 ]; then unresolved "sns-topic: tags unreadable: ${ECODE:-rc$RC}"; fi
  elif [ "$OUT" = 0 ]; then absent "sns-topic $TOPIC_NAME"
  else unresolved "sns-topic: listed $OUT times"; fi
fi
[ -z "$UNRES" ] && echo "reconciliation complete: nothing unresolved" || { echo "unresolved, for Paul (S.4):"; tr '|' '\n' <<<"$UNRES"; }
```

The extra IAM call here (`tag-role`, only when a role exists without its tags) is one of the role
calls R37 covers. Image versions are not reconciled: they go with the image, which livectl deletes
whole.

**S.3 VMs.** If the image was never created (no `IMAGE_ARN`, even after S.2), no VM can exist; the
block records the skip and ends (skip-never-created rule).

```sh
set -euo pipefail; T17='<T17 printed by 0.2>'; . "$T17/env.sh"; guard
if ! have IMAGE_ARN; then echo "no image was ever created, so no VM can exist"; exit 0; fi
! ctl_alive || die "the controller is running"
settle_all
sleep 120
settle_all
```

`settle_all` ends every recorded VM and every live VM an image-scoped List shows, accepts an end
only as `TERMINATED` or two not-found reads at least 60 s apart, and finishes only after three
consecutive scans 30 s apart show nothing live. The second run, at least 2 minutes after the
controller stopped, covers the residual R21 accepts: a launch request AWS held after the client gave
up can still create a VM late. A VM that appears even later is visible to any later scan of the
image while the image exists, and its maximum duration (at most 1 hour for the drivers, 30 minutes
for the orphan, 15 minutes for the contract) ends it.

**S.4 What is left for Paul.** Everything else in the ledger stays in place, and the agent reports
the ledger and this exposure:

| Left in place | Cost while it stays |
| --- | --- |
| MicroVM image (one version, or two after a step down) | about $0.08 per GB-month (Ireland rate not printed), assumed 3 GB: about $0.24 a month; worst case 68 GB at the rate plus 20 %: about $6.53 a month; one-week minimum already paid |
| Connector, VPC, subnet, route table, group, defaults | no listed charge (no NAT, gateway or Elastic IP) |
| IAM roles, log group (1-day retention), SNS topic | none |
| S3 bucket and one object under 10 MB | under $0.01 a month |
| Anything S.2 marked `UNRESOLVED` | its row above; an unresolved image is the only one with a cost (storage), an unresolved MicroVM intent is covered by S.3's scans |
| The run-ID reservation `$HOME/.cache/t17b-runs/<RUN>` (an empty directory on docs-t1) | none; 10.9 removes it |

Teardown (section 10) then runs only on Paul's word, for the recorded resources only.

---

## 11. Spend

### 11.1 Estimate

Rates: Ireland x86_64 compute from spec §10 ($0.155 an hour at 2 GB baseline; above-baseline use up
to 4x costs extra). The pricing page prints snapshot and storage rates for US East only (write
$0.0038 per GB, read $0.00155 per GB, storage $0.08 per GB-month, image storage with a one-week
minimum); the worst case adds 20 % to those for Ireland. As in revision 5, one pause cycle is
counted at $0.0057 per GB, and one week of image storage at $0.08 x 7/30 = $0.01867 per GB. The
page lists no charge for image builds or connectors; the worst case still allows for builds billed
as VM time (20 minutes at 4 GB, twice the 2 GB rate: $0.103 each).

| Item | Expected | Worst case, every approved branch |
| --- | --- | --- |
| Contract VMs (6.1) | 1 VM for about 1 min (attempt 4: 13 to 52 s each): $0.01 | 2 VMs (the first, plus one if AWS ever answered the changed request with a new VM) at the contract's 15-min maximum: 0.5 h x $0.155 = $0.08 |
| Controller VMs (7) | 2 VMs (sequence, crash) for about 5 min each: $0.03 | 2 at the driver's 1-h lifetime, plus one late R21 VM at 1 h: 3 h x $0.155 = $0.47 |
| Orphan VM (8) | about 12 min: $0.03 | 1800 s: 0.5 h x $0.155 = $0.08 |
| Above-baseline use | idle hook server, none expected: $0.00 | 4x on all 4.0 VM-hours, so 3 x 4.0 x $0.155 = $1.86 more |
| Pause and resume | 1 cycle (7.2) at 2 GB: 2 x $0.0057 = $0.01 | 2 cycles (one spare, for a resent suspend) at 40 GB (8 GB memory, 32 GB disk), x1.2: 2 x 40 x $0.0057 x 1.2 = $0.55 |
| Launch snapshot reads | about 4 starts and 1 resume at 2 GB: 5 x 2 x $0.00155 = $0.02 | 10 starts at 40 GB, x1.2: 10 x 40 x $0.00155 x 1.2 = $0.74 |
| Image storage | 1 version, assumed 3 GB, one-week minimum: 3 x $0.01867 = $0.06 | 2 versions (Small, and a failed Small after the step down) at 34 GB: 68 x $0.01867 x 1.2 = $1.52 |
| Image builds | 1 build of about 2 min (attempt 4: 1.8 min): $0.02 | 2 builds (the step down adds one): 2 x $0.103 = $0.21 |
| S3, CloudWatch Logs, SNS, data transfer | tiny object, under 1 MB of logs, one publish, no route out: $0.02 | $0.05 |
| **Total** | **about $0.20** ($0.01 + 0.03 + 0.03 + 0.00 + 0.01 + 0.02 + 0.06 + 0.02 + 0.02) | **about $5.55** (unrounded: 0.0775 + 0.465 + 0.0775 + 1.86 + 0.547 + 0.744 + 1.523 + 0.207 + 0.05 = $5.55; the rounded parts add to $5.56) |

Worst-case VM time: 0.5 + 3.0 + 0.5 = 4.0 VM-hours, $0.62 at baseline. The worst case is the sum of
every bound at once (every VM at its maximum, at 4x, with the largest snapshots and both builds),
which cannot all happen in one run; it is under the $10 approval ceiling with $4.45 to spare. It is
above the $5 self-stop only because the self-stop reads the run's own estimate (11.2), which counts
measured VM time at baseline, not these bounds. Revision 5's worst case was about $9.70; this run
drops the facts VMs (0.97 h), six of the eight contract VMs, the Large version and build, and two
of three pause cycles. **Leftovers after an abort** are not in the total: retained image storage
costs about $0.24 to $6.53 a month until teardown (S.4).

### 11.2 The run's own estimate (stop rule)

Computed from the VM ledger and the journal at the end of every section, with no billing call. Each
VM's life starts at the provider's `startedAt` (from the launch reply or any image-scoped scan);
for a VM known only from a log, at the start of the phase that found it, which is earlier than its
real start. It ends at the time its end was confirmed (`VMGONE`), which is later than its real end,
or now if it has not ended. Both ends err on the long side, so the figure is an upper bound on VM
time at baseline. A VM whose only start is a phase start is counted and listed as such. The fixed
items are 11.1's expected figures: image storage $0.06 per version built, $0.02 per build, $0.02
of small items, two pause cycles at 2 GB ($0.0228), and one launch snapshot read at 2 GB ($0.0031)
per recorded VM.

```sh
set -euo pipefail; . "${TMPDIR:?}/equipo-t17b/env.sh"
python3 -I - "$VMS" "$JOURNAL" <<'EOF'
import sys, datetime as dt
def p(x):
    t = dt.datetime.fromisoformat(x.replace("Z", "+00:00"))
    if t.tzinfo is None or t.utcoffset() is None: raise ValueError(f"timestamp {x!r} has no time zone")
    return t
now = dt.datetime.now(dt.timezone.utc)
prov, phase, end = {}, {}, {}
def bad(kind, n, line, why):
    sys.exit(f"ABORT: {kind} line {n} cannot be read ({why}): {line[:160]!r}")
for n, line in enumerate(open(sys.argv[1]), 1):
    f = line.rstrip("\n").split("\t")
    if len(f) != 4: bad("VM ledger", n, line, f"{len(f)} fields, want 4")
    vid, src, start, _ = f
    if not vid: bad("VM ledger", n, line, "empty VM ID")
    try:
        if start.startswith("phase:"):
            t = p(start[6:]); phase[vid] = min(t, phase.get(vid, t))
        else:
            t = p(start); prov[vid] = min(t, prov.get(vid, t))
    except ValueError as e: bad("VM ledger", n, line, e)
small = failed = False
for n, line in enumerate(open(sys.argv[2]), 1):
    if "\t" not in line: bad("journal", n, line, "no tab")
    ts, msg = line.rstrip("\n").split("\t", 1)
    w = msg.split(" ")
    if w[0] == "VMGONE":
        if len(w) < 2 or not w[1]: bad("journal", n, line, "VMGONE without an ID")
        try: end[w[1]] = p(ts)
        except ValueError as e: bad("journal", n, line, e)
    if w[0] == "CONFIRMED" and len(w) > 1 and w[1] == "VER_SMALL": small = True
    if w[0] == "CONFIRMED" and len(w) > 1 and w[1] == "VER_SMALL_FAILED": failed = True
versions = int(small) + int(failed)  # each version stored is one build
ids = set(prov) | set(phase)
hours, phase_only = 0.0, []
for vid in ids:
    start = prov.get(vid) or phase[vid]
    if vid not in prov: phase_only.append(vid)
    hours += max(0.0, (end.get(vid, now) - start).total_seconds()) / 3600
live = [v for v in ids if v not in end]
est = hours * 0.155 + (0.06 + 0.02) * versions + 0.02 + 0.0057 * 2 * 2 + 0.0031 * len(ids)
print(f"VMs {len(ids)}, not yet ended {len(live)}, started from phase only {len(phase_only)} {phase_only}, "
      f"VM-hours {hours:.2f}, image versions {versions}, estimate ${est:.2f} "
      f"(baseline compute plus image storage, builds, small items, two pause cycles and one launch read per VM; "
      f"retained storage after an abort is separate)")
sys.exit(3 if est >= 5 else 0)
EOF
```

- `versions` is 1 once the Small version is recorded, and 2 after a step down (the failed version
  is kept until the image is deleted); each version is one build.
- Stop rule: exit status 3 (estimate $5 or more), or a VM live outside its step, means the safe
  stop. A journal or VM ledger line that cannot be read ends the block with an `ABORT:` line naming
  it (exit status 1); the estimate is then made by hand from the ledger and reported as such. Paul
  reads the real bill himself (R33).

### 11.3 What goes into the progress file

One line each: the `ChangedSpecConflicts` result (`CONTRACT_CSC`) with any FINDING text; the
sequence attempt, its `timings:` line and its epochs; the crash attempt, the crash VM, the crash
exit status, the recover result and the count of VMs started since the crash launch; the orphan
VM, its plant time, its stop time relative to P, the alert result and the audit row counts; the
interface counts at each snapshot; the 11.2 estimate at the end; every FINDING.

**Wall-clock:** about 2 to 3 hours from 0.1 to 10.9.

---

## 12. UNCONFIRMED items and placeholders

### Settled by attempt 4 (no longer open)

- **U4 and U5, base image and container base:** base `al2023-1` versions 4 and 3 were `AVAILABLE`
  with x86_64; `public.ecr.aws/lambda/microvms:al2023-minimal` built in about 1.8 minutes from
  version 4. 3.6 still picks the newest `AVAILABLE` x86_64 version and keeps the one-time step
  down, since AWS can publish a newer base at any time.
- **U8, image deletion:** `image delete` worked and the image was gone from the list in about
  1.5 minutes.
- **U9 and the create half of U2, connector:** the managed operator policy plus the scoped delete
  was accepted on the first `CreateNetworkConnector`; ACTIVE after about 4.3 minutes; deleted in
  about 13 s with no `DELETE_FAILED`.
- **U11, an unknown VM ref on terminate:** `StopUnknownRef` passed live; not run here.
- **U12, the Date header:** present on GetMicrovm (`ResultMetadata.ServerTime`).
- **U14 and U19, image versions:** versions carry the image's tags; the Small version stayed
  `SUCCESSFUL ACTIVE` after an update. This run makes no update unless it steps down.
- **U17, MicroVM ID format:** `microvm-<uuid>`, 44 characters, inside R36's form. This plan's
  `VMID_RE` is built on it (change 4).
- **U21, a qualified egress ARN on RunMicrovm:** accepted; the VM echoes `<conn>:1`.
- **Client tokens:** the same request under a used token returns the same VM (also after the VM
  ended, at least 7 minutes on); a changed request gets `ValidationException` "The provided
  clientToken was used with different request parameters.", now mapped to `ErrConflict`.
- **Resume on RUNNING, suspend on SUSPENDED:** both accepted as no-ops (not `ConflictException`);
  suspend about 2 s, resume about 4 s.
- **Payload limit:** 4096 ASCII bytes accepted, 4097 refused.
- **TERMINATED visibility:** Get and the image-scoped List still showed a terminated VM 6.5 minutes
  later.

### Still unconfirmed from revision 5, 4

1. **U2, delete half.** Lambda's interface cleanup under the `ec2:ManagedResourceOperator`
   condition is still untested: attempt 4's connector never had interfaces in the run's subnet,
   even with VMs running. 10.2's pre-approved fallback drops that condition (keeping the subnet
   condition) and retries once; a second failure is a hard stop.
2. **U7, build log group.** Other groups under the prefix are never deleted; 10.6 stops for Paul
   (not in the ledger).
3. **U16, Ireland rates** for snapshots, launch reads and image storage: an estimate assumption.
4. **U18, the not-found code for a gone VM** (`ResourceNotFoundException`) is documented but was
   never observed: terminated VMs stayed visible as `TERMINATED` for at least 6.5 minutes, which
   `vm_end` accepts. It stays fail-closed only in `vm_end`.

### New for Task 17b, 9

1. **The controller sequence live** (7.2): `to_running` (the reaper reads states once per 60 s
   pass), the drain and quiescent calls, suspend through the controller, the resume epoch (one
   above), and `stop_to_proof` (2 to 3 minutes, R17) are all unmeasured. Each difference is a
   FINDING.
2. **The crash point live** (7.3): that `os.Exit(137)` in the hostedlive build leaves the job
   `waiting` with no Ref, and that `start_ctl`'s wrapper records 137. First run.
3. **Replay of the crash intent** (7.4): expected to return the crash VM under the same client
   token, from the stored spec (identical maximum duration and payload). If AWS answered with the
   token-reuse `ValidationException` instead, the adapter would now map it to `ErrConflict` and the
   intent would not gain the VM; the VM would then be an orphan, and 7.4 records a FINDING and
   settles it.
4. **The orphan timeline** (8.2): first sighting, the 10-minute grace, the ownership recheck and
   the stop, live for the first time. A stop after P+15:00 is a hard stop (a VM alive outside its
   step).
5. **The first SNS publish** (8.2): no alert has ever been published live (a clean start sends
   none; see section 4). If `kass` cannot publish to the topic, the alert is counted as failed and
   kept queued, the reaper pass reports an error, and 8.2 records a FINDING; the orphan is still
   stopped, because the stop comes before the alert.
6. **`ChangedSpecConflicts` with the fix** (6.1): expected PASS. The mapping matches AWS's message
   text; if AWS changes that text, the subtest fails again as a FINDING.
7. **A controller config with one image version** (`small` only): accepted by the config check
   (`runner.go:141-151`) and covered by unit tests, but not yet run live.
8. **5.6's readiness gate:** now built from the metrics and rows a clean start writes (attempt 4
   saw `network_audit_passing 1`, `reap_last_error 0` and no failure rows). The `provider_bound`
   row check is new; a database that was not fresh would fail it, which 0.2's new scratch rules
   out.
9. **Blocks and the controller as systemd user units (R44).** The coordinator found
   `systemctl --user` usable on docs-t1 (state `degraded`), with a child under `env -i` kept in the
   unit's cgroup and stopped with it; the plan writer's probes (units `t17b-probe-*`, `sleep` only)
   showed the same, plus KILL after `TimeoutStopSec`, exit status 137 and `signal:<name>` recorded by
   `ExecStopPost`, `--collect` removing ended units, and a unit started from inside a unit living on
   as its own unit. Not yet run with the real blocks, `go test` or the controller. 0.2's probe unit
   must pass before any AWS call; any later unit state that cannot be read is `unresolved`, and S.0
   stops and proves every unit before cleanup. Since R45 each unit runs under `env -i` with an
   allowlist; the probes showed the program sees only those names. That the kass
   `credential_process`, `go test` and the controller work with that allowlist alone is not yet
   shown live: a missing variable would surface as a failed call (a FINDING or an abort), not a
   safety problem.

### Placeholders

One per block: `<T17 printed by 0.2>`, the scratch path 0.2 prints, filled in by the executor in
the sandbox-off blocks. `PIN_SHA` is `bf29344a8b6832dff425aafc1337d4883f6a894f`, written once, in 0.1.

