diff --git a/Justfile b/Justfile index 4461bdb9..f10d5aaa 100644 --- a/Justfile +++ b/Justfile @@ -15,6 +15,7 @@ _online_hosts := shell('python3 "$1"', justfile_directory() / "scripts/online_ho # Defined once so a change to how the fleet addresses itself is a one-line # edit instead of eight. _play := "ansible-playbook --connection=local -l " + machine + " -e target=" + machine + " -e ansible_connection=local -e ansible_host=127.0.0.1" +_secret_tag_pattern := "secrets|bitwarden|ssh|ssh_keys|github|tailscale|kube|forgejo|registry|atuin|ai|omp" # Apply all config to this machine (unlocks BW interactively if needed) apply *args: @@ -38,11 +39,15 @@ apply *args: SKIP_TAGS="secrets" fi rc=0 + unit_args=() if [ -n "$SKIP_TAGS" ]; then + unit_args+=(--no-secrets) {{ _play }} site.yml --skip-tags "$SKIP_TAGS" $BECOME_ARGS {{ args }} || rc=$? else - {{ _play }} -e "bw_session=${BW_SESSION:-}" site.yml $BECOME_ARGS {{ args }} || rc=$? + {{ _play }} site.yml $BECOME_ARGS {{ args }} || rc=$? fi + urc=0; scripts/run-units.sh "${unit_args[@]}" || urc=$? + [ "$rc" -ne 0 ] || rc=$urc scripts/record-apply.py "$rc" apply "$SKIP_TAGS" exit $rc @@ -50,9 +55,41 @@ apply *args: apply-tags tags: #!/usr/bin/env bash set -uo pipefail - cd {{ dotfiles_dir }} + cd {{ dotfiles_dir }} || exit 1 rc=0 - {{ _play }} -e "bw_session=${BW_SESSION:-}" site.yml --tags {{ tags }} || rc=$? + ansible_tags="{{ tags }}" + unit_args=(--tags "{{ tags }}") + skip_args=() + needs_secrets=0 + IFS=',' read -ra tag_list <<< "{{ tags }}" + for tag in "${tag_list[@]}"; do + case "$tag" in + {{ _secret_tag_pattern }}) needs_secrets=1 ;; + esac + done + if [ "$needs_secrets" -eq 1 ]; then + # bw-unlock accepts an environment session as-is; reject stale ones first. + if [ -n "${BW_SESSION:-}" ] && ! bw unlock --check >/dev/null 2>&1; then + unset BW_SESSION + fi + if bw_env=$(scripts/bw-resolve.sh local) && eval "$bw_env" && + [ -n "${BW_SESSION:-}" ] && bw unlock --check >/dev/null 2>&1 && + timeout 15 bw sync >/dev/null; then + # Secret roles selected by their own tag still need bw_unlocked set. + ansible_tags="$ansible_tags,bitwarden" + else + echo "Bitwarden unavailable or sync failed; skipping secrets." >&2 + unset BW_SESSION + skip_args=(--skip-tags secrets) + unit_args+=(--no-secrets) + rc=1 + fi + fi + arc=0 + {{ _play }} site.yml --tags "$ansible_tags" "${skip_args[@]}" || arc=$? + [ "$rc" -ne 0 ] || rc=$arc + urc=0; scripts/run-units.sh "${unit_args[@]}" || urc=$? + [ "$rc" -ne 0 ] || rc=$urc scripts/record-apply.py "$rc" apply-tags "{{ tags }}" exit $rc @@ -64,6 +101,8 @@ apply-nosecrets *args: git pull --ff-only || true rc=0 {{ _play }} site.yml --skip-tags secrets {{ args }} || rc=$? + urc=0; scripts/run-units.sh --no-secrets || urc=$? + [ "$rc" -ne 0 ] || rc=$urc scripts/record-apply.py "$rc" apply-nosecrets secrets exit $rc @@ -71,12 +110,22 @@ apply-nosecrets *args: apply-remote-tags name tags: #!/usr/bin/env bash set -euo pipefail - # A BW session is only valid on the machine that unlocked it, so resolve - # one on the remote rather than forwarding ours. - REMOTE_BW_SESSION=$({{ dotfiles_dir }}/scripts/bw-resolve.sh remote {{ name }} || true) - ssh -t {{ name }} " + # Resolve on the target only for explicitly secret-bearing tags. + REMOTE_BW_SESSION="" + IFS=',' read -ra tag_list <<< "{{ tags }}" + for tag in "${tag_list[@]}"; do + case "$tag" in + {{ _secret_tag_pattern }}) + REMOTE_BW_SESSION=$({{ dotfiles_dir }}/scripts/bw-resolve.sh remote {{ name }} || true) + break ;; + esac + done + EXPECT_SESSION=0; [ -z "$REMOTE_BW_SESSION" ] || EXPECT_SESSION=1 + BW_SESSION="$REMOTE_BW_SESSION" ssh -o SendEnv=BW_SESSION -t {{ name }} " export PATH=\"\$HOME/.local/bin:/home/linuxbrew/.linuxbrew/bin:\$PATH\" - export BW_SESSION='${REMOTE_BW_SESSION}' + if [ '$EXPECT_SESSION' = 1 ] && [ -z \"\${BW_SESSION:-}\" ]; then + echo 'SSH server did not accept BW_SESSION; remote apply aborted.' >&2; exit 1 + fi cd ~/.local/share/dotfiles && git pull --ff-only && just apply-tags {{ tags }} " @@ -86,7 +135,18 @@ mesh-check: # Apply only dotfile configs (shell, git, tmux, etc.) dotfiles: - cd {{ dotfiles_dir }} && {{ _play }} site.yml --tags dotfiles + #!/usr/bin/env bash + set -uo pipefail + cd {{ dotfiles_dir }} + rc=0 + {{ _play }} site.yml --tags dotfiles || rc=$? + urc=0; scripts/run-units.sh --tags dotfiles || urc=$? + [ "$rc" -ne 0 ] || rc=$urc + exit $rc + +# Run the bash units (units/*.sh) in parallel via mise, e.g. `just units --tags omp` +units *args: + cd {{ dotfiles_dir }} && scripts/run-units.sh {{ args }} # Apply only packages (Homebrew + Flatpak) packages: @@ -103,10 +163,13 @@ apply-remote name *args: echo "Bitwarden unlocked on {{ name }} (session: ${#APPLY_BW_SESSION} chars)" fi echo "Applying to {{ name }} with forwarded BW session..." - ssh -t {{ name }} " + EXPECT_SESSION=0; [ -z "$APPLY_BW_SESSION" ] || EXPECT_SESSION=1 + BW_SESSION="$APPLY_BW_SESSION" ssh -o SendEnv=BW_SESSION -t {{ name }} " export PATH=\"\$HOME/.local/bin:/home/linuxbrew/.linuxbrew/bin:\$PATH\" - export BW_SESSION='${APPLY_BW_SESSION}' - [ -n \"\$BW_SESSION\" ] && (umask 077 && printf '%s' \"\$BW_SESSION\" > /tmp/bw_session) + if [ '$EXPECT_SESSION' = 1 ] && [ -z \"\${BW_SESSION:-}\" ]; then + echo 'SSH server did not accept BW_SESSION; remote apply aborted.' >&2; exit 1 + fi + [ -n \"\${BW_SESSION:-}\" ] && (umask 077 && printf '%s' \"\$BW_SESSION\" > /tmp/bw_session) cd ~/.local/share/dotfiles && git pull --ff-only && just apply {{ args }} " just push-terminfo {{ name }} @@ -282,8 +345,15 @@ apply-online-tags tags: [ -z "$ONLINE_HOSTS" ] && echo "No remote hosts online." && exit 0 declare -A SESSIONS - for host in $ONLINE_HOSTS; do - SESSIONS[$host]=$(scripts/bw-resolve.sh remote "$host" || true) + IFS=',' read -ra tag_list <<< "{{ tags }}" + for tag in "${tag_list[@]}"; do + case "$tag" in + {{ _secret_tag_pattern }}) + for host in $ONLINE_HOSTS; do + SESSIONS[$host]=$(scripts/bw-resolve.sh remote "$host" || true) + done + break ;; + esac done PIDS=() @@ -296,7 +366,7 @@ apply-online-tags tags: echo "Applying tags '{{ tags }}' to $host (background)..." ssh "$host" " export PATH=\"\$HOME/.local/bin:/home/linuxbrew/.linuxbrew/bin:\$PATH\" - export BW_SESSION='${SESSIONS[$host]}' + export BW_SESSION='${SESSIONS[$host]:-}' cd ~/.local/share/dotfiles && git pull --ff-only && just apply-tags {{ tags }} " > "/tmp/apply_${host}.log" 2>&1 & PIDS+=("$!:$host") @@ -443,7 +513,7 @@ doctor: echo "→ Machine identity" if [ -f /etc/dotfiles-machine ]; then pass "machine: $(cat /etc/dotfiles-machine)"; else warn "/etc/dotfiles-machine missing — run bootstrap"; fi echo "→ Core binaries" - for bin in brew bw gh tailscale ansible-playbook just; do + for bin in brew bw gh tailscale ansible-playbook just mise; do if command -v "$bin" >/dev/null 2>&1; then pass "$bin"; else warn "$bin missing"; fi done echo "→ Tailscale" @@ -516,6 +586,10 @@ docs-build: seed-kube: @{{ dotfiles_dir }}/scripts/bw-seed-kube.sh +# Seed Bitwarden with the omp auth-broker token via SSH to spindle +seed-omp-broker: + @{{ dotfiles_dir }}/scripts/bw-seed-omp-broker.sh + # Show all online fleet machines' doctor status in parallel doctor-fleet: #!/usr/bin/env bash diff --git a/bootstrap.sh b/bootstrap.sh index 3ff87d79..6e1eca13 100755 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -322,7 +322,8 @@ run_phase1() { echo "═══════════════════════════════════════════════════" echo "" - cd "$DOTFILES_DIR" + cd "$DOTFILES_DIR" || return 1 + local rc=0 urc=0 ansible-playbook \ --connection=local \ -l "$MACHINE_NAME" \ @@ -331,7 +332,10 @@ run_phase1() { -e ansible_host=127.0.0.1 \ -e "is_desktop=$is_desktop" \ --skip-tags secrets \ - site.yml + site.yml || rc=$? + scripts/run-units.sh --no-secrets || urc=$? + [ "$rc" -ne 0 ] || rc=$urc + return "$rc" } # ── Bitwarden login ─────────────────────────────────────────────── @@ -346,6 +350,17 @@ setup_bitwarden() { fi local bw_status + # Prefer a usable session, including the cached session from a previous run. + if [ -n "${BW_SESSION:-}" ] && ! bw unlock --check >/dev/null 2>&1; then + unset BW_SESSION + fi + if [ -z "${BW_SESSION:-}" ] && [ -s /tmp/bw_session ]; then + local cached_session + cached_session=$(cat /tmp/bw_session) + if BW_SESSION="$cached_session" bw unlock --check >/dev/null 2>&1; then + export BW_SESSION="$cached_session" + fi + fi bw_status=$(bw status 2>/dev/null | python3 -c "import json,sys; print(json.load(sys.stdin)['status'])" 2>/dev/null || echo "unauthenticated") echo "" @@ -356,24 +371,24 @@ setup_bitwarden() { echo "═══════════════════════════════════════════════════" echo "" - case "$bw_status" in - unlocked) - BW_SESSION=$(bw unlock --raw 2>/dev/null || true) - ;; - locked) - echo "Unlocking Bitwarden..." - BW_SESSION=$(bw unlock --raw) - ;; - unauthenticated) + if [ -z "${BW_SESSION:-}" ]; then + if [ "$bw_status" = "unauthenticated" ]; then echo "Log in to Bitwarden to complete setup:" - bw login - BW_SESSION=$(bw unlock --raw) - ;; - esac - - export BW_SESSION - rm -f /tmp/bw_session - (umask 077 && printf '%s' "$BW_SESSION" > /tmp/bw_session) + bw login || return 1 + fi + echo "Unlocking Bitwarden..." + BW_SESSION=$(bw unlock --raw) || return 1 + export BW_SESSION + fi + if [ -z "$BW_SESSION" ] || ! bw unlock --check >/dev/null 2>&1; then + echo "Bitwarden session is invalid; secrets setup skipped." >&2 + return 1 + fi + if ! timeout 15 bw sync >/dev/null; then + echo "Bitwarden sync failed; secrets setup skipped." >&2 + return 1 + fi + (umask 077 && printf '%s' "$BW_SESSION" > /tmp/bw_session) || return 1 return 0 } @@ -382,7 +397,8 @@ run_phase2() { local is_desktop="false" [ "$MACHINE_TYPE" = "desktop" ] && is_desktop="true" - cd "$DOTFILES_DIR" + cd "$DOTFILES_DIR" || return 1 + local rc=0 urc=0 ansible-playbook \ --connection=local \ -l "$MACHINE_NAME" \ @@ -390,9 +406,11 @@ run_phase2() { -e ansible_connection=local \ -e ansible_host=127.0.0.1 \ -e "is_desktop=$is_desktop" \ - -e "bw_session=${BW_SESSION:-}" \ --tags secrets \ - site.yml + site.yml || rc=$? + scripts/run-units.sh --tags omp,secrets || urc=$? + [ "$rc" -ne 0 ] || rc=$urc + return "$rc" } # ── Push inventory changes (after GitHub auth is set up) ───────── @@ -434,12 +452,23 @@ main() { ensure_sudo ensure_tailscale install_collections - run_phase1 + local rc=0 phase_rc=0 + run_phase1 || rc=$? - # Phase 2 runs if Bitwarden CLI is now available (installed by Homebrew in Phase 1) + # Phase 2 still runs after a Phase 1 failure, if the vault is available. if setup_bitwarden; then - run_phase2 - push_inventory_changes + run_phase2 || phase_rc=$? + [ "$rc" -ne 0 ] || rc=$phase_rc + if [ "$phase_rc" -eq 0 ]; then + push_inventory_changes || { phase_rc=$?; [ "$rc" -ne 0 ] || rc=$phase_rc; } + fi + else + echo "Bitwarden setup failed; Phase 2 was not run." >&2 + [ "$rc" -ne 0 ] || rc=1 + fi + if [ "$rc" -ne 0 ]; then + echo "Bootstrap failed (exit $rc); address the errors and re-run." >&2 + return "$rc" fi echo "" @@ -453,4 +482,6 @@ main() { echo " To re-apply anytime: just apply" } -main +if [[ -z "${BASH_SOURCE[0]:-}" || "${BASH_SOURCE[0]}" == "$0" ]]; then + main +fi diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 8adf5ef5..9f95290f 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -5,6 +5,7 @@ # Core Concepts - [Architecture](architecture.md) +- [Units](units.md) - [Inventory & Groups](inventory.md) - [Secrets with Bitwarden](bitwarden.md) - [Onboarding a New Machine](onboarding.md) diff --git a/docs/src/architecture.md b/docs/src/architecture.md index 940ef1ee..8bb6be1e 100644 --- a/docs/src/architecture.md +++ b/docs/src/architecture.md @@ -47,7 +47,7 @@ SSHes to the target, forwards the Bitwarden session token, pulls the latest dotf just apply-tags kube,shell ``` -Runs only roles tagged with the given tags. Useful for deploying specific configs without running the full playbook. `--skip-tags` works the same way in reverse — `just apply-nosecrets` is `--skip-tags secrets` under the hood (see [Bitwarden](bitwarden.md)). +Runs roles and units selected by the given tags. Explicit secret-bearing tags first resolve and sync Bitwarden; unrelated tags do not prompt. `just apply-nosecrets` passes `--skip-tags secrets` to Ansible and `--no-secrets` to units (see [Bitwarden](bitwarden.md)). #### Available Tags @@ -64,7 +64,7 @@ Every role in `site.yml` carries one or more tags. Tags fall into two kinds: **p | System + packages | `bitwarden` | `secrets`, `bitwarden` | | System + packages | `shell_fonts` | `dotfiles`, `shell`, `fonts` | | System + packages | `shell_dotfiles` | `dotfiles`, `shell`, `dotfiles` | -| System + packages | `omp` | `dotfiles`, `omp` | +| System + packages | `omp` unit | `dotfiles`, `omp` | | System + packages | `hive_ops` | `hive`, `hive_ops` | | System + packages | `git` | `dotfiles`, `git` | | System + packages | `neovim` | `dotfiles`, `neovim`, `editor` | @@ -96,7 +96,7 @@ Common phase-wide selections: - `--tags secrets` — every BW-backed role only (`bitwarden`, `shell_atuin`, `shell_ai`, `ssh_keys`, `github`, `tailscale`, `kube`, `forgejo_registry`) - `--tags desktop` — every desktop-app role (`flatpak`, `bluefin_common`, `gnome`, `zen_browser`, `pipewire_audio`) - `--tags services` — every long-running service role (`syncthing`, `systemd`, `bst_dashboard`, `kirocrew`, `proxy`, `tailscale_cert`) -- `--skip-tags secrets` — everything except BW-backed roles. This is `just apply-nosecrets`, which the daily `dotfiles-update.timer` and the `dots` alias run; `bootstrap.sh` and `phone-apply.service` pass `--skip-tags secrets` directly +- `--skip-tags secrets` — everything except BW-backed roles. `just apply-nosecrets`, bootstrap's first phase and `phone-apply.service` also pass `--no-secrets` to units. Tags do not replace the [`skip_*` host_vars flags](#skip-flags) or inventory-group gating described below — a role can be tag-selected and still no-op if its `when:` condition (group membership, `skip_*`, `machine_profile`) evaluates false. @@ -144,13 +144,13 @@ Every flag `site.yml` reads, all defaulting to `false` (`| default(false)`). Set | `skip_proxy` | `proxy` | not `vps`, not `vm-test` | `mumbai`, `punjab`, `termux` | | `skip_tailscale_cert` | `tailscale_cert` | not `vps`, not `vm-test` | `mumbai`, `termux` | -"desktop" is `is_desktop` (membership of the `desktop` group unless overridden); "not `vm-test`" is `machine_profile != 'vm-test'`. Roles without a flag either always run or are gated another way: `termux_packages` (`termux_hosts` group), `omp` (not Termux), `kirocrew` (`kirocrew_enabled: true`), `server_hardening` (`server`/`vps` groups), `retired_services` (not `vps`, not Termux, systemd hosts). +"desktop" is `is_desktop` (membership of the `desktop` group unless overridden); "not `vm-test`" is `machine_profile != 'vm-test'`. Roles without a flag either always run or are gated another way: `termux_packages` (`termux_hosts` group), `kirocrew` (`kirocrew_enabled: true`), `server_hardening` (`server`/`vps` groups), `retired_services` (not `vps`, not Termux, systemd hosts). The `omp` unit skips Termux. ## Secrets Flow 1. Ansible requests a Bitwarden session (env var, cached file, or interactive unlock) 2. The `bitwarden` role resolves `BW_SESSION` and caches it 3. Secrets-tagged roles consume the session token for API calls -4. For remote applies, `scripts/bw-resolve.sh remote ` unlocks the vault on the target and the recipe exports that session inline over `ssh -t` (no `SendEnv`) — see [Remote Apply](bitwarden.md#remote-apply) +4. For remote applies, `scripts/bw-resolve.sh remote ` unlocks the vault on the target and SSH forwards that session using `SendEnv=BW_SESSION`; the target must accept it — see [Remote Apply](bitwarden.md#remote-apply). No secrets are stored in git — the repo is fully public. diff --git a/docs/src/bitwarden.md b/docs/src/bitwarden.md index 68712e4e..22c34724 100644 --- a/docs/src/bitwarden.md +++ b/docs/src/bitwarden.md @@ -5,7 +5,7 @@ All secrets live in [Bitwarden](https://bitwarden.com/) and are resolved at runt ## How It Works 1. The `bitwarden` role runs first in the secrets phase. -2. It resolves a session token in order: `BW_SESSION` env var → `/tmp/bw_session` → interactive `bw unlock`. +2. The apply wrapper can prompt via `scripts/bw-resolve.sh`; the role itself reads `BW_SESSION` from the environment, then falls back to `/tmp/bw_session`. 3. It runs `bw sync` (with a 15 s hard timeout, so a flaky vault server can't hang the play) to refresh the local cached vault. 4. It calls `bw status` and sets a `bw_unlocked` host fact: `true` only if the CLI is installed, a session was resolved, *and* the vault actually unlocks. 5. Every BW-using role gates on `when: bw_unlocked | default(false)`. The end-of-play `post_tasks` summary prints one of: @@ -13,6 +13,8 @@ All secrets live in [Bitwarden](https://bitwarden.com/) and are resolved at runt - `Bitwarden vault was LOCKED — … skipped. To enable: bw unlock …` - `SKIPPED (--skip-tags secrets). Run dots-apply to include …` +For `just apply-tags` with an explicit secret-bearing tag such as `kube`, `ai` or `omp`, the wrapper validates and syncs a session before running, and adds the `bitwarden` tag so legacy secret roles receive `bw_unlocked`. It skips secret work and returns non-zero if the session or sync fails; unrelated tags do not prompt. + ## Remote Apply `just apply-remote ` (and `just apply-remote-tags `): @@ -22,9 +24,7 @@ All secrets live in [Bitwarden](https://bitwarden.com/) and are resolved at runt out it tries `bw login --apikey` with the `bw-api-key` item from your local vault; to unlock it pipes the master password (item `James Bitwarden`) over stdin, falling back to an interactive `bw unlock` over `ssh -t`. -2. Runs `ssh -t "export BW_SESSION='…'; …; just apply"` — the session - is exported inline in the remote command, not via `SendEnv`. `apply-remote` - also caches it in the remote's `/tmp/bw_session`. +2. Sends the remote session through SSH `SendEnv=BW_SESSION`, not in the command line. The target SSH daemon must accept `BW_SESSION`; if it rejects a resolved session, the apply aborts. `apply-remote` also caches it in the remote's `/tmp/bw_session`. 3. The `bitwarden` role on the remote runs `bw status`: if it reports `unlocked`, `bw_unlocked` flips to true and secrets work proceeds. @@ -61,11 +61,11 @@ just apply-nosecrets # git pull + apply with --skip-tags secrets dots # alias: cd to the repo + just apply-nosecrets ``` -The daily systemd timer (`dotfiles-update.service`) calls `apply-nosecrets` for the same reason: it can't unlock the vault non-interactively, so it doesn't try. +The daily systemd timer (`dotfiles-update.service`) calls `apply-nosecrets`: Ansible skips secret-tagged roles and units receive `--no-secrets`, even if a cached session exists. ## No Session? -If Bitwarden can't unlock (first run, no BW CLI installed, vault genuinely locked on this host), every secret-touching task is skipped automatically. Non-secret roles (system, packages, dotfiles, desktop, most services) run normally and the play exits successfully — the end-of-play summary tells you exactly which roles didn't get to do their BW work. +If Bitwarden can't unlock (first run, no BW CLI installed, vault genuinely locked on this host), `just apply` skips secret work and continues with non-secret configuration. A targeted secret apply (`just apply-tags`) also continues non-secret work but exits non-zero, so the requested secret update is not mistaken for success. ## Seeding New Secrets diff --git a/docs/src/index.md b/docs/src/index.md index 20969ce2..bafdd4a9 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -65,11 +65,9 @@ The `llm` group is dormant (commented out in `inventory.yml`). | Phase | Roles | Main tags | |-------|-------|-----------| -| 1 — System + packages + dotfiles | sudo, sshd, apk_packages, homebrew, termux_packages, bitwarden, shell_fonts, shell_dotfiles, omp, hive_ops, git, neovim | `system`, `packages`, `dotfiles` | +| 1 — System + packages + dotfiles | sudo, sshd, apk_packages, homebrew, termux_packages, bitwarden, shell_fonts, shell_dotfiles, hive_ops, git, neovim | `system`, `packages`, `dotfiles` | | 2 — Secrets + auth | shell_atuin, shell_ai, ssh_keys, ssh_mesh, github, tailscale, kube, forgejo_registry | `secrets` | | 3 — Desktop apps | flatpak, bluefin_common, gnome, zen_browser (+ browser_fxa), pipewire_audio | `desktop` | | 4 — Services | syncthing, systemd, bst_dashboard, kirocrew, proxy, tailscale_cert, server_hardening | `services` | -Only the `secrets`-tagged work needs Bitwarden. With the vault locked (or -`--skip-tags secrets`), phases 1, 3 and 4 run normally and BW-touching tasks -skip cleanly. +The [`omp` unit](units.md) runs after Ansible, and can also use Bitwarden for its broker token. `just apply-nosecrets` skips the secret-tagged roles and passes `--no-secrets` to units. diff --git a/docs/src/onboarding.md b/docs/src/onboarding.md index 31236e16..c1ff0a3c 100644 --- a/docs/src/onboarding.md +++ b/docs/src/onboarding.md @@ -63,8 +63,10 @@ The bootstrap script: 1. Ensures python, git, uv and Ansible, then clones the dotfiles repo from [GitHub](https://github.com/hanthor/dotfiles) 2. Registers the machine in `inventory.yml` if needed (prompts for the type when `--type` isn't given) 3. Writes `/etc/dotfiles-machine` so the playbook can self-identify, sets the hostname, sets up sudo and Tailscale -4. Runs `site.yml` with `--skip-tags secrets` (installs [Homebrew](https://brew.sh/) and core packages among the rest) -5. If the Bitwarden CLI is now available and unlocks, runs `site.yml --tags secrets` and pushes any inventory changes +4. Runs `site.yml --skip-tags secrets`, then all bash units with `--no-secrets` (installing [Homebrew](https://brew.sh/) and core packages among the rest) +5. Unlocks and syncs Bitwarden, runs `site.yml --tags secrets`, then the `omp` and `secrets` units, and pushes any inventory changes + +Each phase runs its units even if Ansible fails. Bootstrap continues to Phase 2 when possible, but exits non-zero if either phase or Bitwarden setup fails. ## After Bootstrap Completes @@ -79,9 +81,9 @@ just apply ``` **Why this step matters:** -- Bootstrap runs `site.yml --skip-tags secrets`, which skips Bitwarden integration -- `just apply` runs the full playbook with secrets, unlocking Bitwarden and completing setup -- This pull-in step distributes SSH keys across the fleet, registers with GitHub and Tailscale, and sets up daily/on-login automation +- Bootstrap's first phase deliberately skips secrets; the second phase only covers secret-tagged roles and the broker unit. +- `just apply` reruns the full playbook and units with secrets and completes any work that was skipped. +- This distributes SSH keys across the fleet, registers with GitHub and Tailscale, and sets up daily/on-login automation. Do **not** edit `host_vars/.yml` before the first `just apply` — bootstrap sets sensible defaults, and `just apply` will pull in critical secrets (SSH keys, GitHub tokens, Tailscale auth). Any per-machine customizations can follow once the first apply succeeds; the `skip_*` flags that turn individual roles off are listed in [Architecture → Skip Flags](architecture.md#skip-flags). diff --git a/docs/src/roles/omp.md b/docs/src/roles/omp.md index 1900f85f..76552a46 100644 --- a/docs/src/roles/omp.md +++ b/docs/src/roles/omp.md @@ -1,29 +1,42 @@ # omp -**Tags:** `dotfiles`, `omp` -**Secrets needed:** No for OMP/Kiro installation; `shell_ai` optionally provides the DeepSeek API key -**Runs on:** All supported hosts except raw Termux +**Unit:** `units/omp.sh` (mise task `unit:omp`; see [Units](../units.md)) +**Tags:** `dotfiles`, `omp` (`just apply-tags omp` runs it after the Ansible pass) +**Secrets needed:** No for the install and routing; the auth-broker token comes from Bitwarden when the vault is unlocked +**Runs on:** All supported hosts except raw Termux (the unit prints `SKIPPED: omp has no Android build`) -Installs Oh My Pi and the Kiro provider on each supported computer. Homebrew hosts install OMP and Bun from the `can1357/tap` tap. musl hosts use OMP's checksum-verified binary installer and Bun's installer. The Kiro provider is installed from `github:elkibalion/omp-kiro-provider`. +Installs Oh My Pi's Kiro provider, skills, routing and the fleet auth-broker client config. Homebrew hosts get `omp` and Bun from the `can1357/tap` tap through `just packages`; musl hosts use OMP's checksum-verified binary installer and Bun's installer, run by the unit itself. This is no longer an Ansible role. -## What It Does +## Steps -1. Installs and verifies `omp`. -2. Installs the Kiro provider plugin for the current user; it is available as `kiro/*` models. -3. Deploys personal skills to `~/.omp/agent/skills/james/` and symlinks them into `~/.claude/skills/`. -4. Exposes the Bitwarden DeepSeek key as `DEEPSEEK_API_KEY` through the shell secret files, not an agent-specific credential file. -5. Removes the legacy Pi CLI from raw Termux. OMP has no native Android/Bionic build; the Debian VM (`mumbai`) is supported normally. +Each step is independent: a failure prints `FAIL `, fails the unit, and the later steps still run. -## Skills and the package manifest +1. `omp installed`: on musl, install `omp` and Bun; elsewhere fail with `omp not installed; run: just packages` if missing. Steps that call `omp` print `skip ... (omp missing)` instead. +2. `skills synced`: copy `roles/pi/files/skills/` to `~/.omp/agent/skills/james/`; make `*.sh`/`*.mjs` executable. (`roles/pi` is skill source data, not an Ansible role.) +3. `claude skill links`: symlink each skill directory into `~/.claude/skills/`. +4. `kiro plugin`: `omp plugin install github:elkibalion/omp-kiro-provider` unless installed. +5. `ccleft` (soft): `go install` the quota probe. +6. `kiro.json`: `~/.config/omp/kiro.json` (kiro-cli ACP fallback on 401/403), creating `~/.config/omp`. +7. `omp-route`: the quota-aware launcher at `~/.local/bin/omp-route`. +8. `routing merged`: deep-merge `units/omp/routing.yml` into `~/.omp/agent/config.yml` with `yq` (lists replace). +9. `broker url`: set `auth.broker.url`; config mode `0600`. +10. `broker token`: set `auth.broker.token` from Bitwarden when the vault is unlocked. If no token ends up in the config the unit prints `PARTIAL: broker token not written ...`. +11. `broker status` (soft): print `omp auth-broker status`. -The playbook copies `roles/pi/files/skills/` to -`~/.omp/agent/skills/james/` and links those skill directories into -`~/.claude/skills/`. The `roles/pi` path is skill source data, not a separate -Ansible role. +## Auth broker -`roles/pi/files/package.json` is tracked by Renovate and protected by -`deps-guard`; it is not installed by this role. OMP plugin installation is -handled separately by the role's explicit plugin tasks. +`omp auth-broker` is the fleet's credential vault: provider logins live on one broker, and every other host is a client that holds only a URL and a bearer token. The broker runs on the OCI `spindle` VPS as a user unit bound to its Tailscale address, `100.113.75.88:8765`. That unit is created by hand and is **not** managed by this repo. + +| Key in `~/.omp/agent/config.yml` | Source | +|---|---| +| `auth.broker.url` | `units/omp/auth-broker.conf` (`OMP_AUTH_BROKER_URL`, spindle's Tailscale address, port 8765) | +| `auth.broker.token` | Bitwarden password item `omp-auth-broker-token` (`OMP_AUTH_BROKER_BW_ITEM`) | + +The token is written only when Bitwarden is unlocked; a locked vault or `--no-secrets` leaves the existing token as it is. The config file is `0600`. + +To seed the token, run `just seed-omp-broker` on a client with the vault unlocked and SSH access to `ubuntu@100.113.75.88`. It reads the live token over SSH without rotating it and creates or updates the Bitwarden item. `OMP_AUTH_BROKER_SSH` overrides the SSH destination. Then run `just apply-tags omp` on each client and verify with `omp auth-broker status`. If the token is rotated on spindle, seed again and re-apply on the clients. + +`DEEPSEEK_API_KEY` and the other provider keys are exposed to the shell by the `shell_ai` role's secret files, not by this unit. ## Kiro authentication @@ -34,8 +47,8 @@ omp /login kiro ``` -Complete the browser sign-in. Then select `kiro/auto` with `/model kiro/auto`. The playbook does not set Kiro as the default model because the OAuth session is not present until a user signs in. +Complete the browser sign-in, then select `kiro/auto` with `/model kiro/auto`. Kiro is not the default model because the OAuth session does not exist until a user signs in. ## Package source -The OMP and Bun Homebrew formulas are in `can1357/tap`; both are core packages for Homebrew-supported hosts. On musl, the official OMP binary installer verifies its SHA-256 and requires `libgcc` and `libstdc++`. Raw Termux receives neither OMP nor the obsolete Pi npm package. +The OMP Homebrew formula is in `can1357/tap`; Bun comes from Homebrew core. Both are core packages for Homebrew-supported hosts. On musl, the official OMP binary installer verifies its SHA-256 and requires `libgcc` and `libstdc++`. `roles/pi/files/package.json` is tracked by Renovate and protected by `deps-guard`; the unit does not install it. diff --git a/docs/src/roles/sshd.md b/docs/src/roles/sshd.md index 15f82757..98ef0fb1 100644 --- a/docs/src/roles/sshd.md +++ b/docs/src/roles/sshd.md @@ -4,10 +4,7 @@ **Secrets needed:** No **Runs on:** All machines -Configures the SSH daemon to accept Bitwarden environment variables from -clients that explicitly use SSH environment forwarding. The current -`just apply-remote` recipe does not depend on this drop-in: it resolves the -session on the target and exports it inside the remote command. +Configures the SSH daemon to accept Bitwarden environment variables. `just apply-remote` resolves the session on the target and forwards it back using `SendEnv=BW_SESSION` without putting it in the remote command line. ## What It Does @@ -17,9 +14,7 @@ Drops a config file at `/etc/ssh/sshd_config.d/99-bw-env.conf`: AcceptEnv BW_SESSION BW_CLIENTID BW_CLIENTSECRET ``` -This drop-in is compatibility for explicit `SendEnv`/`AcceptEnv` workflows. It -is not required by `just apply-remote`, which uses target-side resolution -instead of SSH environment forwarding. +The drop-in is required for session-bearing remote applies; those applies fail if the target rejects `BW_SESSION`. ## Handlers diff --git a/docs/src/roles/systemd.md b/docs/src/roles/systemd.md index 6afc4f16..e0139345 100644 --- a/docs/src/roles/systemd.md +++ b/docs/src/roles/systemd.md @@ -15,6 +15,10 @@ Keeps the dotfiles repo up to date automatically. - **Desktops/servers:** Daily timer (`dotfiles-update.timer`) - **Laptops:** Runs on login via `graphical-session.target` (no timer) +### phone-apply (himachal only) + +Pushes non-secret Ansible configuration to `termux` and `mumbai`, then runs the non-secret units on each phone from a temporary archive of the controller's tracked revision. Each operation is attempted independently; an unreachable phone does not fail the service. SSH aliases for the two inventory hosts must be configured on himachal. + ### atuin-daemon Keeps [Atuin](https://atuin.sh/) shell history synced in the background. diff --git a/docs/src/units.md b/docs/src/units.md new file mode 100644 index 00000000..7f98e8ea --- /dev/null +++ b/docs/src/units.md @@ -0,0 +1,41 @@ +# Units + +A **unit** is an idempotent bash script in `units/` that configures one independent piece of a machine. Units exist because Ansible aborts a whole role when one task fails: on himachal the `omp` role died at `Deploy omp-kiro-provider config` (`~/.config/omp` did not exist), so the routing merge, `omp-route` and the auth-broker config never ran. In a unit, a failing step is recorded and the next independent step still runs; independent units run in parallel. + +[mise](https://mise.jdx.dev) is the runner: each unit is a `mise.toml` task, and `mise run` supplies the dependency graph, parallel jobs and `--continue-on-error`. + +Everything not listed under `units/` is still an Ansible role. + +## Running units + +| Command | What it does | +|---|---| +| `just units` | Run every unit in parallel (`just units --tags omp`, `--no-secrets` also accepted) | +| `mise run units` | Same, straight through mise | +| `mise run unit:omp` | One unit | +| `mise run --dry-run units` | Show what would run | +| `mise tasks deps units` | Show the task graph | +| `just apply`, `apply-nosecrets`, `apply-tags`, `dotfiles` | Run Ansible first, then `scripts/run-units.sh` (never skipped because Ansible failed; exit codes are combined) | + +`scripts/run-units.sh [--no-secrets] [--tags a,b]` is the one wrapper the recipes call. It maps Ansible tags to units (`tasks_for_tag`, mirroring the tags of the roles the units replaced), runs the selection with `mise run --continue-on-error --jobs 8 --output prefix --timeout 15m`, and exits with mise's status. Without `mise` on `PATH` it prints `mise not installed; running units sequentially` and runs the selected units one after another, continuing after failures, so hosts without mise (Termux, musl) keep updating. + +`just apply-tags` resolves, validates and syncs Bitwarden for explicitly secret-bearing tags (including `omp`), and selects the `bitwarden` role so legacy secret roles receive its facts. If that fails, it skips secrets, still runs the non-secret selection, and returns an error. Tags unrelated to secrets do not prompt for a vault unlock. `just apply-nosecrets` and bootstrap's first phase pass `--no-secrets` to units even if a session is already present. + +Bootstrap runs all units after its first Ansible pass and the `omp,secrets` selection after the secret pass. The phone push timer runs the non-secret units remotely from a temporary archive of the controller's tracked revision, after its Ansible passes. + +## Rules for a unit + +- Idempotent bash. `set -uo pipefail`, never `set -e`. +- Source `units/lib.sh`: `step "desc" cmd...` (a failure marks the unit failed and continues), `soft "desc" cmd...` (a failure is only a warning), `note "..."`, `finish` (exit 1 only if a `step` failed), `install_if_changed src dest mode`, `bw_session` (a usable Bitwarden session or nothing; never prompts; honours `UNITS_NO_SECRETS=1`). +- mise treats any non-zero exit as failure, so "skipped" and "partial" are printed as `SKIPPED: ...` / `PARTIAL: ...` lines with exit 0. +- Never echo a secret or put one on a command line. + +## Adding a unit + +1. Create `units/.sh` (executable) with a `# shellcheck source=units/lib.sh` line above its `. lib.sh` line. +2. Add `[tasks."unit:"]` with `file = "units/.sh"` to `mise.toml`. +3. Add `` to `ALL_UNITS` and to the right `tasks_for_tag` branches in `scripts/run-units.sh`. + +`tests/test_units_registry.py` fails if the three places disagree. + +`units/`, `mise.toml` and `scripts/run-units.sh` are executed by the fleet timer, so they are intentionally not carved out of CODEOWNERS. diff --git a/group_vars/all.yml b/group_vars/all.yml index 82fa39dc..11fa59d4 100644 --- a/group_vars/all.yml +++ b/group_vars/all.yml @@ -70,6 +70,7 @@ ssh_mesh_exclude: # ── Core packages (all machines) ───────────────────────────────── core_brews: - bitwarden-cli + - bun - gh - git-lfs - node # Bluefin ships node OTB, but non-Bluefin hosts (e.g. mumbai, the phone's Debian VM) don't @@ -81,6 +82,7 @@ core_brews: - tmux - direnv - just + - mise - make - shellcheck - shfmt @@ -100,6 +102,7 @@ brew_blocked: core_taps: - ublue-os/experimental-tap core_tap_brews: + - can1357/tap/omp - ublue-os/experimental-tap/bluefin-cli # ── Desktop-only packages ──────────────────────────────────────── # Trimmed to essentials — Bluefin already ships gcc, python, node, etc. diff --git a/mise.toml b/mise.toml new file mode 100644 index 00000000..cb4032f2 --- /dev/null +++ b/mise.toml @@ -0,0 +1,7 @@ +[tasks.units] +description = "Run every unit in parallel; one failing unit does not stop the others" +depends = ["unit:*"] + +[tasks."unit:omp"] +description = "omp: skills, Kiro plugin, routing, and the auth-broker client" +file = "units/omp.sh" diff --git a/roles/omp/tasks/main.yml b/roles/omp/tasks/main.yml deleted file mode 100644 index a8d74999..00000000 --- a/roles/omp/tasks/main.yml +++ /dev/null @@ -1,142 +0,0 @@ ---- -- name: Ensure installer cache exists - ansible.builtin.file: - path: "{{ ansible_facts['env']['HOME'] }}/.cache" - state: directory - mode: "0700" - when: is_musl | bool - -- name: Download OMP installer on musl systems - ansible.builtin.get_url: - url: https://omp.sh/install - dest: "{{ ansible_facts['env']['HOME'] }}/.cache/omp-install.sh" - mode: "0700" - when: is_musl | bool - -- name: Install OMP on musl systems - ansible.builtin.command: sh {{ ansible_facts['env']['HOME'] }}/.cache/omp-install.sh --binary - args: - creates: "{{ ansible_facts['env']['HOME'] }}/.local/bin/omp" - environment: - PI_INSTALL_DIR: "{{ ansible_facts['env']['HOME'] }}/.local/bin" - when: is_musl | bool - -- name: Download Bun installer on musl systems - ansible.builtin.get_url: - url: https://bun.sh/install - dest: "{{ ansible_facts['env']['HOME'] }}/.cache/bun-install.sh" - mode: "0700" - when: is_musl | bool - -- name: Install Bun on musl systems for OMP plugins - ansible.builtin.command: bash {{ ansible_facts['env']['HOME'] }}/.cache/bun-install.sh - args: - creates: "{{ ansible_facts['env']['HOME'] }}/.bun/bin/bun" - when: is_musl | bool - - -- name: Verify OMP is installed - ansible.builtin.command: omp --version - environment: - PATH: "{{ ansible_facts['env']['HOME'] }}/.bun/bin:{{ ansible_facts['env']['HOME'] }}/.local/bin:{{ ansible_env_path }}" - changed_when: false - -- name: Ensure OMP personal skills directory exists - ansible.builtin.file: - path: "{{ ansible_facts['env']['HOME'] }}/.omp/agent/skills/james" - state: directory - mode: "0755" - -- name: Deploy personal skills to OMP - ansible.builtin.copy: - src: "{{ playbook_dir }}/roles/pi/files/skills/" - dest: "{{ ansible_facts['env']['HOME'] }}/.omp/agent/skills/james/" - mode: "0644" - directory_mode: "0755" - -- name: Find skill scripts that need to be executable - ansible.builtin.find: - paths: "{{ ansible_facts['env']['HOME'] }}/.omp/agent/skills/james" - patterns: "*.sh,*.mjs" - recurse: true - register: omp_skill_scripts - -- name: Make skill scripts executable - ansible.builtin.file: - path: "{{ item.path }}" - mode: "0755" - loop: "{{ omp_skill_scripts.files }}" - loop_control: - label: "{{ item.path | basename }}" - -- name: Ensure Claude skills directory exists - ansible.builtin.file: - path: "{{ ansible_facts['env']['HOME'] }}/.claude/skills" - state: directory - mode: "0755" - -- name: Enumerate deployed OMP skills - ansible.builtin.find: - paths: "{{ ansible_facts['env']['HOME'] }}/.omp/agent/skills/james" - file_type: directory - recurse: false - register: omp_skill_dirs - -- name: Link OMP skills into Claude's skill directory - ansible.builtin.file: - src: "{{ item.path }}" - dest: "{{ ansible_facts['env']['HOME'] }}/.claude/skills/{{ item.path | basename }}" - state: link - force: true - loop: "{{ omp_skill_dirs.files }}" - loop_control: - label: "{{ item.path | basename }}" - -- name: Check installed OMP plugins - ansible.builtin.command: omp plugin list --json - environment: - PATH: "{{ ansible_facts['env']['HOME'] }}/.bun/bin:{{ ansible_facts['env']['HOME'] }}/.local/bin:{{ ansible_env_path }}" - register: omp_plugin_list - changed_when: false - failed_when: false - -- name: Install Kiro provider plugin from GitHub - ansible.builtin.command: - cmd: omp plugin install github:elkibalion/omp-kiro-provider - environment: - PATH: "{{ ansible_facts['env']['HOME'] }}/.bun/bin:{{ ansible_facts['env']['HOME'] }}/.local/bin:{{ ansible_env_path }}" - when: omp_plugin_list.rc != 0 or 'omp-kiro-provider' not in (omp_plugin_list.stdout | default('')) - -- name: Install ccleft (provider quota-remaining probe) - ansible.builtin.command: go install github.com/tuna-os/ccleft/cmd/ccleft@latest - environment: - PATH: "{{ ansible_facts['env']['HOME'] }}/.local/bin:/home/linuxbrew/.linuxbrew/bin:{{ ansible_env_path }}" - args: - creates: "{{ ansible_facts['env']['HOME'] }}/go/bin/ccleft" - failed_when: false - -- name: Deploy omp-kiro-provider config (kiro-cli ACP fallback on 401/403) - ansible.builtin.copy: - src: kiro.json - dest: "{{ ansible_facts['env']['HOME'] }}/.config/omp/kiro.json" - mode: "0644" - -- name: Install omp-route (quota-aware omp launcher via ccleft) - ansible.builtin.copy: - src: omp-route - dest: "{{ ansible_facts['env']['HOME'] }}/.local/bin/omp-route" - mode: "0755" - -- name: Merge provider routing into OMP config - ansible.builtin.shell: | - set -euo pipefail - cfg="$HOME/.omp/agent/config.yml" - mkdir -p "$(dirname "$cfg")" - [ -f "$cfg" ] || : > "$cfg" - before=$(sha256sum "$cfg") - yq -i '. *= (load("{{ role_path }}/files/routing.yml") | explode(.) | ... comments="")' "$cfg" - [ "$before" = "$(sha256sum "$cfg")" ] || echo changed - environment: - PATH: "/home/linuxbrew/.linuxbrew/bin:{{ ansible_env_path }}" - register: omp_routing_merge - changed_when: "'changed' in omp_routing_merge.stdout" diff --git a/roles/shell_dotfiles/vars/main.yml b/roles/shell_dotfiles/vars/main.yml index f6221585..9d89d4f5 100644 --- a/roles/shell_dotfiles/vars/main.yml +++ b/roles/shell_dotfiles/vars/main.yml @@ -94,7 +94,7 @@ alias_groups: - { name: md, cmd: "mkdir -p" } - { name: h, cmd: history } - # Quota-aware launcher (roles/omp): starts omp on the first provider with + # Quota-aware launcher (units/omp): starts omp on the first provider with # ccleft-reported quota left. `command omp` bypasses it. - guard: omp-route fish_kind: alias diff --git a/roles/systemd/templates/phone-apply.service.j2 b/roles/systemd/templates/phone-apply.service.j2 index 5c409d9a..d7c23e07 100644 --- a/roles/systemd/templates/phone-apply.service.j2 +++ b/roles/systemd/templates/phone-apply.service.j2 @@ -12,6 +12,10 @@ ExecStartPre=/usr/bin/git pull --ff-only # without failing the service (the leading "-"). ExecStart=-{{ brew_prefix }}/bin/ansible-playbook -i inventory.yml -e target=termux site.yml --skip-tags secrets ExecStart=-{{ brew_prefix }}/bin/ansible-playbook -i inventory.yml -e target=mumbai site.yml --skip-tags secrets +# Run the same tracked revision on each target, even if its Ansible pass failed. +# An archive avoids assuming the phones have a checkout or Ansible installed. +ExecStart=-:/bin/bash -c "set -o pipefail; /usr/bin/git archive HEAD | /usr/bin/ssh -o BatchMode=yes termux 'mkdir -p \"$HOME/.cache\"; d=$(mktemp -d \"$HOME/.cache/dotfiles-phone.XXXXXXXX\") || exit 1; tar -xf - -C \"$d\" && DOTFILES_MACHINE=termux bash \"$d/scripts/run-units.sh\" --no-secrets; rc=$?; rm -rf -- \"$d\"; exit \"$rc\"'" +ExecStart=-:/bin/bash -c "set -o pipefail; /usr/bin/git archive HEAD | /usr/bin/ssh -o BatchMode=yes mumbai 'mkdir -p \"$HOME/.cache\"; d=$(mktemp -d \"$HOME/.cache/dotfiles-phone.XXXXXXXX\") || exit 1; tar -xf - -C \"$d\" && DOTFILES_MACHINE=mumbai bash \"$d/scripts/run-units.sh\" --no-secrets; rc=$?; rm -rf -- \"$d\"; exit \"$rc\"'" Environment="PATH={{ brew_prefix }}/bin:%h/.local/bin:/usr/local/bin:/usr/bin:/bin" Environment="HOME={{ ansible_facts['env']['HOME'] }}" StandardOutput=journal diff --git a/scripts/bw-resolve.sh b/scripts/bw-resolve.sh index e343f3de..a43a55c9 100755 --- a/scripts/bw-resolve.sh +++ b/scripts/bw-resolve.sh @@ -47,8 +47,8 @@ if [ "$mode" = "remote" ]; then # Get local BW session for API key lookup local_session=$("$SCRIPT_DIR/bw-unlock.sh" 2>/dev/null || true) if [ -n "$local_session" ]; then - BW_CLIENTID=$(bw get username bw-api-key --session "$local_session" 2>/dev/null || true) - BW_CLIENTSECRET=$(bw get password bw-api-key --session "$local_session" 2>/dev/null || true) + BW_CLIENTID=$(BW_SESSION="$local_session" bw get username bw-api-key 2>/dev/null || true) + BW_CLIENTSECRET=$(BW_SESSION="$local_session" bw get password bw-api-key 2>/dev/null || true) if [ -n "$BW_CLIENTID" ] && [ -n "$BW_CLIENTSECRET" ]; then # Credentials go over stdin (never on either side's command line), and # bw's chatter goes to stderr so it can't pollute the session that @@ -72,7 +72,7 @@ if [ "$mode" = "remote" ]; then # Try non-interactive unlock using master password from local vault local_session=$("$SCRIPT_DIR/bw-unlock.sh" 2>/dev/null || true) if [ -n "$local_session" ]; then - BW_MASTER_PASS=$(bw get password "James Bitwarden" --session "$local_session" 2>/dev/null || true) + BW_MASTER_PASS=$(BW_SESSION="$local_session" bw get password "James Bitwarden" 2>/dev/null || true) if [ -n "$BW_MASTER_PASS" ]; then echo "Unlocking Bitwarden on $host (non-interactive)..." >&2 # Password is piped over stdin and read into a remote env var via diff --git a/scripts/bw-seed-omp-broker.sh b/scripts/bw-seed-omp-broker.sh new file mode 100755 index 00000000..3c5650c2 --- /dev/null +++ b/scripts/bw-seed-omp-broker.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Seed Bitwarden with the live omp auth-broker bearer token over tailnet SSH. +# Run on a client with an unlocked vault and SSH access to ubuntu@spindle. +# Usage: ./scripts/bw-seed-omp-broker.sh +# Re-run safely — updates the existing item in place. The server command prints +# the current token without rotating it. Clients fetch it with just apply-tags omp. +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +source "$SCRIPT_DIR/bw-item.sh" + +if [ -z "${BW_SESSION:-}" ]; then + # Assign then export: `export X=$(cmd)` would mask a failed unlock from set -e. + BW_SESSION=$("$SCRIPT_DIR/bw-unlock.sh") + export BW_SESSION +fi + +NAME="${OMP_AUTH_BROKER_BW_ITEM:-omp-auth-broker-token}" + +broker_host="${OMP_AUTH_BROKER_SSH:-ubuntu@100.113.75.88}" +token=$(ssh -o BatchMode=yes "$broker_host" '/home/ubuntu/.local/bin/omp auth-broker token') +if [ -z "$token" ]; then + echo "no token from broker host $broker_host" >&2 + exit 1 +fi + +# type 1 = login; the role reads it with `bw get password`. +payload=$(bw get template item \ + | jq --arg name "$NAME" --arg tok "$token" ' + . + { + name: $name, + type: 1, + notes: "Bearer token for the omp auth-broker on spindle. Managed by scripts/bw-seed-omp-broker.sh.", + login: {username: "omp-auth-broker", password: $tok} + }') + +bw_upsert_item "$NAME" "$payload" 1 +bw sync >/dev/null +echo "Done. Run \`just apply-tags omp\` on other machines to pick up the token." diff --git a/scripts/run-units.sh b/scripts/run-units.sh new file mode 100755 index 00000000..ac93b734 --- /dev/null +++ b/scripts/run-units.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Run the bash units (units/*.sh) through mise, in parallel, failure-isolated. +# Usage: scripts/run-units.sh [--no-secrets] [--tags a,b] +set -uo pipefail + +ALL_UNITS="omp" # run order for the sequential fallback; keep in step with mise.toml +tasks_for_tag() { case "$1" in # Ansible tag -> units (mirrors the old role tags) + dotfiles|omp) echo omp ;; +esac; } + +repo="$(cd "$(dirname "$0")/.." && pwd)" +export DOTFILES_DIR="$repo" +PATH=/home/linuxbrew/.linuxbrew/bin:$PATH + +tags="" +while [ $# -gt 0 ]; do + case "$1" in + --no-secrets) export UNITS_NO_SECRETS=1 ;; + --tags) tags="${2:-}"; shift ;; + *) echo "usage: $0 [--no-secrets] [--tags a,b]" >&2; exit 2 ;; + esac + shift +done + +wanted=" " +if [ -z "$tags" ]; then + wanted=" $ALL_UNITS " +else + IFS=',' read -ra tag_list <<< "$tags" + for t in "${tag_list[@]}"; do + for u in $(tasks_for_tag "$t"); do wanted="$wanted$u "; done + done +fi +selected=() +for u in $ALL_UNITS; do + case "$wanted" in *" $u "*) selected+=("$u") ;; esac +done +[ "${#selected[@]}" -gt 0 ] || exit 0 + +cd "$repo" || exit 1 +if command -v mise >/dev/null 2>&1; then + mise trust -q "$repo/mise.toml" >/dev/null 2>&1 || true + args=() + for u in "${selected[@]}"; do + [ "${#args[@]}" -gt 0 ] && args+=(":::") + args+=("unit:$u") + done + exec mise run --continue-on-error --jobs "${UNITS_JOBS:-8}" --output prefix --timeout 15m "${args[@]}" +fi + +echo "mise not installed; running units sequentially (brew install mise for parallel runs)" +rc=0 +for u in "${selected[@]}"; do + bash "$repo/units/$u.sh" || rc=1 +done +exit $rc diff --git a/site.yml b/site.yml index bc0581a1..46b332d3 100644 --- a/site.yml +++ b/site.yml @@ -75,9 +75,6 @@ tags: [dotfiles, shell, fonts] - role: shell_dotfiles tags: [dotfiles, shell, dotfiles] - - role: omp - tags: [dotfiles, omp] - when: not is_termux | bool - role: hive_ops tags: [hive, hive_ops] - role: git diff --git a/tests/test_bootstrap_units.py b/tests/test_bootstrap_units.py new file mode 100644 index 00000000..5e1f0058 --- /dev/null +++ b/tests/test_bootstrap_units.py @@ -0,0 +1,86 @@ +import subprocess +from pathlib import Path + +import pytest + +from conftest import REPO, write_stub + + +@pytest.fixture +def phase_env(stub_env, tmp_path): + bindir, env = stub_env + repo = tmp_path / "checkout" + scripts = repo / "scripts" + scripts.mkdir(parents=True) + log = tmp_path / "calls" + write_stub(bindir, "ansible-playbook", 'printf "ansible %s\\n" "$*" >> "$CALLS"\nexit "${ANSIBLE_RC:-0}"\n') + write_stub(scripts, "run-units.sh", 'printf "units %s\\n" "$*" >> "$CALLS"\nexit "${UNITS_RC:-0}"\n') + env.update(CALLS=str(log), TEST_REPO=str(repo), BW_SESSION="test-session") + return env, log + + +def run_phase(env, phase): + return subprocess.run( + ["bash", "-c", 'source "$1/bootstrap.sh" --name test --type desktop; DOTFILES_DIR="$TEST_REPO"; MACHINE_NAME=test; MACHINE_TYPE=desktop; "$2"', + "bash", str(REPO), phase], + env=env, capture_output=True, text=True, + ) + + +@pytest.mark.parametrize("phase,unit_args", [("run_phase1", "--no-secrets"), ("run_phase2", "--tags omp,secrets")]) +@pytest.mark.parametrize("ansible_rc,units_rc,expected", [(0, 0, 0), (7, 0, 7), (0, 9, 9), (7, 9, 7)]) +def test_bootstrap_phases_continue_and_combine_errors(phase_env, phase, unit_args, ansible_rc, units_rc, expected): + env, log = phase_env + env.update(ANSIBLE_RC=str(ansible_rc), UNITS_RC=str(units_rc)) + result = run_phase(env, phase) + assert result.returncode == expected + calls = log.read_text().splitlines() + assert len(calls) == 2 + assert calls[0].startswith("ansible ") + assert calls[1] == f"units {unit_args}" + assert "test-session" not in "\n".join(calls) + if phase == "run_phase1": + assert "--skip-tags secrets" in calls[0] + else: + assert "--tags secrets" in calls[0] + + +def test_bootstrap_runs_second_phase_after_first_fails(stub_env, tmp_path): + _, env = stub_env + env["CALLS"] = str(tmp_path / "calls") + script = r''' +source "$1/bootstrap.sh" --name test --type desktop +for f in ensure_python ensure_git ensure_uv ensure_ansible clone_repo get_machine_name get_machine_type register_in_inventory write_machine_name set_hostname ensure_sudo ensure_tailscale install_collections setup_bitwarden push_inventory_changes; do + eval "$f() { :; }" +done +run_phase1() { echo first >> "$CALLS"; return 7; } +run_phase2() { echo second >> "$CALLS"; return 0; } +main +''' + result = subprocess.run(["bash", "-c", script, "bash", str(REPO)], env=env, capture_output=True, text=True) + assert result.returncode == 7 + assert Path(env["CALLS"]).read_text().splitlines() == ["first", "second"] + assert "Bootstrap complete!" not in result.stdout + + +@pytest.mark.parametrize("no_secrets", [False, True]) +def test_unit_session_respects_no_secrets_and_keeps_session_off_argv(stub_env, tmp_path, no_secrets): + bindir, env = stub_env + log = tmp_path / "bw-calls" + write_stub(bindir, "bw", 'printf "%s\\n" "$*" >> "$CALLS"\n[ "${BW_SESSION:-}" = "test-session" ]\n') + env.update(BW_SESSION="test-session", CALLS=str(log)) + if no_secrets: + env["UNITS_NO_SECRETS"] = "1" + else: + env.pop("UNITS_NO_SECRETS", None) + result = subprocess.run( + ["bash", "-c", 'source "$1/units/lib.sh"; bw_session', "bash", str(REPO)], + env=env, capture_output=True, text=True, + ) + assert result.returncode == 0 + if no_secrets: + assert result.stdout == "" + assert not log.exists() + else: + assert result.stdout == "test-session" + assert log.read_text().splitlines() == ["unlock --check"] diff --git a/tests/test_omp_seed.py b/tests/test_omp_seed.py new file mode 100644 index 00000000..564df672 --- /dev/null +++ b/tests/test_omp_seed.py @@ -0,0 +1,15 @@ +import subprocess + +from conftest import REPO, write_stub + + +def test_seed_does_not_change_vault_when_broker_is_unreachable(stub_env, tmp_path): + bindir, env = stub_env + write_stub(bindir, "ssh", "exit 42\n") + write_stub(bindir, "bw", 'touch "$HOME/bw-called"\nexit 0\n') + result = subprocess.run( + ["bash", str(REPO / "scripts/bw-seed-omp-broker.sh")], + env={**env, "BW_SESSION": "test"}, capture_output=True, text=True, + ) + assert result.returncode != 0 + assert not (tmp_path / "home/bw-called").exists() diff --git a/tests/test_omp_unit.py b/tests/test_omp_unit.py new file mode 100644 index 00000000..0347c392 --- /dev/null +++ b/tests/test_omp_unit.py @@ -0,0 +1,74 @@ +import shutil +import subprocess + +import pytest +import yaml + +from conftest import REPO, write_stub + +pytestmark = pytest.mark.skipif(shutil.which("yq") is None, reason="yq not installed") + +BROKER_URL = "http://100.113.75.88:8765" + +OMP_STUB = """\ +case "$1 $2" in + "--version "*) echo omp/0 ;; + "plugin list") echo '["omp-kiro-provider"]' ;; + "auth-broker status") echo "OK stub" ;; +esac +exit 0 +""" + + +def run_unit(env): + env = {**env, "DOTFILES_DIR": str(REPO), "UNITS_NO_SECRETS": "1"} + return subprocess.run( + ["bash", str(REPO / "units/omp.sh")], env=env, capture_output=True, text=True + ) + + +def broker_url(home): + cfg = yaml.safe_load((home / ".omp/agent/config.yml").read_text()) + return cfg["auth"]["broker"]["url"] + + +@pytest.fixture +def env(stub_env): + bindir, env = stub_env + write_stub(bindir, "omp", OMP_STUB) + return env + + +def snapshot(home): + paths = [".omp/agent/config.yml", ".config/omp/kiro.json", ".local/bin/omp-route"] + return {p: (home / p).read_bytes() for p in paths} + + +def test_fresh_home_is_configured(env, tmp_path): + home = tmp_path / "home" + r = run_unit(env) + assert r.returncode == 0, r.stdout + r.stderr + # himachal regression: ~/.config did not exist and the role aborted. + assert (home / ".config/omp/kiro.json").is_file() + assert (home / ".local/bin/omp-route").stat().st_mode & 0o111 + assert broker_url(home) == BROKER_URL + assert (home / ".omp/agent/config.yml").stat().st_mode & 0o777 == 0o600 + assert "PARTIAL:" in r.stdout + + +def test_second_run_changes_nothing(env, tmp_path): + home = tmp_path / "home" + assert run_unit(env).returncode == 0 + before = snapshot(home) + assert run_unit(env).returncode == 0 + assert snapshot(home) == before + + +def test_failing_step_does_not_stop_later_steps(env, tmp_path): + home = tmp_path / "home" + (home / ".claude").write_text("not a directory") + r = run_unit(env) + assert r.returncode == 1 + assert "FAIL claude skill links" in r.stdout + assert (home / ".config/omp/kiro.json").is_file() + assert broker_url(home) == BROKER_URL diff --git a/tests/test_tagged_apply.py b/tests/test_tagged_apply.py new file mode 100644 index 00000000..f4684ec7 --- /dev/null +++ b/tests/test_tagged_apply.py @@ -0,0 +1,124 @@ +import shutil +import subprocess +from pathlib import Path + +import pytest + +from conftest import REPO, write_stub + + +pytestmark = pytest.mark.skipif(shutil.which("just") is None, reason="just not installed") + + +@pytest.fixture +def apply_env(stub_env, tmp_path): + _, env = stub_env + home = Path(env["HOME"]) + bindir = home / ".local/bin" + bindir.mkdir(parents=True) + repo = home / ".local/share/dotfiles" + scripts = repo / "scripts" + scripts.mkdir(parents=True) + (scripts / "online_hosts.py").write_text("") + shutil.copyfile(REPO / "Justfile", repo / "Justfile") + log = tmp_path / "calls" + env.update(CALLS=str(log), BW_SESSION="stale") + write_stub(bindir, "bw", ''' +printf 'bw %s\n' "$*" >> "$CALLS" +case "$*" in + 'unlock --check') [ "${BW_SESSION:-}" = valid-session ] ;; + sync) [ "${SYNC_FAIL:-0}" = 0 ] ;; + *) exit 1 ;; +esac +''') + write_stub(bindir, "ansible-playbook", 'printf "ansible %s\\n" "$*" >> "$CALLS"\nexit "${ANSIBLE_RC:-0}"\n') + write_stub(bindir, "git", 'exit 0\n') + write_stub(bindir, "ansible-galaxy", 'exit 0\n') + write_stub(bindir, "sudo", 'exit 0\n') + write_stub(bindir, "ssh", 'printf "ssh\\n" >> "$CALLS"\n') + write_stub(scripts, "bw-resolve.sh", ''' +printf 'resolve\n' >> "$CALLS" +[ "${RESOLVE_FAIL:-0}" = 0 ] || exit 1 +printf 'export BW_SESSION=valid-session\n' +''') + write_stub(scripts, "run-units.sh", 'printf "units %s\\n" "$*" >> "$CALLS"\n') + write_stub(scripts, "record-apply.py", 'exit 0\n') + return env, repo, log + + +def run_apply(env, repo, *args): + return subprocess.run(["just", "-f", str(repo / "Justfile"), *args], env=env, capture_output=True, text=True) + + +def test_secret_tag_validates_syncs_and_initializes_legacy_roles(apply_env): + env, repo, log = apply_env + result = run_apply(env, repo, "apply-tags", "omp,kube") + assert result.returncode == 0, result.stderr + calls = log.read_text().splitlines() + assert calls[:4] == ["bw unlock --check", "resolve", "bw unlock --check", "bw sync"] + assert "--tags omp,kube,bitwarden" in calls[4] + assert calls[5] == "units --tags omp,kube" + assert "valid-session" not in result.stdout + result.stderr + "\n".join(calls) + + +def test_nonsecret_tag_does_not_prompt_or_sync(apply_env): + env, repo, log = apply_env + result = run_apply(env, repo, "apply-tags", "git") + assert result.returncode == 0, result.stderr + calls = log.read_text().splitlines() + assert len(calls) == 2 + assert "--tags git" in calls[0] + assert calls[1] == "units --tags git" + + +def test_remote_nonsecret_tag_does_not_resolve_vault(apply_env): + env, repo, log = apply_env + result = run_apply(env, repo, "apply-remote-tags", "phone", "git") + assert result.returncode == 0, result.stderr + assert log.read_text().splitlines() == ["ssh"] + + +def test_failed_sync_runs_nonsecret_work_and_fails(apply_env): + env, repo, log = apply_env + env["SYNC_FAIL"] = "1" + result = run_apply(env, repo, "apply-tags", "omp,kube") + assert result.returncode != 0 + calls = log.read_text().splitlines() + assert "--skip-tags secrets" in calls[-2] + assert calls[-1] == "units --tags omp,kube --no-secrets" + + +def test_full_apply_skips_vault_units_when_unlock_fails(apply_env): + env, repo, log = apply_env + env["RESOLVE_FAIL"] = "1" + result = run_apply(env, repo, "apply") + assert result.returncode == 0, result.stderr + calls = log.read_text().splitlines() + assert "--skip-tags secrets" in calls[-2] + assert calls[-1] == "units --no-secrets" + + +@pytest.mark.parametrize("drop_session", [False, True]) +def test_remote_secret_apply_rejects_lost_ssh_session(apply_env, drop_session): + env, repo, _ = apply_env + bindir = Path(env["HOME"]) / ".local/bin" + write_stub(repo / "scripts", "bw-resolve.sh", 'printf "sentinel-session"\n') + write_stub(bindir, "ssh", ''' +case "$*" in *sentinel-session*) exit 90 ;; esac +if [ "${DROP_SESSION:-0}" = 1 ]; then unset BW_SESSION; fi +exec bash -c "${!#}" +''') + write_stub(bindir, "just", ''' +[ "${BW_SESSION:-}" = sentinel-session ] || exit 91 +touch "$HOME/remote-applied" +''') + env["DROP_SESSION"] = "1" if drop_session else "0" + result = subprocess.run( + [shutil.which("just"), "-f", str(repo / "Justfile"), "apply-remote-tags", "phone", "omp"], + env=env, capture_output=True, text=True, + ) + assert (result.returncode == 0) is not drop_session + assert (Path(env["HOME"]) / "remote-applied").exists() is not drop_session + assert "sentinel-session" not in result.stdout + result.stderr + if drop_session: + assert "did not accept BW_SESSION" in result.stderr diff --git a/tests/test_units_registry.py b/tests/test_units_registry.py new file mode 100644 index 00000000..c1522032 --- /dev/null +++ b/tests/test_units_registry.py @@ -0,0 +1,36 @@ +import re +import tomllib + +from conftest import REPO + + +def mise_units(): + tasks = tomllib.loads((REPO / "mise.toml").read_text())["tasks"] + return {k.removeprefix("unit:"): v for k, v in tasks.items() if k.startswith("unit:")} + + +def wrapper(): + return (REPO / "scripts/run-units.sh").read_text() + + +def all_units(): + return set(re.search(r'^ALL_UNITS="([^"]*)"', wrapper(), re.M).group(1).split()) + + +def test_every_unit_is_registered_everywhere(): + on_disk = {p.stem for p in (REPO / "units").glob("*.sh")} - {"lib"} + assert set(mise_units()) == on_disk == all_units() + + +def test_mise_task_files_exist(): + for name, task in mise_units().items(): + assert task["file"] == f"units/{name}.sh" + assert (REPO / task["file"]).is_file() + + +def test_tag_map_only_names_known_units(): + case = re.search(r"tasks_for_tag\(\) \{ case .*?esac; \}", wrapper(), re.S).group(0) + named = set() + for echoed in re.findall(r'echo "?([a-z0-9 -]+?)"? ?;;', case): + named.update(echoed.split()) + assert named and named <= all_units() diff --git a/units/lib.sh b/units/lib.sh new file mode 100644 index 00000000..ca312c96 --- /dev/null +++ b/units/lib.sh @@ -0,0 +1,25 @@ +# shellcheck shell=bash +# Shared helpers for units/*.sh. Source this; do not execute it. +# Units use `set -uo pipefail` and never `set -e`: a failing step is recorded +# and the later independent steps still run. +UNIT_FAILED=0 +step() { local d="$1"; shift; if "$@"; then echo "ok $d"; else echo "FAIL $d (exit $?)"; UNIT_FAILED=1; fi; } +soft() { local d="$1"; shift; if "$@"; then echo "ok $d"; else echo "warn $d (exit $?, ignored)"; fi; } +finish() { [ "$UNIT_FAILED" = 0 ] || exit 1; exit 0; } # failed steps fail the unit; everything else is exit 0 +note() { echo "$*"; } # e.g. note "PARTIAL: vault locked, broker token not written" +install_if_changed() { # src dest mode + if [ -f "$2" ] && cmp -s "$1" "$2"; then chmod "$3" "$2"; return 0; fi + mkdir -p "$(dirname "$2")" && install -m "$3" "$1" "$2" +} +DOTFILES_DIR="${DOTFILES_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}" +IS_TERMUX=0; [ -d /data/data/com.termux/files/usr ] && IS_TERMUX=1 +IS_MUSL=0; { [ -e /lib/ld-musl-x86_64.so.1 ] || [ -e /lib/ld-musl-aarch64.so.1 ]; } && IS_MUSL=1 +# bw_session: print a usable Bitwarden session or nothing. Never prompts. +bw_session() { + [ "${UNITS_NO_SECRETS:-0}" = 1 ] && return 0 + command -v bw >/dev/null 2>&1 || return 0 + local s="${BW_SESSION:-}" + [ -n "$s" ] || { [ -s /tmp/bw_session ] && s="$(cat /tmp/bw_session)"; } + [ -n "$s" ] && BW_SESSION="$s" bw unlock --check >/dev/null 2>&1 && printf '%s' "$s" + return 0 +} diff --git a/units/omp.sh b/units/omp.sh new file mode 100755 index 00000000..b97b34e4 --- /dev/null +++ b/units/omp.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +# omp unit: install, skills, Kiro plugin, routing, auth-broker client config. +set -uo pipefail +# shellcheck source=units/lib.sh +. "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +PATH="$HOME/.bun/bin:$HOME/.local/bin:/home/linuxbrew/.linuxbrew/bin:$PATH" +cfg="$HOME/.omp/agent/config.yml" +skills_dest="$HOME/.omp/agent/skills/james" + +if [ "$IS_TERMUX" = 1 ]; then + note "SKIPPED: omp has no Android build" + exit 0 +fi + +# shellcheck source=units/omp/auth-broker.conf +. "$DOTFILES_DIR/units/omp/auth-broker.conf" + +omp_install() { + if ! command -v omp >/dev/null 2>&1 && [ "$IS_MUSL" = 1 ]; then + mkdir -p "$HOME/.cache" || return 1 + curl -fsSL https://omp.sh/install -o "$HOME/.cache/omp-install.sh" || return 1 + PI_INSTALL_DIR="$HOME/.local/bin" sh "$HOME/.cache/omp-install.sh" --binary || return 1 + if [ ! -x "$HOME/.bun/bin/bun" ]; then + curl -fsSL https://bun.sh/install -o "$HOME/.cache/bun-install.sh" || return 1 + bash "$HOME/.cache/bun-install.sh" || return 1 + fi + fi + if ! command -v omp >/dev/null 2>&1; then + echo "omp not installed; run: just packages" >&2 + return 1 + fi +} + +skills_sync() { + local src="$DOTFILES_DIR/roles/pi/files/skills" + mkdir -p "$skills_dest" || return 1 + if command -v rsync >/dev/null 2>&1; then + rsync -a "$src/" "$skills_dest/" || return 1 + else + cp -a "$src/." "$skills_dest/" || return 1 + fi + find "$skills_dest" -type f \( -name '*.sh' -o -name '*.mjs' \) -exec chmod 755 {} + +} + +claude_links() { + local d rc=0 + mkdir -p "$HOME/.claude/skills" || return 1 + for d in "$skills_dest"/*/; do + [ -d "$d" ] || continue + d="${d%/}" + ln -sfn "$d" "$HOME/.claude/skills/$(basename "$d")" || rc=1 + done + return $rc +} + +kiro_plugin() { + if omp plugin list --json 2>/dev/null | grep -q omp-kiro-provider; then + return 0 + fi + omp plugin install github:elkibalion/omp-kiro-provider +} + +ccleft_install() { + [ -x "$HOME/go/bin/ccleft" ] && return 0 + command -v go >/dev/null 2>&1 || return 0 + go install github.com/tuna-os/ccleft/cmd/ccleft@latest +} + +routing_merge() { + mkdir -p "$(dirname "$cfg")" || return 1 + [ -f "$cfg" ] || : > "$cfg" || return 1 + yq -i ". *= (load(\"$DOTFILES_DIR/units/omp/routing.yml\") | explode(.) | ... comments=\"\")" "$cfg" +} + +broker_url() { + mkdir -p "$(dirname "$cfg")" || return 1 + [ -f "$cfg" ] || : > "$cfg" || return 1 + URL="$OMP_AUTH_BROKER_URL" yq -i '.auth.broker.url = strenv(URL)' "$cfg" || return 1 + chmod 600 "$cfg" +} + +broker_token() { + local s tok + s="$(bw_session)" + [ -n "$s" ] || return 0 + tok="$(BW_SESSION="$s" bw get password "$OMP_AUTH_BROKER_BW_ITEM" 2>/dev/null)" + [ -n "$tok" ] || return 0 + TOKEN="$tok" yq -i '.auth.broker.token = strenv(TOKEN)' "$cfg" || return 1 + chmod 600 "$cfg" +} + +broker_status() { + omp auth-broker status +} + +have_omp() { command -v omp >/dev/null 2>&1; } + +step "omp installed" omp_install +step "skills synced" skills_sync +step "claude skill links" claude_links +if have_omp; then step "kiro plugin" kiro_plugin; else note "skip kiro plugin (omp missing)"; fi +soft "ccleft" ccleft_install +step "kiro.json" install_if_changed "$DOTFILES_DIR/units/omp/kiro.json" "$HOME/.config/omp/kiro.json" 0644 +step "omp-route" install_if_changed "$DOTFILES_DIR/units/omp/omp-route" "$HOME/.local/bin/omp-route" 0755 +step "routing merged" routing_merge +step "broker url" broker_url +step "broker token" broker_token +if [ "$(yq '.auth.broker | has("token")' "$cfg" 2>/dev/null)" != true ]; then + note "PARTIAL: broker token not written (vault locked or item missing); run: just seed-omp-broker from a client with SSH access to spindle, then just apply-tags omp" +fi +if have_omp; then soft "broker status" broker_status; else note "skip broker status (omp missing)"; fi +finish diff --git a/units/omp/auth-broker.conf b/units/omp/auth-broker.conf new file mode 100644 index 00000000..4fd6cd1e --- /dev/null +++ b/units/omp/auth-broker.conf @@ -0,0 +1,3 @@ +# The broker runs on spindle's tailnet address. It is not in inventory.yml. +OMP_AUTH_BROKER_URL="${OMP_AUTH_BROKER_URL:-http://100.113.75.88:8765}" +OMP_AUTH_BROKER_BW_ITEM="${OMP_AUTH_BROKER_BW_ITEM:-omp-auth-broker-token}" diff --git a/roles/omp/files/kiro.json b/units/omp/kiro.json similarity index 100% rename from roles/omp/files/kiro.json rename to units/omp/kiro.json diff --git a/roles/omp/files/omp-route b/units/omp/omp-route similarity index 100% rename from roles/omp/files/omp-route rename to units/omp/omp-route diff --git a/roles/omp/files/routing.yml b/units/omp/routing.yml similarity index 95% rename from roles/omp/files/routing.yml rename to units/omp/routing.yml index b1a4e408..4338163a 100644 --- a/roles/omp/files/routing.yml +++ b/units/omp/routing.yml @@ -1,4 +1,4 @@ -# Merged into ~/.omp/agent/config.yml by roles/omp (yq deep-merge; lists replace). +# Merged into ~/.omp/agent/config.yml by units/omp (yq deep-merge; lists replace). # Order everywhere: Claude Max → Codex → Antigravity → Kiro → Muse contributor. # omp-route (aliased to `omp`) picks the starting model from ccleft quota; # these chains handle exhaustion mid-session.