@astrofoundry/astrogate 0.1.5 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/astrogate.sh CHANGED
@@ -9,12 +9,17 @@
9
9
  # (sudo astrogate core activate <x.y.z> the second half of update: the new version's own code installs
10
10
  # its tools and switches to it; update runs it, nobody else needs to)
11
11
  # astrogate tools each tool's installed version and the version the core pins
12
+ # sudo astrogate workspace create <ws> the workspace's two users, their sudo rule, the agent user's Pi
13
+ # and gate files, and the keys user's Vaultwarden login (asked once)
14
+ # astrogate workspace list the workspaces on this host
15
+ # sudo astrogate pack update <ws> <x.y.z> the workspace's signed pack from /private/var/tmp/astrogate-packs
12
16
  # astrogate doctor read-only checks; exits 1 when one fails
13
17
  #
14
18
  # The first install runs this script from a tarball the owner checked with the repo's
15
19
  # verify-release.sh, and adds `--signers <the repo's allowed_signers>`; root keeps that file
16
20
  # in /usr/local/etc/astrogate. Root runs only system programs and files in root-owned folders;
17
- # it runs a new tool only as nobody. macOS on Apple silicon only for now.
21
+ # it runs a new tool only as nobody. macOS on Apple silicon only for now. workspace.sh holds the
22
+ # workspace and pack commands.
18
23
  set -eu
19
24
  PATH=/usr/bin:/bin:/usr/sbin:/sbin
20
25
  export PATH
@@ -30,7 +35,7 @@ REGISTRY=https://registry.npmjs.org
30
35
  TOOL_NAMES="node jq bw python gcloud"
31
36
 
32
37
  usage() {
33
- echo "usage: astrogate core [status] | core update [<x.y.z>] [--signers <allowed_signers>] | core rollback | tools | doctor" >&2
38
+ echo "usage: astrogate core [status] | core update [<x.y.z>] [--signers <allowed_signers>] | core rollback | tools | workspace create <ws> | workspace list | pack update <ws> <x.y.z> | doctor" >&2
34
39
  exit 2
35
40
  }
36
41
 
@@ -67,6 +72,8 @@ version_lt() {
67
72
  action=""
68
73
  version=""
69
74
  signers_arg=""
75
+ ws=""
76
+ invocation="$*"
70
77
  case "${1:-}" in
71
78
  core)
72
79
  action=${2:-status}
@@ -98,6 +105,21 @@ case "${1:-}" in
98
105
  [ $# -eq 1 ] || usage
99
106
  action=$1
100
107
  ;;
108
+ workspace)
109
+ case "${2:-}" in
110
+ create) [ $# -eq 3 ] && [ -n "$3" ] || usage ;;
111
+ list) [ $# -eq 2 ] || usage ;;
112
+ *) usage ;;
113
+ esac
114
+ action=workspace-$2
115
+ ws=${3:-}
116
+ ;;
117
+ pack)
118
+ [ "${2:-}" = update ] && [ $# -eq 4 ] && valid_version "$4" || usage
119
+ action=pack-update
120
+ ws=$3
121
+ version=$4
122
+ ;;
101
123
  *) usage ;;
102
124
  esac
103
125
 
@@ -110,6 +132,7 @@ while [ -L "$self" ]; do
110
132
  case "$target" in /*) self=$target ;; *) self=$(/usr/bin/dirname "$self")/$target ;; esac
111
133
  done
112
134
  HERE=$(cd "$(/usr/bin/dirname "$self")" && /bin/pwd -P)
135
+ . "$HERE/workspace.sh"
113
136
 
114
137
  # The version a link in $BASE names (current or previous), or nothing.
115
138
  link_version() {
@@ -187,7 +210,7 @@ prune() {
187
210
  }
188
211
 
189
212
  require_root() {
190
- [ "$(/usr/bin/id -u)" = 0 ] || fail "run it as root: sudo astrogate core $action"
213
+ [ "$(/usr/bin/id -u)" = 0 ] || fail "run it as root: sudo astrogate $invocation"
191
214
  [ "$(/usr/bin/uname -m)" = arm64 ] || fail "only Apple silicon is supported yet"
192
215
  }
193
216
 
@@ -213,17 +236,22 @@ pinned_version() {
213
236
  /usr/bin/awk -v t="$2" '$1 == t && NF == 4 { print $2; exit }' "$1/tools.lock"
214
237
  }
215
238
 
216
- # Fails unless core folder $1 has no tools.lock, or one whose lines are all
217
- # "<tool> <version> <sha256> <https url>" with one valid version per tool.
218
- check_lock() {
219
- [ -f "$1/tools.lock" ] || return 0
220
- bad_line=$(/usr/bin/awk -v names=" $TOOL_NAMES " '
239
+ # Fails unless lock file $1 has only "<tool> <version> <sha256> <https url>" lines, with tools
240
+ # among the names $2, hosts the pattern $3 matches, and one version per tool. A pattern writes a
241
+ # dot as [.]: awk would read a backslash in a -v value as an escape.
242
+ check_lock_lines() {
243
+ bad_line=$(/usr/bin/awk -v names=" $2 " -v url="^https://($3)/[A-Za-z0-9./_+@-]+$" '
221
244
  /^#/ || NF == 0 { next }
222
- NF != 4 || index(names, " " $1 " ") == 0 || length($3) != 64 || $3 !~ /^[0-9a-f]+$/ { print NR; exit }
223
- $4 !~ /^https:\/\/(nodejs\.org|github\.com|dl\.google\.com)\/[A-Za-z0-9.\/_+-]+$/ { print NR; exit }
245
+ NF != 4 || index(names, " " $1 " ") == 0 || length($3) != 64 || $3 !~ /^[0-9a-f]+$/ || $4 !~ url { print NR; exit }
224
246
  ($1 in seen) && seen[$1] != $2 { print NR; exit }
225
- { seen[$1] = $2 }' "$1/tools.lock")
226
- [ -z "$bad_line" ] || fail "$1/tools.lock line $bad_line is no <tool> <version> <sha256> <https url>, or pins a second version"
247
+ { seen[$1] = $2 }' "$1")
248
+ [ -z "$bad_line" ] || fail "$1 line $bad_line is no <tool> <version> <sha256> <https url>, or pins a second version"
249
+ }
250
+
251
+ # Fails unless core folder $1 has no tools.lock, or one with valid lines and versions.
252
+ check_lock() {
253
+ [ -f "$1/tools.lock" ] || return 0
254
+ check_lock_lines "$1/tools.lock" "$TOOL_NAMES" 'nodejs[.]org|github[.]com|dl[.]google[.]com'
227
255
  for tool in $TOOL_NAMES; do
228
256
  pin=$(pinned_version "$1" "$tool")
229
257
  [ -z "$pin" ] || tool_version_ok "$tool" "$pin" || fail "$1/tools.lock pins $tool $pin, which is no valid version"
@@ -405,7 +433,7 @@ core_update() {
405
433
  /bin/mv "$work/check/package" "$target.new"
406
434
  /usr/sbin/chown -R root:wheel "$target.new"
407
435
  /bin/chmod -R u+rwX,go+rX,go-w "$target.new"
408
- /bin/chmod 0755 "$target.new/cli/astrogate.sh" "$target.new/cli/verify-release.sh"
436
+ /bin/chmod 0755 "$target.new/cli/astrogate.sh" "$target.new/cli/verify-release.sh" "$target.new/specialists/entry/astrogate-run.sh"
409
437
  /bin/rm -rf "$target"
410
438
  /bin/mv "$target.new" "$target"
411
439
  # The checked version's own code finishes, so a release's new install steps apply to itself.
@@ -442,6 +470,10 @@ core_activate() {
442
470
  /bin/ln -shf "$BASE/current/cli/astrogate.sh" "$COMMAND"
443
471
  echo "linked $COMMAND"
444
472
  fi
473
+ if [ "$(/usr/bin/readlink "$ENTRY" 2>/dev/null || true)" != "$BASE/current/specialists/entry/astrogate-run.sh" ]; then
474
+ /bin/ln -shf "$BASE/current/specialists/entry/astrogate-run.sh" "$ENTRY"
475
+ echo "linked $ENTRY"
476
+ fi
445
477
  echo "core ${current:-none} -> $version${current:+; astrogate core rollback goes back to $current}"
446
478
  }
447
479
 
@@ -542,5 +574,8 @@ case "$action" in
542
574
  activate) core_activate ;;
543
575
  rollback) core_rollback ;;
544
576
  tools) tools_status ;;
577
+ workspace-create) workspace_create ;;
578
+ workspace-list) workspace_list ;;
579
+ pack-update) pack_update ;;
545
580
  doctor) doctor ;;
546
581
  esac
@@ -9,7 +9,7 @@ const isRoot = process.getuid?.() === 0;
9
9
  const isMac = process.platform === "darwin";
10
10
  const REPO = join(import.meta.dirname, "..");
11
11
  const SHA = "a".repeat(64);
12
- const TOOL_FUNCTIONS = ["fail", "valid_version", "valid_python_version", "tool_version_ok", "pinned_version", "check_lock"];
12
+ const TOOL_FUNCTIONS = ["fail", "valid_version", "valid_python_version", "tool_version_ok", "pinned_version", "check_lock_lines", "check_lock"];
13
13
 
14
14
  function astrogate(...args: string[]) {
15
15
  return spawnSync("/bin/sh", [SCRIPT, ...args], { encoding: "utf-8" });
@@ -49,6 +49,14 @@ describe("astrogate", () => {
49
49
  [["core", "activate", "1.2"]],
50
50
  [["doctor", "now"]],
51
51
  [["tools", "now"]],
52
+ [["workspace"]],
53
+ [["workspace", "create"]],
54
+ [["workspace", "create", "a", "b"]],
55
+ [["workspace", "list", "now"]],
56
+ [["workspace", "remove", "work"]],
57
+ [["pack", "update", "homelab"]],
58
+ [["pack", "update", "homelab", "1.2"]],
59
+ [["pack", "rollback", "homelab"]],
52
60
  [["update"]],
53
61
  ])("refuses %j with a usage error before anything else", (args) => {
54
62
  const result = astrogate(...args);
@@ -56,10 +64,10 @@ describe("astrogate", () => {
56
64
  expect(result.stderr).toMatch(/^usage: astrogate/);
57
65
  });
58
66
 
59
- it.runIf(isMac && !isRoot).each([["update"], ["update", "1.2.3", "--signers", "x"], ["rollback"], ["activate", "1.2.3"]])("refuses core %s without root", (...args) => {
60
- const result = astrogate("core", ...args);
67
+ it.runIf(isMac && !isRoot).each([["core", "update"], ["core", "update", "1.2.3", "--signers", "x"], ["core", "rollback"], ["core", "activate", "1.2.3"], ["workspace", "create", "work"], ["pack", "update", "work", "1.2.3"]])("refuses %s without root", (...args) => {
68
+ const result = astrogate(...args);
61
69
  expect(result.status).toBe(1);
62
- expect(result.stderr).toContain("run it as root: sudo astrogate core");
70
+ expect(result.stderr).toContain(`run it as root: sudo astrogate ${args.join(" ")}`);
63
71
  });
64
72
 
65
73
  it.each([
@@ -0,0 +1,442 @@
1
+ # Sourced by astrogate.sh: workspaces and their packs. A workspace <ws> is two hidden users:
2
+ # astrogate-<ws> runs the agents and the bridge, astrogate-<ws>-keys holds the credentials and
3
+ # the specialists' wrappers. The agent user reaches the wrappers only through
4
+ # astrogate-<ws> ALL=(astrogate-<ws>-keys) NOPASSWD: /usr/local/bin/astrogate-run
5
+ # Root works inside a workspace home only as that home's user, from a staging folder it hands
6
+ # over, so a link planted there cannot redirect a root write.
7
+
8
+ ENTRY=/usr/local/bin/astrogate-run
9
+ PACK_DROP=/private/var/tmp/astrogate-packs
10
+ NODE=$TOOLS/node/current/bin/node
11
+ JQ=$TOOLS/jq/current/jq
12
+ # The admin rules: the user who installs the first workspace may update the core and the packs
13
+ # without a password. sudoers.d files load in name order and the last match wins, so the name
14
+ # sorts after files such as `cortex` that hold a general rule with a password.
15
+ ADMIN_RULES=/etc/sudoers.d/zz-astrogate
16
+
17
+ # A workspace name: short, lower case, and not "host", which the host bridge's user takes.
18
+ # The character checks also rule out newlines, which would let grep match one line of several.
19
+ valid_workspace() {
20
+ [ "$1" != host ] || return 1
21
+ case "$1" in '' | *[!a-z0-9]*) return 1 ;; esac
22
+ printf '%s\n' "$1" | /usr/bin/grep -Eq '^[a-z][a-z0-9]{1,15}$'
23
+ }
24
+
25
+ # A pack service name; the other names in the wrapper folder are taken.
26
+ valid_service() {
27
+ case "$1" in '' | lib | provision | VERSION | rollback | *[!a-z0-9-]*) return 1 ;; esac
28
+ printf '%s\n' "$1" | /usr/bin/grep -Eq '^[a-z][a-z0-9-]{0,30}$'
29
+ }
30
+
31
+ # A config file name in a pack's site/config folder: <service>.json, or a .yml a wrapper names.
32
+ valid_config_name() {
33
+ case "$1" in '' | *[!a-z0-9.-]*) return 1 ;; esac
34
+ printf '%s\n' "$1" | /usr/bin/grep -Eq '^[a-z][a-z0-9-]{0,30}\.(json|yml)$'
35
+ }
36
+
37
+ json_field() {
38
+ /usr/bin/plutil -extract "$2" raw -o - "$1" 2>/dev/null
39
+ }
40
+
41
+ # Runs a script as user $1 from its home with a clean PATH; the script never sees root's environment.
42
+ as_user() {
43
+ run_as=$1
44
+ script=$2
45
+ shift 2
46
+ /usr/bin/sudo -n -u "$run_as" -H /bin/sh -c "set -eu; umask 077; PATH=/usr/bin:/bin:/usr/sbin:/sbin; cd \"\$HOME\"; $script" astrogate "$@"
47
+ }
48
+
49
+ # A root-made folder in the work folder that user $1 then owns, for files it copies into its home.
50
+ user_stage() {
51
+ stage_dir=$work/stage-$1
52
+ /bin/rm -rf "$stage_dir"
53
+ /bin/mkdir -m 0700 "$stage_dir"
54
+ printf '%s' "$stage_dir"
55
+ }
56
+
57
+ hand_stage() {
58
+ /usr/sbin/chown -R "$1:staff" "$2"
59
+ }
60
+
61
+ require_workspace() {
62
+ agent=astrogate-$ws
63
+ keys=astrogate-$ws-keys
64
+ /usr/bin/id -u "$agent" >/dev/null 2>&1 && /usr/bin/id -u "$keys" >/dev/null 2>&1 || fail "no workspace $ws: sudo astrogate workspace create $ws"
65
+ }
66
+
67
+ require_tools() {
68
+ [ -x "$NODE" ] && [ -x "$JQ" ] || fail "the core's node and jq are missing: sudo astrogate core update"
69
+ }
70
+
71
+ # --- users ------------------------------------------------------------------
72
+
73
+ # The first free uid from 450; macOS hides uids below 500 from the login window.
74
+ free_uid() {
75
+ uid=450
76
+ while [ -n "$(/usr/bin/dscl . -search /Users UniqueID "$uid" 2>/dev/null)" ]; do
77
+ uid=$((uid + 1))
78
+ [ "$uid" -lt 500 ] || fail "no free uid between 450 and 499"
79
+ done
80
+ printf '%s' "$uid"
81
+ }
82
+
83
+ # A hidden user $1 without a password (no login), shell zsh so the owner can `sudo -u $1 -i`,
84
+ # and a home only it can open.
85
+ create_user() {
86
+ if ! /usr/bin/id -u "$1" >/dev/null 2>&1; then
87
+ uid=$(free_uid)
88
+ /usr/bin/dscl . -create "/Users/$1"
89
+ /usr/bin/dscl . -create "/Users/$1" UniqueID "$uid"
90
+ /usr/bin/dscl . -create "/Users/$1" PrimaryGroupID 20
91
+ /usr/bin/dscl . -create "/Users/$1" RealName "$2"
92
+ /usr/bin/dscl . -create "/Users/$1" NFSHomeDirectory "/Users/$1"
93
+ /usr/bin/dscl . -create "/Users/$1" UserShell /bin/zsh
94
+ /usr/bin/dscl . -create "/Users/$1" Password '*'
95
+ /usr/bin/dscl . -create "/Users/$1" IsHidden 1
96
+ echo "created the user $1 (uid $uid)"
97
+ fi
98
+ [ -d "/Users/$1" ] || /usr/sbin/createhomedir -c -u "$1" >/dev/null
99
+ [ -d "/Users/$1" ] && [ ! -L "/Users/$1" ] || fail "/Users/$1 is not a folder"
100
+ /usr/sbin/chown "$1:staff" "/Users/$1"
101
+ /bin/chmod 0700 "/Users/$1"
102
+ }
103
+
104
+ # One sudoers file with the given rules, checked by visudo before it is installed.
105
+ write_rules() {
106
+ rules_file=$work/rules
107
+ target_file=$1
108
+ shift
109
+ printf '%s\n' "$@" >"$rules_file"
110
+ /usr/sbin/visudo -cf "$rules_file" >/dev/null || fail "visudo refuses the rules for $target_file"
111
+ /usr/bin/install -m 0440 -o root -g wheel "$rules_file" "$target_file"
112
+ /usr/sbin/visudo -c >/dev/null || fail "visudo -c fails after $target_file; check /etc/sudoers.d now"
113
+ }
114
+
115
+ # Reads one line from the terminal without showing it.
116
+ ask_secret() {
117
+ printf '%s' "$1" >/dev/tty
118
+ /bin/stty -echo </dev/tty
119
+ IFS= read -r secret_value </dev/tty || secret_value=""
120
+ /bin/stty echo </dev/tty
121
+ printf '\n' >/dev/tty
122
+ }
123
+
124
+ # --- workspace create ---------------------------------------------------------
125
+
126
+ WRITE_VAULT_LOGIN='umask 077; /bin/mkdir -p "$HOME/.config/specialists"; /bin/cat >"$HOME/.config/specialists/$1"'
127
+
128
+ AGENT_HOME='/bin/mkdir -p "$HOME/.pi/agent" "$HOME/.claude/agents"
129
+ settings="$HOME/.pi/agent/settings.json"
130
+ [ -f "$settings" ] || printf "{ \"packages\": [\"%s\"] }\n" "$1" >"$settings"
131
+ gate="$HOME/.pi/agent/specialists.json"
132
+ [ -f "$gate" ] || printf "{ \"entry\": \"%s\", \"user\": \"%s\", \"specialists\": [] }\n" "$2" "$3" >"$gate"'
133
+
134
+ workspace_create() {
135
+ require_root
136
+ valid_workspace "$ws" || fail "a workspace name is 2 to 16 lower-case letters and digits, starting with a letter, and not host"
137
+ current=$(link_version current)
138
+ [ -n "$current" ] || fail "no core is installed"
139
+ require_tools
140
+ [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ] || fail "run it with sudo from the admin user, which then may update the core and the packs"
141
+ printf '%s\n' "$SUDO_USER" | /usr/bin/grep -Eq '^[a-z_][a-z0-9_-]{0,31}$' || fail "the user name $SUDO_USER cannot go into a sudoers rule"
142
+ agent=astrogate-$ws
143
+ keys=astrogate-$ws-keys
144
+ make_work
145
+
146
+ create_user "$agent" "Astrogate $ws"
147
+ create_user "$keys" "Astrogate $ws keys"
148
+ write_rules "/etc/sudoers.d/zz-astrogate-$ws" "$agent ALL=($keys) NOPASSWD: $ENTRY"
149
+ write_rules "$ADMIN_RULES" "$SUDO_USER ALL=(root) NOPASSWD: $COMMAND core update" "$SUDO_USER ALL=(root) NOPASSWD: $COMMAND pack update *"
150
+ echo "sudo rules: $agent runs $ENTRY as $keys; $SUDO_USER runs astrogate core update and pack update"
151
+
152
+ as_user "$agent" "$AGENT_HOME" "$BASE/current" "$ENTRY" "$keys"
153
+ echo "$agent: Pi loads the core from $BASE/current; the gate runs $ENTRY as $keys"
154
+
155
+ if as_user "$keys" '[ -f "$HOME/.config/specialists/client.env" ] && [ -f "$HOME/.config/specialists/master-password" ]'; then
156
+ echo "$keys: the Vaultwarden login is there"
157
+ else
158
+ [ -t 0 ] || fail "the Vaultwarden login needs a terminal: run sudo astrogate workspace create $ws in one"
159
+ trap '/bin/stty echo </dev/tty 2>/dev/null; exit 1' HUP INT TERM
160
+ printf 'The Vaultwarden account of workspace %s (web vault: Settings, Security, Keys).\nserver (https://...): ' "$ws" >/dev/tty
161
+ IFS= read -r bw_server </dev/tty
162
+ case "$bw_server" in https://*) ;; *) fail "the server must start with https://" ;; esac
163
+ printf 'client_id: ' >/dev/tty
164
+ IFS= read -r bw_client_id </dev/tty
165
+ ask_secret "client_secret (not shown): "
166
+ bw_client_secret=$secret_value
167
+ ask_secret "master password (not shown): "
168
+ [ -n "$bw_client_id" ] && [ -n "$bw_client_secret" ] && [ -n "$secret_value" ] || fail "an empty value; nothing was written"
169
+ printf 'BW_SERVER=%s\nBW_CLIENTID=%s\nBW_CLIENTSECRET=%s\n' "$bw_server" "$bw_client_id" "$bw_client_secret" | as_user "$keys" "$WRITE_VAULT_LOGIN" client.env
170
+ printf '%s\n' "$secret_value" | as_user "$keys" "$WRITE_VAULT_LOGIN" master-password
171
+ unset bw_client_secret secret_value
172
+ trap 'exit 1' HUP INT TERM
173
+ echo "$keys: the Vaultwarden login is written"
174
+ fi
175
+ echo "workspace $ws is ready for its pack: astrogate pack update $ws <version>"
176
+ }
177
+
178
+ workspace_list() {
179
+ for user in $(/usr/bin/dscl . -list /Users | /usr/bin/grep -E '^astrogate-[a-z][a-z0-9]{1,15}$'); do
180
+ name=${user#astrogate-}
181
+ valid_workspace "$name" || continue
182
+ pack=$(/usr/bin/sudo -n -u "$user" /bin/cat "/Users/$user/.pi/agent/pack/pack.json" 2>/dev/null | /usr/bin/sed -n 's/^ "version": "\([0-9][0-9.]*\)",\{0,1\}$/\1/p' || true)
183
+ echo "$name${pack:+ pack $pack}"
184
+ done
185
+ }
186
+
187
+ # --- pack update ----------------------------------------------------------------
188
+
189
+ WRAPPER_VERSION='v=$(cat "$HOME/.specialists/bin/VERSION" 2>/dev/null) || exit 0; printf "%s" "$v"'
190
+
191
+ # Moves the new wrapper files in and the old ones aside, two renames per item, then checks
192
+ # every wrapper; on failure the old files come back. Config files follow the same way.
193
+ SWAP_WRAPPERS='node=$1; stage=$2; shift 2
194
+ bin="$HOME/.specialists/bin"; back="$HOME/.specialists/rollback/wrappers"
195
+ items="lib provision.sh VERSION pack.json $*"
196
+ smoke() { d=$1; shift; for s in "$@"; do "$node" --disable-warning=ExperimentalWarning "$d/$s/run.ts" --caller astrogate -- --help >/dev/null 2>&1 || { echo "$s --help failed" >&2; return 1; }; done; }
197
+ smoke "$stage" "$@" || exit 1
198
+ for f in "$stage/config"/*.json; do
199
+ [ ! -f "$f" ] || "$node" -e "JSON.parse(require(\"node:fs\").readFileSync(process.argv[1], \"utf8\"))" "$f" 2>/dev/null || { echo "config ${f##*/} is not valid JSON" >&2; exit 1; }
200
+ done
201
+ mkdir -p "$bin" "$HOME/.specialists/rollback"
202
+ rm -rf "$back.new"; mkdir "$back.new"
203
+ for i in $items; do rm -rf "$bin/.new-$i"; [ ! -e "$stage/$i" ] || cp -R "$stage/$i" "$bin/.new-$i"; done
204
+ for i in $items; do
205
+ [ ! -e "$bin/$i" ] || mv "$bin/$i" "$back.new/$i"
206
+ [ ! -e "$bin/.new-$i" ] || mv "$bin/.new-$i" "$bin/$i"
207
+ done
208
+ chmod -R go-rwx "$bin"
209
+ if ! smoke "$bin" "$@"; then
210
+ for i in $items; do rm -rf "$bin/$i"; [ ! -e "$back.new/$i" ] || mv "$back.new/$i" "$bin/$i"; done
211
+ rm -rf "$back.new"
212
+ echo "restored the previous wrappers" >&2
213
+ exit 1
214
+ fi
215
+ rm -rf "$back"; mv "$back.new" "$back"
216
+ conf="$HOME/.specialists/config"
217
+ for f in "$stage/config"/*; do
218
+ [ -f "$f" ] || continue
219
+ n=${f##*/}
220
+ mkdir -p "$conf" "$back/.config"
221
+ if [ -f "$conf/$n" ]; then
222
+ ! cmp -s "$f" "$conf/$n" || continue
223
+ cp "$conf/$n" "$back/.config/$n"
224
+ fi
225
+ cp "$f" "$conf/.new-$n"; mv "$conf/.new-$n" "$conf/$n"
226
+ echo "config $n written"
227
+ done'
228
+
229
+ # The agent side of a pack: agents, skills, bridge plugin, and site files in ~/.pi/agent/pack
230
+ # (the previous pack stays in pack.previous), and the pack's specialists in the gate file.
231
+ SWAP_AGENT_PACK='jq=$1; stage=$2
232
+ dir="$HOME/.pi/agent"; gate="$dir/specialists.json"
233
+ [ -f "$gate" ] || { echo "$gate is missing: sudo astrogate workspace create" >&2; exit 1; }
234
+ rm -rf "$dir/pack.new"; cp -R "$stage" "$dir/pack.new"
235
+ "$jq" --slurpfile pack "$dir/pack.new/pack.json" ".specialists = [\$pack[0].specialists[] | {agent, tool, service, timeoutMs} + (if (.risky | length) > 0 then {risky} else {} end)]" "$gate" >"$gate.new"
236
+ rm -rf "$dir/pack.previous"; [ ! -e "$dir/pack" ] || mv "$dir/pack" "$dir/pack.previous"
237
+ mv "$dir/pack.new" "$dir/pack"
238
+ cp "$gate" "$gate.before-pack"; mv "$gate.new" "$gate"'
239
+
240
+ # Claude Code's specialist subagents, the foreman, and the gate hook, from the installed pack.
241
+ # The core runs through its `current` link, so the files it writes stay valid after core updates.
242
+ CLAUDE_FILES='node=$1; bundle=$2
243
+ mkdir -p "$HOME/.claude/agents"
244
+ "$node" --preserve-symlinks-main "$bundle" agents "$HOME/.claude/agents" "$node"
245
+ "$node" --preserve-symlinks-main "$bundle" settings "$HOME/.claude/settings.json" "$node"'
246
+
247
+ # Tools a pack pins in site/tools.lock, the same line format as the core's: they install into the
248
+ # keys user's home, each download checked against the signed pack's sha256.
249
+ PACK_TOOLS="arcane-cli trendarr"
250
+ PACK_TOOL_HOSTS='github[.]com|registry[.]npmjs[.]org'
251
+
252
+ ARCANE_VERSION='out=$("$HOME/.specialists/bin/arcane-cli" --version 2>/dev/null) || exit 0
253
+ printf "%s\n" "$out" | awk '"'"'{ for (i = 1; i < NF; i++) if ($i == "version") { print $(i + 1); exit } }'"'"''
254
+
255
+ # Swaps in the staged arcane-cli after it reports version $2; the old one stays as arcane-cli.previous.
256
+ INSTALL_ARCANE='stage=$1; v=$2
257
+ bin="$HOME/.specialists/bin"
258
+ check() { "$1" --version 2>/dev/null | awk -v v="$v" '"'"'{ for (i = 1; i < NF; i++) if ($i == "version" && $(i + 1) == v) f = 1 } END { exit !f }'"'"'; }
259
+ mkdir -p "$bin"
260
+ cp "$stage/arcane-cli" "$bin/.arcane-cli.new"
261
+ chmod 0700 "$bin/.arcane-cli.new"
262
+ check "$bin/.arcane-cli.new" || { rm -f "$bin/.arcane-cli.new"; echo "the new arcane-cli does not report version $v" >&2; exit 1; }
263
+ had=no
264
+ if [ -e "$bin/arcane-cli" ]; then mv "$bin/arcane-cli" "$bin/arcane-cli.previous"; had=yes; fi
265
+ mv "$bin/.arcane-cli.new" "$bin/arcane-cli"
266
+ if ! check "$bin/arcane-cli"; then
267
+ rm -f "$bin/arcane-cli"
268
+ [ "$had" = no ] || mv "$bin/arcane-cli.previous" "$bin/arcane-cli"
269
+ echo "restored the previous arcane-cli" >&2
270
+ exit 1
271
+ fi'
272
+
273
+ # trendarr lives in versioned folders behind the stable link bin/trendarr, so media.json's
274
+ # trendarrCli path never changes; bin/trendarr.previous keeps the last one.
275
+ TRENDARR_COMMON='bin="$HOME/.specialists/bin"
276
+ cli() { printf "%s/node_modules/@astrofoundry/trendarr/dist/cli.js" "$1"; }
277
+ version_of() { plutil -extract version raw -o - "$1/node_modules/@astrofoundry/trendarr/package.json" 2>/dev/null; }
278
+ link() { rm -f "$bin/.$1.tmp"; ln -s "$2" "$bin/.$1.tmp"; mv -h "$bin/.$1.tmp" "$bin/$1"; }'
279
+
280
+ TRENDARR_VERSION="$TRENDARR_COMMON"'
281
+ [ -e "$bin/trendarr" ] || exit 0
282
+ version_of "$bin/trendarr" || exit 0'
283
+
284
+ # npm installs the checked tarball and its dependencies, without install scripts.
285
+ INSTALL_TRENDARR="$TRENDARR_COMMON"'
286
+ node=$1; npm=$2; tarball=$3; v=$4
287
+ dir="$bin/trendarr-$v"
288
+ mkdir -p "$bin"
289
+ rm -rf "$dir.partial"
290
+ "$node" "$npm" install --prefix "$dir.partial" --omit=dev --ignore-scripts --no-audit --no-fund --no-update-notifier "$tarball" >/dev/null
291
+ [ "$("$node" "$(cli "$dir.partial")" --version)" = "$v" ] || { rm -rf "$dir.partial"; echo "trendarr $v does not report its version" >&2; exit 1; }
292
+ before=$(readlink "$bin/trendarr" 2>/dev/null || true)
293
+ rm -rf "$dir"
294
+ mv "$dir.partial" "$dir"
295
+ link trendarr "trendarr-$v"
296
+ if [ "$("$node" "$(cli "$bin/trendarr")" --version)" != "$v" ]; then
297
+ if [ -n "$before" ]; then link trendarr "$before"; else rm -f "$bin/trendarr"; fi
298
+ echo "restored the previous trendarr" >&2
299
+ exit 1
300
+ fi
301
+ if [ -n "$before" ] && [ "$before" != "trendarr-$v" ]; then link trendarr.previous "$before"; fi
302
+ keep=$(readlink "$bin/trendarr.previous" 2>/dev/null || true)
303
+ for d in "$bin"/trendarr-*; do
304
+ [ -d "$d" ] || continue
305
+ n=${d##*/}
306
+ [ "$n" = "trendarr-$v" ] || [ "$n" = "$keep" ] || rm -rf "$d"
307
+ done'
308
+
309
+ # Downloads every pack tool the pack folder $1 pins into $work/tools-<tool>, each checked against its sha256.
310
+ fetch_pack_tools() {
311
+ [ -f "$1/site/tools.lock" ] || return 0
312
+ check_lock_lines "$1/site/tools.lock" "$PACK_TOOLS" "$PACK_TOOL_HOSTS"
313
+ for tool in $PACK_TOOLS; do
314
+ pin=$(pinned_version "$1/site" "$tool")
315
+ [ -n "$pin" ] || continue
316
+ valid_version "$pin" || fail "site/tools.lock pins $tool $pin, which is no valid version"
317
+ /bin/mkdir -p "$work/tools-$tool"
318
+ downloads=$(/usr/bin/awk -v t="$tool" '$1 == t && NF == 4 { print $3, $4 }' "$1/site/tools.lock")
319
+ while read -r sum url; do
320
+ file=$work/tools-$tool/${url##*/}
321
+ fetch "$url" "$file"
322
+ [ "$(/usr/bin/shasum -a 256 "$file" | /usr/bin/cut -d' ' -f1)" = "$sum" ] || fail "checksum mismatch for $url"
323
+ done <<DOWNLOADS
324
+ $downloads
325
+ DOWNLOADS
326
+ done
327
+ }
328
+
329
+ # Installs the fetched pack tools as the keys user, each only when its version changes.
330
+ install_pack_tools() {
331
+ [ -f "$1/site/tools.lock" ] || return 0
332
+ pin=$(pinned_version "$1/site" arcane-cli)
333
+ if [ -n "$pin" ] && [ "$(as_user "$keys" "$ARCANE_VERSION")" != "$pin" ]; then
334
+ /bin/mkdir "$work/acli"
335
+ for archive in "$work/tools-arcane-cli"/*; do /usr/bin/tar -xzf "$archive" --no-same-owner -C "$work/acli"; done
336
+ cli=$(/usr/bin/find "$work/acli" -type f -name arcane-cli | /usr/bin/head -n 1)
337
+ [ -n "$cli" ] || fail "no arcane-cli binary in the pinned download"
338
+ tool_stage=$(user_stage "$keys-arcane")
339
+ /bin/cp "$cli" "$tool_stage/arcane-cli"
340
+ hand_stage "$keys" "$tool_stage"
341
+ as_user "$keys" "$INSTALL_ARCANE" "$tool_stage" "$pin" || fail "arcane-cli $pin failed its check"
342
+ echo "arcane-cli $pin installed"
343
+ fi
344
+ pin=$(pinned_version "$1/site" trendarr)
345
+ if [ -n "$pin" ] && [ "$(as_user "$keys" "$TRENDARR_VERSION")" != "$pin" ]; then
346
+ npm=$TOOLS/node/current/lib/node_modules/npm/bin/npm-cli.js
347
+ [ -f "$npm" ] || fail "the core's Node has no npm"
348
+ tool_stage=$(user_stage "$keys-trendarr")
349
+ /bin/cp "$work/tools-trendarr"/*.tgz "$tool_stage/trendarr.tgz"
350
+ hand_stage "$keys" "$tool_stage"
351
+ as_user "$keys" "$INSTALL_TRENDARR" "$NODE" "$npm" "$tool_stage/trendarr.tgz" "$pin" || fail "trendarr $pin failed its check"
352
+ echo "trendarr $pin installed"
353
+ fi
354
+ }
355
+
356
+ # The services pack.json $1 names, checked, one per line; fails on none, a bad name, or a repeat.
357
+ pack_services() {
358
+ i=0
359
+ found=" "
360
+ while s=$(json_field "$1" "specialists.$i.service"); do
361
+ valid_service "$s" || fail "pack.json names an invalid service"
362
+ case "$found" in *" $s "*) fail "pack.json names $s twice" ;; esac
363
+ found="$found$s "
364
+ printf '%s\n' "$s"
365
+ i=$((i + 1))
366
+ [ "$i" -lt 100 ] || fail "pack.json names more than 100 specialists"
367
+ done
368
+ [ "$i" -gt 0 ] || fail "pack.json names no specialists"
369
+ }
370
+
371
+ # Copies the config files of the pack's site/config folder $1 into $2/config; a pack without the folder has none.
372
+ stage_config() {
373
+ [ -e "$1" ] || [ -L "$1" ] || return 0
374
+ [ -d "$1" ] && [ ! -L "$1" ] || fail "the pack's site/config is not a folder"
375
+ /bin/mkdir "$2/config"
376
+ for f in "$1"/* "$1"/.[!.]* "$1"/..?*; do
377
+ [ -e "$f" ] || [ -L "$f" ] || continue
378
+ name=${f##*/}
379
+ valid_config_name "$name" || fail "the pack's site/config holds a name that is no <service>.json or .yml"
380
+ [ -f "$f" ] && [ ! -L "$f" ] || fail "the pack's site/config/$name is not a plain file"
381
+ [ "$(/usr/bin/stat -f '%z' "$f")" -le 65536 ] || fail "the pack's site/config/$name is larger than 64 KiB"
382
+ /bin/cp "$f" "$2/config/$name"
383
+ done
384
+ }
385
+
386
+ pack_update() {
387
+ require_root
388
+ valid_workspace "$ws" || fail "no valid workspace name: $ws"
389
+ require_workspace
390
+ require_tools
391
+ signers=$BASE/current/pack_signers
392
+ [ -f "$signers" ] || fail "the core has no pack_signers"
393
+ make_work
394
+ # Root copies the drop into its own folder before it reads anything.
395
+ for f in "$PACK_DROP/pack-$ws-$version.tgz" "$PACK_DROP/pack-$ws-$version.tgz.sig"; do
396
+ [ -f "$f" ] && [ ! -L "$f" ] || fail "$f is missing"
397
+ done
398
+ /bin/cp "$PACK_DROP/pack-$ws-$version.tgz" "$work/pack.tgz"
399
+ /bin/cp "$PACK_DROP/pack-$ws-$version.tgz.sig" "$work/pack.sig"
400
+ /usr/bin/ssh-keygen -Y verify -f "$signers" -I astro-pack -n astro-pack -s "$work/pack.sig" <"$work/pack.tgz" >/dev/null 2>&1 ||
401
+ fail "pack-$ws-$version.tgz carries no valid astro-pack signature from a key in $signers"
402
+ /bin/mkdir "$work/pkg"
403
+ /usr/bin/tar -xzf "$work/pack.tgz" --no-same-owner -C "$work/pkg"
404
+ manifest=$work/pkg/pack.json
405
+ [ -f "$manifest" ] && [ ! -L "$manifest" ] || fail "the pack has no pack.json"
406
+ [ "$(json_field "$manifest" version)" = "$version" ] || fail "pack.json does not name version $version"
407
+ [ "$(json_field "$manifest" workspace)" = "$ws" ] || fail "the pack is not for workspace $ws"
408
+ installed=$(as_user "$keys" "$WRAPPER_VERSION")
409
+ valid_version "$installed" || installed=""
410
+ if [ -n "$installed" ] && version_lt "$version" "$installed"; then fail "pack $version is older than the installed $installed; use astrogate pack rollback $ws"; fi
411
+
412
+ src=$work/pkg/specialists
413
+ [ -d "$src/lib" ] && [ -f "$src/provision/provision.sh" ] || fail "the pack has no specialists/lib or provision.sh"
414
+ services=$(pack_services "$manifest")
415
+ fetch_pack_tools "$work/pkg"
416
+ wrappers=$(user_stage "$keys")
417
+ /bin/cp -R "$src/lib" "$wrappers/lib"
418
+ for s in $services; do
419
+ [ -f "$src/$s/run.ts" ] || fail "the pack has no $s wrapper"
420
+ /bin/mkdir "$wrappers/$s"
421
+ /bin/cp "$src/$s/run.ts" "$wrappers/$s/run.ts"
422
+ done
423
+ /bin/cp "$src/provision/provision.sh" "$wrappers/provision.sh"
424
+ /bin/cp "$manifest" "$wrappers/pack.json"
425
+ stage_config "$work/pkg/site/config" "$wrappers"
426
+ /usr/bin/find "$wrappers" -type f -name '*.test.ts' -delete
427
+ printf '%s\n' "$version" >"$wrappers/VERSION"
428
+
429
+ agent_pack=$(user_stage "$agent")
430
+ for part in agents skills bridge site; do
431
+ [ ! -d "$work/pkg/$part" ] || /bin/cp -R "$work/pkg/$part" "$agent_pack/$part"
432
+ done
433
+ /bin/cp "$manifest" "$agent_pack/pack.json"
434
+
435
+ hand_stage "$keys" "$wrappers"
436
+ hand_stage "$agent" "$agent_pack"
437
+ as_user "$keys" "$SWAP_WRAPPERS" "$NODE" "$wrappers" $services || fail "pack $version failed its check; ${installed:-no} previous version kept"
438
+ install_pack_tools "$work/pkg"
439
+ as_user "$agent" "$SWAP_AGENT_PACK" "$JQ" "$agent_pack" || fail "the agent side of pack $version failed; the wrappers are in, run the update again"
440
+ as_user "$agent" "$CLAUDE_FILES" "$NODE" "$BASE/current/dist/claude.js" >/dev/null || fail "the Claude Code files of $agent failed; run the update again"
441
+ echo "pack $version in workspace $ws: wrappers, config, tools, agents, skills, bridge plugin, gate, Claude Code agents${installed:+; previous $installed}"
442
+ }
@@ -0,0 +1,242 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ const SCRIPT = join(import.meta.dirname, "workspace.sh");
8
+ const ENTRY = join(import.meta.dirname, "..", "specialists", "entry", "astrogate-run.sh");
9
+ const isMac = process.platform === "darwin";
10
+ const jq = ["/usr/bin/jq", "/opt/homebrew/bin/jq"].find((p) => existsSync(p));
11
+
12
+ /** Runs the named shell functions of workspace.sh on their own, with a `fail` that exits 1, followed by `call`. */
13
+ function shellFunctions(names: string[], call: string) {
14
+ const source = readFileSync(SCRIPT, "utf-8");
15
+ const bodies = names.map((name) => {
16
+ const match = new RegExp(`^${name}\\(\\) \\{\\n[\\s\\S]*?^\\}`, "m").exec(source);
17
+ if (!match) throw new Error(`${name} not found in the script`);
18
+ return match[0];
19
+ });
20
+ return spawnSync("/bin/sh", ["-c", `set -eu\nfail() { echo "$*" >&2; exit 1; }\n${bodies.join("\n")}\n${call}`], { encoding: "utf-8" });
21
+ }
22
+
23
+ /** The value of a workspace.sh variable that holds a script for a workspace user, as the shell reads it. */
24
+ function userScript(name: string): string {
25
+ const result = spawnSync("/bin/sh", ["-c", `TOOLS=/t; . '${SCRIPT}'; printf '%s' "$${name}"`], { encoding: "utf-8" });
26
+ if (result.status !== 0 || result.stdout === "") throw new Error(`${name} not found in the script: ${result.stderr}`);
27
+ return result.stdout;
28
+ }
29
+
30
+ function runAs(home: string, name: string, ...args: string[]) {
31
+ return spawnSync("/bin/sh", ["-c", `set -eu; umask 077; cd "$HOME"; ${userScript(name)}`, "astrogate", ...args], { encoding: "utf-8", env: { HOME: home, PATH: "/usr/bin:/bin" } });
32
+ }
33
+
34
+ describe("workspace.sh", () => {
35
+ it("parses as POSIX sh and never runs Homebrew binaries", () => {
36
+ expect(spawnSync("/bin/sh", ["-n", SCRIPT]).status).toBe(0);
37
+ expect(readFileSync(SCRIPT, "utf-8")).not.toContain("/opt/homebrew");
38
+ });
39
+
40
+ it.each([
41
+ ["homelab", 0],
42
+ ["work", 0],
43
+ ["w2", 0],
44
+ ["host", 1],
45
+ ["a", 1],
46
+ ["Work", 1],
47
+ ["2work", 1],
48
+ ["work-x", 1],
49
+ ["abcdefghijklmnopq", 1],
50
+ ["work\nx", 1],
51
+ ])("valid_workspace %j exits %i", (name, code) => {
52
+ expect(shellFunctions(["valid_workspace"], `valid_workspace '${name}'`).status).toBe(code);
53
+ });
54
+
55
+ it.runIf(isMac)("reads the services a pack names and refuses bad, repeated, or missing ones", () => {
56
+ const dir = mkdtempSync(join(tmpdir(), "pack-json-"));
57
+ try {
58
+ const services = (specialists: object[]) => {
59
+ writeFileSync(join(dir, "pack.json"), JSON.stringify({ name: "t", version: "1.0.0", workspace: "homelab", specialists }));
60
+ return shellFunctions(["json_field", "valid_service", "pack_services"], `pack_services '${join(dir, "pack.json")}'`);
61
+ };
62
+ expect(services([{ service: "dns" }, { service: "arcane" }]).stdout).toBe("dns\narcane\n");
63
+ expect(services([]).stderr).toContain("names no specialists");
64
+ expect(services([{ service: "dns" }, { service: "dns" }]).stderr).toContain("names dns twice");
65
+ expect(services([{ service: "../x" }]).stderr).toContain("invalid service");
66
+ expect(services([{ service: "lib" }]).stderr).toContain("invalid service");
67
+ expect(services([{ service: "dns\nx" }]).stderr).toContain("invalid service");
68
+ } finally {
69
+ rmSync(dir, { recursive: true, force: true });
70
+ }
71
+ });
72
+
73
+ it.runIf(isMac)("stages only plain, small, well-named config files of a pack", () => {
74
+ const dir = mkdtempSync(join(tmpdir(), "pack-config-"));
75
+ try {
76
+ let n = 0;
77
+ const stage = (files: Record<string, string>, extra = "") => {
78
+ const root = join(dir, String(n++));
79
+ mkdirSync(join(root, "stage"), { recursive: true });
80
+ if (Object.keys(files).length > 0) mkdirSync(join(root, "config"));
81
+ for (const [name, text] of Object.entries(files)) writeFileSync(join(root, "config", name), text);
82
+ const result = shellFunctions(["valid_config_name", "stage_config"], `${extra.replaceAll("ROOT", root)}\nstage_config '${join(root, "config")}' '${join(root, "stage")}'`);
83
+ return { result, staged: existsSync(join(root, "stage", "config")) ? readdirSync(join(root, "stage", "config")).sort() : null };
84
+ };
85
+ expect(stage({}).staged).toBeNull();
86
+ expect(stage({ "media.json": "{}", "arcanecli.yml": "a: b\n" }).staged).toEqual(["arcanecli.yml", "media.json"]);
87
+ expect(stage({ "Media.json": "{}" }).result.stderr).toContain("no <service>.json or .yml");
88
+ expect(stage({ ".hidden.json": "{}" }).result.stderr).toContain("no <service>.json or .yml");
89
+ expect(shellFunctions(["valid_config_name"], "valid_config_name 'media.json\nx.json'").status).toBe(1);
90
+ expect(stage({ "media.json": "x".repeat(65537) }).result.stderr).toContain("larger than 64 KiB");
91
+ expect(stage({ "media.json": "{}" }, "ln -s /etc/hosts ROOT/config/dns.json").result.stderr).toContain("dns.json is not a plain file");
92
+ expect(stage({}, "ln -s /etc ROOT/config").result.stderr).toContain("site/config is not a folder");
93
+ } finally {
94
+ rmSync(dir, { recursive: true, force: true });
95
+ }
96
+ });
97
+
98
+ it("swaps the wrappers in, writes changed config files, and keeps the old wrappers when a check fails", () => {
99
+ const dir = mkdtempSync(join(tmpdir(), "pack-swap-"));
100
+ try {
101
+ const home = join(dir, "home");
102
+ const conf = join(home, ".specialists", "config");
103
+ mkdirSync(conf, { recursive: true });
104
+ writeFileSync(join(conf, "dns.json"), '{"old":true}');
105
+ const makeStage = (version: string, configs: Record<string, string> | null, wrapper = "process.exit(0);\n") => {
106
+ const stage = join(dir, `stage-${version}`);
107
+ mkdirSync(join(stage, "lib"), { recursive: true });
108
+ mkdirSync(join(stage, "dns"));
109
+ writeFileSync(join(stage, "dns", "run.ts"), wrapper);
110
+ writeFileSync(join(stage, "provision.sh"), "");
111
+ writeFileSync(join(stage, "pack.json"), "{}");
112
+ writeFileSync(join(stage, "VERSION"), `${version}\n`);
113
+ if (configs) {
114
+ mkdirSync(join(stage, "config"));
115
+ for (const [name, text] of Object.entries(configs)) writeFileSync(join(stage, "config", name), text);
116
+ }
117
+ return stage;
118
+ };
119
+ const version = () => readFileSync(join(home, ".specialists", "bin", "VERSION"), "utf-8").trim();
120
+ expect(runAs(home, "SWAP_WRAPPERS", process.execPath, makeStage("1.0.0", null), "dns").status).toBe(0);
121
+ expect(runAs(home, "WRAPPER_VERSION").stdout).toBe("1.0.0");
122
+
123
+ const broken = runAs(home, "SWAP_WRAPPERS", process.execPath, makeStage("1.0.1", null, "process.exit(1);\n"), "dns");
124
+ expect(broken.status).toBe(1);
125
+ expect(broken.stderr).toContain("dns --help failed");
126
+ expect(version()).toBe("1.0.0");
127
+
128
+ const badConfig = runAs(home, "SWAP_WRAPPERS", process.execPath, makeStage("1.0.2", { "dns.json": "{broken" }), "dns");
129
+ expect(badConfig.stderr).toContain("config dns.json is not valid JSON");
130
+ expect(version()).toBe("1.0.0");
131
+
132
+ const good = runAs(home, "SWAP_WRAPPERS", process.execPath, makeStage("1.0.3", { "dns.json": '{"new":true}', "home.json": "{}" }), "dns");
133
+ expect(good.stderr).toBe("");
134
+ expect(good.stdout.trim().split("\n").sort()).toEqual(["config dns.json written", "config home.json written"]);
135
+ expect(version()).toBe("1.0.3");
136
+ expect(readFileSync(join(conf, "dns.json"), "utf-8")).toBe('{"new":true}');
137
+ expect(statSync(join(conf, "home.json")).mode & 0o777).toBe(0o600);
138
+ expect(readFileSync(join(home, ".specialists", "rollback", "wrappers", "VERSION"), "utf-8").trim()).toBe("1.0.0");
139
+ } finally {
140
+ rmSync(dir, { recursive: true, force: true });
141
+ }
142
+ });
143
+
144
+ it.runIf(jq !== undefined)("puts the agent side of a pack in place and the pack's specialists in the gate file", () => {
145
+ const dir = mkdtempSync(join(tmpdir(), "pack-agent-"));
146
+ try {
147
+ const home = join(dir, "home");
148
+ const agent = join(home, ".pi", "agent");
149
+ mkdirSync(agent, { recursive: true });
150
+ const stage = (version: string) => {
151
+ const s = join(dir, `stage-${version}`);
152
+ mkdirSync(join(s, "agents"), { recursive: true });
153
+ writeFileSync(join(s, "agents", "dns.md"), `dns ${version}\n`);
154
+ writeFileSync(
155
+ join(s, "pack.json"),
156
+ JSON.stringify({
157
+ version,
158
+ workspace: "homelab",
159
+ specialists: [
160
+ { agent: "astro.dns", tool: "dns", service: "dns", timeoutMs: 1000, risky: ["^zone delete"], claude: { model: "x" } },
161
+ { agent: "astro.media", tool: "media", service: "media", timeoutMs: 2000, risky: [] },
162
+ ],
163
+ }),
164
+ );
165
+ return s;
166
+ };
167
+ expect(runAs(home, "SWAP_AGENT_PACK", jq ?? "", stage("1.0.0")).stderr).toContain("specialists.json is missing");
168
+ writeFileSync(join(agent, "specialists.json"), JSON.stringify({ entry: "/usr/local/bin/astrogate-run", user: "astrogate-homelab-keys", specialists: [] }));
169
+ expect(runAs(home, "SWAP_AGENT_PACK", jq ?? "", stage("1.0.0")).status).toBe(0);
170
+ expect(runAs(home, "SWAP_AGENT_PACK", jq ?? "", stage("1.0.1")).status).toBe(0);
171
+ expect(readFileSync(join(agent, "pack", "agents", "dns.md"), "utf-8")).toBe("dns 1.0.1\n");
172
+ expect(readFileSync(join(agent, "pack.previous", "agents", "dns.md"), "utf-8")).toBe("dns 1.0.0\n");
173
+ expect(JSON.parse(readFileSync(join(agent, "specialists.json"), "utf-8"))).toEqual({
174
+ entry: "/usr/local/bin/astrogate-run",
175
+ user: "astrogate-homelab-keys",
176
+ specialists: [
177
+ { agent: "astro.dns", tool: "dns", service: "dns", timeoutMs: 1000, risky: ["^zone delete"] },
178
+ { agent: "astro.media", tool: "media", service: "media", timeoutMs: 2000 },
179
+ ],
180
+ });
181
+ expect(existsSync(join(agent, "specialists.json.before-pack"))).toBe(true);
182
+ } finally {
183
+ rmSync(dir, { recursive: true, force: true });
184
+ }
185
+ });
186
+ });
187
+
188
+ describe("astrogate-run", () => {
189
+ it("runs the wrappers with the core's root-owned Node only", () => {
190
+ const text = readFileSync(ENTRY, "utf-8");
191
+ expect(text).toContain("exec /usr/local/libexec/astrogate/tools/node/current/bin/node ");
192
+ expect(text).not.toContain("/opt/homebrew");
193
+ expect(statSync(ENTRY).mode & 0o111).not.toBe(0);
194
+ });
195
+
196
+ it.runIf(existsSync("/bin/zsh")).each([
197
+ ["", 2, "usage"],
198
+ ["lib", 2, "usage"],
199
+ ["VERSION", 2, "usage"],
200
+ ["../arcane", 2, "usage"],
201
+ ["Arcane", 2, "usage"],
202
+ ["dns;id", 2, "usage"],
203
+ ["zz-not-installed", 2, "is not installed"],
204
+ ])("refuses service %j", (service, status, message) => {
205
+ const result = spawnSync("/bin/zsh", [ENTRY, ...(service ? [service] : [])], { encoding: "utf-8", env: { HOME: tmpdir(), PATH: "/usr/bin:/bin" } });
206
+ expect(result.status).toBe(status);
207
+ expect(result.stderr).toContain(message);
208
+ });
209
+ });
210
+
211
+ describe("pack tools", () => {
212
+ it("swaps in an arcane-cli that reports the pinned version and keeps the old one", () => {
213
+ const dir = mkdtempSync(join(tmpdir(), "pack-arcane-"));
214
+ try {
215
+ const home = join(dir, "home");
216
+ mkdirSync(home);
217
+ const stage = (version: string) => {
218
+ const s = join(dir, `stage-${version}`);
219
+ mkdirSync(s);
220
+ writeFileSync(join(s, "arcane-cli"), `#!/bin/sh\necho "arcane-cli version ${version}"\n`, { mode: 0o755 });
221
+ return s;
222
+ };
223
+ expect(runAs(home, "ARCANE_VERSION").stdout).toBe("");
224
+ expect(runAs(home, "INSTALL_ARCANE", stage("3.2.1"), "3.2.1").status).toBe(0);
225
+ expect(runAs(home, "ARCANE_VERSION").stdout).toBe("3.2.1\n");
226
+ const wrong = runAs(home, "INSTALL_ARCANE", stage("3.2.2"), "3.3.0");
227
+ expect(wrong.stderr).toContain("does not report version 3.3.0");
228
+ expect(runAs(home, "ARCANE_VERSION").stdout).toBe("3.2.1\n");
229
+ expect(runAs(home, "INSTALL_ARCANE", stage("3.3.0"), "3.3.0").status).toBe(0);
230
+ expect(runAs(home, "ARCANE_VERSION").stdout).toBe("3.3.0\n");
231
+ expect(existsSync(join(home, ".specialists", "bin", "arcane-cli.previous"))).toBe(true);
232
+ } finally {
233
+ rmSync(dir, { recursive: true, force: true });
234
+ }
235
+ });
236
+
237
+ it("names the pack tools and their download hosts in one place", () => {
238
+ const text = readFileSync(SCRIPT, "utf-8");
239
+ expect(text).toContain('PACK_TOOLS="arcane-cli trendarr"');
240
+ expect(text).toContain("PACK_TOOL_HOSTS='github[.]com|registry[.]npmjs[.]org'");
241
+ });
242
+ });
package/pack_signers ADDED
@@ -0,0 +1 @@
1
+ astro-pack namespaces="astro-pack" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFLXiMD3Sqj8HzXOLx0D1BPiVjAp5rjFMLbS3l+cLciK
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/astrogate",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "description": "Astrogate core: isolated agent workspaces with specialists, a foreman, and chat bridges, for the pi coding agent and Claude Code.",
5
5
  "packageManager": "pnpm@12.23.0",
6
6
  "scripts": {
@@ -35,6 +35,7 @@
35
35
  "dist",
36
36
  "extensions",
37
37
  "harness",
38
+ "pack_signers",
38
39
  "release.sha256",
39
40
  "release.sha256.sig",
40
41
  "specialists",
package/release.sha256 CHANGED
@@ -3,10 +3,12 @@ b9b0f9fa90b9a230157de1fefef1aa5a624bfd7b50527b67ad86ecc62414aadb agents/foreman
3
3
  4091f50a5a9ff72e2f1571c6de054d9c891dbe294aa58e6a55ad9a1bff2f766a cli/astro-install.sh
4
4
  9f371247fdaea09e1551f940fd91eacb7d242baea343fce66f12fc8e22ba064b cli/astro.sh
5
5
  8e054f8286876b77e0887d0b0e2a62d4a048fd41bfa0048d126e0c9171869cf6 cli/astro.test.ts
6
- 01882995b53a4f528f39668c50256533c8b6aef1f882dbf7d4cd1ec82ff9969f cli/astrogate.sh
7
- 1f8a0d0914b30582793399cf16cebcf6266d3c716f5925919073d2c7e85c4c6e cli/astrogate.test.ts
6
+ b6d6a42fffba89e8456e668a1e5d6e7b1c1ce3c1c9ed4d674cdc487ea4af8340 cli/astrogate.sh
7
+ 14fe7aeb17c89708f5d26f6224756f2aad3083e470bc5c8b907303714d6fcc62 cli/astrogate.test.ts
8
8
  07b9aef7e5d0ee43959e0c16e00ec3a202769c94faea4167257513bf15b9383c cli/verify-release.sh
9
9
  29614fd0eb1ad08215baf827b00ee2b98ccb73ca0ccf770bc5a0084c71da5926 cli/verify-release.test.ts
10
+ d2d6a57b6848067b466d357d9338460cd97d24283b111ef7b9deea56408b8cd0 cli/workspace.sh
11
+ e7851bc2fccc1cdae49ce8444bda7caeb781748665a4da95c01d81d94b5bb918 cli/workspace.test.ts
10
12
  87077122362031c7496ad6c191c00bd3ab90e39d8901286f78462ddbb7c76bae dist/bridge.js
11
13
  06d6ce0f4763fe1552573336ad32e5dff23fc5e1e8a2b4243c974b6f7e439840 dist/claude.js
12
14
  04ed58933a8ff2c05d92df0068038a6003c8b2fbc2f323a377fa530a16a3a867 dist/extensions/bridge/index.js
@@ -69,9 +71,11 @@ e6a327ff2e489bb9f3ed72d4e7eed207f9f2532e1da9b1d520ccf74aeaf594b5 harness/claude
69
71
  9d0f68180f5958ea40550df140a677f611108a402faf94b05669ed7807aa598e harness/claude/main.ts
70
72
  e1d07bd981bd4ff6385246b6c1ad41349718c1e490b2bff675291dc7b568cd69 harness/claude/mcp.ts
71
73
  194b623038d56a2565ad42d30d1db72ca453e654bfc84996800362e8a972282b harness/claude/settings.ts
72
- b5971a8d98fd9011a546ab13f3805cf5bca00552d26ce1e21eb01e30dd3bb4ef package.json
74
+ 987ae3b35d82ae3212cc70d12cff6913ac3f91a803fe7056ccd8010a8f960d2f pack_signers
75
+ 42ca45c84ac2b36434fbe2dd93451f821f7881609a929afdd0b33e41420b93ce package.json
73
76
  642383b14db5dbfb7caa6a185591263e4294a73323bf4c78606f7b85f0817fd0 specialists/AGENTS.md
74
77
  a385cf5e3b59de30b5ed9b0840d6cf6198b577668f18dfd5de13a714fb047c3e specialists/README.md
78
+ 270cf6cf3b4df6246d0aa8714ed02bd505e5a78c00f35fded4d20a6ac0382f30 specialists/entry/astrogate-run.sh
75
79
  729f8c29d7cf716be5b01d5df869eeda6d4683f86a4915a52fb8adfdebe1f9d2 specialists/entry/specialist-cli.sh
76
80
  d5f31c5a1a0dea35966cbbc57001b626320826b92c423379e2c852ae89d1ad3d specialists/entry/specialist-install.sh
77
81
  8918c907fe01b40253b77a2ece0e6dca21d3cde2454211b531cbfbf2498d1750 specialists/entry/specialist-install.test.ts
@@ -96,5 +100,5 @@ cf173051f31cc92bc3715cf05c27e78ad000148136eca2deb402a0565a955c63 specialists/li
96
100
  c1abde1e550c0f4703fd0b2536cc4002c7edf6468c18a03ebaa516fd1ce093c3 specialists/lib/ssh.ts
97
101
  31959f525a0b0aff070b4a19a9677d446d3425481e936dcd9ca2d957f4e51142 specialists/lib/tunnel.test.ts
98
102
  ed93bfcef355a0a3aa7d679395b2f6ce9ce4c5709253fda7f63c1f3927f5d324 specialists/lib/tunnel.ts
99
- 7a36850a90c3a5e8c2a02fe386f93a0b6e664431799154f548e7ac9f33e84a90 specialists/provision/provision.sh
103
+ b116df8b203f1a3353cca404d519dd838122392b1c2ef292aa5716b62839e65a specialists/provision/provision.sh
100
104
  d182f87697c383c29075dc8b5415fc6fa3832ab33ccf14d5df8a941d9435b5c9 tools.lock
@@ -1,6 +1,6 @@
1
1
  -----BEGIN SSH SIGNATURE-----
2
2
  U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAgUteIwPdKqPwfNc4vHQPUE+JWMC
3
3
  nmuMUwttLeX5wtyIoAAAAOYXN0cm9nYXRlLWNvcmUAAAAAAAAABnNoYTUxMgAAAFMAAAAL
4
- c3NoLWVkMjU1MTkAAABAAwn4E/iPEm295nZbAQe2JW5xgyF2jUlmr7yymi1I+NY97vR1pq
5
- 5DeBq3lN0Vmww3tBwOwVVDTezRcfze2nBgAw==
4
+ c3NoLWVkMjU1MTkAAABAbY0iFrYWd84L/4RUgVlTVjR4tCBNLaRav/kT0sI5JGEDsDTHHt
5
+ AWnJT8FYTiyN4i+JAZD92Y7M12OL4YxrAOCg==
6
6
  -----END SSH SIGNATURE-----
@@ -0,0 +1,25 @@
1
+ #!/bin/zsh
2
+ # /usr/local/bin/astrogate-run: the only sudo entry point into a workspace's keys user.
3
+ # It links into the installed core, which only root can change. A workspace's agent user
4
+ # runs it as that workspace's keys user through
5
+ # astrogate-<ws> ALL=(astrogate-<ws>-keys) NOPASSWD: /usr/local/bin/astrogate-run
6
+ set -euo pipefail
7
+
8
+ usage() { print -u2 "usage: astrogate-run <service> [--caller <agent>] [--] <args...>"; exit 2; }
9
+
10
+ service="${1:-}"; [[ -n "$service" ]] && shift
11
+ # Any service the installed pack provides; the other names in the wrapper folder are taken.
12
+ case "$service" in
13
+ provision) exec /bin/sh "$HOME/.specialists/bin/provision.sh" ;;
14
+ lib|VERSION|rollback) usage ;;
15
+ esac
16
+ [[ "$service" =~ '^[a-z][a-z0-9-]{0,30}$' ]] || usage
17
+
18
+ caller="unknown"
19
+ if [[ "${1:-}" == "--caller" ]]; then caller="${2:-unknown}"; shift 2; fi
20
+ [[ "${1:-}" == "--" ]] && shift
21
+
22
+ runner="$HOME/.specialists/bin/$service/run.ts"
23
+ [[ -f "$runner" ]] || { print -u2 "specialist '$service' is not installed"; exit 2; }
24
+ # The core's root-owned Node: Homebrew's belongs to the host's admin user.
25
+ exec /usr/local/libexec/astrogate/tools/node/current/bin/node --disable-warning=ExperimentalWarning "$runner" --caller "$caller" -- "$@"
@@ -2,7 +2,7 @@
2
2
  # specialist-provision: copy every Secure Note of the Vaultwarden collection
3
3
  # `specialists` into ~/.specialists/secrets/<note>/<FIELD> (mode 0600).
4
4
  # Fields ending in _B64 are base64-decoded and written without the suffix.
5
- # Runs as the `specialist` user. Idempotent; stale fields are removed.
5
+ # Runs as a workspace's keys user, with the core's bw and jq. Idempotent; stale fields are removed.
6
6
  set -eu
7
7
  umask 077
8
8
 
@@ -12,8 +12,8 @@ client_file="$config_dir/client.env"
12
12
  password_file="$config_dir/master-password"
13
13
  root="$home/.specialists"
14
14
  collection_name="${SPECIALISTS_COLLECTION:-specialists}"
15
- BW=/usr/local/libexec/specialist-bw/current/bw
16
- JQ=/usr/local/libexec/specialist-jq/current/jq
15
+ BW=/usr/local/libexec/astrogate/tools/bw/current/bw
16
+ JQ=/usr/local/libexec/astrogate/tools/jq/current/jq
17
17
 
18
18
  for f in "$client_file" "$password_file"; do
19
19
  [ -f "$f" ] || { echo "missing $f" >&2; exit 2; }