#!/usr/bin/env bash set -euo pipefail script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P) workspace=${WEALTH_LEDGER_WORKSPACE:-$(cd "$script_dir/../.." && pwd -P)} source_root="$workspace/specs/agent-projection/opencode" projection_root="$workspace/.opencode" for tree in commands skills; do if [[ ! -d "$source_root/$tree" ]]; then printf 'Missing canonical projection tree: %s\n' "${source_root#$workspace/}/$tree" >&2 exit 1 fi done mkdir -p "$projection_root" stage=$(mktemp -d "$projection_root/.projection-stage.XXXXXX") backup=$(mktemp -d "$projection_root/.projection-backup.XXXXXX") commands_existed=0 skills_existed=0 cutover_started=0 cleanup_temporary() { rm -rf "$stage" "$backup" } rollback() { if [[ $cutover_started -eq 1 ]]; then rm -rf "$projection_root/commands" "$projection_root/skills" if [[ $commands_existed -eq 1 && -d "$backup/commands" ]]; then mv "$backup/commands" "$projection_root/commands" fi if [[ $skills_existed -eq 1 && -d "$backup/skills" ]]; then mv "$backup/skills" "$projection_root/skills" fi fi cleanup_temporary } trap rollback EXIT cp -R "$source_root/commands" "$stage/commands" cp -R "$source_root/skills" "$stage/skills" if [[ -d "$projection_root/commands" ]]; then commands_existed=1 cp -R "$projection_root/commands" "$backup/commands" fi if [[ "${WEALTH_LEDGER_SYNC_FAIL_DURING_BACKUP:-0}" == '1' ]]; then printf 'Injected projection backup failure; local projection was not modified.\n' >&2 exit 1 fi if [[ -d "$projection_root/skills" ]]; then skills_existed=1 cp -R "$projection_root/skills" "$backup/skills" fi cutover_started=1 rm -rf "$projection_root/commands" "$projection_root/skills" if ! mv "$stage/commands" "$projection_root/commands"; then printf 'Projection sync failed while installing commands; previous state will be restored.\n' >&2 exit 1 fi if [[ "${WEALTH_LEDGER_SYNC_FAIL_AFTER_COMMANDS:-0}" == '1' ]]; then printf 'Injected projection sync failure after commands; previous state will be restored.\n' >&2 exit 1 fi if ! mv "$stage/skills" "$projection_root/skills"; then printf 'Projection sync failed while installing skills; previous state will be restored.\n' >&2 exit 1 fi if ! WEALTH_LEDGER_WORKSPACE="$workspace" bash "$script_dir/verify-agent-projection.sh"; then printf 'Projection verification failed after cutover; previous state will be restored.\n' >&2 exit 1 fi cutover_started=0 trap - EXIT cleanup_temporary printf 'Agent projection synchronized from specs authority.\n'