chore: consolidate new foundation and archive v1 (#1495)

This commit is contained in:
2026-09-07 12:32:57 -05:00
3511 changed files with 727899 additions and 10 deletions
+339
View File
@@ -0,0 +1,339 @@
#!/usr/bin/env bash
#
# credentials.sh — Shared credential loader for Mosaic tool suites
#
# Usage: source ~/.config/mosaic/tools/_lib/credentials.sh
# load_credentials <service-name>
#
# credentials.json is the single source of truth.
# For Woodpecker, credentials are also synced to ~/.woodpecker/<instance>.env.
#
# Supported services:
# portainer, coolify, authentik, glpi, github,
# gitea-mosaicstack, gitea-usc, woodpecker, cloudflare,
# turbo-cache, openbrain
#
# After loading, service-specific env vars are exported.
# Run `load_credentials --help` for details.
#
# Resolution order (first match wins):
# 1. $MOSAIC_CREDENTIALS_FILE (explicit override — never second-guessed)
# 2. $HOME/.config/mosaic/credentials.json
# 3. /etc/mosaic/credentials.json (host-level fallback)
# The /etc fallback exists for HOME-redirected profile environments, where
# $HOME points at a per-profile directory that has no credentials file.
# Operators symlink /etc/mosaic/credentials.json to the host's canonical
# file once, instead of exporting MOSAIC_CREDENTIALS_FILE per invocation.
if [[ -z "${MOSAIC_CREDENTIALS_FILE:-}" ]]; then
for _cand in "$HOME/.config/mosaic/credentials.json" "/etc/mosaic/credentials.json"; do
if [[ -f "$_cand" ]]; then MOSAIC_CREDENTIALS_FILE="$_cand"; break; fi
done
: "${MOSAIC_CREDENTIALS_FILE:=$HOME/.config/mosaic/credentials.json}"
fi
export MOSAIC_CREDENTIALS_FILE
_mosaic_require_jq() {
if ! command -v jq &>/dev/null; then
echo "Error: jq is required but not installed" >&2
return 1
fi
}
_mosaic_read_cred() {
local jq_path="$1"
if [[ ! -f "$MOSAIC_CREDENTIALS_FILE" ]]; then
echo "Error: Credentials file not found: $MOSAIC_CREDENTIALS_FILE" >&2
return 1
fi
jq -r "$jq_path // empty" "$MOSAIC_CREDENTIALS_FILE"
}
# Decide curl TLS flag for a target URL: validate public hosts (MITM matters on
# WAN); allow self-signed only for private-network IP literals (trusted LAN) or an
# explicit $MOSAIC_INSECURE_TLS opt-in. Echoes "-k" or "" (empty).
_mosaic_tls_opt() {
local url="$1" host
[[ -n "${MOSAIC_INSECURE_TLS:-}" ]] && { echo "-k"; return; }
host=$(printf '%s' "$url" | sed -E 's#^[a-zA-Z]+://([^/:]+).*#\1#')
if [[ "$host" =~ ^(10\.|127\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.) ]]; then
echo "-k"; return
fi
echo ""
}
# Sync Woodpecker credentials to ~/.woodpecker/<instance>.env
# Only writes when values differ to avoid unnecessary disk writes.
_mosaic_sync_woodpecker_env() {
local instance="$1" url="$2" token="$3"
local env_file="$HOME/.woodpecker/${instance}.env"
[[ -d "$HOME/.woodpecker" ]] || return 0
local expected
expected=$(printf '# %s Woodpecker CI\nexport WOODPECKER_SERVER="%s"\nexport WOODPECKER_TOKEN="%s"\n' \
"$instance" "$url" "$token")
if [[ -f "$env_file" ]]; then
local current_url current_token
current_url=$(grep -oP '(?<=WOODPECKER_SERVER=").*(?=")' "$env_file" 2>/dev/null || true)
current_token=$(grep -oP '(?<=WOODPECKER_TOKEN=").*(?=")' "$env_file" 2>/dev/null || true)
[[ "$current_url" == "$url" && "$current_token" == "$token" ]] && return 0
fi
printf '%s\n' "$expected" > "$env_file"
}
# Load legacy flat Woodpecker credentials (.woodpecker.url / .woodpecker.token).
# Some environments export WOODPECKER_INSTANCE=mosaic, but the current
# credentials.json may still use the legacy flat schema. Treat "mosaic" as the
# default flat instance when a nested .woodpecker.mosaic object is absent.
_mosaic_load_woodpecker_legacy() {
export WOODPECKER_URL="$(_mosaic_read_cred '.woodpecker.url')"
export WOODPECKER_TOKEN="$(_mosaic_read_cred '.woodpecker.token')"
export WOODPECKER_INSTANCE="${WOODPECKER_INSTANCE:-mosaic}"
WOODPECKER_URL="${WOODPECKER_URL%/}"
[[ -n "$WOODPECKER_URL" ]] || { echo "Error: woodpecker.url not found" >&2; return 1; }
[[ -n "$WOODPECKER_TOKEN" ]] || { echo "Error: woodpecker.token not found" >&2; return 1; }
_mosaic_sync_woodpecker_env "$WOODPECKER_INSTANCE" "$WOODPECKER_URL" "$WOODPECKER_TOKEN"
}
load_credentials() {
local service="$1"
if [[ -z "$service" || "$service" == "--help" ]]; then
cat <<'EOF'
Usage: load_credentials <service>
Services and exported variables:
portainer → PORTAINER_URL, PORTAINER_API_KEY
coolify → COOLIFY_URL, COOLIFY_TOKEN
authentik → AUTHENTIK_URL, AUTHENTIK_TOKEN, AUTHENTIK_TEST_USER, AUTHENTIK_TEST_PASSWORD (uses default instance)
authentik-<name> → AUTHENTIK_URL, AUTHENTIK_TOKEN, AUTHENTIK_TEST_USER, AUTHENTIK_TEST_PASSWORD (specific instance, e.g. authentik-usc)
glpi → GLPI_URL, GLPI_APP_TOKEN, GLPI_USER_TOKEN
github → GITHUB_TOKEN
gitea-mosaicstack → GITEA_URL, GITEA_TOKEN
gitea-usc → GITEA_URL, GITEA_TOKEN
woodpecker → WOODPECKER_URL, WOODPECKER_TOKEN (uses default instance)
woodpecker-<name> → WOODPECKER_URL, WOODPECKER_TOKEN (specific instance, e.g. woodpecker-usc)
cloudflare → CLOUDFLARE_API_TOKEN (uses default instance)
cloudflare-<name> → CLOUDFLARE_API_TOKEN (specific instance, e.g. cloudflare-personal)
turbo-cache → TURBO_API, TURBO_TOKEN, TURBO_TEAM
openbrain → OPENBRAIN_URL, OPENBRAIN_TOKEN
EOF
return 0
fi
_mosaic_require_jq || return 1
case "$service" in
portainer)
export PORTAINER_URL="${PORTAINER_URL:-$(_mosaic_read_cred '.portainer.url')}"
export PORTAINER_API_KEY="${PORTAINER_API_KEY:-$(_mosaic_read_cred '.portainer.api_key')}"
PORTAINER_URL="${PORTAINER_URL%/}"
[[ -n "$PORTAINER_URL" ]] || { echo "Error: portainer.url not found" >&2; return 1; }
[[ -n "$PORTAINER_API_KEY" ]] || { echo "Error: portainer.api_key not found" >&2; return 1; }
;;
coolify)
export COOLIFY_URL="${COOLIFY_URL:-$(_mosaic_read_cred '.coolify.url')}"
export COOLIFY_TOKEN="${COOLIFY_TOKEN:-$(_mosaic_read_cred '.coolify.app_token')}"
COOLIFY_URL="${COOLIFY_URL%/}"
[[ -n "$COOLIFY_URL" ]] || { echo "Error: coolify.url not found" >&2; return 1; }
[[ -n "$COOLIFY_TOKEN" ]] || { echo "Error: coolify.app_token not found" >&2; return 1; }
;;
authentik-*)
local ak_instance="${service#authentik-}"
export AUTHENTIK_URL="$(_mosaic_read_cred ".authentik.${ak_instance}.url")"
export AUTHENTIK_TOKEN="$(_mosaic_read_cred ".authentik.${ak_instance}.token")"
export AUTHENTIK_TEST_USER="$(_mosaic_read_cred ".authentik.${ak_instance}.test_user.username")"
export AUTHENTIK_TEST_PASSWORD="$(_mosaic_read_cred ".authentik.${ak_instance}.test_user.password")"
export AUTHENTIK_INSTANCE="$ak_instance"
AUTHENTIK_URL="${AUTHENTIK_URL%/}"
[[ -n "$AUTHENTIK_URL" ]] || { echo "Error: authentik.${ak_instance}.url not found" >&2; return 1; }
;;
authentik)
local ak_default
ak_default="${AUTHENTIK_INSTANCE:-$(_mosaic_read_cred '.authentik.default')}"
if [[ -z "$ak_default" ]]; then
# Fallback: try legacy flat structure (.authentik.url)
local legacy_url
legacy_url="$(_mosaic_read_cred '.authentik.url')"
if [[ -n "$legacy_url" ]]; then
export AUTHENTIK_URL="${AUTHENTIK_URL:-$legacy_url}"
export AUTHENTIK_TOKEN="${AUTHENTIK_TOKEN:-$(_mosaic_read_cred '.authentik.token')}"
export AUTHENTIK_TEST_USER="${AUTHENTIK_TEST_USER:-$(_mosaic_read_cred '.authentik.test_user.username')}"
export AUTHENTIK_TEST_PASSWORD="${AUTHENTIK_TEST_PASSWORD:-$(_mosaic_read_cred '.authentik.test_user.password')}"
AUTHENTIK_URL="${AUTHENTIK_URL%/}"
[[ -n "$AUTHENTIK_URL" ]] || { echo "Error: authentik.url not found" >&2; return 1; }
else
echo "Error: authentik.default not set and no AUTHENTIK_INSTANCE env var" >&2
echo "Available instances: $(jq -r '.authentik | keys | join(", ")' "$MOSAIC_CREDENTIALS_FILE" 2>/dev/null)" >&2
return 1
fi
else
load_credentials "authentik-${ak_default}"
fi
;;
glpi)
export GLPI_URL="${GLPI_URL:-$(_mosaic_read_cred '.glpi.url')}"
export GLPI_APP_TOKEN="${GLPI_APP_TOKEN:-$(_mosaic_read_cred '.glpi.app_token')}"
export GLPI_USER_TOKEN="${GLPI_USER_TOKEN:-$(_mosaic_read_cred '.glpi.user_token')}"
GLPI_URL="${GLPI_URL%/}"
[[ -n "$GLPI_URL" ]] || { echo "Error: glpi.url not found" >&2; return 1; }
;;
github)
export GITHUB_TOKEN="${GITHUB_TOKEN:-$(_mosaic_read_cred '.github.token')}"
[[ -n "$GITHUB_TOKEN" ]] || { echo "Error: github.token not found" >&2; return 1; }
;;
gitea-mosaicstack)
export GITEA_URL="${GITEA_URL:-$(_mosaic_read_cred '.gitea.mosaicstack.url')}"
export GITEA_TOKEN="${GITEA_TOKEN:-$(_mosaic_read_cred '.gitea.mosaicstack.token')}"
GITEA_URL="${GITEA_URL%/}"
[[ -n "$GITEA_URL" ]] || { echo "Error: gitea.mosaicstack.url not found" >&2; return 1; }
[[ -n "$GITEA_TOKEN" ]] || { echo "Error: gitea.mosaicstack.token not found" >&2; return 1; }
;;
gitea-usc)
export GITEA_URL="${GITEA_URL:-$(_mosaic_read_cred '.gitea.usc.url')}"
export GITEA_TOKEN="${GITEA_TOKEN:-$(_mosaic_read_cred '.gitea.usc.token')}"
GITEA_URL="${GITEA_URL%/}"
[[ -n "$GITEA_URL" ]] || { echo "Error: gitea.usc.url not found" >&2; return 1; }
[[ -n "$GITEA_TOKEN" ]] || { echo "Error: gitea.usc.token not found" >&2; return 1; }
;;
woodpecker-*)
local wp_instance="${service#woodpecker-}"
# credentials.json is authoritative — always read from it, ignore env.
# Backward compatibility: the default Mosaic Woodpecker instance may be
# stored in the legacy flat schema (.woodpecker.url/.token) instead of
# .woodpecker.mosaic.url/.token.
if [[ "$wp_instance" == "mosaic" ]] && [[ -z "$(_mosaic_read_cred '.woodpecker.mosaic.url')" ]] && [[ -n "$(_mosaic_read_cred '.woodpecker.url')" ]]; then
WOODPECKER_INSTANCE="mosaic" _mosaic_load_woodpecker_legacy
return $?
fi
export WOODPECKER_URL="$(_mosaic_read_cred ".woodpecker.${wp_instance}.url")"
export WOODPECKER_TOKEN="$(_mosaic_read_cred ".woodpecker.${wp_instance}.token")"
export WOODPECKER_INSTANCE="$wp_instance"
WOODPECKER_URL="${WOODPECKER_URL%/}"
[[ -n "$WOODPECKER_URL" ]] || { echo "Error: woodpecker.${wp_instance}.url not found" >&2; return 1; }
[[ -n "$WOODPECKER_TOKEN" ]] || { echo "Error: woodpecker.${wp_instance}.token not found" >&2; return 1; }
# Sync to ~/.woodpecker/<instance>.env so the wp CLI wrapper stays current
_mosaic_sync_woodpecker_env "$wp_instance" "$WOODPECKER_URL" "$WOODPECKER_TOKEN"
;;
woodpecker)
# Resolve default instance, then load it. If WOODPECKER_INSTANCE is set to
# "mosaic" by a shell/profile but credentials.json still uses the legacy
# flat .woodpecker.url/.token schema, load the flat credentials instead of
# failing with "woodpecker.mosaic.url not found".
local wp_default
wp_default="${WOODPECKER_INSTANCE:-$(_mosaic_read_cred '.woodpecker.default')}"
if [[ -z "$wp_default" ]]; then
# Fallback: try legacy flat structure (.woodpecker.url / .woodpecker.token)
local legacy_url
legacy_url="$(_mosaic_read_cred '.woodpecker.url')"
if [[ -n "$legacy_url" ]]; then
_mosaic_load_woodpecker_legacy
else
echo "Error: woodpecker.default not set and no WOODPECKER_INSTANCE env var" >&2
echo "Available instances: $(jq -r '.woodpecker | keys | join(", ")' "$MOSAIC_CREDENTIALS_FILE" 2>/dev/null)" >&2
return 1
fi
else
if [[ "$wp_default" == "mosaic" ]] && [[ -z "$(_mosaic_read_cred '.woodpecker.mosaic.url')" ]] && [[ -n "$(_mosaic_read_cred '.woodpecker.url')" ]]; then
WOODPECKER_INSTANCE="mosaic" _mosaic_load_woodpecker_legacy
else
load_credentials "woodpecker-${wp_default}"
fi
fi
;;
cloudflare-*)
local cf_instance="${service#cloudflare-}"
export CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN:-$(_mosaic_read_cred ".cloudflare.${cf_instance}.api_token")}"
export CLOUDFLARE_INSTANCE="$cf_instance"
[[ -n "$CLOUDFLARE_API_TOKEN" ]] || { echo "Error: cloudflare.${cf_instance}.api_token not found" >&2; return 1; }
;;
cloudflare)
# Resolve default instance, then load it
local cf_default
cf_default="${CLOUDFLARE_INSTANCE:-$(_mosaic_read_cred '.cloudflare.default')}"
if [[ -z "$cf_default" ]]; then
echo "Error: cloudflare.default not set and no CLOUDFLARE_INSTANCE env var" >&2
return 1
fi
load_credentials "cloudflare-${cf_default}"
;;
turbo-cache)
export TURBO_API="${TURBO_API:-$(_mosaic_read_cred '.turbo_cache.api_url')}"
export TURBO_TOKEN="${TURBO_TOKEN:-$(_mosaic_read_cred '.turbo_cache.token')}"
export TURBO_TEAM="${TURBO_TEAM:-$(_mosaic_read_cred '.turbo_cache.team')}"
[[ -n "$TURBO_API" ]] || { echo "Error: turbo_cache.api_url not found" >&2; return 1; }
[[ -n "$TURBO_TOKEN" ]] || { echo "Error: turbo_cache.token not found" >&2; return 1; }
[[ -n "$TURBO_TEAM" ]] || { echo "Error: turbo_cache.team not found" >&2; return 1; }
;;
openbrain)
export OPENBRAIN_URL="${OPENBRAIN_URL:-$(_mosaic_read_cred '.openbrain.url')}"
export OPENBRAIN_TOKEN="${OPENBRAIN_TOKEN:-$(_mosaic_read_cred '.openbrain.api_key')}"
OPENBRAIN_URL="${OPENBRAIN_URL%/}"
[[ -n "$OPENBRAIN_URL" ]] || { echo "Error: openbrain.url not found" >&2; return 1; }
[[ -n "$OPENBRAIN_TOKEN" ]] || { echo "Error: openbrain.api_key not found" >&2; return 1; }
;;
*)
echo "Error: Unknown service '$service'" >&2
echo "Supported: portainer, coolify, authentik[-<name>], glpi, github, gitea-mosaicstack, gitea-usc, woodpecker[-<name>], cloudflare[-<name>], turbo-cache, openbrain" >&2
return 1
;;
esac
}
# Common HTTP helper — makes a curl request and separates body from status code
# Usage: mosaic_http GET "/api/v1/endpoint" "Authorization: Bearer $TOKEN" [base_url]
# Returns: body on stdout, sets MOSAIC_HTTP_CODE
mosaic_http() {
local method="$1"
local endpoint="$2"
local auth_header="$3"
local base_url="${4:-}"
local response
local _tls; _tls=$(_mosaic_tls_opt "${base_url}${endpoint}")
response=$(curl -sS $_tls -w "\n%{http_code}" -X "$method" \
-H "$auth_header" \
-H "Content-Type: application/json" \
"${base_url}${endpoint}")
MOSAIC_HTTP_CODE=$(echo "$response" | tail -n1)
echo "$response" | sed '$d'
}
# POST variant with body
# Usage: mosaic_http_post "/api/v1/endpoint" "Authorization: Bearer $TOKEN" '{"key":"val"}' [base_url]
mosaic_http_post() {
local endpoint="$1"
local auth_header="$2"
local data="$3"
local base_url="${4:-}"
local response
local _tls; _tls=$(_mosaic_tls_opt "${base_url}${endpoint}")
response=$(curl -sS $_tls -w "\n%{http_code}" -X POST \
-H "$auth_header" \
-H "Content-Type: application/json" \
-d "$data" \
"${base_url}${endpoint}")
MOSAIC_HTTP_CODE=$(echo "$response" | tail -n1)
echo "$response" | sed '$d'
}
# PATCH variant with body
mosaic_http_patch() {
local endpoint="$1"
local auth_header="$2"
local data="$3"
local base_url="${4:-}"
local response
local _tls; _tls=$(_mosaic_tls_opt "${base_url}${endpoint}")
response=$(curl -sS $_tls -w "\n%{http_code}" -X PATCH \
-H "$auth_header" \
-H "Content-Type: application/json" \
-d "$data" \
"${base_url}${endpoint}")
MOSAIC_HTTP_CODE=$(echo "$response" | tail -n1)
echo "$response" | sed '$d'
}
@@ -0,0 +1,257 @@
#!/usr/bin/env bash
# Shared bash reader for framework-manifest.txt (#791).
#
# This is the bash half of the SSOT ownership resolver; the TypeScript half is
# packages/mosaic/src/framework/manifest.ts. BOTH read the same
# framework-manifest.txt and MUST resolve identical ownership for any path — the
# parity test (manifest-parity.spec.ts) invokes this file's `resolve` CLI and
# compares it against the TS resolver, so the two can never drift (the #631
# two-copies failure class this closes).
#
# Ownership resolution (deny-wins / fail-safe):
# 1. operator glob matches -> operator
# 2. else framework glob -> framework
# 3. else -> operator (UNKNOWN defaults to operator, #791)
#
# Globs are compiled once at load into exact-prefix checks or POSIX EREs, so the
# hot resolver (manifest_is_framework) forks no subprocesses — the installer
# calls it once per file across the whole tree.
#
# Usage as a library (source it, then):
# manifest_load [manifest-file] # populates + compiles the manifest
# manifest_is_framework <rel-path> # rc 0 = framework-owned, rc 1 = operator
# manifest_resolve <rel-path> # echoes: framework | operator
# manifest_subtree_roots # echoes shipped framework `dir/**` roots
#
# Usage as a CLI (parity harness):
# bash manifest.sh resolve <rel-path>
# bash manifest.sh subtree-roots
# bash manifest.sh classify # reads paths on stdin -> "<own>\t<path>"
MANIFEST_FRAMEWORK=()
MANIFEST_OPERATOR=()
# Compiled forms (parallel arrays). _*_KIND[i] is "exact" or "re".
_MF_KIND=(); _MF_EXACT=(); _MF_RE=()
_MO_KIND=(); _MO_EXACT=(); _MO_RE=()
_MF_ROOTS=()
_manifest_default_root() { cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd; }
# Normalize a path/glob: backslashes -> slashes, strip leading ./ and /, strip
# trailing / (mirrors normalizeRel in manifest.ts).
_manifest_norm() {
local p="$1"
p="${p//\\//}"
p="${p#./}"
while [[ "$p" == /* ]]; do p="${p#/}"; done
while [[ "$p" == */ ]]; do p="${p%/}"; done
printf '%s' "$p"
}
# Translate a normalized glob into a POSIX ERE body (mirrors globToRegExpBody).
_manifest_glob_to_ere() {
local pattern; pattern="$(_manifest_norm "$1")"
local out="" c n i len=${#pattern} trailing
for (( i = 0; i < len; i++ )); do
c="${pattern:i:1}"
if [[ "$c" == "*" ]]; then
n="${pattern:i+1:1}"
if [[ "$n" == "*" ]]; then
i=$((i + 1))
trailing=0
if [[ "${pattern:i+1:1}" == "/" ]]; then i=$((i + 1)); trailing=1; fi
if [[ "$out" == */ ]]; then
out="${out%/}(/.*)?"
elif [[ "$trailing" -eq 1 ]]; then
out="$out(.*/)?"
else
out="$out.*"
fi
else
out="${out}[^/]*"
fi
else
case "$c" in
.|+|\?|^|\$|\{|\}|\(|\)|\||\[|\]|\\) out="$out\\$c" ;;
*) out="$out$c" ;;
esac
fi
done
printf '%s' "$out"
}
# Compile one raw glob into (kind, exact, re) appended to the given section.
# $1 = raw glob, $2 = section letter (F|O).
_manifest_compile_one() {
local norm; norm="$(_manifest_norm "$1")"
[[ -n "$norm" ]] || return 0
if [[ "$norm" == *"*"* ]]; then
local re
re="^$(_manifest_glob_to_ere "$norm")\$"
if [[ "$2" == F ]]; then
_MF_KIND+=(re); _MF_EXACT+=(""); _MF_RE+=("$re")
else
_MO_KIND+=(re); _MO_EXACT+=(""); _MO_RE+=("$re")
fi
else
if [[ "$2" == F ]]; then
_MF_KIND+=(exact); _MF_EXACT+=("$norm"); _MF_RE+=("")
else
_MO_KIND+=(exact); _MO_EXACT+=("$norm"); _MO_RE+=("")
fi
fi
[[ "$2" == F && "$norm" == */"**" ]] && _MF_ROOTS+=("${norm%/**}")
return 0
}
_manifest_compile() {
_MF_KIND=(); _MF_EXACT=(); _MF_RE=(); _MF_ROOTS=()
_MO_KIND=(); _MO_EXACT=(); _MO_RE=()
local g
for g in "${MANIFEST_FRAMEWORK[@]:-}"; do [[ -n "$g" ]] && _manifest_compile_one "$g" F; done
for g in "${MANIFEST_OPERATOR[@]:-}"; do [[ -n "$g" ]] && _manifest_compile_one "$g" O; done
# Explicit success: an empty operator array makes the final `[[ -n "" ]] && …`
# short-circuit to rc 1, which would otherwise become this function's (and
# manifest_load's) return code — a spurious failure (#791 B2). Never rely on
# the last loop's exit status here.
return 0
}
# Load + compile the manifest. Rejects a malformed file the same way
# parseManifest() does (entry before a section header / unknown header).
manifest_load() {
local file="${1:-}"
[[ -n "$file" ]] || file="$(_manifest_default_root)/framework-manifest.txt"
# Fail CLOSED on a missing/unreadable manifest. Without this, `done < "$file"`
# aborts on a raw redirection error with no explanation; downstream that reads
# as "no framework paths" and an upgrade could no-op silently (#791 B2/B3).
if [[ ! -r "$file" ]]; then
echo "manifest: cannot read manifest file: $file — refusing to sync (fail-closed)." >&2
return 1
fi
MANIFEST_FRAMEWORK=()
MANIFEST_OPERATOR=()
local section="" line
while IFS= read -r line || [[ -n "$line" ]]; do
line="${line#"${line%%[![:space:]]*}"}" # ltrim
line="${line%"${line##*[![:space:]]}"}" # rtrim
[[ -z "$line" || "${line:0:1}" == "#" ]] && continue
case "$line" in
"[framework]") section=framework; continue ;;
"[operator]") section=operator; continue ;;
"["*) echo "manifest: unknown section header: $line" >&2; return 1 ;;
esac
if [[ -z "$section" ]]; then
echo "manifest: entry before any [section] header: $line" >&2
return 1
fi
if [[ "$section" == framework ]]; then
MANIFEST_FRAMEWORK+=("$line")
else
MANIFEST_OPERATOR+=("$line")
fi
done < "$file"
# An empty or comment-only manifest defines NO framework-owned paths. Treating
# that as valid would make every path resolve operator and an upgrade prune
# nothing / write nothing — a silent no-op indistinguishable from success.
# Fail loud instead, mirroring parseManifest()'s throw in manifest.ts (#791 B2).
if [[ ${#MANIFEST_FRAMEWORK[@]} -eq 0 ]]; then
echo "manifest: no [framework] entries in $file — refusing to sync (empty or malformed manifest)." >&2
return 1
fi
# An entry like `/` or `./` normalizes to nothing and compiles to a glob that
# matches no path — so a manifest whose only [framework] entries are degenerate
# passes the count guard above but leaves the framework matcher empty: every
# path resolves operator, the exact silent no-op we fail closed against. Require
# at least one entry with a real (non-slash, non-dot) character. Mirrors
# parseManifest()'s `isUsableFrameworkGlob` `/[^/.]/` test in manifest.ts (#791 blocker-B).
local _g _usable=0
for _g in "${MANIFEST_FRAMEWORK[@]:-}"; do
if [[ "$(_manifest_norm "$_g")" =~ [^/.] ]]; then _usable=1; break; fi
done
if [[ "$_usable" -eq 0 ]]; then
echo "manifest: no usable [framework] entries in $file (every entry is empty or a bare dot segment) — refusing to sync (malformed manifest)." >&2
return 1
fi
_manifest_compile
return 0
}
# Fork-free: does $1 (a mosaic-home-relative path) match an operator glob?
_mo_matches() {
local path="$1" i n=${#_MO_KIND[@]} re pat
for (( i = 0; i < n; i++ )); do
if [[ "${_MO_KIND[i]}" == exact ]]; then
pat="${_MO_EXACT[i]}"
# Operator exact entries are file carve-outs, not implicit directory
# prefixes. Subtree ownership must be declared explicitly as `dir/**`;
# otherwise one bare directory entry can hide all drift beneath it.
[[ "$path" == "$pat" ]] && return 0
else
re="${_MO_RE[i]}"
[[ "$path" =~ $re ]] && return 0
fi
done
return 1
}
# Fork-free: does $1 match a framework glob?
_mf_matches() {
local path="$1" i n=${#_MF_KIND[@]} re pat
for (( i = 0; i < n; i++ )); do
if [[ "${_MF_KIND[i]}" == exact ]]; then
pat="${_MF_EXACT[i]}"
[[ "$path" == "$pat" || "$path" == "$pat/"* ]] && return 0
else
re="${_MF_RE[i]}"
[[ "$path" =~ $re ]] && return 0
fi
done
return 1
}
# The installer hot path — no subshell. rc 0 = framework-owned, rc 1 = operator
# (deny-wins / fail-safe). Assumes an already-clean POSIX relative path.
manifest_is_framework() {
_mo_matches "$1" && return 1
_mf_matches "$1" && return 0
return 1
}
# Echo the ownership of a path: framework | operator. Normalizes first, so it is
# safe for CLI / test callers passing unnormalized input.
manifest_resolve() {
local path; path="$(_manifest_norm "$1")"
if manifest_is_framework "$path"; then echo framework; else echo operator; fi
}
# Echo each shipped framework subtree root (a `dir/**` entry, without the /**).
manifest_subtree_roots() {
local r
for r in "${_MF_ROOTS[@]:-}"; do [[ -n "$r" ]] && printf '%s\n' "$r"; done
}
# CLI dispatch — only when executed directly, never when sourced.
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
set -o pipefail
# Propagate a fail-closed manifest_load (missing/empty/malformed) as a non-zero
# exit instead of continuing to resolve against empty compiled arrays — that is
# what lets the parity test assert bash and TS reject the same bad inputs (#791 B2).
manifest_load "${MANIFEST_FILE:-}" || exit 1
cmd="${1:-}"
case "$cmd" in
resolve) manifest_resolve "${2:?path required}" ;;
subtree-roots) manifest_subtree_roots ;;
classify)
while IFS= read -r p; do
[[ -z "$p" ]] && continue
printf '%s\t%s\n' "$(manifest_resolve "$p")" "$p"
done
;;
*)
echo "usage: manifest.sh {resolve <path>|subtree-roots|classify}" >&2
exit 2
;;
esac
fi
@@ -0,0 +1,126 @@
#!/usr/bin/env bash
set -euo pipefail
TARGET_DIR="$(pwd)"
FORCE=0
QUALITY_TEMPLATE=""
while [[ $# -gt 0 ]]; do
case "$1" in
--force)
FORCE=1
shift
;;
--quality-template)
QUALITY_TEMPLATE="${2:-}"
shift 2
;;
*)
TARGET_DIR="$1"
shift
;;
esac
done
if [[ ! -d "$TARGET_DIR" ]]; then
echo "[mosaic] Target directory does not exist: $TARGET_DIR" >&2
exit 1
fi
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
TEMPLATE_ROOT="$MOSAIC_HOME/templates/repo"
if [[ ! -d "$TEMPLATE_ROOT" ]]; then
echo "[mosaic] Missing templates at $TEMPLATE_ROOT" >&2
echo "[mosaic] Install or refresh framework: ~/.config/mosaic/install.sh" >&2
exit 1
fi
mkdir -p "$TARGET_DIR/.mosaic" "$TARGET_DIR/scripts/agent"
mkdir -p "$TARGET_DIR/.mosaic/orchestrator" "$TARGET_DIR/.mosaic/orchestrator/logs" "$TARGET_DIR/.mosaic/orchestrator/results"
copy_file() {
local src="$1"
local dst="$2"
if [[ -f "$dst" && "$FORCE" -ne 1 ]]; then
echo "[mosaic] Skip existing: $dst"
return
fi
cp "$src" "$dst"
echo "[mosaic] Wrote: $dst"
}
copy_file "$TEMPLATE_ROOT/.mosaic/README.md" "$TARGET_DIR/.mosaic/README.md"
copy_file "$TEMPLATE_ROOT/.mosaic/repo-hooks.sh" "$TARGET_DIR/.mosaic/repo-hooks.sh"
copy_file "$TEMPLATE_ROOT/.mosaic/quality-rails.yml" "$TARGET_DIR/.mosaic/quality-rails.yml"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/config.json" "$TARGET_DIR/.mosaic/orchestrator/config.json"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/tasks.json" "$TARGET_DIR/.mosaic/orchestrator/tasks.json"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/state.json" "$TARGET_DIR/.mosaic/orchestrator/state.json"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/matrix_state.json" "$TARGET_DIR/.mosaic/orchestrator/matrix_state.json"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/logs/.gitkeep" "$TARGET_DIR/.mosaic/orchestrator/logs/.gitkeep"
copy_file "$TEMPLATE_ROOT/.mosaic/orchestrator/results/.gitkeep" "$TARGET_DIR/.mosaic/orchestrator/results/.gitkeep"
for file in "$TEMPLATE_ROOT"/scripts/agent/*.sh; do
base="$(basename "$file")"
copy_file "$file" "$TARGET_DIR/scripts/agent/$base"
chmod +x "$TARGET_DIR/scripts/agent/$base"
done
if [[ ! -f "$TARGET_DIR/AGENTS.md" ]]; then
cat > "$TARGET_DIR/AGENTS.md" <<'AGENTS_EOF'
# Agent Guidelines
## Required Load Order
1. `~/.config/mosaic/SOUL.md`
2. `~/.config/mosaic/STANDARDS.md`
3. `~/.config/mosaic/AGENTS.md`
4. `~/.config/mosaic/guides/E2E-DELIVERY.md`
5. `AGENTS.md` (this file)
6. Runtime-specific guide: `~/.config/mosaic/runtime/<runtime>/RUNTIME.md`
7. `.mosaic/repo-hooks.sh`
## Session Lifecycle
```bash
bash scripts/agent/session-start.sh
bash scripts/agent/critical.sh
bash scripts/agent/session-end.sh
```
## Shared Tools
- Quality and orchestration guides: `~/.config/mosaic/guides/`
- Shared automation tools: `~/.config/mosaic/tools/`
## Repo-Specific Notes
- Add project constraints and workflows here.
- Implement hook functions in `.mosaic/repo-hooks.sh`.
- Scratchpads are mandatory for non-trivial tasks.
AGENTS_EOF
echo "[mosaic] Wrote: $TARGET_DIR/AGENTS.md"
else
echo "[mosaic] AGENTS.md exists; add standards load order if missing"
fi
echo "[mosaic] Repo bootstrap complete: $TARGET_DIR"
echo "[mosaic] Next: edit $TARGET_DIR/.mosaic/repo-hooks.sh with project workflows"
echo "[mosaic] Optional: apply quality tools via ~/.config/mosaic/bin/mosaic-quality-apply --template <template> --target $TARGET_DIR"
echo "[mosaic] Optional: run orchestrator rail via ~/.config/mosaic/bin/mosaic-orchestrator-drain"
echo "[mosaic] Optional: run detached orchestrator via bash $TARGET_DIR/scripts/agent/orchestrator-daemon.sh start"
if [[ -n "$QUALITY_TEMPLATE" ]]; then
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-quality-apply" ]]; then
"$MOSAIC_HOME/tools/_scripts/mosaic-quality-apply" --template "$QUALITY_TEMPLATE" --target "$TARGET_DIR"
if [[ -f "$TARGET_DIR/.mosaic/quality-rails.yml" ]]; then
sed -i "s/^enabled:.*/enabled: true/" "$TARGET_DIR/.mosaic/quality-rails.yml"
sed -i "s/^template:.*/template: \"$QUALITY_TEMPLATE\"/" "$TARGET_DIR/.mosaic/quality-rails.yml"
fi
echo "[mosaic] Applied quality tools template: $QUALITY_TEMPLATE"
else
echo "[mosaic] WARN: mosaic-quality-apply not found; skipping quality tools apply" >&2
fi
fi
@@ -0,0 +1,147 @@
#!/usr/bin/env bash
set -euo pipefail
RUNTIME="claude"
APPLY=0
ALL_EMPTY=0
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Remove empty runtime directories created by migration/drift.
Default mode only checks managed legacy surfaces. Use --all-empty for broader cleanup.
Options:
--runtime <name> Runtime to clean (default: claude)
--all-empty Scan all runtime directories (except protected paths)
--apply Perform deletions (default: dry-run)
-h, --help Show help
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--runtime)
[[ $# -lt 2 ]] && { echo "Missing value for --runtime" >&2; exit 1; }
RUNTIME="$2"
shift 2
;;
--all-empty)
ALL_EMPTY=1
shift
;;
--apply)
APPLY=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
case "$RUNTIME" in
claude)
TARGET_ROOT="$HOME/.claude"
managed_roots=(
"$HOME/.claude/agent-guides"
"$HOME/.claude/scripts"
"$HOME/.claude/templates"
"$HOME/.claude/presets"
"$HOME/.claude/skills"
"$HOME/.claude/agents"
"$HOME/.claude/agents.bak"
)
protected_roots=(
"$HOME/.claude/.git"
"$HOME/.claude/debug"
"$HOME/.claude/file-history"
"$HOME/.claude/projects"
"$HOME/.claude/session-env"
"$HOME/.claude/tasks"
"$HOME/.claude/todos"
"$HOME/.claude/plugins"
"$HOME/.claude/statsig"
"$HOME/.claude/logs"
"$HOME/.claude/shell-snapshots"
"$HOME/.claude/paste-cache"
"$HOME/.claude/plans"
"$HOME/.claude/ide"
"$HOME/.claude/cache"
)
;;
*)
echo "Unsupported runtime: $RUNTIME" >&2
exit 1
;;
esac
[[ -d "$TARGET_ROOT" ]] || { echo "[mosaic-clean] Runtime dir missing: $TARGET_ROOT" >&2; exit 1; }
is_protected() {
local path="$1"
for p in "${protected_roots[@]}"; do
[[ -e "$p" ]] || continue
case "$path" in
"$p"|"$p"/*)
return 0
;;
esac
done
return 1
}
collect_empty_dirs() {
if [[ $ALL_EMPTY -eq 1 ]]; then
find "$TARGET_ROOT" -depth -type d -empty
else
for r in "${managed_roots[@]}"; do
[[ -d "$r" ]] || continue
find "$r" -depth -type d -empty
done
fi
}
count_candidates=0
count_deletable=0
while IFS= read -r d; do
[[ -n "$d" ]] || continue
count_candidates=$((count_candidates + 1))
# Never remove runtime root.
[[ "$d" == "$TARGET_ROOT" ]] && continue
if is_protected "$d"; then
continue
fi
count_deletable=$((count_deletable + 1))
if [[ $APPLY -eq 1 ]]; then
rmdir "$d" 2>/dev/null || true
if [[ ! -d "$d" ]]; then
echo "[mosaic-clean] deleted: $d"
fi
else
echo "[mosaic-clean] would delete: $d"
fi
done < <(collect_empty_dirs | sort -u)
mode="managed"
[[ $ALL_EMPTY -eq 1 ]] && mode="all-empty"
if [[ $APPLY -eq 1 ]]; then
echo "[mosaic-clean] complete: mode=$mode deleted_or_attempted=$count_deletable candidates=$count_candidates runtime=$RUNTIME"
else
echo "[mosaic-clean] dry-run: mode=$mode deletable=$count_deletable candidates=$count_candidates runtime=$RUNTIME"
echo "[mosaic-clean] re-run with --apply to delete"
fi
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -x "scripts/agent/critical.sh" ]]; then
exec bash scripts/agent/critical.sh
fi
echo "[mosaic] Missing scripts/agent/critical.sh in $(pwd)" >&2
exit 1
+639
View File
@@ -0,0 +1,639 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
FAIL_ON_WARN=0
VERBOSE=0
FIX_MODE=0
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Audit Mosaic runtime state and detect drift across agent runtimes.
Options:
--fix Auto-fix: create missing dirs, wire skills into all harnesses
--fail-on-warn Exit non-zero when warnings are found
--verbose Print pass checks too
-h, --help Show help
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--fix)
FIX_MODE=1
shift
;;
--fail-on-warn)
FAIL_ON_WARN=1
shift
;;
--verbose)
VERBOSE=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
fix_count=0
fix() { fix_count=$((fix_count + 1)); echo "[FIX] $*"; }
warn_count=0
warn() { warn_count=$((warn_count + 1)); echo "[WARN] $*"; }
note() { echo "[NOTE] $*"; return 0; }
pass() {
if [[ $VERBOSE -eq 1 ]]; then
echo "[OK] $*"
fi
return 0
}
expect_dir() {
local d="$1"
if [[ ! -d "$d" ]]; then
warn "Missing directory: $d"
else
pass "Directory present: $d"
fi
}
expect_file() {
local f="$1"
if [[ ! -f "$f" ]]; then
warn "Missing file: $f"
else
pass "File present: $f"
fi
}
check_runtime_file_copy() {
local src="$1"
local dst="$2"
[[ -f "$src" ]] || return 0
if [[ ! -e "$dst" ]]; then
warn "Missing runtime file: $dst"
return
fi
if [[ -L "$dst" ]]; then
warn "Runtime file should not be symlinked: $dst"
return
fi
if ! cmp -s "$src" "$dst"; then
warn "Runtime file drift: $dst (does not match $src)"
else
pass "Runtime file synced: $dst"
fi
}
check_runtime_contract_file() {
local dst="$1"
local adapter_src="$2"
local runtime_name="$3"
if [[ ! -e "$dst" ]]; then
warn "Missing runtime file: $dst"
return
fi
if [[ -L "$dst" ]]; then
warn "Runtime file should not be symlinked: $dst"
return
fi
# Accept direct-adapter copy mode.
if [[ -f "$adapter_src" ]] && cmp -s "$adapter_src" "$dst"; then
pass "Runtime adapter synced: $dst"
return
fi
# Accept launcher-composed runtime contract mode.
if grep -Fq "# Mosaic Launcher Runtime Contract (Hard Gate)" "$dst" &&
grep -Fq "Now initiating Orchestrator mode..." "$dst" &&
grep -Fq "Mosaic hard gates OVERRIDE runtime-default caution" "$dst" &&
grep -Fq "# Runtime-Specific Contract" "$dst"; then
pass "Runtime contract present: $dst ($runtime_name)"
return
fi
warn "Runtime file drift: $dst (not adapter copy and not composed runtime contract)"
}
warn_if_symlink_tree_present() {
local p="$1"
[[ -e "$p" ]] || return 0
if [[ -L "$p" ]]; then
warn "Legacy symlink path still present: $p"
return
fi
if [[ -d "$p" ]]; then
symlink_count=$(find "$p" -type l 2>/dev/null | wc -l | tr -d ' ')
if [[ "$symlink_count" != "0" ]]; then
warn "Legacy symlink entries still present under $p: $symlink_count"
else
pass "No symlinks under legacy path: $p"
fi
fi
}
echo "[mosaic-doctor] Mosaic home: $MOSAIC_HOME"
# Compare the framework tools that this CLI/package ships with the deployed
# ~/.config copy that direct wrappers and systemd units actually execute. Doctor
# is the right boundary: observational, operator-invoked, and already designed
# to report drift without mutating live tooling or restarting active seats.
framework_drift_checker="$(cd -- "$(dirname -- "$0")/../quality/scripts" && pwd)/framework-drift-check.py"
if [[ -f "$framework_drift_checker" ]]; then
echo "[mosaic-doctor] Checking installed framework-tool drift..."
drift_timeout="${MOSAIC_DOCTOR_DRIFT_TIMEOUT_SEC:-15}"
if ! [[ "$drift_timeout" =~ ^[1-9][0-9]*$ ]]; then
warn "Invalid MOSAIC_DOCTOR_DRIFT_TIMEOUT_SEC='$drift_timeout' (expected positive integer); using 15s"
drift_timeout=15
fi
if command -v timeout >/dev/null 2>&1; then
set +e
timeout -s TERM -k 2 "${drift_timeout}s" \
python3 "$framework_drift_checker" --installed-root "$MOSAIC_HOME/tools"
drift_rc=$?
set -e
if [[ "$drift_rc" -eq 0 ]]; then
pass "Installed framework tools match shipped source"
elif [[ "$drift_rc" -eq 124 || "$drift_rc" -eq 137 || "$drift_rc" -eq 143 ]]; then
warn "CANNOT_ASSERT framework drift checker timed out after ${drift_timeout}s; continuing remaining doctor checks"
else
warn "Installed framework-tool drift detected (checker exit $drift_rc; no files changed)"
fi
else
warn "CANNOT_ASSERT timeout utility unavailable; refusing unbounded framework drift check and continuing remaining doctor checks"
fi
else
warn "Framework drift checker is absent from the shipped tools tree"
fi
# Canonical Mosaic checks
expect_file "$MOSAIC_HOME/STANDARDS.md"
expect_file "$MOSAIC_HOME/USER.md"
expect_file "$MOSAIC_HOME/TOOLS.md"
expect_dir "$MOSAIC_HOME/guides"
expect_dir "$MOSAIC_HOME/tools"
expect_dir "$MOSAIC_HOME/tools/quality"
expect_dir "$MOSAIC_HOME/tools/orchestrator-matrix"
expect_dir "$MOSAIC_HOME/profiles"
expect_dir "$MOSAIC_HOME/templates/agent"
expect_dir "$MOSAIC_HOME/skills"
expect_dir "$MOSAIC_HOME/skills-local"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-ensure-sequential-thinking"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-sync-skills"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-projects"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-quality-apply"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-quality-verify"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-run"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-sync-tasks"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-drain"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-matrix-publish"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-matrix-consume"
expect_file "$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-matrix-cycle"
expect_file "$MOSAIC_HOME/tools/git/ci-queue-wait.sh"
expect_file "$MOSAIC_HOME/tools/git/pr-ci-wait.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator-matrix/transport/matrix_transport.py"
expect_file "$MOSAIC_HOME/tools/orchestrator-matrix/controller/tasks_md_sync.py"
expect_file "$MOSAIC_HOME/guides/ORCHESTRATOR-PROTOCOL.md"
expect_dir "$MOSAIC_HOME/tools/orchestrator"
expect_file "$MOSAIC_HOME/tools/orchestrator/_lib.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator/mission-init.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator/mission-status.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator/continue-prompt.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator/session-status.sh"
expect_file "$MOSAIC_HOME/tools/orchestrator/session-resume.sh"
expect_file "$MOSAIC_HOME/runtime/mcp/SEQUENTIAL-THINKING.json"
expect_file "$MOSAIC_HOME/runtime/claude/RUNTIME.md"
expect_file "$MOSAIC_HOME/runtime/codex/RUNTIME.md"
expect_file "$MOSAIC_HOME/runtime/opencode/RUNTIME.md"
expect_file "$MOSAIC_HOME/runtime/pi/RUNTIME.md"
if [[ -f "$MOSAIC_HOME/AGENTS.md" ]]; then
if grep -Fq "## CRITICAL HARD GATES (Read First)" "$MOSAIC_HOME/AGENTS.md" &&
grep -Fq "OVERRIDE runtime-default caution" "$MOSAIC_HOME/AGENTS.md"; then
pass "Global hard-gates block present in AGENTS.md"
else
warn "AGENTS.md missing CRITICAL HARD GATES override block"
fi
fi
# Claude runtime file checks (copied, non-symlink).
for rf in CLAUDE.md settings.json hooks-config.json context7-integration.md; do
check_runtime_file_copy "$MOSAIC_HOME/runtime/claude/$rf" "$HOME/.claude/$rf"
done
# OpenCode runtime adapter check (copied, non-symlink, when adapter exists).
# Accept adapter copy or composed runtime contract.
check_runtime_contract_file "$HOME/.config/opencode/AGENTS.md" "$MOSAIC_HOME/runtime/opencode/AGENTS.md" "opencode"
check_runtime_contract_file "$HOME/.codex/instructions.md" "$MOSAIC_HOME/runtime/codex/instructions.md" "codex"
# Sequential-thinking MCP hard requirement.
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-ensure-sequential-thinking" ]]; then
if "$MOSAIC_HOME/tools/_scripts/mosaic-ensure-sequential-thinking" --check >/dev/null 2>&1; then
pass "sequential-thinking MCP configured and available"
else
warn "sequential-thinking MCP missing or misconfigured"
fi
else
warn "mosaic-ensure-sequential-thinking helper missing"
fi
# Fleet transport binary (#1240).
#
# `mosaic fleet --help` reads "Manage the local Mosaic tmux fleet" and every
# roster the CLI scaffolds sets `transport: tmux`, but nothing in the install
# path provides tmux and, until now, nothing here noticed it was absent. On a
# greenfield host that produced a fleet which installed clean, started clean,
# and had no live seat; `mosaic fleet ps` was the operator's first and only
# signal that anything was wrong.
#
# The roster's own `transport:` is read rather than assumed, so a host that
# declares something other than tmux is told about the binary it actually
# needs. Absent a roster the check still runs — `mosaic fleet init` will
# scaffold a tmux fleet on this host, and finding out beforehand is the point.
#
# `tools/install.sh` carries a deliberately parallel check at the end of its
# summary. The two are separate because the installer must be able to say this
# before the framework's own scripts are guaranteed to be on disk; keep their
# wording in step.
fleet_declared_transport() {
local roster="$MOSAIC_HOME/fleet/roster.yaml"
local declared=""
if [[ -f "$roster" ]]; then
declared="$(sed -n 's/^[[:space:]]*transport:[[:space:]]*//p' "$roster" | head -1 |
tr -d '"'\''' | tr -d '\r' | awk '{print $1}')"
fi
printf '%s\n' "${declared:-tmux}"
}
# Brain-home fleet-state resolution (#1298; canon STRUCTURE-CANON §2).
#
# Seat launch envs, roles.local overrides, and profile working copies resolve
# from the brain home when one is active; roster, baseline roles, run/, and
# services stay under MOSAIC_HOME. This check surfaces which tree fleet state
# resolves from and the drift a launch would otherwise hit at runtime:
#
# - a stale MOSAIC_BRAIN_HOME pointing at a directory with no fleet/agents is a
# misconfiguration the resolver honors (explicit wins) — warn, don't pass;
# - a symlinked brain or agents dir defeats the managed-directory boundary;
# - a group/world-readable agents dir violates the 0700 projection boundary;
# - env files left in the config-home tree while a brain is active are split
# state — the write path rejects NEW split writes, but nothing would ever
# tell the operator the old files are stranded.
resolve_brain_home() {
local explicit="${MOSAIC_BRAIN_HOME:-}"
if [[ -n "$(printf '%s' "$explicit" | tr -d '[:space:]')" ]]; then
printf '%s' "$explicit"
return
fi
if [[ "$(cd "$MOSAIC_HOME" 2>/dev/null && pwd -P)" == "$HOME/.config/mosaic" \
&& -d "$HOME/.mosaic/fleet/agents" ]]; then
printf '%s' "$HOME/.mosaic"
return
fi
printf '%s' "$MOSAIC_HOME"
}
check_brain_home() {
local brain agents mode
brain="$(resolve_brain_home)"
if [[ "$brain" == "$MOSAIC_HOME" ]]; then
# Implicit-path greenfield case (#1288 comment 23133, fred's trace): nothing
# in product code creates ~/.mosaic/fleet/agents — the first fleet write
# resolves legacy (generated-env-boundary resolves before creating) and
# then manufactures the evidence that keeps the host legacy. On a host with
# ~/.mosaic but no fleet/agents, the three operator checks all agree and all
# point the wrong way; this doctor is the only one that can disagree, so it
# must say it — as a note, not a warn: nothing is broken yet.
if [[ "$(cd "$MOSAIC_HOME" 2>/dev/null && pwd -P)" == "$HOME/.config/mosaic" \
&& -d "$HOME/.mosaic" && ! -d "$HOME/.mosaic/fleet/agents" ]]; then
note "Fleet state home: $MOSAIC_HOME (legacy). NOTE: ~/.mosaic exists but carries no fleet/agents — the first 'mosaic fleet regen' on this host locks in the legacy tree. Create ~/.mosaic/fleet/agents first to adopt the brain."
return
fi
pass "Fleet state home: $MOSAIC_HOME (legacy single-tree; no brain adopted)"
return
fi
agents="$brain/fleet/agents"
if [[ ! -d "$agents" ]]; then
warn "Brain home '$brain' has no fleet/agents — seat envs will not resolve from it. Point MOSAIC_BRAIN_HOME at a brain carrying fleet/agents, or unset it."
return
fi
if [[ -L "$brain" || -L "$agents" ]]; then
warn "Brain fleet-state path resolves through a symlink ($brain) — the managed-directory boundary requires regular directories."
return
fi
mode="$(stat -c '%a' -- "$agents" 2>/dev/null)" || mode=""
if [[ -n "$mode" ]] && (( (8#$mode & 8#077) != 0 )); then
warn "Brain agents dir '$agents' is group/world-accessible (mode $mode) — the projection boundary requires 0700."
return
fi
if [[ -d "$MOSAIC_HOME/fleet/agents" ]] \
&& ls "$MOSAIC_HOME/fleet/agents/"*.env* >/dev/null 2>&1; then
warn "Fleet env files exist in BOTH trees — brain '$brain' is active but '$MOSAIC_HOME/fleet/agents' still carries env files (split state). Migrate them (mosaic fleet regen) and remove the config-home copies."
return
fi
pass "Fleet state home: $brain (brain active); roster + templates: $MOSAIC_HOME"
}
check_fleet_transport() {
local transport
transport="$(fleet_declared_transport)"
if command -v "$transport" >/dev/null 2>&1; then
pass "Fleet transport available: $transport"
return
fi
if [[ -f "$MOSAIC_HOME/fleet/roster.yaml" ]]; then
warn "Fleet transport '$transport' is not installed — this host has a roster and no seat can launch. Install it (e.g. sudo apt-get install -y $transport), then 'mosaic fleet start'."
else
warn "Fleet transport '$transport' is not installed — 'mosaic fleet' cannot run seats here. Install it (e.g. sudo apt-get install -y $transport) before 'mosaic fleet init'."
fi
}
check_structure_anchor_provisioning() {
# T51 WP0b (spec §1.2a + PHASE2-MAP F7): audit the two declaration anchors.
# Doctor runs from operator shells and CI where the launcher exports do not
# exist, so this is an AUDIT ONLY — it never exports, writes, or fabricates
# values for consumption. Four states (charter):
# both present+nonempty PASS (values reported as paths only)
# one missing/empty WARN naming the var + the launcher as authority
# neither present INFORMATIONAL launcher-equivalent derivation,
# explicitly non-authoritative, + launcher warning;
# never an error by design (F7(b))
# Severity follows the doctor's existing conventions: pass/note are quiet
# (note unless --verbose), warn counts toward --fail-on-warn.
local host_root="${MOSAIC_HOST_ROOT:-}" brain_home="${MOSAIC_BRAIN_HOME:-}"
# T51P2WP0BRW B1: presence is tracked SEPARATELY from value — `${VAR:-}`
# collapses exported-empty into genuinely-unset, which mis-filed both-empty
# and the mixed empty/unset states as informational. Only BOTH-genuinely-
# absent may be informational (charter state 3); any present-but-empty or
# single-present state warns.
local host_set=0 brain_set=0
[[ -v MOSAIC_HOST_ROOT ]] && host_set=1
[[ -v MOSAIC_BRAIN_HOME ]] && brain_set=1
if [[ "$host_set" -eq 1 && "$brain_set" -eq 1 && -n "$host_root" && -n "$brain_home" ]]; then
pass "Structure anchors provisioned: MOSAIC_HOST_ROOT=$host_root MOSAIC_BRAIN_HOME=$brain_home (paths reported only; not expanded, not consumed)"
return
fi
if [[ "$host_set" -eq 0 && "$brain_set" -eq 0 ]]; then
note "Structure anchors not provisioned in this environment. Launcher-equivalent derivation (INFORMATIONAL, NON-AUTHORITATIVE — seats receive the authoritative values from the launchers): MOSAIC_HOST_ROOT would default to the operator home; MOSAIC_BRAIN_HOME would default to the brain tree resolved at launch. Doctor does not guess values for consumption; it audits provisioning."
note "Provision both anchors via the seat launchers (launch-seat.sh / launch-seat-claude.sh export them; see T51 spec §1.2a)."
return
fi
# At least one variable is present (possibly empty), or exactly one exists:
# every missing/empty anchor gets its own loud WARN naming the launchers.
if [[ "$host_set" -eq 0 ]]; then
warn "MOSAIC_HOST_ROOT is not set in this environment while MOSAIC_BRAIN_HOME is — declaration consumers fail closed without it (spec §1.2a). The seat launchers are the authoritative source."
elif [[ -z "$host_root" ]]; then
warn "MOSAIC_HOST_ROOT is present but EMPTY in this environment — declaration consumers fail closed without a usable value (spec §1.2a). The seat launchers are the authoritative source."
fi
if [[ "$brain_set" -eq 0 ]]; then
warn "MOSAIC_BRAIN_HOME is not set in this environment while MOSAIC_HOST_ROOT is — the projects/ mirror and brain declaration resolve from it (spec §1.2a). The seat launchers are the authoritative source."
elif [[ -z "$brain_home" ]]; then
warn "MOSAIC_BRAIN_HOME is present but EMPTY in this environment — the projects/ mirror and brain declaration resolve from it (spec §1.2a). The seat launchers are the authoritative source."
fi
}
check_fleet_transport
check_structure_anchor_provisioning
check_brain_home
# Legacy migration surfaces should no longer contain symlink trees.
legacy_paths=(
"$HOME/.claude/agent-guides"
"$HOME/.claude/scripts/git"
"$HOME/.claude/scripts/codex"
"$HOME/.claude/scripts/bootstrap"
"$HOME/.claude/scripts/cicd"
"$HOME/.claude/scripts/portainer"
"$HOME/.claude/templates"
"$HOME/.claude/presets/domains"
"$HOME/.claude/presets/tech-stacks"
"$HOME/.claude/presets/workflows"
)
for p in "${legacy_paths[@]}"; do
warn_if_symlink_tree_present "$p"
done
# Skills runtime checks (still symlinked into runtime-specific skills dirs).
for runtime_skills in "$HOME/.claude/skills" "$HOME/.codex/skills" "$HOME/.config/opencode/skills" "$HOME/.pi/agent/skills"; do
[[ -d "$runtime_skills" ]] || continue
while IFS= read -r -d '' skill; do
name="$(basename "$skill")"
[[ "$name" == .* ]] && continue
target="$runtime_skills/$name"
if [[ ! -e "$target" ]]; then
warn "Missing skill link: $target"
continue
fi
if [[ ! -L "$target" ]]; then
warn "Non-symlink skill entry: $target"
continue
fi
target_real="$(readlink -f "$target" 2>/dev/null || true)"
skill_real="$(readlink -f "$skill" 2>/dev/null || true)"
if [[ -z "$target_real" || -z "$skill_real" || "$target_real" != "$skill_real" ]]; then
warn "Drifted skill link: $target (expected -> $skill)"
else
pass "Linked skill: $target"
fi
done < <(find "$MOSAIC_HOME/skills" "$MOSAIC_HOME/skills-local" -mindepth 1 -maxdepth 1 -type d -print0)
done
# Broken links only in managed runtime skill dirs.
link_roots=(
"$HOME/.claude/skills"
"$HOME/.codex/skills"
"$HOME/.config/opencode/skills"
"$HOME/.pi/agent/skills"
)
existing_link_roots=()
for d in "${link_roots[@]}"; do
[[ -e "$d" ]] && existing_link_roots+=("$d")
done
broken_links=0
if [[ ${#existing_link_roots[@]} -gt 0 ]]; then
broken_links=$(find "${existing_link_roots[@]}" -xtype l 2>/dev/null | wc -l | tr -d ' ')
fi
if [[ "$broken_links" != "0" ]]; then
warn "Broken skill symlinks detected: $broken_links"
fi
# Pi agent skills directory check.
if [[ ! -d "$HOME/.pi/agent/skills" ]]; then
warn "Pi skills directory missing: $HOME/.pi/agent/skills"
else
pass "Pi skills directory present: $HOME/.pi/agent/skills"
fi
# Pi settings.json — check skills path is configured.
pi_settings="$HOME/.pi/agent/settings.json"
if [[ -f "$pi_settings" ]]; then
if grep -q 'skills' "$pi_settings" 2>/dev/null; then
pass "Pi settings.json has skills configuration"
else
warn "Pi settings.json missing skills array — Mosaic skills may not load"
fi
fi
# Mosaic-specific skills presence check.
mosaic_skills=(mosaic-board mosaic-forge mosaic-prdy mosaic-macp mosaic-standards mosaic-prd mosaic-setup-cicd)
for skill_name in "${mosaic_skills[@]}"; do
if [[ -d "$MOSAIC_HOME/skills/$skill_name" ]] || [[ -L "$MOSAIC_HOME/skills/$skill_name" ]]; then
pass "Mosaic skill present: $skill_name"
elif [[ -d "$MOSAIC_HOME/skills-local/$skill_name" ]]; then
pass "Mosaic skill present (local): $skill_name"
else
warn "Missing Mosaic skill: $skill_name"
fi
done
# ── --fix mode: auto-wire skills into all harness directories ──────────────
if [[ $FIX_MODE -eq 1 ]]; then
echo ""
echo "[mosaic-doctor] Running auto-fix..."
# 1. Ensure all harness skill directories exist
harness_skill_dirs=(
"$HOME/.claude/skills"
"$HOME/.codex/skills"
"$HOME/.config/opencode/skills"
"$HOME/.pi/agent/skills"
)
for hdir in "${harness_skill_dirs[@]}"; do
if [[ ! -d "$hdir" ]]; then
mkdir -p "$hdir"
fix "Created missing directory: $hdir"
fi
done
# 2. Wire all Mosaic skills (canonical + local) into every harness
skill_sources=("$MOSAIC_HOME/skills" "$MOSAIC_HOME/skills-local")
for hdir in "${harness_skill_dirs[@]}"; do
# Skip if target resolves to canonical dir (avoid self-link)
hdir_real="$(readlink -f "$hdir" 2>/dev/null || true)"
canonical_real="$(readlink -f "$MOSAIC_HOME/skills" 2>/dev/null || true)"
if [[ -n "$hdir_real" && -n "$canonical_real" && "$hdir_real" == "$canonical_real" ]]; then
continue
fi
for src_dir in "${skill_sources[@]}"; do
[[ -d "$src_dir" ]] || continue
while IFS= read -r -d '' skill_path; do
skill_name="$(basename "$skill_path")"
[[ "$skill_name" == .* ]] && continue
link_path="$hdir/$skill_name"
if [[ -L "$link_path" ]]; then
# Repoint if target differs
current_target="$(readlink -f "$link_path" 2>/dev/null || true)"
expected_target="$(readlink -f "$skill_path" 2>/dev/null || true)"
if [[ "$current_target" != "$expected_target" ]]; then
ln -sfn "$skill_path" "$link_path"
fix "Repointed skill link: $link_path -> $skill_path"
fi
elif [[ -e "$link_path" ]]; then
# Non-symlink entry — preserve runtime-specific override
continue
else
ln -s "$skill_path" "$link_path"
fix "Linked skill: $link_path -> $skill_path"
fi
done < <(find "$src_dir" -mindepth 1 -maxdepth 1 -type d -print0; find "$src_dir" -mindepth 1 -maxdepth 1 -type l -print0)
done
# Prune broken symlinks in this harness dir
while IFS= read -r -d '' broken_link; do
rm -f "$broken_link"
fix "Removed broken link: $broken_link"
done < <(find "$hdir" -mindepth 1 -maxdepth 1 -xtype l -print0 2>/dev/null)
done
# 3. Ensure Pi settings.json includes Mosaic skills path
pi_settings_dir="$HOME/.pi/agent"
pi_settings_file="$pi_settings_dir/settings.json"
mkdir -p "$pi_settings_dir"
if [[ ! -f "$pi_settings_file" ]]; then
echo '{}' > "$pi_settings_file"
fix "Created Pi settings.json: $pi_settings_file"
fi
# Add skills paths if not already present
mosaic_skills_path="$MOSAIC_HOME/skills"
mosaic_local_path="$MOSAIC_HOME/skills-local"
if ! grep -q "$mosaic_skills_path" "$pi_settings_file" 2>/dev/null; then
# Use a simple approach: read, patch, write
if command -v python3 >/dev/null 2>&1; then
python3 -c "
import json, sys
with open('$pi_settings_file', 'r') as f:
data = json.load(f)
skills = data.get('skills', [])
if not isinstance(skills, list):
skills = []
for p in ['$mosaic_skills_path', '$mosaic_local_path']:
if p not in skills:
skills.append(p)
data['skills'] = skills
with open('$pi_settings_file', 'w') as f:
json.dump(data, f, indent=2)
f.write('\\n')
" 2>/dev/null && fix "Added Mosaic skills paths to Pi settings.json"
else
warn "python3 not available — cannot patch Pi settings.json. Add manually: skills: [\"$mosaic_skills_path\", \"$mosaic_local_path\"]"
fi
fi
# 4. Run link-runtime-assets if available
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets" ]]; then
"$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets" >/dev/null 2>&1 && fix "Re-ran mosaic-link-runtime-assets"
fi
echo "[mosaic-doctor] fixes=$fix_count"
fi
echo "[mosaic-doctor] warnings=$warn_count"
if [[ $FAIL_ON_WARN -eq 1 && $warn_count -gt 0 ]]; then
exit 1
fi
@@ -0,0 +1,283 @@
# mosaic-doctor.ps1
# Audits Mosaic runtime state and detects drift across agent runtimes.
# PowerShell equivalent of mosaic-doctor (bash).
$ErrorActionPreference = "Stop"
param(
[switch]$FailOnWarn,
[switch]$Verbose,
[switch]$Help
)
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
if ($Help) {
Write-Host @"
Usage: mosaic-doctor.ps1 [-FailOnWarn] [-Verbose] [-Help]
Audit Mosaic runtime state and detect drift across agent runtimes.
"@
exit 0
}
$script:warnCount = 0
function Warn {
param([string]$Message)
$script:warnCount++
Write-Host "[WARN] $Message" -ForegroundColor Yellow
}
function Pass {
param([string]$Message)
if ($Verbose) { Write-Host "[OK] $Message" -ForegroundColor Green }
}
function Expect-Dir {
param([string]$Path)
if (-not (Test-Path $Path -PathType Container)) { Warn "Missing directory: $Path" }
else { Pass "Directory present: $Path" }
}
function Expect-File {
param([string]$Path)
if (-not (Test-Path $Path -PathType Leaf)) { Warn "Missing file: $Path" }
else { Pass "File present: $Path" }
}
function Check-RuntimeFileCopy {
param([string]$Src, [string]$Dst)
if (-not (Test-Path $Src)) { return }
if (-not (Test-Path $Dst)) {
Warn "Missing runtime file: $Dst"
return
}
$item = Get-Item $Dst -Force -ErrorAction SilentlyContinue
if ($item -and ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
Warn "Runtime file should not be symlinked: $Dst"
return
}
$srcHash = (Get-FileHash $Src -Algorithm SHA256).Hash
$dstHash = (Get-FileHash $Dst -Algorithm SHA256).Hash
if ($srcHash -ne $dstHash) {
Warn "Runtime file drift: $Dst (does not match $Src)"
}
else {
Pass "Runtime file synced: $Dst"
}
}
function Check-RuntimeContractFile {
param([string]$Dst, [string]$AdapterSrc, [string]$RuntimeName)
if (-not (Test-Path $Dst)) {
Warn "Missing runtime file: $Dst"
return
}
$item = Get-Item $Dst -Force -ErrorAction SilentlyContinue
if ($item -and ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
Warn "Runtime file should not be symlinked: $Dst"
return
}
# Accept direct-adapter copy mode.
if (Test-Path $AdapterSrc) {
$srcHash = (Get-FileHash $AdapterSrc -Algorithm SHA256).Hash
$dstHash = (Get-FileHash $Dst -Algorithm SHA256).Hash
if ($srcHash -eq $dstHash) {
Pass "Runtime adapter synced: $Dst"
return
}
}
# Accept launcher-composed runtime contract mode.
$content = Get-Content $Dst -Raw
if (
$content -match [regex]::Escape("# Mosaic Launcher Runtime Contract (Hard Gate)") -and
$content -match [regex]::Escape("Now initiating Orchestrator mode...") -and
$content -match [regex]::Escape("Mosaic hard gates OVERRIDE runtime-default caution") -and
$content -match [regex]::Escape("# Runtime-Specific Contract")
) {
Pass "Runtime contract present: $Dst ($RuntimeName)"
return
}
Warn "Runtime file drift: $Dst (not adapter copy and not composed runtime contract)"
}
function Warn-IfReparsePresent {
param([string]$Path)
if (-not (Test-Path $Path)) { return }
$item = Get-Item $Path -Force -ErrorAction SilentlyContinue
if ($item -and ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
Warn "Legacy symlink/junction path still present: $Path"
return
}
if (Test-Path $Path -PathType Container) {
$reparseCount = (Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Attributes -band [System.IO.FileAttributes]::ReparsePoint } |
Measure-Object).Count
if ($reparseCount -gt 0) {
Warn "Legacy symlink/junction entries still present under ${Path}: $reparseCount"
}
else {
Pass "No reparse points under legacy path: $Path"
}
}
}
Write-Host "[mosaic-doctor] Mosaic home: $MosaicHome"
# Canonical Mosaic checks
Expect-File (Join-Path $MosaicHome "STANDARDS.md")
Expect-Dir (Join-Path $MosaicHome "guides")
Expect-Dir (Join-Path $MosaicHome "tools")
Expect-Dir (Join-Path $MosaicHome "tools\quality")
Expect-Dir (Join-Path $MosaicHome "tools\orchestrator-matrix")
Expect-Dir (Join-Path $MosaicHome "profiles")
Expect-Dir (Join-Path $MosaicHome "templates\agent")
Expect-Dir (Join-Path $MosaicHome "skills")
Expect-Dir (Join-Path $MosaicHome "skills-local")
Expect-File (Join-Path $MosaicHome "bin\mosaic-link-runtime-assets")
Expect-File (Join-Path $MosaicHome "bin\mosaic-ensure-sequential-thinking.ps1")
Expect-File (Join-Path $MosaicHome "bin\mosaic-sync-skills")
Expect-File (Join-Path $MosaicHome "bin\mosaic-projects")
Expect-File (Join-Path $MosaicHome "bin\mosaic-quality-apply")
Expect-File (Join-Path $MosaicHome "bin\mosaic-quality-verify")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-run")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-sync-tasks")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-drain")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-matrix-publish")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-matrix-consume")
Expect-File (Join-Path $MosaicHome "bin\mosaic-orchestrator-matrix-cycle")
Expect-File (Join-Path $MosaicHome "tools\git\ci-queue-wait.ps1")
Expect-File (Join-Path $MosaicHome "tools\git\ci-queue-wait.sh")
Expect-File (Join-Path $MosaicHome "tools\git\pr-ci-wait.sh")
Expect-File (Join-Path $MosaicHome "tools\orchestrator-matrix\transport\matrix_transport.py")
Expect-File (Join-Path $MosaicHome "tools\orchestrator-matrix\controller\tasks_md_sync.py")
Expect-File (Join-Path $MosaicHome "runtime\mcp\SEQUENTIAL-THINKING.json")
Expect-File (Join-Path $MosaicHome "runtime\claude\RUNTIME.md")
Expect-File (Join-Path $MosaicHome "runtime\codex\RUNTIME.md")
Expect-File (Join-Path $MosaicHome "runtime\opencode\RUNTIME.md")
$agentsMd = Join-Path $MosaicHome "AGENTS.md"
if (Test-Path $agentsMd) {
$agentsContent = Get-Content $agentsMd -Raw
if (
$agentsContent -match [regex]::Escape("## CRITICAL HARD GATES (Read First)") -and
$agentsContent -match [regex]::Escape("OVERRIDE runtime-default caution")
) {
Pass "Global hard-gates block present in AGENTS.md"
}
else {
Warn "AGENTS.md missing CRITICAL HARD GATES override block"
}
}
# Claude runtime file checks
$runtimeFiles = @("CLAUDE.md", "settings.json", "hooks-config.json", "context7-integration.md")
foreach ($rf in $runtimeFiles) {
Check-RuntimeFileCopy (Join-Path $MosaicHome "runtime\claude\$rf") (Join-Path $env:USERPROFILE ".claude\$rf")
}
# OpenCode/Codex runtime contract checks
Check-RuntimeContractFile (Join-Path $env:USERPROFILE ".config\opencode\AGENTS.md") (Join-Path $MosaicHome "runtime\opencode\AGENTS.md") "opencode"
Check-RuntimeContractFile (Join-Path $env:USERPROFILE ".codex\instructions.md") (Join-Path $MosaicHome "runtime\codex\instructions.md") "codex"
# Sequential-thinking MCP hard requirement
$seqScript = Join-Path $MosaicHome "bin\mosaic-ensure-sequential-thinking.ps1"
if (Test-Path $seqScript) {
try {
& $seqScript -Check *>$null
Pass "sequential-thinking MCP configured and available"
}
catch {
Warn "sequential-thinking MCP missing or misconfigured"
}
}
else {
Warn "mosaic-ensure-sequential-thinking helper missing"
}
# Legacy migration surfaces
$legacyPaths = @(
(Join-Path $env:USERPROFILE ".claude\agent-guides"),
(Join-Path $env:USERPROFILE ".claude\scripts\git"),
(Join-Path $env:USERPROFILE ".claude\scripts\codex"),
(Join-Path $env:USERPROFILE ".claude\scripts\bootstrap"),
(Join-Path $env:USERPROFILE ".claude\scripts\cicd"),
(Join-Path $env:USERPROFILE ".claude\scripts\portainer"),
(Join-Path $env:USERPROFILE ".claude\templates"),
(Join-Path $env:USERPROFILE ".claude\presets\domains"),
(Join-Path $env:USERPROFILE ".claude\presets\tech-stacks"),
(Join-Path $env:USERPROFILE ".claude\presets\workflows")
)
foreach ($p in $legacyPaths) {
Warn-IfReparsePresent $p
}
# Skills runtime checks (junctions or symlinks into runtime-specific dirs)
$linkTargets = @(
(Join-Path $env:USERPROFILE ".claude\skills"),
(Join-Path $env:USERPROFILE ".codex\skills"),
(Join-Path $env:USERPROFILE ".config\opencode\skills")
)
$skillSources = @($MosaicHome + "\skills", $MosaicHome + "\skills-local")
foreach ($runtimeSkills in $linkTargets) {
if (-not (Test-Path $runtimeSkills)) { continue }
foreach ($sourceDir in $skillSources) {
if (-not (Test-Path $sourceDir)) { continue }
Get-ChildItem $sourceDir -Directory | Where-Object { -not $_.Name.StartsWith(".") } | ForEach-Object {
$name = $_.Name
$skillPath = $_.FullName
$target = Join-Path $runtimeSkills $name
if (-not (Test-Path $target)) {
Warn "Missing skill link: $target"
return
}
$item = Get-Item $target -Force -ErrorAction SilentlyContinue
if (-not ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
Warn "Non-junction skill entry: $target"
return
}
$targetResolved = $item.Target
if (-not $targetResolved -or (Resolve-Path $targetResolved -ErrorAction SilentlyContinue).Path -ne (Resolve-Path $skillPath -ErrorAction SilentlyContinue).Path) {
Warn "Drifted skill link: $target (expected -> $skillPath)"
}
else {
Pass "Linked skill: $target"
}
}
}
}
# Broken junctions/symlinks in managed runtime skill dirs
$brokenLinks = 0
foreach ($d in $linkTargets) {
if (-not (Test-Path $d)) { continue }
Get-ChildItem $d -Force -ErrorAction SilentlyContinue | Where-Object {
($_.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -and -not (Test-Path $_.FullName)
} | ForEach-Object { $brokenLinks++ }
}
if ($brokenLinks -gt 0) {
Warn "Broken skill junctions/symlinks detected: $brokenLinks"
}
Write-Host "[mosaic-doctor] warnings=$($script:warnCount)"
if ($FailOnWarn -and $script:warnCount -gt 0) {
exit 1
}
@@ -0,0 +1,119 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
TOOLS_DIR="$MOSAIC_HOME/tools/excalidraw"
MODE="apply"
SCOPE="user"
err() { echo "[mosaic-excalidraw] ERROR: $*" >&2; }
log() { echo "[mosaic-excalidraw] $*"; }
while [[ $# -gt 0 ]]; do
case "$1" in
--check) MODE="check"; shift ;;
--scope)
if [[ $# -lt 2 ]]; then
err "--scope requires a value: user|local"
exit 2
fi
SCOPE="$2"
shift 2
;;
*)
err "Unknown argument: $1"
exit 2
;;
esac
done
require_binary() {
local name="$1"
if ! command -v "$name" >/dev/null 2>&1; then
err "Required binary missing: $name"
return 1
fi
}
check_software() {
require_binary node
require_binary npm
}
check_tool_dir() {
[[ -d "$TOOLS_DIR" ]] || { err "Tool dir not found: $TOOLS_DIR"; return 1; }
[[ -f "$TOOLS_DIR/package.json" ]] || { err "package.json not found in $TOOLS_DIR"; return 1; }
[[ -f "$TOOLS_DIR/launch.sh" ]] || { err "launch.sh not found in $TOOLS_DIR"; return 1; }
}
check_npm_deps() {
[[ -d "$TOOLS_DIR/node_modules/@modelcontextprotocol" ]] || return 1
[[ -d "$TOOLS_DIR/node_modules/@excalidraw" ]] || return 1
[[ -d "$TOOLS_DIR/node_modules/jsdom" ]] || return 1
}
install_npm_deps() {
if check_npm_deps; then
return 0
fi
log "Installing npm deps in $TOOLS_DIR..."
(cd "$TOOLS_DIR" && npm install --silent) || {
err "npm install failed in $TOOLS_DIR"
return 1
}
}
check_claude_config() {
python3 - <<'PY'
import json
from pathlib import Path
p = Path.home() / ".claude.json"
if not p.exists():
raise SystemExit(1)
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
raise SystemExit(1)
mcp = data.get("mcpServers")
if not isinstance(mcp, dict):
raise SystemExit(1)
entry = mcp.get("excalidraw")
if not isinstance(entry, dict):
raise SystemExit(1)
cmd = entry.get("command", "")
if not cmd.endswith("launch.sh"):
raise SystemExit(1)
PY
}
apply_claude_config() {
require_binary claude
local launch_sh="$TOOLS_DIR/launch.sh"
claude mcp add --scope user excalidraw -- "$launch_sh"
}
# ── Check mode ────────────────────────────────────────────────────────────────
if [[ "$MODE" == "check" ]]; then
check_software
check_tool_dir
if ! check_npm_deps; then
err "npm deps not installed in $TOOLS_DIR (run without --check to install)"
exit 1
fi
if ! check_claude_config; then
err "excalidraw not registered in ~/.claude.json"
exit 1
fi
log "excalidraw MCP is configured and available"
exit 0
fi
# ── Apply mode ────────────────────────────────────────────────────────────────
check_software
check_tool_dir
install_npm_deps
apply_claude_config
log "excalidraw MCP configured (scope: $SCOPE)"
@@ -0,0 +1,262 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
MODE="apply"
RUNTIME="all"
STRICT_CHECK=0
PKG="@modelcontextprotocol/server-sequential-thinking"
err() { echo "[mosaic-seq] ERROR: $*" >&2; }
log() { echo "[mosaic-seq] $*"; }
while [[ $# -gt 0 ]]; do
case "$1" in
--check)
MODE="check"
shift
;;
--runtime)
if [[ $# -lt 2 ]]; then
err "--runtime requires a value: claude|codex|opencode|all"
exit 2
fi
RUNTIME="$2"
shift 2
;;
--strict)
STRICT_CHECK=1
shift
;;
*)
err "Unknown argument: $1"
exit 2
;;
esac
done
case "$RUNTIME" in
all|claude|codex|opencode) ;;
*)
err "Invalid runtime: $RUNTIME (expected claude|codex|opencode|all)"
exit 2
;;
esac
require_binary() {
local name="$1"
if ! command -v "$name" >/dev/null 2>&1; then
err "Required binary missing: $name"
return 1
fi
}
check_software() {
require_binary node
require_binary npx
}
warm_package() {
local timeout_sec="${MOSAIC_SEQ_WARM_TIMEOUT_SEC:-15}"
if command -v timeout >/dev/null 2>&1; then
timeout "$timeout_sec" npx -y "$PKG" --help >/dev/null 2>&1
else
npx -y "$PKG" --help >/dev/null 2>&1
fi
}
check_claude_config() {
python3 - <<'PY'
import json
from pathlib import Path
p = Path.home() / ".claude" / "settings.json"
if not p.exists():
raise SystemExit(1)
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
raise SystemExit(1)
mcp = data.get("mcpServers")
if not isinstance(mcp, dict):
raise SystemExit(1)
entry = mcp.get("sequential-thinking")
if not isinstance(entry, dict):
raise SystemExit(1)
if entry.get("command") != "npx":
raise SystemExit(1)
args = entry.get("args")
if args != ["-y", "@modelcontextprotocol/server-sequential-thinking"]:
raise SystemExit(1)
PY
}
apply_claude_config() {
python3 - <<'PY'
import json
from pathlib import Path
p = Path.home() / ".claude" / "settings.json"
p.parent.mkdir(parents=True, exist_ok=True)
if p.exists():
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
data = {}
else:
data = {}
mcp = data.get("mcpServers")
if not isinstance(mcp, dict):
mcp = {}
mcp["sequential-thinking"] = {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
}
data["mcpServers"] = mcp
p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
PY
}
check_codex_config() {
local cfg="$HOME/.codex/config.toml"
[[ -f "$cfg" ]] || return 1
grep -Eq '^\[mcp_servers\.(sequential-thinking|sequential_thinking)\]' "$cfg" && \
grep -q '^command = "npx"' "$cfg" && \
grep -q '@modelcontextprotocol/server-sequential-thinking' "$cfg"
}
apply_codex_config() {
local cfg="$HOME/.codex/config.toml"
mkdir -p "$(dirname "$cfg")"
[[ -f "$cfg" ]] || touch "$cfg"
local tmp
tmp="$(mktemp)"
awk '
BEGIN { skip = 0 }
/^\[mcp_servers\.(sequential-thinking|sequential_thinking)\]/ { skip = 1; next }
skip && /^\[/ { skip = 0 }
!skip { print }
' "$cfg" > "$tmp"
mv "$tmp" "$cfg"
{
echo ""
echo "[mcp_servers.sequential-thinking]"
echo "command = \"npx\""
echo "args = [\"-y\", \"@modelcontextprotocol/server-sequential-thinking\"]"
} >> "$cfg"
}
check_opencode_config() {
python3 - <<'PY'
import json
from pathlib import Path
p = Path.home() / ".config" / "opencode" / "config.json"
if not p.exists():
raise SystemExit(1)
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
raise SystemExit(1)
mcp = data.get("mcp")
if not isinstance(mcp, dict):
raise SystemExit(1)
entry = mcp.get("sequential-thinking")
if not isinstance(entry, dict):
raise SystemExit(1)
if entry.get("type") != "local":
raise SystemExit(1)
if entry.get("command") != ["npx", "-y", "@modelcontextprotocol/server-sequential-thinking"]:
raise SystemExit(1)
if entry.get("enabled") is not True:
raise SystemExit(1)
PY
}
apply_opencode_config() {
python3 - <<'PY'
import json
from pathlib import Path
p = Path.home() / ".config" / "opencode" / "config.json"
p.parent.mkdir(parents=True, exist_ok=True)
if p.exists():
try:
data = json.loads(p.read_text(encoding="utf-8"))
except Exception:
data = {}
else:
data = {}
mcp = data.get("mcp")
if not isinstance(mcp, dict):
mcp = {}
mcp["sequential-thinking"] = {
"type": "local",
"command": ["npx", "-y", "@modelcontextprotocol/server-sequential-thinking"],
"enabled": True
}
data["mcp"] = mcp
p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
PY
}
check_runtime_config() {
case "$RUNTIME" in
all)
check_claude_config
check_codex_config
check_opencode_config
;;
claude)
check_claude_config
;;
codex)
check_codex_config
;;
opencode)
check_opencode_config
;;
esac
}
apply_runtime_config() {
case "$RUNTIME" in
all)
apply_claude_config
apply_codex_config
apply_opencode_config
;;
claude)
apply_claude_config
;;
codex)
apply_codex_config
;;
opencode)
apply_opencode_config
;;
esac
}
if [[ "$MODE" == "check" ]]; then
check_software
check_runtime_config
# Runtime launch checks should be local/fast by default.
if [[ "$STRICT_CHECK" -eq 1 || "${MOSAIC_SEQ_CHECK_WARM:-0}" == "1" ]]; then
if ! warm_package; then
err "sequential-thinking package warm-up failed in strict mode"
exit 1
fi
fi
log "sequential-thinking MCP is configured and available (${RUNTIME})"
exit 0
fi
check_software
if ! warm_package; then
err "Unable to warm sequential-thinking package (npx timeout/failure)"
exit 1
fi
apply_runtime_config
log "sequential-thinking MCP configured (${RUNTIME})"
@@ -0,0 +1,114 @@
# mosaic-ensure-sequential-thinking.ps1
param(
[switch]$Check
)
$ErrorActionPreference = "Stop"
$Pkg = "@modelcontextprotocol/server-sequential-thinking"
function Require-Binary {
param([string]$Name)
if (-not (Get-Command $Name -ErrorAction SilentlyContinue)) {
throw "Required binary missing: $Name"
}
}
function Warm-Package {
$null = & npx -y $Pkg --help 2>$null
}
function Set-ClaudeConfig {
$path = Join-Path $env:USERPROFILE ".claude\settings.json"
New-Item -ItemType Directory -Path (Split-Path $path -Parent) -Force | Out-Null
$data = @{}
if (Test-Path $path) {
try { $data = Get-Content $path -Raw | ConvertFrom-Json -AsHashtable } catch { $data = @{} }
}
if (-not $data.ContainsKey("mcpServers") -or -not ($data["mcpServers"] -is [hashtable])) {
$data["mcpServers"] = @{}
}
$data["mcpServers"]["sequential-thinking"] = @{
command = "npx"
args = @("-y", "@modelcontextprotocol/server-sequential-thinking")
}
$data | ConvertTo-Json -Depth 20 | Set-Content -Path $path -Encoding UTF8
}
function Set-CodexConfig {
$path = Join-Path $env:USERPROFILE ".codex\config.toml"
New-Item -ItemType Directory -Path (Split-Path $path -Parent) -Force | Out-Null
if (-not (Test-Path $path)) { New-Item -ItemType File -Path $path -Force | Out-Null }
$content = Get-Content $path -Raw
$content = [regex]::Replace($content, "(?ms)^\[mcp_servers\.(sequential-thinking|sequential_thinking)\].*?(?=^\[|\z)", "")
$content = $content.TrimEnd() + "`n`n[mcp_servers.sequential-thinking]`ncommand = `"npx`"`nargs = [`"-y`", `"@modelcontextprotocol/server-sequential-thinking`"]`n"
Set-Content -Path $path -Value $content -Encoding UTF8
}
function Set-OpenCodeConfig {
$path = Join-Path $env:USERPROFILE ".config\opencode\config.json"
New-Item -ItemType Directory -Path (Split-Path $path -Parent) -Force | Out-Null
$data = @{}
if (Test-Path $path) {
try { $data = Get-Content $path -Raw | ConvertFrom-Json -AsHashtable } catch { $data = @{} }
}
if (-not $data.ContainsKey("mcp") -or -not ($data["mcp"] -is [hashtable])) {
$data["mcp"] = @{}
}
$data["mcp"]["sequential-thinking"] = @{
type = "local"
command = @("npx", "-y", "@modelcontextprotocol/server-sequential-thinking")
enabled = $true
}
$data | ConvertTo-Json -Depth 20 | Set-Content -Path $path -Encoding UTF8
}
function Test-Configs {
$claudeOk = $false
$codexOk = $false
$opencodeOk = $false
$claudePath = Join-Path $env:USERPROFILE ".claude\settings.json"
if (Test-Path $claudePath) {
try {
$c = Get-Content $claudePath -Raw | ConvertFrom-Json -AsHashtable
$claudeOk = $c.ContainsKey("mcpServers") -and $c["mcpServers"].ContainsKey("sequential-thinking")
} catch {}
}
$codexPath = Join-Path $env:USERPROFILE ".codex\config.toml"
if (Test-Path $codexPath) {
$raw = Get-Content $codexPath -Raw
$codexOk = $raw -match "\[mcp_servers\.(sequential-thinking|sequential_thinking)\]" -and $raw -match "@modelcontextprotocol/server-sequential-thinking"
}
$opencodePath = Join-Path $env:USERPROFILE ".config\opencode\config.json"
if (Test-Path $opencodePath) {
try {
$o = Get-Content $opencodePath -Raw | ConvertFrom-Json -AsHashtable
$opencodeOk = $o.ContainsKey("mcp") -and $o["mcp"].ContainsKey("sequential-thinking")
} catch {}
}
if (-not ($claudeOk -and $codexOk -and $opencodeOk)) {
throw "Sequential-thinking MCP runtime config is incomplete"
}
}
Require-Binary node
Require-Binary npx
Warm-Package
if ($Check) {
Test-Configs
Write-Host "[mosaic-seq] sequential-thinking MCP is configured and available"
exit 0
}
Set-ClaudeConfig
Set-CodexConfig
Set-OpenCodeConfig
Write-Host "[mosaic-seq] sequential-thinking MCP configured for Claude, Codex, and OpenCode"
+562
View File
@@ -0,0 +1,562 @@
#!/usr/bin/env bash
set -euo pipefail
# mosaic-init — Interactive agent identity, user profile, and tool config generator
#
# Usage:
# mosaic-init # Interactive mode
# mosaic-init --name "Mosaic Agent" --style direct # Flag overrides
# mosaic-init --name "Mosaic Agent" --role "memory steward" --style direct \
# --accessibility "ADHD-friendly chunking" --guardrails "Never auto-commit"
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SOUL_TEMPLATE="$MOSAIC_HOME/templates/SOUL.md.template"
USER_TEMPLATE="$MOSAIC_HOME/templates/USER.md.template"
TOOLS_TEMPLATE="$MOSAIC_HOME/templates/TOOLS.md.template"
SOUL_OUTPUT="$MOSAIC_HOME/SOUL.md"
USER_OUTPUT="$MOSAIC_HOME/USER.md"
TOOLS_OUTPUT="$MOSAIC_HOME/TOOLS.md"
# Defaults
AGENT_NAME=""
ROLE_DESCRIPTION=""
STYLE=""
ACCESSIBILITY=""
CUSTOM_GUARDRAILS=""
# USER.md defaults
USER_NAME=""
PRONOUNS=""
TIMEZONE=""
BACKGROUND=""
COMMUNICATION_PREFS=""
PERSONAL_BOUNDARIES=""
PROJECTS_TABLE=""
# TOOLS.md defaults
GIT_PROVIDERS_TABLE=""
CREDENTIALS_LOCATION=""
CUSTOM_TOOLS_SECTION=""
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Generate Mosaic identity and configuration files:
- SOUL.md — Agent identity contract
- USER.md — User profile and accessibility
- TOOLS.md — Machine-level tool reference
Interactive by default. Use flags to skip prompts.
Options:
--name <name> Agent name (e.g., "Mosaic Agent", "Assistant")
--role <description> Role description (e.g., "memory steward, execution partner")
--style <style> Communication style: direct, friendly, or formal
--accessibility <prefs> Accessibility preferences (e.g., "ADHD-friendly chunking")
--guardrails <rules> Custom guardrails (appended to defaults)
--user-name <name> Your name for USER.md
--pronouns <pronouns> Your pronouns (e.g., "He/Him")
--timezone <tz> Your timezone (e.g., "America/Chicago")
--non-interactive Fail if any required value is missing (no prompts)
--soul-only Only generate SOUL.md
--force Overwrite existing files without prompting
-h, --help Show help
USAGE
}
NON_INTERACTIVE=0
SOUL_ONLY=0
FORCE=0
while [[ $# -gt 0 ]]; do
case "$1" in
--name) AGENT_NAME="$2"; shift 2 ;;
--role) ROLE_DESCRIPTION="$2"; shift 2 ;;
--style) STYLE="$2"; shift 2 ;;
--accessibility) ACCESSIBILITY="$2"; shift 2 ;;
--guardrails) CUSTOM_GUARDRAILS="$2"; shift 2 ;;
--user-name) USER_NAME="$2"; shift 2 ;;
--pronouns) PRONOUNS="$2"; shift 2 ;;
--timezone) TIMEZONE="$2"; shift 2 ;;
--non-interactive) NON_INTERACTIVE=1; shift ;;
--soul-only) SOUL_ONLY=1; shift ;;
--force) FORCE=1; shift ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown argument: $1" >&2; usage >&2; exit 1 ;;
esac
done
prompt_if_empty() {
local var_name="$1"
local prompt_text="$2"
local default_value="${3:-}"
local current_value="${!var_name}"
if [[ -n "$current_value" ]]; then
return
fi
if [[ $NON_INTERACTIVE -eq 1 ]]; then
if [[ -n "$default_value" ]]; then
printf -v "$var_name" %s "$default_value"
return
fi
echo "[mosaic-init] ERROR: --$var_name is required in non-interactive mode" >&2
exit 1
fi
if [[ -n "$default_value" ]]; then
prompt_text="$prompt_text [$default_value]"
fi
printf "%s: " "$prompt_text"
read -r value
if [[ -z "$value" && -n "$default_value" ]]; then
value="$default_value"
fi
printf -v "$var_name" %s "$value"
}
prompt_multiline() {
local var_name="$1"
local prompt_text="$2"
local default_value="${3:-}"
local current_value="${!var_name}"
if [[ -n "$current_value" ]]; then
return
fi
if [[ $NON_INTERACTIVE -eq 1 ]]; then
printf -v "$var_name" %s "$default_value"
return
fi
echo "$prompt_text"
printf "(Press Enter to skip, or type your response): "
read -r value
if [[ -z "$value" ]]; then
value="$default_value"
fi
printf -v "$var_name" %s "$value"
}
# ── Existing file detection ────────────────────────────────────
detect_existing_config() {
local found=0
local existing_files=()
[[ -f "$SOUL_OUTPUT" ]] && { found=1; existing_files+=("SOUL.md"); }
[[ -f "$USER_OUTPUT" ]] && { found=1; existing_files+=("USER.md"); }
[[ -f "$TOOLS_OUTPUT" ]] && { found=1; existing_files+=("TOOLS.md"); }
if [[ $found -eq 0 || $FORCE -eq 1 ]]; then
return 0 # No existing files or --force: proceed with fresh install
fi
echo "[mosaic-init] Existing configuration detected:"
for f in "${existing_files[@]}"; do
echo " ✓ $f"
done
# Show current agent name if SOUL.md exists
if [[ -f "$SOUL_OUTPUT" ]]; then
local current_name
current_name=$(grep -oP 'You are \*\*\K[^*]+' "$SOUL_OUTPUT" 2>/dev/null || true)
if [[ -n "$current_name" ]]; then
echo " Agent: $current_name"
fi
fi
echo ""
if [[ $NON_INTERACTIVE -eq 1 ]]; then
echo "[mosaic-init] Existing config found. Use --force to overwrite in non-interactive mode."
exit 0
fi
echo "What would you like to do?"
echo " 1) keep — Keep existing files, skip init (default)"
echo " 2) import — Import values from existing files as defaults, then regenerate"
echo " 3) overwrite — Start fresh, overwrite all files"
printf "Choose [1/2/3]: "
read -r choice
case "${choice:-1}" in
1|keep)
echo "[mosaic-init] Keeping existing configuration."
# Still push to runtime adapters in case framework was updated
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets" ]]; then
echo "[mosaic-init] Updating runtime adapters..."
"$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets"
fi
echo "[mosaic-init] Done. Launch with: mosaic claude"
exit 0
;;
2|import)
echo "[mosaic-init] Importing values from existing files as defaults..."
import_existing_values
;;
3|overwrite)
echo "[mosaic-init] Starting fresh install..."
# Back up existing files
local ts
ts=$(date +%Y%m%d%H%M%S)
for f in "${existing_files[@]}"; do
local src="$MOSAIC_HOME/$f"
if [[ -f "$src" ]]; then
cp "$src" "${src}.bak.${ts}"
echo " Backed up $f → ${f}.bak.${ts}"
fi
done
;;
*)
echo "[mosaic-init] Invalid choice. Keeping existing configuration."
exit 0
;;
esac
}
import_existing_values() {
# Import SOUL.md values
if [[ -f "$SOUL_OUTPUT" ]]; then
local content
content=$(cat "$SOUL_OUTPUT")
if [[ -z "$AGENT_NAME" ]]; then
AGENT_NAME=$(echo "$content" | grep -oP 'You are \*\*\K[^*]+' 2>/dev/null || true)
fi
if [[ -z "$ROLE_DESCRIPTION" ]]; then
ROLE_DESCRIPTION=$(echo "$content" | grep -oP 'Role identity: \K.+' 2>/dev/null || true)
fi
if [[ -z "$STYLE" ]]; then
if echo "$content" | grep -q 'Be direct, concise'; then
STYLE="direct"
elif echo "$content" | grep -q 'Be warm and conversational'; then
STYLE="friendly"
elif echo "$content" | grep -q 'Use professional, structured'; then
STYLE="formal"
fi
fi
fi
# Import USER.md values
if [[ -f "$USER_OUTPUT" ]]; then
local content
content=$(cat "$USER_OUTPUT")
if [[ -z "$USER_NAME" ]]; then
USER_NAME=$(echo "$content" | grep -oP '\*\*Name:\*\* \K.+' 2>/dev/null || true)
fi
if [[ -z "$PRONOUNS" ]]; then
PRONOUNS=$(echo "$content" | grep -oP '\*\*Pronouns:\*\* \K.+' 2>/dev/null || true)
fi
if [[ -z "$TIMEZONE" ]]; then
TIMEZONE=$(echo "$content" | grep -oP '\*\*Timezone:\*\* \K.+' 2>/dev/null || true)
fi
fi
# Import TOOLS.md values
if [[ -f "$TOOLS_OUTPUT" ]]; then
local content
content=$(cat "$TOOLS_OUTPUT")
if [[ -z "$CREDENTIALS_LOCATION" ]]; then
CREDENTIALS_LOCATION=$(echo "$content" | grep -oP '\*\*Location:\*\* \K.+' 2>/dev/null || true)
fi
fi
}
detect_existing_config
# ── SOUL.md Generation ────────────────────────────────────────
echo "[mosaic-init] Generating SOUL.md — agent identity contract"
echo ""
# Fail-closed persona: in non-interactive mode the agent NAME must be supplied
# explicitly (--name) — never silently ship an agent named "Assistant".
if [[ $NON_INTERACTIVE -eq 1 && -z "$AGENT_NAME" ]]; then
echo "[mosaic-init] ERROR: --name (agent name) is required in non-interactive mode." >&2
exit 1
fi
prompt_if_empty AGENT_NAME "What name should agents use" "Assistant"
prompt_if_empty ROLE_DESCRIPTION "Agent role description" "execution partner and visibility engine"
if [[ -z "$STYLE" && $NON_INTERACTIVE -eq 0 ]]; then
echo ""
echo "Communication style:"
echo " 1) direct — Concise, no fluff, actionable"
echo " 2) friendly — Warm but efficient, conversational"
echo " 3) formal — Professional, structured, thorough"
printf "Choose [1/2/3] (default: 1): "
read -r style_choice
case "${style_choice:-1}" in
1|direct) STYLE="direct" ;;
2|friendly) STYLE="friendly" ;;
3|formal) STYLE="formal" ;;
*) STYLE="direct" ;;
esac
elif [[ -z "$STYLE" ]]; then
STYLE="direct"
fi
prompt_if_empty ACCESSIBILITY "Accessibility preferences (or 'none')" "none"
if [[ $NON_INTERACTIVE -eq 0 && -z "$CUSTOM_GUARDRAILS" ]]; then
echo ""
printf "Custom guardrails (optional, press Enter to skip): "
read -r CUSTOM_GUARDRAILS
fi
# Build behavioral principles based on style + accessibility
BEHAVIORAL_PRINCIPLES=""
case "$STYLE" in
direct)
BEHAVIORAL_PRINCIPLES="1. Clarity over performance theater.
2. Practical execution over abstract planning.
3. Truthfulness over confidence: state uncertainty explicitly.
4. Visible state over hidden assumptions.
5. Accessibility-aware — see \`~/.config/mosaic/USER.md\` for user-specific accommodations."
;;
friendly)
BEHAVIORAL_PRINCIPLES="1. Be helpful and approachable while staying efficient.
2. Provide context and explain reasoning when helpful.
3. Truthfulness over confidence: state uncertainty explicitly.
4. Visible state over hidden assumptions.
5. Accessibility-aware — see \`~/.config/mosaic/USER.md\` for user-specific accommodations."
;;
formal)
BEHAVIORAL_PRINCIPLES="1. Maintain professional, structured communication.
2. Provide thorough analysis with explicit tradeoffs.
3. Truthfulness over confidence: state uncertainty explicitly.
4. Document decisions and rationale clearly.
5. Accessibility-aware — see \`~/.config/mosaic/USER.md\` for user-specific accommodations."
;;
esac
if [[ "$ACCESSIBILITY" != "none" && -n "$ACCESSIBILITY" ]]; then
BEHAVIORAL_PRINCIPLES="$BEHAVIORAL_PRINCIPLES
6. $ACCESSIBILITY."
fi
# Build communication style section
COMMUNICATION_STYLE=""
case "$STYLE" in
direct)
COMMUNICATION_STYLE="- Be direct, concise, and concrete.
- Avoid fluff, hype, and anthropomorphic roleplay.
- Do not simulate certainty when facts are missing.
- Prefer actionable next steps and explicit tradeoffs."
;;
friendly)
COMMUNICATION_STYLE="- Be warm and conversational while staying focused.
- Explain your reasoning when it helps the user.
- Do not simulate certainty when facts are missing.
- Prefer actionable next steps with clear context."
;;
formal)
COMMUNICATION_STYLE="- Use professional, structured language.
- Provide thorough explanations with supporting detail.
- Do not simulate certainty when facts are missing.
- Present options with explicit tradeoffs and recommendations."
;;
esac
# Format custom guardrails
FORMATTED_GUARDRAILS=""
if [[ -n "$CUSTOM_GUARDRAILS" ]]; then
FORMATTED_GUARDRAILS="- $CUSTOM_GUARDRAILS"
fi
# Verify template exists
if [[ ! -f "$SOUL_TEMPLATE" ]]; then
echo "[mosaic-init] ERROR: Template not found: $SOUL_TEMPLATE" >&2
echo "[mosaic-init] Run the Mosaic installer first." >&2
exit 1
fi
# Generate SOUL.md from template using awk (handles multi-line values)
awk -v name="$AGENT_NAME" \
-v role="$ROLE_DESCRIPTION" \
-v principles="$BEHAVIORAL_PRINCIPLES" \
-v comms="$COMMUNICATION_STYLE" \
-v guardrails="$FORMATTED_GUARDRAILS" \
'{
gsub(/\{\{AGENT_NAME\}\}/, name)
gsub(/\{\{ROLE_DESCRIPTION\}\}/, role)
gsub(/\{\{BEHAVIORAL_PRINCIPLES\}\}/, principles)
gsub(/\{\{COMMUNICATION_STYLE\}\}/, comms)
gsub(/\{\{CUSTOM_GUARDRAILS\}\}/, guardrails)
print
}' "$SOUL_TEMPLATE" > "$SOUL_OUTPUT"
echo ""
echo "[mosaic-init] Generated: $SOUL_OUTPUT"
echo "[mosaic-init] Agent name: $AGENT_NAME"
echo "[mosaic-init] Style: $STYLE"
if [[ $SOUL_ONLY -eq 1 ]]; then
# Push to runtime adapters and exit
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets" ]]; then
echo "[mosaic-init] Updating runtime adapters..."
"$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets"
fi
echo "[mosaic-init] Done. Launch with: mosaic claude"
exit 0
fi
# ── USER.md Generation ────────────────────────────────────────
echo ""
echo "[mosaic-init] Generating USER.md — user profile"
echo ""
prompt_if_empty USER_NAME "Your name" ""
prompt_if_empty PRONOUNS "Your pronouns" "They/Them"
prompt_if_empty TIMEZONE "Your timezone" "UTC"
prompt_multiline BACKGROUND "Your professional background (brief summary)" "(not configured)"
# Build accessibility section
ACCESSIBILITY_SECTION=""
if [[ "$ACCESSIBILITY" != "none" && -n "$ACCESSIBILITY" ]]; then
ACCESSIBILITY_SECTION="$ACCESSIBILITY"
else
if [[ $NON_INTERACTIVE -eq 0 ]]; then
echo ""
prompt_multiline ACCESSIBILITY_SECTION \
"Accessibility or neurodivergence accommodations (or press Enter to skip)" \
"(No specific accommodations configured. Edit this section to add any.)"
else
ACCESSIBILITY_SECTION="(No specific accommodations configured. Edit this section to add any.)"
fi
fi
# Build communication preferences
if [[ -z "$COMMUNICATION_PREFS" ]]; then
case "$STYLE" in
direct)
COMMUNICATION_PREFS="- Direct and concise
- No sycophancy
- Executive summaries and tables for overview"
;;
friendly)
COMMUNICATION_PREFS="- Warm and conversational
- Explain reasoning when helpful
- Balance thoroughness with brevity"
;;
formal)
COMMUNICATION_PREFS="- Professional and structured
- Thorough explanations with supporting detail
- Formal tone with explicit recommendations"
;;
esac
fi
prompt_multiline PERSONAL_BOUNDARIES \
"Personal boundaries or preferences agents should respect" \
"(Edit this section to add any personal boundaries.)"
if [[ -z "$PROJECTS_TABLE" ]]; then
PROJECTS_TABLE="| Project | Stack | Registry |
|---------|-------|----------|
| (none configured) | | |"
fi
if [[ ! -f "$USER_TEMPLATE" ]]; then
echo "[mosaic-init] WARN: USER.md template not found: $USER_TEMPLATE" >&2
echo "[mosaic-init] Skipping USER.md generation." >&2
else
awk -v user_name="$USER_NAME" \
-v pronouns="$PRONOUNS" \
-v timezone="$TIMEZONE" \
-v background="$BACKGROUND" \
-v accessibility="$ACCESSIBILITY_SECTION" \
-v comms="$COMMUNICATION_PREFS" \
-v boundaries="$PERSONAL_BOUNDARIES" \
-v projects="$PROJECTS_TABLE" \
'{
gsub(/\{\{USER_NAME\}\}/, user_name)
gsub(/\{\{PRONOUNS\}\}/, pronouns)
gsub(/\{\{TIMEZONE\}\}/, timezone)
gsub(/\{\{BACKGROUND\}\}/, background)
gsub(/\{\{ACCESSIBILITY_SECTION\}\}/, accessibility)
gsub(/\{\{COMMUNICATION_PREFS\}\}/, comms)
gsub(/\{\{PERSONAL_BOUNDARIES\}\}/, boundaries)
gsub(/\{\{PROJECTS_TABLE\}\}/, projects)
print
}' "$USER_TEMPLATE" > "$USER_OUTPUT"
echo "[mosaic-init] Generated: $USER_OUTPUT"
fi
# ── TOOLS.md Generation ───────────────────────────────────────
echo ""
echo "[mosaic-init] Generating TOOLS.md — machine-level tool reference"
echo ""
if [[ -z "$GIT_PROVIDERS_TABLE" ]]; then
if [[ $NON_INTERACTIVE -eq 0 ]]; then
echo "Git providers (add rows for your Gitea/GitHub/GitLab instances):"
printf "Primary git provider URL (or press Enter to skip): "
read -r git_url
if [[ -n "$git_url" ]]; then
printf "Provider name: "
read -r git_name
printf "CLI tool (tea/gh/glab): "
read -r git_cli
printf "Purpose: "
read -r git_purpose
GIT_PROVIDERS_TABLE="| Instance | URL | CLI | Purpose |
|----------|-----|-----|---------|
| $git_name | $git_url | \`$git_cli\` | $git_purpose |"
else
GIT_PROVIDERS_TABLE="| Instance | URL | CLI | Purpose |
|----------|-----|-----|---------|
| (add your git providers here) | | | |"
fi
else
GIT_PROVIDERS_TABLE="| Instance | URL | CLI | Purpose |
|----------|-----|-----|---------|
| (add your git providers here) | | | |"
fi
fi
prompt_if_empty CREDENTIALS_LOCATION "Credential file path (or 'none')" "none"
if [[ -z "$CUSTOM_TOOLS_SECTION" ]]; then
CUSTOM_TOOLS_SECTION="## Custom Tools
(Add any machine-specific tools, scripts, or workflows here.)"
fi
if [[ ! -f "$TOOLS_TEMPLATE" ]]; then
echo "[mosaic-init] WARN: TOOLS.md template not found: $TOOLS_TEMPLATE" >&2
echo "[mosaic-init] Skipping TOOLS.md generation." >&2
else
awk -v providers="$GIT_PROVIDERS_TABLE" \
-v creds="$CREDENTIALS_LOCATION" \
-v custom="$CUSTOM_TOOLS_SECTION" \
'{
gsub(/\{\{GIT_PROVIDERS_TABLE\}\}/, providers)
gsub(/\{\{CREDENTIALS_LOCATION\}\}/, creds)
gsub(/\{\{CUSTOM_TOOLS_SECTION\}\}/, custom)
print
}' "$TOOLS_TEMPLATE" > "$TOOLS_OUTPUT"
echo "[mosaic-init] Generated: $TOOLS_OUTPUT"
fi
# ── Finalize ──────────────────────────────────────────────────
# Push to runtime adapters
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets" ]]; then
echo ""
echo "[mosaic-init] Updating runtime adapters..."
"$MOSAIC_HOME/tools/_scripts/mosaic-link-runtime-assets"
fi
echo ""
echo "[mosaic-init] Done. Launch with: mosaic claude"
echo "[mosaic-init] Edit USER.md and TOOLS.md directly for further customization."
@@ -0,0 +1,144 @@
# mosaic-init.ps1 — Interactive SOUL.md generator (Windows)
#
# Usage:
# mosaic-init.ps1 # Interactive mode
# mosaic-init.ps1 -Name "Mosaic Agent" -Style direct # Flag overrides
$ErrorActionPreference = "Stop"
param(
[string]$Name,
[string]$Role,
[ValidateSet("direct", "friendly", "formal")]
[string]$Style,
[string]$Accessibility,
[string]$Guardrails,
[switch]$NonInteractive,
[switch]$Help
)
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$Template = Join-Path $MosaicHome "templates\SOUL.md.template"
$Output = Join-Path $MosaicHome "SOUL.md"
if ($Help) {
Write-Host @"
Usage: mosaic-init.ps1 [-Name <name>] [-Role <desc>] [-Style direct|friendly|formal]
[-Accessibility <prefs>] [-Guardrails <rules>] [-NonInteractive]
Generate ~/.config/mosaic/SOUL.md - the universal agent identity contract.
Interactive by default. Use flags to skip prompts.
"@
exit 0
}
function Prompt-IfEmpty {
param([string]$Current, [string]$PromptText, [string]$Default = "")
if ($Current) { return $Current }
if ($NonInteractive) {
if ($Default) { return $Default }
Write-Host "[mosaic-init] ERROR: Value required in non-interactive mode: $PromptText" -ForegroundColor Red
exit 1
}
$display = if ($Default) { "$PromptText [$Default]" } else { $PromptText }
$value = Read-Host $display
if (-not $value -and $Default) { return $Default }
return $value
}
Write-Host "[mosaic-init] Generating SOUL.md - your universal agent identity contract"
Write-Host ""
$Name = Prompt-IfEmpty $Name "What name should agents use" "Assistant"
$Role = Prompt-IfEmpty $Role "Agent role description" "execution partner and visibility engine"
if (-not $Style) {
if ($NonInteractive) {
$Style = "direct"
}
else {
Write-Host ""
Write-Host "Communication style:"
Write-Host " 1) direct - Concise, no fluff, actionable"
Write-Host " 2) friendly - Warm but efficient, conversational"
Write-Host " 3) formal - Professional, structured, thorough"
$choice = Read-Host "Choose [1/2/3] (default: 1)"
$Style = switch ($choice) {
"2" { "friendly" }
"3" { "formal" }
default { "direct" }
}
}
}
$Accessibility = Prompt-IfEmpty $Accessibility "Accessibility preferences (or 'none')" "none"
if (-not $Guardrails -and -not $NonInteractive) {
Write-Host ""
$Guardrails = Read-Host "Custom guardrails (optional, press Enter to skip)"
}
# Build behavioral principles
$BehavioralPrinciples = switch ($Style) {
"direct" {
"1. Clarity over performance theater.`n2. Practical execution over abstract planning.`n3. Truthfulness over confidence: state uncertainty explicitly.`n4. Visible state over hidden assumptions."
}
"friendly" {
"1. Be helpful and approachable while staying efficient.`n2. Provide context and explain reasoning when helpful.`n3. Truthfulness over confidence: state uncertainty explicitly.`n4. Visible state over hidden assumptions."
}
"formal" {
"1. Maintain professional, structured communication.`n2. Provide thorough analysis with explicit tradeoffs.`n3. Truthfulness over confidence: state uncertainty explicitly.`n4. Document decisions and rationale clearly."
}
}
if ($Accessibility -and $Accessibility -ne "none") {
$BehavioralPrinciples += "`n5. $Accessibility."
}
# Build communication style
$CommunicationStyle = switch ($Style) {
"direct" {
"- Be direct, concise, and concrete.`n- Avoid fluff, hype, and anthropomorphic roleplay.`n- Do not simulate certainty when facts are missing.`n- Prefer actionable next steps and explicit tradeoffs."
}
"friendly" {
"- Be warm and conversational while staying focused.`n- Explain your reasoning when it helps the user.`n- Do not simulate certainty when facts are missing.`n- Prefer actionable next steps with clear context."
}
"formal" {
"- Use professional, structured language.`n- Provide thorough explanations with supporting detail.`n- Do not simulate certainty when facts are missing.`n- Present options with explicit tradeoffs and recommendations."
}
}
# Format custom guardrails
$FormattedGuardrails = if ($Guardrails) { "- $Guardrails" } else { "" }
# Verify template
if (-not (Test-Path $Template)) {
Write-Host "[mosaic-init] ERROR: Template not found: $Template" -ForegroundColor Red
exit 1
}
# Generate SOUL.md
$content = Get-Content $Template -Raw
$content = $content -replace '\{\{AGENT_NAME\}\}', $Name
$content = $content -replace '\{\{ROLE_DESCRIPTION\}\}', $Role
$content = $content -replace '\{\{BEHAVIORAL_PRINCIPLES\}\}', $BehavioralPrinciples
$content = $content -replace '\{\{COMMUNICATION_STYLE\}\}', $CommunicationStyle
$content = $content -replace '\{\{CUSTOM_GUARDRAILS\}\}', $FormattedGuardrails
Set-Content -Path $Output -Value $content -Encoding UTF8
Write-Host ""
Write-Host "[mosaic-init] Generated: $Output"
Write-Host "[mosaic-init] Agent name: $Name"
Write-Host "[mosaic-init] Style: $Style"
# Push to runtime adapters
$linkScript = Join-Path $MosaicHome "bin\mosaic-link-runtime-assets.ps1"
if (Test-Path $linkScript) {
Write-Host "[mosaic-init] Updating runtime adapters..."
& $linkScript
}
Write-Host "[mosaic-init] Done. Launch with: mosaic claude"
@@ -0,0 +1,306 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
backup_stamp="$(date +%Y%m%d%H%M%S)"
# ─── Install-ordering guard opt-out (#869 Point-1 C2) ───────────────────────
# Explicit, per-invocation CLI flag ONLY — deliberately NOT read from an
# environment variable, so it can never sit as a silently-inherited default in
# a shell profile or CI env. Absent (the default) => hard fail-loud path.
allow_inactive_enforcement=0
for arg in "$@"; do
case "$arg" in
--allow-inactive-enforcement) allow_inactive_enforcement=1 ;;
esac
done
# Tracks whether the Claude settings install-ordering guard (below) reported a
# degraded (enforcement-not-wired) outcome, so this script's own exit status
# reflects it even though the rest of the runtime-asset sync must still run.
guard_degraded=0
copy_file_managed() {
local src="$1"
local dst="$2"
mkdir -p "$(dirname "$dst")"
if [[ -L "$dst" ]]; then
rm -f "$dst"
fi
if [[ -f "$dst" ]]; then
if cmp -s "$src" "$dst"; then
return
fi
mv "$dst" "${dst}.mosaic-bak-${backup_stamp}"
fi
cp "$src" "$dst"
}
# ─── Install-ordering guard for settings.json (#869 Point-1 C2) ─────────────
#
# settings.json is where #828's enforcement hooks (PreToolUse mutator-gate.py,
# Stop receipt-observer-client.py) get wired unconditionally. Before copying
# it, delegate to `mosaic __link-claude-settings` (packages/mosaic/src/commands/
# install-ordering-guard.ts) so the wiring decision is made by importing the
# C1 activation probe (`leaseEnforcementActivatable()`) directly, rather than
# re-implementing the capability/supervisor checks in shell. That subcommand:
# - activatable -> writes settings.json with hooks intact, exits 0
# - NOT activatable -> writes settings.json with hooks STRIPPED,
# prints an actionable message, exits 1
# - NOT activatable + opt-out -> writes settings.json with hooks intact,
# prints a loud warning, exits 0
# The `mosaic` CLI is expected on PATH at this point ("No executables are
# placed on PATH — the mosaic npm CLI is the only binary", per install.sh).
# If it is not resolvable at all, that is itself strong evidence the
# activation half is absent, so the same fail-loud default applies via a
# minimal python3 fallback (this repo already depends on python3 for the
# lease broker itself).
copy_claude_settings_guarded() {
local src="$1"
local dst="$2"
local guard_args=(__link-claude-settings "$src" "$dst")
if [[ "$allow_inactive_enforcement" == "1" ]]; then
guard_args+=(--allow-inactive-enforcement)
fi
if command -v mosaic >/dev/null 2>&1; then
if mosaic "${guard_args[@]}"; then
return 0
fi
echo "[mosaic-link] Enforcement hooks were NOT wired into $dst (see message above)." >&2
guard_degraded=1
return 0
fi
echo "[mosaic-link] ERROR: 'mosaic' CLI not found on PATH — cannot confirm lease-enforcement" >&2
echo "[mosaic-link] activation capability. enforcement requested but activation half absent —" >&2
echo "[mosaic-link] needs a published CLI carrying launch-runtime activation + a broker" >&2
echo "[mosaic-link] supervisor; refusing to wire a dead gate (see #869)." >&2
if [[ "$allow_inactive_enforcement" == "1" ]]; then
echo "[mosaic-link] WARNING: --allow-inactive-enforcement set — wiring $dst AS-IS (with" >&2
echo "[mosaic-link] enforcement hooks) despite being unable to confirm activation." >&2
copy_file_managed "$src" "$dst"
return 0
fi
mkdir -p "$(dirname "$dst")"
if command -v python3 >/dev/null 2>&1; then
python3 - "$src" "$dst" <<'PYEOF'
import json, sys
src, dest = sys.argv[1], sys.argv[2]
with open(src) as f:
data = json.load(f)
hooks = data.get("hooks", {})
pre = hooks.get("PreToolUse", [])
hooks["PreToolUse"] = [
t for t in pre
if not any("mutator-gate.py" in h.get("command", "") for h in t.get("hooks", []))
]
if not hooks["PreToolUse"]:
del hooks["PreToolUse"]
stop = hooks.get("Stop", [])
new_stop = []
for t in stop:
kept = [h for h in t.get("hooks", []) if "receipt-observer-client.py" not in h.get("command", "")]
if kept:
t = dict(t)
t["hooks"] = kept
new_stop.append(t)
if new_stop:
hooks["Stop"] = new_stop
elif "Stop" in hooks:
del hooks["Stop"]
if hooks:
data["hooks"] = hooks
else:
data.pop("hooks", None)
with open(dest, "w") as f:
json.dump(data, f, indent=2)
f.write("\n")
PYEOF
else
cp "$src" "$dst"
fi
guard_degraded=1
return 0
}
remove_legacy_path() {
local p="$1"
if [[ -L "$p" ]]; then
rm -f "$p"
return
fi
if [[ -d "$p" ]]; then
find "$p" -depth -type l -delete 2>/dev/null || true
find "$p" -depth -type d -empty -delete 2>/dev/null || true
return
fi
# Remove stale symlinked files if present.
if [[ -e "$p" && -L "$p" ]]; then
rm -f "$p"
fi
}
# Remove compatibility symlink surfaces for migrated content.
legacy_paths=(
"$HOME/.claude/agent-guides"
"$HOME/.claude/scripts/git"
"$HOME/.claude/scripts/codex"
"$HOME/.claude/scripts/bootstrap"
"$HOME/.claude/scripts/cicd"
"$HOME/.claude/scripts/portainer"
"$HOME/.claude/scripts/debug-hook.sh"
"$HOME/.claude/scripts/qa-hook-handler.sh"
"$HOME/.claude/scripts/qa-hook-stdin.sh"
"$HOME/.claude/scripts/qa-hook-wrapper.sh"
"$HOME/.claude/scripts/qa-queue-monitor.sh"
"$HOME/.claude/scripts/remediation-hook-handler.sh"
"$HOME/.claude/templates"
"$HOME/.claude/presets/domains"
"$HOME/.claude/presets/tech-stacks"
"$HOME/.claude/presets/workflows"
)
for p in "${legacy_paths[@]}"; do
remove_legacy_path "$p"
done
# Claude-specific runtime files (settings, hooks — NOT CLAUDE.md which is now a thin pointer)
# When MOSAIC_SKIP_CLAUDE_HOOKS=1 is set (user declined hooks in the wizard
# preview stage), skip hooks-config.json but still copy the other runtime
# files so Claude still gets CLAUDE.md/settings.json/context7 guidance.
for runtime_file in \
CLAUDE.md \
settings.json \
hooks-config.json \
context7-integration.md; do
if [[ "$runtime_file" == "hooks-config.json" ]] && [[ "${MOSAIC_SKIP_CLAUDE_HOOKS:-0}" == "1" ]]; then
echo "[mosaic-link] Skipping hooks-config.json (user declined in wizard)"
# An existing ~/.claude/hooks-config.json that we previously installed
# is identified by one of:
# 1. It's a symlink (legacy symlink-mode install)
# 2. It contains the `mosaic-managed` marker string we embed in the
# template (survives template updates unlike byte-equality)
# 3. It is byte-identical to the current Mosaic template (fallback
# for templates that pre-date the marker)
# Anything else is user-owned and we must leave it alone.
existing_hooks="$HOME/.claude/hooks-config.json"
mosaic_hooks_src="$MOSAIC_HOME/runtime/claude/hooks-config.json"
if [[ -L "$existing_hooks" ]]; then
rm -f "$existing_hooks"
echo "[mosaic-link] Removed previously-linked Mosaic hooks-config.json (was symlink)"
elif [[ -f "$existing_hooks" ]]; then
is_mosaic_managed=0
if grep -q 'mosaic-managed' "$existing_hooks" 2>/dev/null; then
is_mosaic_managed=1
elif [[ -f "$mosaic_hooks_src" ]] && cmp -s "$existing_hooks" "$mosaic_hooks_src"; then
is_mosaic_managed=1
fi
if [[ "$is_mosaic_managed" == "1" ]]; then
mv "$existing_hooks" "${existing_hooks}.mosaic-bak-${backup_stamp}"
echo "[mosaic-link] Removed previously-linked Mosaic hooks-config.json (backup at ${existing_hooks}.mosaic-bak-${backup_stamp})"
else
echo "[mosaic-link] Leaving existing non-Mosaic hooks-config.json in place"
fi
fi
continue
fi
src="$MOSAIC_HOME/runtime/claude/$runtime_file"
[[ -f "$src" ]] || continue
if [[ "$runtime_file" == "settings.json" ]]; then
# Install-ordering guard (#869 Point-1 C2): gate enforcement-hook wiring
# on confirmed activation instead of the plain copy_file_managed used for
# every other runtime file. See copy_claude_settings_guarded() above.
copy_claude_settings_guarded "$src" "$HOME/.claude/$runtime_file"
continue
fi
copy_file_managed "$src" "$HOME/.claude/$runtime_file"
done
if [[ -d "$MOSAIC_HOME/runtime/claude/commands" ]]; then
mkdir -p "$HOME/.claude/commands"
for command_file in "$MOSAIC_HOME/runtime/claude/commands/"*; do
[[ -f "$command_file" ]] || continue
copy_file_managed "$command_file" "$HOME/.claude/commands/$(basename "$command_file")"
done
fi
# OpenCode runtime adapter (thin pointer to AGENTS.md)
opencode_adapter="$MOSAIC_HOME/runtime/opencode/AGENTS.md"
if [[ -f "$opencode_adapter" ]]; then
copy_file_managed "$opencode_adapter" "$HOME/.config/opencode/AGENTS.md"
fi
# Codex runtime adapter (thin pointer to AGENTS.md)
codex_adapter="$MOSAIC_HOME/runtime/codex/instructions.md"
if [[ -f "$codex_adapter" ]]; then
mkdir -p "$HOME/.codex"
copy_file_managed "$codex_adapter" "$HOME/.codex/instructions.md"
fi
# Pi runtime settings (MCP + skills paths)
pi_settings_dir="$HOME/.pi/agent"
pi_settings_file="$pi_settings_dir/settings.json"
mkdir -p "$pi_settings_dir"
if [[ ! -f "$pi_settings_file" ]]; then
echo '{}' > "$pi_settings_file"
fi
# Ensure Pi settings.json has Mosaic skills paths
mosaic_skills_path="$MOSAIC_HOME/skills"
mosaic_local_path="$MOSAIC_HOME/skills-local"
if ! grep -q "$mosaic_skills_path" "$pi_settings_file" 2>/dev/null; then
if command -v python3 >/dev/null 2>&1; then
python3 -c "
import json
with open('$pi_settings_file', 'r') as f:
data = json.load(f)
skills = data.get('skills', [])
if not isinstance(skills, list):
skills = []
for p in ['$mosaic_skills_path', '$mosaic_local_path']:
if p not in skills:
skills.append(p)
data['skills'] = skills
with open('$pi_settings_file', 'w') as f:
json.dump(data, f, indent=2)
f.write('\\n')
" 2>/dev/null
fi
fi
# Pi extension is loaded via --extension flag in the mosaic launcher.
# Do NOT copy into ~/.pi/agent/extensions/ — that causes duplicate loading.
if [[ -x "$MOSAIC_HOME/tools/_scripts/mosaic-ensure-sequential-thinking" ]]; then
"$MOSAIC_HOME/tools/_scripts/mosaic-ensure-sequential-thinking"
fi
echo "[mosaic-link] Runtime assets synced (non-symlink mode)"
echo "[mosaic-link] Canonical source: $MOSAIC_HOME"
# Propagate the install-ordering guard's outcome (#869 Point-1 C2): every
# other runtime asset above is best-effort/non-fatal, but a degraded
# (enforcement-not-wired) settings.json must make THIS script's own exit
# status non-zero so callers (framework/install.sh, finalize.ts) can surface
# it — never silently.
if [[ "$guard_degraded" == "1" ]]; then
exit 1
fi
@@ -0,0 +1,110 @@
# mosaic-link-runtime-assets.ps1
# Syncs Mosaic runtime config files into agent runtime directories.
# PowerShell equivalent of mosaic-link-runtime-assets (bash).
$ErrorActionPreference = "Stop"
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$BackupStamp = Get-Date -Format "yyyyMMddHHmmss"
function Copy-FileManaged {
param([string]$Src, [string]$Dst)
$parent = Split-Path $Dst -Parent
if (-not (Test-Path $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
# Remove existing symlink/junction
$item = Get-Item $Dst -Force -ErrorAction SilentlyContinue
if ($item -and $item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
Remove-Item $Dst -Force
}
if (Test-Path $Dst) {
$srcHash = (Get-FileHash $Src -Algorithm SHA256).Hash
$dstHash = (Get-FileHash $Dst -Algorithm SHA256).Hash
if ($srcHash -eq $dstHash) { return }
Rename-Item $Dst "$Dst.mosaic-bak-$BackupStamp"
}
Copy-Item $Src $Dst -Force
}
function Remove-LegacyPath {
param([string]$Path)
if (-not (Test-Path $Path)) { return }
$item = Get-Item $Path -Force -ErrorAction SilentlyContinue
if ($item -and $item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
Remove-Item $Path -Force
return
}
if (Test-Path $Path -PathType Container) {
# Remove symlinks/junctions inside, then empty dirs
Get-ChildItem $Path -Recurse -Force | Where-Object {
$_.Attributes -band [System.IO.FileAttributes]::ReparsePoint
} | Remove-Item -Force
Get-ChildItem $Path -Recurse -Directory -Force |
Sort-Object { $_.FullName.Length } -Descending |
Where-Object { (Get-ChildItem $_.FullName -Force | Measure-Object).Count -eq 0 } |
Remove-Item -Force
}
}
# Remove legacy compatibility paths
$legacyPaths = @(
(Join-Path $env:USERPROFILE ".claude\agent-guides"),
(Join-Path $env:USERPROFILE ".claude\scripts\git"),
(Join-Path $env:USERPROFILE ".claude\scripts\codex"),
(Join-Path $env:USERPROFILE ".claude\scripts\bootstrap"),
(Join-Path $env:USERPROFILE ".claude\scripts\cicd"),
(Join-Path $env:USERPROFILE ".claude\scripts\portainer"),
(Join-Path $env:USERPROFILE ".claude\scripts\debug-hook.sh"),
(Join-Path $env:USERPROFILE ".claude\scripts\qa-hook-handler.sh"),
(Join-Path $env:USERPROFILE ".claude\scripts\qa-hook-stdin.sh"),
(Join-Path $env:USERPROFILE ".claude\scripts\qa-hook-wrapper.sh"),
(Join-Path $env:USERPROFILE ".claude\scripts\qa-queue-monitor.sh"),
(Join-Path $env:USERPROFILE ".claude\scripts\remediation-hook-handler.sh"),
(Join-Path $env:USERPROFILE ".claude\templates"),
(Join-Path $env:USERPROFILE ".claude\presets\domains"),
(Join-Path $env:USERPROFILE ".claude\presets\tech-stacks"),
(Join-Path $env:USERPROFILE ".claude\presets\workflows"),
)
foreach ($p in $legacyPaths) {
Remove-LegacyPath $p
}
# Claude-specific runtime files (settings, hooks — CLAUDE.md is now a thin pointer)
$runtimeFiles = @("CLAUDE.md", "settings.json", "hooks-config.json", "context7-integration.md")
foreach ($rf in $runtimeFiles) {
$src = Join-Path $MosaicHome "runtime\claude\$rf"
if (-not (Test-Path $src)) { continue }
$dst = Join-Path $env:USERPROFILE ".claude\$rf"
Copy-FileManaged $src $dst
}
# OpenCode runtime adapter
$opencodeSrc = Join-Path $MosaicHome "runtime\opencode\AGENTS.md"
if (Test-Path $opencodeSrc) {
$opencodeDst = Join-Path $env:USERPROFILE ".config\opencode\AGENTS.md"
Copy-FileManaged $opencodeSrc $opencodeDst
}
# Codex runtime adapter
$codexSrc = Join-Path $MosaicHome "runtime\codex\instructions.md"
if (Test-Path $codexSrc) {
$codexDir = Join-Path $env:USERPROFILE ".codex"
if (-not (Test-Path $codexDir)) { New-Item -ItemType Directory -Path $codexDir -Force | Out-Null }
$codexDst = Join-Path $codexDir "instructions.md"
Copy-FileManaged $codexSrc $codexDst
}
$seqScript = Join-Path $MosaicHome "bin\mosaic-ensure-sequential-thinking.ps1"
if (Test-Path $seqScript) {
& $seqScript
}
Write-Host "[mosaic-link] Runtime assets synced (non-symlink mode)"
Write-Host "[mosaic-link] Canonical source: $MosaicHome"
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -x "scripts/agent/log-limitation.sh" ]]; then
exec bash scripts/agent/log-limitation.sh "$@"
fi
echo "[mosaic] Missing scripts/agent/log-limitation.sh in $(pwd)" >&2
exit 1
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
APPLY=0
usage() {
cat <<USAGE
Usage: $(basename "$0") [--apply]
Migrate runtime-local skill directories (e.g. ~/.claude/skills/<name>) to Mosaic-managed
skills by replacing local directories with symlinks to ~/.config/mosaic/skills-local.
Default mode is dry-run.
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--apply)
APPLY=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
skill_roots=(
"$HOME/.claude/skills"
"$HOME/.codex/skills"
"$HOME/.config/opencode/skills"
"$HOME/.pi/agent/skills"
)
if [[ ! -d "$MOSAIC_HOME/skills-local" ]]; then
echo "[mosaic-local-skills] Missing local skills dir: $MOSAIC_HOME/skills-local" >&2
exit 1
fi
count=0
while IFS= read -r -d '' local_skill; do
name="$(basename "$local_skill")"
src="$MOSAIC_HOME/skills-local/$name"
[[ -d "$src" ]] || continue
for root in "${skill_roots[@]}"; do
[[ -d "$root" ]] || continue
target="$root/$name"
# Already linked correctly.
if [[ -L "$target" ]]; then
target_real="$(readlink -f "$target" 2>/dev/null || true)"
src_real="$(readlink -f "$src" 2>/dev/null || true)"
if [[ -n "$target_real" && -n "$src_real" && "$target_real" == "$src_real" ]]; then
continue
fi
fi
# Only migrate local directories containing SKILL.md
if [[ -d "$target" && -f "$target/SKILL.md" && ! -L "$target" ]]; then
count=$((count + 1))
if [[ $APPLY -eq 1 ]]; then
stamp="$(date +%Y%m%d%H%M%S)"
mv "$target" "${target}.mosaic-bak-${stamp}"
ln -s "$src" "$target"
echo "[mosaic-local-skills] migrated: $target -> $src"
else
echo "[mosaic-local-skills] would migrate: $target -> $src"
fi
fi
done
done < <(find "$MOSAIC_HOME/skills-local" -mindepth 1 -maxdepth 1 \( -type d -o -type l \) -print0)
if [[ $APPLY -eq 1 ]]; then
echo "[mosaic-local-skills] complete: migrated=$count"
else
echo "[mosaic-local-skills] dry-run: migratable=$count"
echo "[mosaic-local-skills] re-run with --apply to migrate"
fi
@@ -0,0 +1,90 @@
# mosaic-migrate-local-skills.ps1
# Migrates runtime-local skill directories to Mosaic-managed junctions.
# Uses directory junctions (no elevation required) with fallback to copies.
# PowerShell equivalent of mosaic-migrate-local-skills (bash).
$ErrorActionPreference = "Stop"
param(
[switch]$Apply,
[switch]$Help
)
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$LocalSkillsDir = Join-Path $MosaicHome "skills-local"
if ($Help) {
Write-Host @"
Usage: mosaic-migrate-local-skills.ps1 [-Apply] [-Help]
Migrate runtime-local skill directories (e.g. ~/.claude/skills/<name>) to
Mosaic-managed skills by replacing local directories with junctions to
~/.config/mosaic/skills-local.
Default mode is dry-run.
"@
exit 0
}
if (-not (Test-Path $LocalSkillsDir)) {
Write-Host "[mosaic-local-skills] Missing local skills dir: $LocalSkillsDir" -ForegroundColor Red
exit 1
}
$skillRoots = @(
(Join-Path $env:USERPROFILE ".claude\skills"),
(Join-Path $env:USERPROFILE ".codex\skills"),
(Join-Path $env:USERPROFILE ".config\opencode\skills")
)
$count = 0
Get-ChildItem $LocalSkillsDir -Directory | ForEach-Object {
$name = $_.Name
$src = $_.FullName
foreach ($root in $skillRoots) {
if (-not (Test-Path $root)) { continue }
$target = Join-Path $root $name
# Already a junction/symlink — check if it points to the right place
$existing = Get-Item $target -Force -ErrorAction SilentlyContinue
if ($existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
$currentTarget = $existing.Target
if ($currentTarget -and ($currentTarget -eq $src -or (Resolve-Path $currentTarget -ErrorAction SilentlyContinue).Path -eq (Resolve-Path $src -ErrorAction SilentlyContinue).Path)) {
continue
}
}
# Only migrate local directories containing SKILL.md
if ((Test-Path $target -PathType Container) -and
(Test-Path (Join-Path $target "SKILL.md")) -and
-not ($existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint))) {
$count++
if ($Apply) {
$stamp = Get-Date -Format "yyyyMMddHHmmss"
Rename-Item $target "$target.mosaic-bak-$stamp"
try {
New-Item -ItemType Junction -Path $target -Target $src -ErrorAction Stop | Out-Null
Write-Host "[mosaic-local-skills] migrated: $target -> $src"
}
catch {
Write-Host "[mosaic-local-skills] Junction failed for $name, falling back to copy"
Copy-Item $src $target -Recurse -Force
Write-Host "[mosaic-local-skills] copied: $target <- $src"
}
}
else {
Write-Host "[mosaic-local-skills] would migrate: $target -> $src"
}
}
}
}
if ($Apply) {
Write-Host "[mosaic-local-skills] complete: migrated=$count"
}
else {
Write-Host "[mosaic-local-skills] dry-run: migratable=$count"
Write-Host "[mosaic-local-skills] re-run with -Apply to migrate"
}
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
sync_cmd="$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-sync-tasks"
run_cmd="$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-run"
do_sync=1
poll_sec=15
extra_args=()
while [[ $# -gt 0 ]]; do
case "$1" in
--no-sync)
do_sync=0
shift
;;
--poll-sec)
poll_sec="${2:-15}"
shift 2
;;
*)
extra_args+=("$1")
shift
;;
esac
done
if [[ $do_sync -eq 1 ]]; then
"$sync_cmd" --apply
fi
exec "$run_cmd" --until-drained --poll-sec "$poll_sec" "${extra_args[@]}"
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
BRIDGE="$MOSAIC_HOME/tools/orchestrator-matrix/transport/matrix_transport.py"
if [[ ! -f "$BRIDGE" ]]; then
echo "[mosaic-orch-matrix] missing transport bridge: $BRIDGE" >&2
exit 1
fi
exec python3 "$BRIDGE" --repo "$(pwd)" --mode consume "$@"
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
consume="$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-matrix-consume"
run="$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-run"
publish="$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-matrix-publish"
for cmd in "$consume" "$run" "$publish"; do
if [[ ! -x "$cmd" ]]; then
echo "[mosaic-orch-cycle] missing executable: $cmd" >&2
exit 1
fi
done
"$consume"
"$run" --once "$@"
"$publish"
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
BRIDGE="$MOSAIC_HOME/tools/orchestrator-matrix/transport/matrix_transport.py"
if [[ ! -f "$BRIDGE" ]]; then
echo "[mosaic-orch-matrix] missing transport bridge: $BRIDGE" >&2
exit 1
fi
exec python3 "$BRIDGE" --repo "$(pwd)" --mode publish "$@"
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
CTRL="$MOSAIC_HOME/tools/orchestrator-matrix/controller/mosaic_orchestrator.py"
if [[ ! -f "$CTRL" ]]; then
echo "[mosaic-orchestrator] missing controller: $CTRL" >&2
exit 1
fi
exec python3 "$CTRL" --repo "$(pwd)" "$@"
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SYNC="$MOSAIC_HOME/tools/orchestrator-matrix/controller/tasks_md_sync.py"
if [[ ! -f "$SYNC" ]]; then
echo "[mosaic-orchestrator-sync] missing sync script: $SYNC" >&2
exit 1
fi
exec python3 "$SYNC" --repo "$(pwd)" "$@"
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
PROJECTS_FILE="$MOSAIC_HOME/projects.txt"
usage() {
cat <<USAGE
Usage: $(basename "$0") <command> [options]
Commands:
init
Create projects registry file at ~/.config/mosaic/projects.txt
add <repo-path> [repo-path...]
Add one or more repos to the registry
remove <repo-path> [repo-path...]
Remove one or more repos from the registry
list
Show registered repos
bootstrap [--all|repo-path...] [--force] [--quality-template <name>]
Bootstrap registered repos or explicit repo paths
orchestrate <drain|start|status|stop> [--all|repo-path...] [--poll-sec N] [--no-sync] [--worker-cmd "cmd"]
Run orchestrator actions across repos from one command
Examples:
mosaic-projects init
mosaic-projects add ~/src/syncagent ~/src/inventory-stickers
mosaic-projects bootstrap --all
mosaic-projects orchestrate drain --all --worker-cmd "codex -p"
mosaic-projects orchestrate start ~/src/syncagent --worker-cmd "opencode -p"
USAGE
}
ensure_registry() {
mkdir -p "$MOSAIC_HOME"
if [[ ! -f "$PROJECTS_FILE" ]]; then
cat > "$PROJECTS_FILE" <<EOF
# Mosaic managed projects (one absolute path per line)
# Lines starting with # are ignored.
EOF
fi
}
norm_path() {
local p="$1"
if [[ -d "$p" ]]; then
(cd "$p" && pwd)
else
return 1
fi
}
read_registry() {
ensure_registry
grep -vE '^\s*#|^\s*$' "$PROJECTS_FILE" | while read -r p; do
[[ -d "$p" ]] && echo "$p"
done
}
add_repo() {
local p="$1"
ensure_registry
local np
np="$(norm_path "$p")" || { echo "[mosaic-projects] skip missing dir: $p" >&2; return 1; }
if grep -Fxq "$np" "$PROJECTS_FILE"; then
echo "[mosaic-projects] already registered: $np"
return 0
fi
echo "$np" >> "$PROJECTS_FILE"
echo "[mosaic-projects] added: $np"
}
remove_repo() {
local p="$1"
ensure_registry
local np
np="$(norm_path "$p" 2>/dev/null || echo "$p")"
tmp="$(mktemp)"
grep -vFx "$np" "$PROJECTS_FILE" > "$tmp" || true
mv "$tmp" "$PROJECTS_FILE"
echo "[mosaic-projects] removed: $np"
}
resolve_targets() {
local use_all="$1"
shift
if [[ "$use_all" == "1" ]]; then
read_registry
return 0
fi
if [[ $# -gt 0 ]]; then
for p in "$@"; do
norm_path "$p" || { echo "[mosaic-projects] missing target: $p" >&2; exit 1; }
done
return 0
fi
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
git rev-parse --show-toplevel
return 0
fi
echo "[mosaic-projects] no targets provided. Use --all or pass repo paths." >&2
exit 1
}
cmd="${1:-}"
if [[ -z "$cmd" ]]; then
usage
exit 1
fi
shift || true
case "$cmd" in
init)
ensure_registry
echo "[mosaic-projects] registry ready: $PROJECTS_FILE"
;;
add)
[[ $# -gt 0 ]] || { echo "[mosaic-projects] add requires repo path(s)" >&2; exit 1; }
for p in "$@"; do add_repo "$p"; done
;;
remove)
[[ $# -gt 0 ]] || { echo "[mosaic-projects] remove requires repo path(s)" >&2; exit 1; }
for p in "$@"; do remove_repo "$p"; done
;;
list)
read_registry
;;
bootstrap)
use_all=0
force=0
quality_template=""
targets=()
while [[ $# -gt 0 ]]; do
case "$1" in
--all) use_all=1; shift ;;
--force) force=1; shift ;;
--quality-template) quality_template="${2:-}"; shift 2 ;;
*) targets+=("$1"); shift ;;
esac
done
mapfile -t repos < <(resolve_targets "$use_all" "${targets[@]}")
[[ ${#repos[@]} -gt 0 ]] || { echo "[mosaic-projects] no repos resolved"; exit 1; }
for repo in "${repos[@]}"; do
args=()
[[ $force -eq 1 ]] && args+=(--force)
[[ -n "$quality_template" ]] && args+=(--quality-template "$quality_template")
args+=("$repo")
echo "[mosaic-projects] bootstrap: $repo"
"$MOSAIC_HOME/tools/_scripts/mosaic-bootstrap-repo" "${args[@]}"
add_repo "$repo" || true
done
;;
orchestrate)
action="${1:-}"
[[ -n "$action" ]] || { echo "[mosaic-projects] orchestrate requires action: drain|start|status|stop" >&2; exit 1; }
shift || true
use_all=0
poll_sec=15
no_sync=0
worker_cmd=""
targets=()
while [[ $# -gt 0 ]]; do
case "$1" in
--all) use_all=1; shift ;;
--poll-sec) poll_sec="${2:-15}"; shift 2 ;;
--no-sync) no_sync=1; shift ;;
--worker-cmd) worker_cmd="${2:-}"; shift 2 ;;
*) targets+=("$1"); shift ;;
esac
done
mapfile -t repos < <(resolve_targets "$use_all" "${targets[@]}")
[[ ${#repos[@]} -gt 0 ]] || { echo "[mosaic-projects] no repos resolved"; exit 1; }
for repo in "${repos[@]}"; do
echo "[mosaic-projects] orchestrate:$action -> $repo"
(
cd "$repo"
if [[ -n "$worker_cmd" ]]; then
export MOSAIC_WORKER_EXEC="$worker_cmd"
fi
if [[ -x "scripts/agent/orchestrator-daemon.sh" ]]; then
args=()
[[ "$action" == "start" || "$action" == "drain" ]] && args+=(--poll-sec "$poll_sec")
[[ $no_sync -eq 1 ]] && args+=(--no-sync)
bash scripts/agent/orchestrator-daemon.sh "$action" "${args[@]}"
else
case "$action" in
drain)
args=(--poll-sec "$poll_sec")
[[ $no_sync -eq 1 ]] && args+=(--no-sync)
"$MOSAIC_HOME/tools/_scripts/mosaic-orchestrator-drain" "${args[@]}"
;;
status)
echo "[mosaic-projects] no daemon script in repo; run from bootstrapped repo or re-bootstrap"
;;
start|stop)
echo "[mosaic-projects] action '$action' requires scripts/agent/orchestrator-daemon.sh (run bootstrap first)" >&2
exit 1
;;
*)
echo "[mosaic-projects] unsupported action: $action" >&2
exit 1
;;
esac
fi
)
done
;;
*)
usage
exit 1
;;
esac
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
RUNTIME="claude"
APPLY=0
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Remove legacy runtime files that were preserved as *.mosaic-bak-* after Mosaic linking.
Only removes backups when the active file is a symlink to ~/.config/mosaic.
Options:
--runtime <name> Runtime to prune (default: claude)
--apply Perform deletions (default: dry-run)
-h, --help Show help
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--runtime)
[[ $# -lt 2 ]] && { echo "Missing value for --runtime" >&2; exit 1; }
RUNTIME="$2"
shift 2
;;
--apply)
APPLY=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
case "$RUNTIME" in
claude)
TARGET_ROOT="$HOME/.claude"
;;
*)
echo "Unsupported runtime: $RUNTIME" >&2
exit 1
;;
esac
if [[ ! -d "$TARGET_ROOT" ]]; then
echo "[mosaic-prune] Runtime directory not found: $TARGET_ROOT" >&2
exit 1
fi
mosaic_real="$(readlink -f "$MOSAIC_HOME")"
count_candidates=0
count_deletable=0
while IFS= read -r -d '' bak; do
count_candidates=$((count_candidates + 1))
base="${bak%%.mosaic-bak-*}"
if [[ ! -L "$base" ]]; then
continue
fi
base_real="$(readlink -f "$base" 2>/dev/null || true)"
if [[ -z "$base_real" ]]; then
continue
fi
if [[ "$base_real" != "$mosaic_real"/* ]]; then
continue
fi
count_deletable=$((count_deletable + 1))
if [[ $APPLY -eq 1 ]]; then
rm -rf "$bak"
echo "[mosaic-prune] deleted: $bak"
else
echo "[mosaic-prune] would delete: $bak"
fi
done < <(find "$TARGET_ROOT" \( -type f -o -type d \) -name '*.mosaic-bak-*' -print0)
if [[ $APPLY -eq 1 ]]; then
echo "[mosaic-prune] complete: deleted=$count_deletable candidates=$count_candidates runtime=$RUNTIME"
else
echo "[mosaic-prune] dry-run: deletable=$count_deletable candidates=$count_candidates runtime=$RUNTIME"
echo "[mosaic-prune] re-run with --apply to delete"
fi
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
TARGET_DIR="$(pwd)"
TEMPLATE=""
usage() {
cat <<USAGE
Usage: $(basename "$0") --template <name> [--target <dir>]
Apply Mosaic quality tools templates into a project.
Templates:
typescript-node
typescript-nextjs
monorepo
Examples:
$(basename "$0") --template typescript-node --target ~/src/my-project
$(basename "$0") --template monorepo
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--template)
TEMPLATE="${2:-}"
shift 2
;;
--target)
TARGET_DIR="${2:-}"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
if [[ -z "$TEMPLATE" ]]; then
echo "[mosaic-quality] Missing required --template" >&2
usage >&2
exit 1
fi
if [[ ! -d "$TARGET_DIR" ]]; then
echo "[mosaic-quality] Target directory does not exist: $TARGET_DIR" >&2
exit 1
fi
SCRIPT="$MOSAIC_HOME/tools/quality/scripts/install.sh"
if [[ ! -x "$SCRIPT" ]]; then
echo "[mosaic-quality] Missing install script: $SCRIPT" >&2
exit 1
fi
echo "[mosaic-quality] Applying template '$TEMPLATE' to $TARGET_DIR"
"$SCRIPT" --template "$TEMPLATE" --target "$TARGET_DIR"
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
TARGET_DIR="$(pwd)"
usage() {
cat <<USAGE
Usage: $(basename "$0") [--target <dir>]
Run quality-rails verification checks inside a target repository.
Examples:
$(basename "$0")
$(basename "$0") --target ~/src/my-project
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--target)
TARGET_DIR="${2:-}"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
if [[ ! -d "$TARGET_DIR" ]]; then
echo "[mosaic-quality] Target directory does not exist: $TARGET_DIR" >&2
exit 1
fi
SCRIPT="$MOSAIC_HOME/tools/quality/scripts/verify.sh"
if [[ ! -x "$SCRIPT" ]]; then
echo "[mosaic-quality] Missing verify script: $SCRIPT" >&2
exit 1
fi
echo "[mosaic-quality] Running verification in $TARGET_DIR"
(
cd "$TARGET_DIR"
"$SCRIPT"
)
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
set -euo pipefail
# mosaic-release-upgrade — Upgrade installed Mosaic framework release.
#
# This re-runs the remote installer with explicit install mode controls.
# Default behavior is safe/idempotent (keep SOUL.md + memory).
#
# Usage:
# mosaic-release-upgrade
# mosaic-release-upgrade --ref main --keep
# mosaic-release-upgrade --ref v0.2.0 --overwrite --yes
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
REMOTE_SCRIPT_URL="${MOSAIC_REMOTE_INSTALL_URL:-https://git.mosaicstack.dev/mosaic/mosaic-stack/raw/branch/main/tools/install.sh}"
BOOTSTRAP_REF="${MOSAIC_BOOTSTRAP_REF:-main}"
INSTALL_MODE="${MOSAIC_INSTALL_MODE:-keep}" # keep|overwrite
YES=false
DRY_RUN=false
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Upgrade the installed Mosaic framework release.
Options:
--ref <name> Bootstrap archive ref (branch/tag/commit). Default: main
--keep Keep local files (SOUL.md, memory/) during upgrade (default)
--overwrite Overwrite target install directory contents
-y, --yes Skip confirmation prompt
--dry-run Show actions without executing
-h, --help Show this help
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--ref)
[[ $# -lt 2 ]] && { echo "Missing value for --ref" >&2; exit 1; }
BOOTSTRAP_REF="$2"
shift 2
;;
--keep)
INSTALL_MODE="keep"
shift
;;
--overwrite)
INSTALL_MODE="overwrite"
shift
;;
-y|--yes)
YES=true
shift
;;
--dry-run)
DRY_RUN=true
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
case "$INSTALL_MODE" in
keep|overwrite) ;;
*)
echo "[mosaic-release-upgrade] Invalid install mode: $INSTALL_MODE" >&2
exit 1
;;
esac
current_version="unknown"
if [[ -x "$MOSAIC_HOME/bin/mosaic" ]]; then
current_version="$("$MOSAIC_HOME/bin/mosaic" --version 2>/dev/null | awk '{print $2}' || true)"
[[ -n "$current_version" ]] || current_version="unknown"
fi
echo "[mosaic-release-upgrade] Current version: $current_version"
echo "[mosaic-release-upgrade] Target ref: $BOOTSTRAP_REF"
echo "[mosaic-release-upgrade] Install mode: $INSTALL_MODE"
echo "[mosaic-release-upgrade] Installer URL: $REMOTE_SCRIPT_URL"
if [[ "$DRY_RUN" == "true" ]]; then
echo "[mosaic-release-upgrade] Dry run: no changes applied."
exit 0
fi
if [[ "$YES" != "true" && -t 0 ]]; then
printf "Proceed with Mosaic release upgrade? [y/N]: "
read -r confirm
case "${confirm:-n}" in
y|Y|yes|YES) ;;
*)
echo "[mosaic-release-upgrade] Aborted."
exit 1
;;
esac
fi
if command -v curl >/dev/null 2>&1; then
curl -sL "$REMOTE_SCRIPT_URL" | \
MOSAIC_BOOTSTRAP_REF="$BOOTSTRAP_REF" \
MOSAIC_INSTALL_MODE="$INSTALL_MODE" \
MOSAIC_HOME="$MOSAIC_HOME" \
sh
elif command -v wget >/dev/null 2>&1; then
wget -qO- "$REMOTE_SCRIPT_URL" | \
MOSAIC_BOOTSTRAP_REF="$BOOTSTRAP_REF" \
MOSAIC_INSTALL_MODE="$INSTALL_MODE" \
MOSAIC_HOME="$MOSAIC_HOME" \
sh
else
echo "[mosaic-release-upgrade] ERROR: curl or wget required." >&2
exit 1
fi
@@ -0,0 +1,65 @@
# mosaic-release-upgrade.ps1 — Upgrade installed Mosaic framework release (Windows)
#
# Usage:
# mosaic-release-upgrade.ps1
# mosaic-release-upgrade.ps1 -Ref main -Keep
# mosaic-release-upgrade.ps1 -Ref v0.2.0 -Overwrite -Yes
#
param(
[string]$Ref = $(if ($env:MOSAIC_BOOTSTRAP_REF) { $env:MOSAIC_BOOTSTRAP_REF } else { "main" }),
[switch]$Keep,
[switch]$Overwrite,
[switch]$Yes,
[switch]$DryRun
)
$ErrorActionPreference = "Stop"
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$RemoteInstallerUrl = if ($env:MOSAIC_REMOTE_INSTALL_URL) {
$env:MOSAIC_REMOTE_INSTALL_URL
} else {
"https://git.mosaicstack.dev/mosaic/mosaic-stack/raw/branch/main/tools/install.sh"
}
$installMode = if ($Overwrite) { "overwrite" } elseif ($Keep) { "keep" } elseif ($env:MOSAIC_INSTALL_MODE) { $env:MOSAIC_INSTALL_MODE } else { "keep" }
if ($installMode -notin @("keep", "overwrite")) {
Write-Host "[mosaic-release-upgrade] Invalid install mode: $installMode" -ForegroundColor Red
exit 1
}
$currentVersion = "unknown"
$mosaicCmd = Join-Path $MosaicHome "bin\mosaic.ps1"
if (Test-Path $mosaicCmd) {
try {
$currentVersion = (& $mosaicCmd --version) -replace '^mosaic\s+', ''
}
catch {
$currentVersion = "unknown"
}
}
Write-Host "[mosaic-release-upgrade] Current version: $currentVersion"
Write-Host "[mosaic-release-upgrade] Target ref: $Ref"
Write-Host "[mosaic-release-upgrade] Install mode: $installMode"
Write-Host "[mosaic-release-upgrade] Installer URL: $RemoteInstallerUrl"
if ($DryRun) {
Write-Host "[mosaic-release-upgrade] Dry run: no changes applied."
exit 0
}
if (-not $Yes) {
$confirmation = Read-Host "Proceed with Mosaic release upgrade? [y/N]"
if ($confirmation -notin @("y", "Y", "yes", "YES")) {
Write-Host "[mosaic-release-upgrade] Aborted."
exit 1
}
}
$env:MOSAIC_BOOTSTRAP_REF = $Ref
$env:MOSAIC_INSTALL_MODE = $installMode
$env:MOSAIC_HOME = $MosaicHome
Invoke-RestMethod -Uri $RemoteInstallerUrl | Invoke-Expression
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -x "scripts/agent/session-end.sh" ]]; then
exec bash scripts/agent/session-end.sh "$@"
fi
echo "[mosaic] Missing scripts/agent/session-end.sh in $(pwd)" >&2
exit 1
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -x "scripts/agent/session-start.sh" ]]; then
exec bash scripts/agent/session-start.sh
fi
echo "[mosaic] Missing scripts/agent/session-start.sh in $(pwd)" >&2
exit 1
@@ -0,0 +1,269 @@
#!/usr/bin/env bash
set -euo pipefail
# Link the INSTALLED canonical skills into runtime skill directories.
#
# The canonical skills ship inside the framework package itself
# (packages/mosaic/framework/skills in the monorepo) and are installed into
# $MOSAIC_HOME/skills by the framework installer — there is no second
# repository to clone. This script only maintains the runtime symlinks.
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
MOSAIC_SKILLS_DIR="$MOSAIC_HOME/skills"
MOSAIC_LOCAL_SKILLS_DIR="$MOSAIC_HOME/skills-local"
# Colon-separated list of skill names to install. When set, only these skills
# are linked into runtime skill directories. Empty/unset = link all skills
# (the legacy "mosaic sync" full-catalog behavior).
MOSAIC_INSTALL_SKILLS="${MOSAIC_INSTALL_SKILLS:-}"
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Link installed skills from ~/.config/mosaic/{skills,skills-local} into runtime
skill directories. Canonical skills arrive with the framework installer; this
script never clones or pulls a second repository.
Options:
--link-only Accepted for compatibility; linking is now the whole job
--no-link Do nothing (kept for compatibility)
-h, --help Show help
Env:
MOSAIC_HOME Default: ~/.config/mosaic
MOSAIC_INSTALL_SKILLS Colon-separated list of skills to link (default: all)
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--link-only)
# Compat no-op: fetching a skills repo no longer exists.
shift
;;
--no-link)
echo "[mosaic-skills] Nothing to do (--no-link; canonical skills ship with the installer)"
exit 0
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
mkdir -p "$MOSAIC_HOME" "$MOSAIC_SKILLS_DIR" "$MOSAIC_LOCAL_SKILLS_DIR"
if [[ ! -d "$MOSAIC_SKILLS_DIR" ]]; then
echo "[mosaic-skills] Canonical skills dir missing: $MOSAIC_SKILLS_DIR" >&2
echo "[mosaic-skills] Canonical skills ship with the framework — reinstall or update the framework package" >&2
exit 1
fi
# Skills are linked into the MOSAIC-OWNED harness homes, never a base install.
# Paths mirror the config-dir env vars the launcher injects (HARNESS_HOME_ENV in
# commands/launch.js):
# claude CLAUDE_CONFIG_DIR -> <home>/skills
# pi PI_CODING_AGENT_DIR -> <home>/skills (replaces ~/.pi/agent)
# codex CODEX_HOME -> <home>/skills
# opencode XDG_CONFIG_HOME -> <home>/opencode/skills (XDG adds a level)
link_targets=(
"$MOSAIC_HOME/.claude/skills"
"$MOSAIC_HOME/.codex/skills"
"$MOSAIC_HOME/.opencode/opencode/skills"
"$MOSAIC_HOME/.pi/skills"
)
# Pre-isolation installs planted the same symlink farm directly in the operator's
# base installs. Those are now orphaned: the launcher no longer reads them, but
# they persist and make a "clean" base install look mosaic-managed.
legacy_link_targets=(
"$HOME/.claude/skills"
"$HOME/.codex/skills"
"$HOME/.config/opencode/skills"
"$HOME/.pi/agent/skills"
)
canonical_real="$(readlink -f "$MOSAIC_SKILLS_DIR")"
local_real="$(readlink -f "$MOSAIC_LOCAL_SKILLS_DIR")"
# Build an associative array from the colon-separated whitelist for O(1) lookup.
# When MOSAIC_INSTALL_SKILLS is empty, all skills are allowed.
declare -A _skill_whitelist=()
_whitelist_active=0
if [[ -n "$MOSAIC_INSTALL_SKILLS" ]]; then
_whitelist_active=1
IFS=':' read -ra _wl_items <<< "$MOSAIC_INSTALL_SKILLS"
for _item in "${_wl_items[@]}"; do
[[ -n "$_item" ]] && _skill_whitelist["$_item"]=1
done
fi
is_skill_selected() {
local name="$1"
if [[ $_whitelist_active -eq 0 ]]; then
return 0
fi
[[ -n "${_skill_whitelist[$name]:-}" ]] && return 0
return 1
}
link_skill_into_target() {
local skill_path="$1"
local target_dir="$2"
local name link_path
name="$(basename "$skill_path")"
# Do not distribute hidden/system skill directories globally.
if [[ "$name" == .* ]]; then
return
fi
# Respect the install whitelist (set during first-run wizard).
if ! is_skill_selected "$name"; then
return
fi
link_path="$target_dir/$name"
if [[ -L "$link_path" ]]; then
local raw_target resolved_target
raw_target="$(readlink "$link_path")"
resolved_target="$(node -e 'const p=require("node:path"); process.stdout.write(p.resolve(p.dirname(process.argv[1]), process.argv[2]));' "$link_path" "$raw_target")"
if [[ "$resolved_target" == "$canonical_real/"* || "$resolved_target" == "$local_real/"* ]]; then
ln -sfn "$skill_path" "$link_path"
else
echo "[mosaic-skills] Preserve foreign runtime symlink: $link_path"
fi
return
fi
if [[ -e "$link_path" ]]; then
echo "[mosaic-skills] Preserve existing runtime-specific entry: $link_path"
return
fi
ln -s "$skill_path" "$link_path"
}
is_mosaic_skill_name() {
local name="$1"
# -d follows symlinks; -L catches broken symlinks that still indicate ownership
[[ -d "$MOSAIC_SKILLS_DIR/$name" || -L "$MOSAIC_SKILLS_DIR/$name" ]] && return 0
[[ -d "$MOSAIC_LOCAL_SKILLS_DIR/$name" || -L "$MOSAIC_LOCAL_SKILLS_DIR/$name" ]] && return 0
return 1
}
prune_stale_links_in_target() {
local target_dir="$1"
while IFS= read -r -d '' link_path; do
local name resolved
name="$(basename "$link_path")"
if is_mosaic_skill_name "$name"; then
continue
fi
# -m resolves lexical dangling targets too. If resolution fails, ownership
# is unproven and the link must be preserved.
resolved="$(readlink -m "$link_path" 2>/dev/null || true)"
# $canonical_real must be length-checked BEFORE use as a prefix: if it were
# ever empty, "$resolved" == "$canonical_real/"* collapses to == "/"* and
# matches every absolute path. Combined with the is_mosaic_skill_name skip
# above, that inverts the function precisely — it would delete exactly the
# FOREIGN symlinks and keep the mosaic ones. (#1087, reported by mos-claude.)
if [[ -n "$resolved" && -n "$canonical_real" && "$resolved" == "$canonical_real/"* ]]; then
rm -f "$link_path"
echo "[mosaic-skills] Removed stale retired skill link: $link_path"
fi
done < <(find "$target_dir" -mindepth 1 -maxdepth 1 -type l -print0)
}
# Remove mosaic-owned symlinks left in a base install by a pre-isolation sync.
#
# Ownership is proven by RESOLUTION, not by name: only links resolving inside the
# canonical or local skills dirs are removed. Anything else — a real directory, a
# link elsewhere, an unresolvable link — is left untouched. This mirrors the
# refusal in commands/skill.js ("only symlinks pointing inside the Mosaic skills
# directory are managed") and preserves e.g. codex's own `.system` dir.
#
# The directory itself is kept: mosaic-doctor warns when ~/.pi/agent/skills is
# missing, and an empty dir is the correct end state, not an absent one.
cleanup_legacy_target() {
local target_dir="$1"
local removed=0 kept=0
[[ -d "$target_dir" ]] || return 0
while IFS= read -r -d '' link_path; do
local resolved owned=0
resolved="$(readlink -m "$link_path" 2>/dev/null || true)"
# Guard the empty-prefix trap: an unset *_real would make "$resolved" == "/"*
# match every absolute path and delete foreign links.
if [[ -n "$resolved" ]]; then
if [[ -n "$canonical_real" && "$resolved" == "$canonical_real/"* ]]; then
owned=1
elif [[ -n "$local_real" && "$resolved" == "$local_real/"* ]]; then
owned=1
fi
fi
if [[ $owned -eq 1 ]]; then
rm -f "$link_path"
removed=$((removed + 1))
else
kept=$((kept + 1))
fi
done < <(find "$target_dir" -mindepth 1 -maxdepth 1 -type l -print0)
if [[ $removed -gt 0 ]]; then
echo "[mosaic-skills] Legacy cleanup: removed $removed mosaic symlink(s) from $target_dir (preserved $kept foreign)"
fi
}
for legacy in "${legacy_link_targets[@]}"; do
# Skip anything that is also a current target, so isolation can never
# self-destruct if the two lists ever overlap.
skip=0
for target in "${link_targets[@]}"; do
[[ "$legacy" == "$target" ]] && skip=1
done
[[ $skip -eq 1 ]] && continue
cleanup_legacy_target "$legacy"
done
for target in "${link_targets[@]}"; do
mkdir -p "$target"
# If target already resolves to canonical dir, skip to avoid self-link recursion/corruption.
target_real="$(readlink -f "$target" 2>/dev/null || true)"
if [[ -n "$target_real" && "$target_real" == "$canonical_real" ]]; then
echo "[mosaic-skills] Skip target (already canonical): $target"
continue
fi
prune_stale_links_in_target "$target"
while IFS= read -r -d '' skill; do
link_skill_into_target "$skill" "$target"
done < <(find "$MOSAIC_SKILLS_DIR" -mindepth 1 -maxdepth 1 -type d -print0)
if [[ -d "$MOSAIC_LOCAL_SKILLS_DIR" ]]; then
while IFS= read -r -d '' skill; do
link_skill_into_target "$skill" "$target"
done < <(find "$MOSAIC_LOCAL_SKILLS_DIR" -mindepth 1 -maxdepth 1 \( -type d -o -type l \) -print0)
fi
echo "[mosaic-skills] Linked skills into: $target"
done
echo "[mosaic-skills] Complete"
@@ -0,0 +1,124 @@
# mosaic-sync-skills.ps1
# Links the INSTALLED canonical skills into agent runtime skill directories.
# Canonical skills ship inside the framework package and are installed into
# ~/.config/mosaic/skills by the framework installer — there is no second
# repository to clone. This script only maintains the runtime links.
# Uses directory junctions (no elevation required) with fallback to copies.
# PowerShell equivalent of mosaic-sync-skills (bash).
$ErrorActionPreference = "Stop"
param(
[switch]$LinkOnly,
[switch]$NoLink,
[switch]$Help
)
$MosaicHome = if ($env:MOSAIC_HOME) { $env:MOSAIC_HOME } else { Join-Path $env:USERPROFILE ".config\mosaic" }
$MosaicSkillsDir = Join-Path $MosaicHome "skills"
$MosaicLocalSkillsDir = Join-Path $MosaicHome "skills-local"
if ($Help) {
Write-Host @"
Usage: mosaic-sync-skills.ps1 [-LinkOnly] [-NoLink] [-Help]
Link installed skills from ~/.config/mosaic/{skills,skills-local} into runtime
skill directories using directory junctions. Canonical skills arrive with the
framework installer; this script never clones or pulls a second repository.
Options:
-LinkOnly Accepted for compatibility; linking is now the whole job
-NoLink Do nothing (kept for compatibility)
-Help Show help
"@
exit 0
}
if ($NoLink) {
Write-Host "[mosaic-skills] Nothing to do (-NoLink; canonical skills ship with the installer)"
exit 0
}
foreach ($d in @($MosaicHome, $MosaicSkillsDir, $MosaicLocalSkillsDir)) {
if (-not (Test-Path $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }
}
if (-not (Test-Path $MosaicSkillsDir)) {
Write-Host "[mosaic-skills] Canonical skills dir missing: $MosaicSkillsDir" -ForegroundColor Red
exit 1
}
if ($NoLink) {
Write-Host "[mosaic-skills] Canonical sync completed (link update skipped)"
exit 0
}
function Link-SkillIntoTarget {
param([string]$SkillPath, [string]$TargetDir)
$name = Split-Path $SkillPath -Leaf
if ($name.StartsWith(".")) { return }
$linkPath = Join-Path $TargetDir $name
# Recreate only Mosaic-owned junctions/symlinks. Foreign reparse points are
# runtime-owned and must never be clobbered by install/upgrade auto-sync.
$existing = Get-Item $linkPath -Force -ErrorAction SilentlyContinue
if ($existing -and ($existing.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
$rawTarget = @($existing.Target)[0]
$candidate = if ([System.IO.Path]::IsPathRooted($rawTarget)) {
$rawTarget
}
else {
Join-Path (Split-Path $linkPath -Parent) $rawTarget
}
$resolvedTarget = [System.IO.Path]::GetFullPath($candidate)
$canonicalRoot = [System.IO.Path]::GetFullPath($MosaicSkillsDir).TrimEnd('\') + '\'
$localRoot = [System.IO.Path]::GetFullPath($MosaicLocalSkillsDir).TrimEnd('\') + '\'
$owned = $resolvedTarget.StartsWith($canonicalRoot, [System.StringComparison]::OrdinalIgnoreCase) -or
$resolvedTarget.StartsWith($localRoot, [System.StringComparison]::OrdinalIgnoreCase)
if (-not $owned) {
Write-Host "[mosaic-skills] Preserve foreign runtime symlink: $linkPath"
return
}
Remove-Item $linkPath -Force
}
elseif ($existing) {
Write-Host "[mosaic-skills] Preserve existing runtime-specific entry: $linkPath"
return
}
# Try junction first, fall back to copy
try {
New-Item -ItemType Junction -Path $linkPath -Target $SkillPath -ErrorAction Stop | Out-Null
}
catch {
Write-Host "[mosaic-skills] Junction failed for $name, falling back to copy"
Copy-Item $SkillPath $linkPath -Recurse -Force
}
}
$linkTargets = @(
(Join-Path $env:USERPROFILE ".claude\skills"),
(Join-Path $env:USERPROFILE ".codex\skills"),
(Join-Path $env:USERPROFILE ".config\opencode\skills")
)
foreach ($target in $linkTargets) {
if (-not (Test-Path $target)) { New-Item -ItemType Directory -Path $target -Force | Out-Null }
# Link canonical skills
Get-ChildItem $MosaicSkillsDir -Directory | ForEach-Object {
Link-SkillIntoTarget $_.FullName $target
}
# Link local skills
if (Test-Path $MosaicLocalSkillsDir) {
Get-ChildItem $MosaicLocalSkillsDir -Directory | ForEach-Object {
Link-SkillIntoTarget $_.FullName $target
}
}
Write-Host "[mosaic-skills] Linked skills into: $target"
}
Write-Host "[mosaic-skills] Complete"
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env bash
set -euo pipefail
# mosaic-upgrade — Clean up stale per-project files after Mosaic centralization
#
# SOUL.md → Now global at ~/.config/mosaic/SOUL.md (remove from projects)
# CLAUDE.md → Now a thin pointer or removable (replace with pointer or remove)
# AGENTS.md → Keep project-specific content, strip stale load-order directives
#
# Usage:
# mosaic-upgrade [path] Upgrade a specific project (default: current dir)
# mosaic-upgrade --all Scan ~/src/* for projects to upgrade
# mosaic-upgrade --dry-run Show what would change without touching anything
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
# Colors (disabled if not a terminal)
if [[ -t 1 ]]; then
GREEN='\033[0;32m' YELLOW='\033[0;33m' RED='\033[0;31m'
CYAN='\033[0;36m' BOLD='\033[1m' DIM='\033[2m' RESET='\033[0m'
else
GREEN='' YELLOW='' RED='' CYAN='' BOLD='' DIM='' RESET=''
fi
ok() { echo -e " ${GREEN}✓${RESET} $1"; }
skip() { echo -e " ${DIM}${RESET} $1"; }
warn() { echo -e " ${YELLOW}⚠${RESET} $1"; }
act() { echo -e " ${CYAN}→${RESET} $1"; }
DRY_RUN=false
ALL=false
TARGET=""
SEARCH_ROOT="${HOME}/src"
usage() {
cat <<USAGE
mosaic-upgrade — Clean up stale per-project files
Usage:
mosaic-upgrade [path] Upgrade a specific project (default: cwd)
mosaic-upgrade --all Scan ~/src/* for all git projects
mosaic-upgrade --dry-run Preview changes without writing
mosaic-upgrade --all --dry-run Preview all projects
After Mosaic centralization:
SOUL.md → Removed (now global at ~/.config/mosaic/SOUL.md)
CLAUDE.md → Replaced with thin pointer or removed
AGENTS.md → Stale load-order sections stripped; project content preserved
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--dry-run) DRY_RUN=true; shift ;;
--all) ALL=true; shift ;;
--root) SEARCH_ROOT="$2"; shift 2 ;;
-h|--help) usage; exit 0 ;;
-*) echo "Unknown flag: $1" >&2; usage >&2; exit 1 ;;
*) TARGET="$1"; shift ;;
esac
done
# Generate the thin CLAUDE.md pointer
CLAUDE_POINTER='# CLAUDE Compatibility Pointer
This file exists so Claude Code sessions load Mosaic standards.
## MANDATORY — Read Before Any Response
BEFORE responding to any user message, READ `~/.config/mosaic/AGENTS.md`.
That file is the universal agent configuration. Do NOT respond until you have loaded it.
Then read the project-local `AGENTS.md` in this repository for project-specific guidance.'
upgrade_project() {
local project_dir="$1"
local project_name
project_name="$(basename "$project_dir")"
local changed=false
echo -e "\n${BOLD}$project_name${RESET} ${DIM}($project_dir)${RESET}"
# ── SOUL.md ──────────────────────────────────────────────
local soul="$project_dir/SOUL.md"
if [[ -f "$soul" ]]; then
if [[ "$DRY_RUN" == "true" ]]; then
act "Would remove SOUL.md (now global at ~/.config/mosaic/SOUL.md)"
else
rm "$soul"
ok "Removed SOUL.md (now global)"
fi
changed=true
else
skip "No SOUL.md (already clean)"
fi
# ── CLAUDE.md ────────────────────────────────────────────
local claude_md="$project_dir/CLAUDE.md"
if [[ -f "$claude_md" ]]; then
local claude_content
claude_content="$(cat "$claude_md")"
# Check if it's already a thin pointer to AGENTS.md
if echo "$claude_content" | grep -q "READ.*~/.config/mosaic/AGENTS.md"; then
skip "CLAUDE.md already points to global AGENTS.md"
else
if [[ "$DRY_RUN" == "true" ]]; then
act "Would replace CLAUDE.md with thin pointer to global AGENTS.md"
else
# Back up the original
cp "$claude_md" "${claude_md}.mosaic-bak"
echo "$CLAUDE_POINTER" > "$claude_md"
ok "Replaced CLAUDE.md with pointer (backup: CLAUDE.md.mosaic-bak)"
fi
changed=true
fi
else
skip "No CLAUDE.md"
fi
# ── AGENTS.md (strip stale load-order, preserve project content) ─
local agents="$project_dir/AGENTS.md"
if [[ -f "$agents" ]]; then
# Detect stale load-order patterns
local has_stale=false
# Pattern 1: References to SOUL.md in load order
if grep -qE "(Read|READ|Load).*SOUL\.md" "$agents" 2>/dev/null; then
has_stale=true
fi
# Pattern 2: Old "## Load Order" section that references centralized files
if grep -q "## Load Order" "$agents" 2>/dev/null && \
grep -qE "STANDARDS\.md|SOUL\.md" "$agents" 2>/dev/null; then
has_stale=true
fi
# Pattern 3: Old ~/.mosaic/ path (pre-centralization)
if grep -q '~/.mosaic/' "$agents" 2>/dev/null; then
has_stale=true
fi
if [[ "$has_stale" == "true" ]]; then
if [[ "$DRY_RUN" == "true" ]]; then
act "Would strip stale load-order section from AGENTS.md"
# Show what we detect
if grep -qn "## Load Order" "$agents" 2>/dev/null; then
local line
line=$(grep -n "## Load Order" "$agents" | head -1 | cut -d: -f1)
echo -e " ${DIM}Line $line: Found '## Load Order' section referencing SOUL.md/STANDARDS.md${RESET}"
fi
if grep -qn '~/.mosaic/' "$agents" 2>/dev/null; then
echo -e " ${DIM}Found references to old ~/.mosaic/ path${RESET}"
fi
else
cp "$agents" "${agents}.mosaic-bak"
# Strip the Load Order section (from "## Load Order" to next "##" or "---")
if grep -q "## Load Order" "$agents"; then
awk '
/^## Load Order/ { skip=1; next }
skip && /^(## |---)/ { skip=0 }
skip { next }
{ print }
' "${agents}.mosaic-bak" > "$agents"
fi
# Fix old ~/.mosaic/ → ~/.config/mosaic/
if grep -q '~/.mosaic/' "$agents"; then
sed -i 's|~/.mosaic/|~/.config/mosaic/|g' "$agents"
fi
ok "Stripped stale load-order from AGENTS.md (backup: AGENTS.md.mosaic-bak)"
fi
changed=true
else
skip "AGENTS.md has no stale directives"
fi
else
skip "No AGENTS.md"
fi
# ── .claude/settings.json (leave alone) ──────────────────
# Project-specific settings are fine — don't touch them.
if [[ "$changed" == "false" ]]; then
echo -e " ${GREEN}Already up to date.${RESET}"
fi
}
# ── Main ───────────────────────────────────────────────────
if [[ "$DRY_RUN" == "true" ]]; then
echo -e "${BOLD}Mode: DRY RUN (no files will be changed)${RESET}"
fi
if [[ "$ALL" == "true" ]]; then
echo -e "${BOLD}Scanning $SEARCH_ROOT for projects...${RESET}"
count=0
for dir in "$SEARCH_ROOT"/*/; do
[[ -d "$dir/.git" ]] || continue
upgrade_project "$dir"
count=$((count + 1))
done
echo -e "\n${BOLD}Scanned $count projects.${RESET}"
elif [[ -n "$TARGET" ]]; then
if [[ ! -d "$TARGET" ]]; then
echo "[mosaic-upgrade] ERROR: $TARGET is not a directory." >&2
exit 1
fi
upgrade_project "$TARGET"
else
upgrade_project "$(pwd)"
fi
if [[ "$DRY_RUN" == "true" ]]; then
echo -e "\n${YELLOW}This was a dry run. Run without --dry-run to apply changes.${RESET}"
fi
@@ -0,0 +1,116 @@
#!/usr/bin/env bash
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
BOOTSTRAP_CMD="$MOSAIC_HOME/tools/_scripts/mosaic-bootstrap-repo"
roots=("$HOME/src")
apply=0
usage() {
cat <<USAGE
Usage: $(basename "$0") [options]
Upgrade all Mosaic-linked slave repositories by re-running repo bootstrap with --force.
Options:
--root <path> Add a search root (repeatable). Default: $HOME/src
--apply Execute upgrades. Without this flag, script is dry-run.
-h, --help Show this help
USAGE
}
while [[ $# -gt 0 ]]; do
case "$1" in
--root)
[[ $# -lt 2 ]] && { echo "Missing value for --root" >&2; exit 1; }
roots+=("$2")
shift 2
;;
--apply)
apply=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown argument: $1" >&2
usage >&2
exit 1
;;
esac
done
if [[ ! -x "$BOOTSTRAP_CMD" ]]; then
echo "[mosaic-upgrade] Missing bootstrap command: $BOOTSTRAP_CMD" >&2
echo "[mosaic-upgrade] Install/refresh framework first: ~/.config/mosaic/install.sh" >&2
exit 1
fi
# De-duplicate roots while preserving order.
uniq_roots=()
for r in "${roots[@]}"; do
skip=0
for e in "${uniq_roots[@]}"; do
[[ "$r" == "$e" ]] && { skip=1; break; }
done
[[ $skip -eq 0 ]] && uniq_roots+=("$r")
done
candidates=()
for root in "${uniq_roots[@]}"; do
[[ -d "$root" ]] || continue
while IFS= read -r marker; do
repo_dir="$(dirname "$(dirname "$marker")")"
if [[ -d "$repo_dir/.git" ]]; then
candidates+=("$repo_dir")
fi
done < <(find "$root" -type f -path '*/.mosaic/README.md' 2>/dev/null)
done
# De-duplicate repos while preserving order.
repos=()
for repo in "${candidates[@]}"; do
skip=0
for existing in "${repos[@]}"; do
[[ "$repo" == "$existing" ]] && { skip=1; break; }
done
[[ $skip -eq 0 ]] && repos+=("$repo")
done
count_total=${#repos[@]}
count_ok=0
count_fail=0
mode="DRY-RUN"
[[ $apply -eq 1 ]] && mode="APPLY"
echo "[mosaic-upgrade] Mode: $mode"
echo "[mosaic-upgrade] Roots: ${uniq_roots[*]}"
echo "[mosaic-upgrade] Linked repos found: $count_total"
if [[ $count_total -eq 0 ]]; then
exit 0
fi
for repo in "${repos[@]}"; do
if [[ $apply -eq 1 ]]; then
if "$BOOTSTRAP_CMD" "$repo" --force >/dev/null; then
echo "[mosaic-upgrade] upgraded: $repo"
count_ok=$((count_ok + 1))
else
echo "[mosaic-upgrade] FAILED: $repo" >&2
count_fail=$((count_fail + 1))
fi
else
echo "[mosaic-upgrade] would upgrade: $repo"
fi
done
if [[ $apply -eq 1 ]]; then
echo "[mosaic-upgrade] complete: ok=$count_ok failed=$count_fail total=$count_total"
[[ $count_fail -gt 0 ]] && exit 1
fi
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
# mosaic-wizard — Thin shell wrapper for the bundled TypeScript wizard
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
# Look for the bundle in the installed location first, then the source repo
WIZARD_BIN="$MOSAIC_HOME/dist/mosaic-wizard.mjs"
if [[ ! -f "$WIZARD_BIN" ]]; then
WIZARD_BIN="$(cd "$(dirname "$0")/.." && pwd)/dist/mosaic-wizard.mjs"
fi
if [[ ! -f "$WIZARD_BIN" ]]; then
echo "[mosaic-wizard] ERROR: Wizard bundle not found." >&2
echo "[mosaic-wizard] Re-install with: npm install -g @mosaic/mosaic" >&2
exit 1
fi
if ! command -v node >/dev/null 2>&1; then
echo "[mosaic-wizard] ERROR: Node.js is required but not found." >&2
echo "[mosaic-wizard] Install Node.js 18+ from https://nodejs.org" >&2
exit 1
fi
exec node "$WIZARD_BIN" "$@"
@@ -0,0 +1,127 @@
#!/usr/bin/env bash
# Covers the brain-home fleet-state check in `mosaic-doctor` (#1298 follow-up).
#
# The functions are extracted from the shipped script rather than copied here
# (same discipline as test-fleet-transport-check.sh): a test that carries its
# own copy of the logic keeps passing after the shipped copy changes.
# Extraction is by exact function header and a closing brace in column one.
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname "$0")" && pwd)
DOCTOR="$SCRIPT_DIR/mosaic-doctor"
fail() {
echo "FAIL: $*" >&2
exit 1
}
[ -f "$DOCTOR" ] || fail "missing mosaic-doctor at $DOCTOR"
extract_function() {
local name="$1"
local extracted
extracted=$(sed -n "/^${name}() {/,/^}/p" "$DOCTOR")
[ -n "$extracted" ] || fail "could not extract ${name}() from mosaic-doctor — script reshaped?"
printf '%s\n' "$extracted"
}
for fn in resolve_brain_home check_brain_home; do
extract_function "$fn" >/dev/null
done
warn_count=0
warn() { warn_count=$((warn_count + 1)); echo "[WARN] $*"; }
pass() { echo "[OK] $*"; return 0; }
eval "$(extract_function resolve_brain_home)"
eval "$(extract_function check_brain_home)"
ROOT=$(mktemp -d)
trap 'rm -rf "$ROOT"' EXIT
# note output is neither [OK] nor [WARN] — assert it directly in the case below.
run_case() {
# label, expect (ok|warn|note), then env assignments as arguments.
# The check runs under `env` in a subshell, so its warn() also prints a
# sentinel the parent counts — a subshell counter would never be visible.
local label="$1" expect="$2"
shift 2
local out warns notes
out=$(env "$@" bash -c "warn() { echo \"[WARN] \$*\"; }; note() { echo \"[NOTE] \$*\"; return 0; }; pass() { echo \"[OK] \$*\"; return 0; }; $(extract_function resolve_brain_home); $(extract_function check_brain_home); check_brain_home" 2>&1)
warns=$(printf '%s\n' "$out" | grep -c '^\[WARN\]' || true)
notes=$(printf '%s\n' "$out" | grep -c '^\[NOTE\]' || true)
if [[ "$expect" == ok && "$warns" -eq 0 && "$notes" -eq 0 ]]; then
echo "ok - $label"
elif [[ "$expect" == warn && "$warns" -gt 0 ]]; then
echo "ok - $label (warned)"
elif [[ "$expect" == note && "$notes" -gt 0 ]]; then
echo "ok - $label (noted)"
else
echo "output: $out" >&2
fail "$label: expected $expect (warns=$warns notes=$notes)"
fi
}
# ── legacy: no brain, custom home never adopts ─────────────────────────────
mkdir -p "$ROOT/legacy-mosaic/fleet/agents"
run_case "custom home without brain stays legacy" ok \
MOSAIC_HOME="$ROOT/legacy-mosaic" HOME="$ROOT"
# ── healthy brain at the default config home ───────────────────────────────
mkdir -p "$ROOT/home/.config/mosaic" "$ROOT/home/.mosaic/fleet/agents"
chmod 700 "$ROOT/home/.mosaic/fleet/agents"
run_case "default home adopts healthy brain" ok \
MOSAIC_HOME="$ROOT/home/.config/mosaic" HOME="$ROOT/home"
# ── explicit MOSAIC_BRAIN_HOME to a brain without fleet/agents → warn ──────
mkdir -p "$ROOT/brain-noagents/fleet" "$ROOT/config"
run_case "explicit brain without agents warns" warn \
MOSAIC_HOME="$ROOT/config" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-noagents"
# ── explicit MOSAIC_BRAIN_HOME to a healthy brain → ok ─────────────────────
mkdir -p "$ROOT/brain-ok/fleet/agents" "$ROOT/config2"
chmod 700 "$ROOT/brain-ok/fleet/agents"
run_case "explicit healthy brain passes" ok \
MOSAIC_HOME="$ROOT/config2" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-ok"
# ── group-readable agents dir → warn (0700 boundary) ───────────────────────
mkdir -p "$ROOT/brain-loose/fleet/agents" "$ROOT/config3"
chmod 750 "$ROOT/brain-loose/fleet/agents"
run_case "group-readable brain agents warns" warn \
MOSAIC_HOME="$ROOT/config3" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-loose"
# ── symlinked agents dir → warn (managed-directory boundary) ───────────────
mkdir -p "$ROOT/brain-link/real-agents" "$ROOT/brain-link/fleet" "$ROOT/config4"
ln -s "$ROOT/brain-link/real-agents" "$ROOT/brain-link/fleet/agents"
run_case "symlinked brain agents warns" warn \
MOSAIC_HOME="$ROOT/config4" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-link"
# ── split state: envs in BOTH trees → warn ─────────────────────────────────
mkdir -p "$ROOT/brain-split/fleet/agents" "$ROOT/config5/fleet/agents"
chmod 700 "$ROOT/brain-split/fleet/agents" "$ROOT/config5/fleet/agents"
touch "$ROOT/config5/fleet/agents/coder0.env.generated"
run_case "env files in both trees warns (split state)" warn \
MOSAIC_HOME="$ROOT/config5" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-split"
# ── config-home agents dir WITHOUT env files alongside a brain → ok ────────
mkdir -p "$ROOT/brain-clean/fleet/agents" "$ROOT/config6/fleet/agents"
chmod 700 "$ROOT/brain-clean/fleet/agents" "$ROOT/config6/fleet/agents"
run_case "empty config-home agents dir alongside brain passes" ok \
MOSAIC_HOME="$ROOT/config6" HOME="$ROOT" MOSAIC_BRAIN_HOME="$ROOT/brain-clean"
# ── greenfield brain-without-agents at the default home → note (#1288) ─────
mkdir -p "$ROOT/gf-home/.config/mosaic/fleet" "$ROOT/gf-home/.mosaic"
run_case "~/.mosaic without fleet/agents at default home notes the lock-in" note \
MOSAIC_HOME="$ROOT/gf-home/.config/mosaic" HOME="$ROOT/gf-home"
# ── no ~/.mosaic at all at the default home → clean pass ─────────────────
mkdir -p "$ROOT/plain-home/.config/mosaic/fleet"
run_case "no ~/.mosaic at default home passes silently" ok \
MOSAIC_HOME="$ROOT/plain-home/.config/mosaic" HOME="$ROOT/plain-home"
# ── custom (non-default) home with a stray ~/.mosaic → still silent ──────
mkdir -p "$ROOT/custom-home/fleet/agents" "$ROOT/custom-home/.mosaic"
run_case "custom home with stray ~/.mosaic stays silent" ok \
MOSAIC_HOME="$ROOT/custom-home" HOME="$ROOT/custom-home"
echo "ok - mosaic-doctor brain-home check"
@@ -0,0 +1,215 @@
#!/usr/bin/env bash
# Covers the #1240 fleet-transport checks in `mosaic-doctor` and in
# `tools/install.sh`.
#
# Both checks answer the same question — "can a seat actually launch on this
# host?" — from two different places, because the installer has to be able to
# answer it before the framework's own scripts are guaranteed to be on disk.
# Two implementations of one rule is exactly the shape that drifts, so this
# harness drives BOTH, in one file, from the same table of cases.
#
# The functions are extracted from the shipped scripts rather than copied here.
# A test that carries its own copy of the logic is a test that keeps passing
# after the shipped copy changes — the failure mode this whole change is about.
# Extraction is by exact function header and a closing brace in column one; if
# either script is reshaped so that stops matching, the extraction yields
# nothing and this fails loudly instead of silently measuring an empty string.
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
DOCTOR="$SCRIPT_DIR/mosaic-doctor"
# framework/tools/_scripts -> framework/tools -> framework -> mosaic -> packages -> repo
INSTALLER=$(cd -- "$SCRIPT_DIR/../../../../.." && pwd)/tools/install.sh
fail() {
echo "FAIL: $*" >&2
exit 1
}
[ -f "$DOCTOR" ] || fail "missing mosaic-doctor at $DOCTOR"
[ -f "$INSTALLER" ] || fail "missing install.sh at $INSTALLER"
ROOT=$(mktemp -d)
trap 'rm -rf "$ROOT"' EXIT
# The cases below run with PATH set to a directory that deliberately does not
# contain a shell, and a PATH assignment on a command also governs how that
# command is looked up — so bash has to be named absolutely or it becomes the
# thing that is missing.
BASH_BIN=$(command -v bash) || fail "host is missing 'bash'"
# A PATH containing exactly the utilities these functions use and nothing else.
# The absent-transport cases are only meaningful on a PATH where the transport
# is genuinely unresolvable, and this host (like most) has tmux in /usr/bin —
# so the system path cannot be part of the path under test.
FAKE_BIN="$ROOT/bin"
mkdir -p "$FAKE_BIN"
for utility in sed head tr awk; do
utility_path=$(command -v "$utility") || fail "host is missing '$utility'"
ln -s "$utility_path" "$FAKE_BIN/$utility"
done
if PATH="$FAKE_BIN" command -v tmux >/dev/null 2>&1; then
fail "'tmux' is resolvable on the minimal test path; absent-transport cases are not measurable"
fi
# Extract a function by its exact header, up to a closing brace in column one.
extract_function() {
local source_file="$1"
local function_name="$2"
local destination="$3"
awk -v name="$function_name" '
$0 == name "() {" { collecting = 1 }
collecting { print }
collecting && $0 == "}" { exit }
' "$source_file" > "$destination"
grep -qF "$function_name() {" "$destination" ||
fail "could not extract '$function_name' from $source_file — has it been renamed or reshaped?"
# An unterminated extraction would be a syntax error the moment it is sourced,
# but saying so here names the cause instead of leaving a bash parse error.
bash -n "$destination" ||
fail "extracted '$function_name' does not parse; the closing brace was probably not found"
}
extract_function "$DOCTOR" fleet_declared_transport "$ROOT/doctor-declared.sh"
extract_function "$DOCTOR" check_fleet_transport "$ROOT/doctor-check.sh"
extract_function "$INSTALLER" check_fleet_transport "$ROOT/installer-check.sh"
# Build a MOSAIC_HOME, optionally with a roster declaring a transport.
make_home() {
local home="$ROOT/$1"
local declared="${2-}"
rm -rf "$home"
mkdir -p "$home"
if [ -n "$declared" ]; then
mkdir -p "$home/fleet"
cat > "$home/fleet/roster.yaml" <<EOF
version: 2
generation: 1
transport: $declared
agents: []
EOF
fi
printf '%s\n' "$home"
}
# Run the doctor's check against a given home and path, capturing which
# reporter the check chose. The real `pass` prints only under `--verbose` and
# the real `warn` always prints; these stubs make both unconditional on
# purpose, because what is under test is the severity the check selects, not
# whether the default verbosity happens to show it. A check that warned where
# it should pass would otherwise be invisible here.
run_doctor_check() {
local home="$1"
local path="$2"
MOSAIC_HOME="$home" PATH="$path" "$BASH_BIN" --noprofile --norc -c '
set -euo pipefail
warn() { echo "[WARN] $*"; }
pass() { echo "[OK] $*"; }
MOSAIC_HOME="$1"
source "$2"
source "$3"
check_fleet_transport
' _ "$home" "$ROOT/doctor-declared.sh" "$ROOT/doctor-check.sh" 2>&1
}
run_installer_check() {
local home="$1"
local path="$2"
MOSAIC_HOME="$home" PATH="$path" "$BASH_BIN" --noprofile --norc -c '
set -euo pipefail
warn() { echo "[WARN] $*"; }
C="" RESET=""
MOSAIC_HOME="$1"
source "$2"
check_fleet_transport
' _ "$home" "$ROOT/installer-check.sh" 2>&1
}
# A transport that exists. Named tmux because that is what the default roster
# declares; the binary never runs, it only has to resolve.
PRESENT_BIN="$ROOT/present-bin"
mkdir -p "$PRESENT_BIN"
printf '#!/usr/bin/env bash\nexit 0\n' > "$PRESENT_BIN/tmux"
chmod +x "$PRESENT_BIN/tmux"
PATH_WITH_TMUX="$PRESENT_BIN:$FAKE_BIN"
# ── absent, no roster ────────────────────────────────────────────────────────
# Nothing has been configured yet, so the honest thing to point at is `init`.
home=$(make_home no-roster)
output=$(run_doctor_check "$home" "$FAKE_BIN")
echo "$output" | grep -qF '[WARN]' || fail "doctor did not warn when tmux was absent"
echo "$output" | grep -qF 'tmux' || fail "doctor warning did not name the transport"
echo "$output" | grep -qF 'mosaic fleet init' || fail "doctor did not point a rosterless host at init"
output=$(run_installer_check "$home" "$FAKE_BIN")
echo "$output" | grep -qF '[WARN]' || fail "installer did not warn when tmux was absent"
echo "$output" | grep -qF 'reports success and no seat comes up' ||
fail "installer warning did not say what the missing transport actually breaks"
# ── absent, roster present ───────────────────────────────────────────────────
# A configured fleet that cannot launch is a stronger statement than a
# hypothetical one, and the message says so.
home=$(make_home with-roster tmux)
output=$(run_doctor_check "$home" "$FAKE_BIN")
echo "$output" | grep -qF '[WARN]' || fail "doctor did not warn with a roster present and tmux absent"
echo "$output" | grep -qF 'roster' || fail "doctor did not mention the roster it found"
echo "$output" | grep -qF 'mosaic fleet start' || fail "doctor did not point a configured host at start"
# ── present ──────────────────────────────────────────────────────────────────
# Silence from the installer, and a pass (not a warning) from the audit.
for home_name in no-roster with-roster; do
home="$ROOT/$home_name"
output=$(run_doctor_check "$home" "$PATH_WITH_TMUX")
if echo "$output" | grep -qF '[WARN]'; then
fail "doctor warned about the transport while tmux was present ($home_name)"
fi
echo "$output" | grep -qF '[OK]' || fail "doctor did not record a pass with tmux present ($home_name)"
output=$(run_installer_check "$home" "$PATH_WITH_TMUX")
if [ -n "$output" ]; then
fail "installer was not silent with tmux present ($home_name): $output"
fi
done
# ── the roster declares something other than tmux ────────────────────────────
# The roster is read, not assumed. A host that declares a different transport
# is told about the binary it actually needs, and never about tmux — being sent
# to install the wrong package is worse than no advice at all.
home=$(make_home other-transport zellij)
output=$(run_doctor_check "$home" "$PATH_WITH_TMUX")
echo "$output" | grep -qF 'zellij' || fail "doctor ignored the roster's declared transport"
if echo "$output" | grep -qF 'tmux'; then
fail "doctor named tmux for a host whose roster declares zellij"
fi
output=$(run_installer_check "$home" "$PATH_WITH_TMUX")
echo "$output" | grep -qF 'zellij' || fail "installer ignored the roster's declared transport"
if echo "$output" | grep -qF 'tmux'; then
fail "installer named tmux for a host whose roster declares zellij"
fi
# ── a quoted or trailing-comment transport value ─────────────────────────────
# YAML permits both and neither is exotic; a check that installs `tmux"` or
# reads `tmux # default` as a binary name would send the operator nowhere.
home=$(make_home quoted-transport '"tmux" # the only transport today')
output=$(run_doctor_check "$home" "$PATH_WITH_TMUX")
echo "$output" | grep -qF '[OK] Fleet transport available: tmux' ||
fail "doctor did not parse a quoted/commented transport value: $output"
output=$(run_installer_check "$home" "$PATH_WITH_TMUX")
if [ -n "$output" ]; then
fail "installer did not parse a quoted/commented transport value: $output"
fi
echo "ok - fleet transport checks (mosaic-doctor + install.sh)"
@@ -0,0 +1,180 @@
#!/usr/bin/env bash
# Regression harness for issue #869 Point-1 C2 — the install-ordering guard
# wired into mosaic-link-runtime-assets.
#
# Root cause under test: mosaic-link-runtime-assets copies
# runtime/claude/settings.json (which embeds the PreToolUse mutator-gate.py
# hook and the Stop receipt-observer-client.py hook) straight into
# ~/.claude/settings.json, unconditionally. If the lease-broker activation
# half cannot be confirmed on this host, wiring those hooks bricks it with a
# fail-closed gate that can never be satisfied.
#
# This harness never invokes a real `mosaic` CLI build — it stubs the
# `__link-claude-settings` contract with a fake `mosaic` on PATH so the shell
# WIRING (does mosaic-link-runtime-assets call out correctly? does it
# propagate a degraded outcome? does it still copy every other runtime file?
# does --allow-inactive-enforcement forward through?) is exercised
# independently of the TS guard's own logic (already covered by
# install-ordering-guard.spec.ts). It also exercises the no-mosaic-on-PATH
# python3 fallback directly.
#
# Scenarios:
# 1. probe=true (fake mosaic exits 0) -> settings.json copied, script exits 0.
# 2. probe=false (fake mosaic exits 1) -> script exits 1 (guard_degraded
# propagated), but every OTHER runtime file is still copied.
# 3. probe=false + --allow-inactive-enforcement -> the flag is forwarded to
# the fake mosaic stub.
# 4. No `mosaic` on PATH at all (activation unconfirmable) -> the python3
# fallback strips the enforcement hooks itself and the script exits 1.
# 5. No `mosaic` on PATH + --allow-inactive-enforcement -> the python3
# fallback wires the hooks AS-IS and the script exits 0.
set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LINK_SCRIPT="$SCRIPT_DIR/mosaic-link-runtime-assets"
TMP_ROOT=$(mktemp -d)
trap 'rm -rf "$TMP_ROOT"' EXIT
fail=0
fail_msg() {
echo "FAIL: $*" >&2
fail=1
}
FIXTURE_SETTINGS='{
"model": "opus",
"hooks": {
"PreToolUse": [
{ "matcher": ".*", "hooks": [ { "type": "command", "command": "python3 ~/.config/mosaic/tools/lease-broker/mutator-gate.py --runtime claude" } ] },
{ "matcher": "Write|Edit|MultiEdit", "hooks": [ { "type": "command", "command": "~/.config/mosaic/tools/qa/prevent-memory-write.sh" } ] }
],
"Stop": [
{ "hooks": [
{ "type": "command", "command": "python3 ~/.config/mosaic/tools/lease-broker/receipt-observer-client.py --runtime claude" },
{ "type": "command", "command": "~/.config/mosaic/tools/qa/reflect-stop-hook.sh" }
] }
]
}
}'
# Sets up a fresh $MOSAIC_HOME/runtime/claude/{settings.json,CLAUDE.md,
# hooks-config.json,context7-integration.md} + fresh $HOME, echoes both paths
# space-separated for the caller to `read`.
new_scenario_dirs() {
local scenario="$1"
local base="$TMP_ROOT/$scenario"
local mosaic_home="$base/mosaic-home"
local home="$base/home"
mkdir -p "$mosaic_home/runtime/claude" "$home"
printf '%s' "$FIXTURE_SETTINGS" > "$mosaic_home/runtime/claude/settings.json"
echo "claude.md fixture" > "$mosaic_home/runtime/claude/CLAUDE.md"
echo '{"hooks":{}}' > "$mosaic_home/runtime/claude/hooks-config.json"
echo "context7 fixture" > "$mosaic_home/runtime/claude/context7-integration.md"
echo "$mosaic_home" "$home"
}
settings_has_marker() {
local file="$1" marker="$2"
[[ -f "$file" ]] && grep -q "$marker" "$file"
}
# A fake `mosaic` binary implementing only the __link-claude-settings contract
# this harness needs: writes dest verbatim (fixture is unmodified either way —
# this stub only exercises the CALL CONTRACT, not the TS strip logic, which
# has its own vitest coverage) and exits with the code the scenario wants.
# Records the args it was called with so the harness can assert forwarding.
make_fake_mosaic() {
local bin_dir="$1" exit_code="$2"
mkdir -p "$bin_dir"
cat > "$bin_dir/mosaic" <<EOF
#!/usr/bin/env bash
set -euo pipefail
echo "\$@" > "$bin_dir/mosaic.args"
if [[ "\$1" == "__link-claude-settings" ]]; then
cp "\$2" "\$3"
exit $exit_code
fi
exit 0
EOF
chmod +x "$bin_dir/mosaic"
}
# --- Scenario 1: probe=true (fake mosaic exits 0) ---------------------------
read -r MOSAIC_HOME_1 HOME_1 < <(new_scenario_dirs scenario1)
BIN_1="$TMP_ROOT/scenario1/bin"
make_fake_mosaic "$BIN_1" 0
OUTPUT=$(MOSAIC_HOME="$MOSAIC_HOME_1" HOME="$HOME_1" PATH="$BIN_1:$PATH" "$LINK_SCRIPT" 2>&1)
STATUS=$?
[[ "$STATUS" -eq 0 ]] || fail_msg "scenario1 (probe=true): expected exit 0, got $STATUS. Output: $OUTPUT"
[[ -f "$HOME_1/.claude/settings.json" ]] || fail_msg "scenario1: settings.json was not copied"
# --- Scenario 2: probe=false (fake mosaic exits 1) --------------------------
read -r MOSAIC_HOME_2 HOME_2 < <(new_scenario_dirs scenario2)
BIN_2="$TMP_ROOT/scenario2/bin"
make_fake_mosaic "$BIN_2" 1
OUTPUT=$(MOSAIC_HOME="$MOSAIC_HOME_2" HOME="$HOME_2" PATH="$BIN_2:$PATH" "$LINK_SCRIPT" 2>&1)
STATUS=$?
[[ "$STATUS" -ne 0 ]] || fail_msg "scenario2 (probe=false, default): expected non-zero exit, got 0. Output: $OUTPUT"
[[ -f "$HOME_2/.claude/CLAUDE.md" ]] || fail_msg "scenario2: CLAUDE.md was NOT copied even though it is independent of the settings.json guard"
[[ -f "$HOME_2/.claude/hooks-config.json" ]] || fail_msg "scenario2: hooks-config.json was NOT copied"
[[ -f "$HOME_2/.claude/context7-integration.md" ]] || fail_msg "scenario2: context7-integration.md was NOT copied"
case "$OUTPUT" in
*"NOT be wired"*|*"NOT wired"*) ;;
*) fail_msg "scenario2: expected an actionable degraded-wiring message in output, got: $OUTPUT" ;;
esac
# --- Scenario 3: probe=false + --allow-inactive-enforcement forwards the flag
read -r MOSAIC_HOME_3 HOME_3 < <(new_scenario_dirs scenario3)
BIN_3="$TMP_ROOT/scenario3/bin"
make_fake_mosaic "$BIN_3" 0
MOSAIC_HOME="$MOSAIC_HOME_3" HOME="$HOME_3" PATH="$BIN_3:$PATH" "$LINK_SCRIPT" --allow-inactive-enforcement >/dev/null 2>&1
RECORDED_ARGS="$(cat "$BIN_3/mosaic.args" 2>/dev/null || true)"
case "$RECORDED_ARGS" in
*"--allow-inactive-enforcement"*) ;;
*) fail_msg "scenario3: --allow-inactive-enforcement was not forwarded to the mosaic CLI invocation (got: '$RECORDED_ARGS')" ;;
esac
# --- Scenario 4: no `mosaic` on PATH at all -> python3 fallback strips hooks
read -r MOSAIC_HOME_4 HOME_4 < <(new_scenario_dirs scenario4)
EMPTY_BIN="$TMP_ROOT/scenario4/empty-bin"
mkdir -p "$EMPTY_BIN"
# A PATH containing only python3 (for the fallback) + core utils, no mosaic.
FALLBACK_PATH="$EMPTY_BIN:/usr/bin:/bin"
OUTPUT=$(MOSAIC_HOME="$MOSAIC_HOME_4" HOME="$HOME_4" PATH="$FALLBACK_PATH" "$LINK_SCRIPT" 2>&1)
STATUS=$?
[[ "$STATUS" -ne 0 ]] || fail_msg "scenario4 (no mosaic on PATH, default): expected non-zero exit, got 0. Output: $OUTPUT"
if settings_has_marker "$HOME_4/.claude/settings.json" "mutator-gate.py"; then
fail_msg "scenario4: mutator-gate.py hook was wired even though mosaic could not be resolved (activation unconfirmable)"
fi
if settings_has_marker "$HOME_4/.claude/settings.json" "receipt-observer-client.py"; then
fail_msg "scenario4: receipt-observer-client.py hook was wired even though mosaic could not be resolved"
fi
if ! settings_has_marker "$HOME_4/.claude/settings.json" "prevent-memory-write.sh"; then
fail_msg "scenario4: the unrelated prevent-memory-write.sh hook was incorrectly dropped too"
fi
# --- Scenario 5: no `mosaic` on PATH + --allow-inactive-enforcement --------
read -r MOSAIC_HOME_5 HOME_5 < <(new_scenario_dirs scenario5)
OUTPUT=$(MOSAIC_HOME="$MOSAIC_HOME_5" HOME="$HOME_5" PATH="$FALLBACK_PATH" "$LINK_SCRIPT" --allow-inactive-enforcement 2>&1)
STATUS=$?
[[ "$STATUS" -eq 0 ]] || fail_msg "scenario5 (no mosaic, opt-out): expected exit 0, got $STATUS. Output: $OUTPUT"
if ! settings_has_marker "$HOME_5/.claude/settings.json" "mutator-gate.py"; then
fail_msg "scenario5: mutator-gate.py hook should have been wired (explicit opt-out set)"
fi
case "$OUTPUT" in
*"WARNING"*"--allow-inactive-enforcement"*) ;;
*) fail_msg "scenario5: expected a loud WARNING mentioning --allow-inactive-enforcement, got: $OUTPUT" ;;
esac
if [[ "$fail" -eq 0 ]]; then
echo "install-ordering-guard regression passed (5/5 scenarios)"
fi
exit "$fail"
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -euo pipefail
# Source only the prompt helpers; executing mosaic-init itself requires templates.
source <(head -n 144 "$(dirname "$0")/mosaic-init")
rm -f /tmp/pwned
payload='literal "$(touch /tmp/pwned)"'
AGENT_NAME=""
prompt_if_empty AGENT_NAME "Agent name" <<<"$payload"
[[ "$AGENT_NAME" == "$payload" ]] || {
echo "FAIL: prompt answer did not round-trip literally" >&2
exit 1
}
[[ ! -e /tmp/pwned ]] || {
echo "FAIL: prompt answer executed code" >&2
rm -f /tmp/pwned
exit 1
}
echo "mosaic-init RCE regression: PASS"
@@ -0,0 +1,131 @@
#!/usr/bin/env bash
# Covers the structure-anchor provisioning check in `mosaic-doctor` (T51 WP0b).
#
# Same discipline as test-brain-home-check.sh: functions are extracted from the
# shipped script (exact header + closing brace), never copied — a test carrying
# its own copy of the logic keeps passing after the shipped copy changes.
#
# Four contract states (charter T51P2WP0B-20260824):
# 1. both present+nonempty -> pass ([OK]), no warns, no notes
# 2a. host missing, brain set -> warn naming MOSAIC_HOST_ROOT + launchers
# 2b. brain missing, host set -> warn naming MOSAIC_BRAIN_HOME + launchers
# 2c. present-but-EMPTY counts as missing (warns; NEVER informational)
# 3. neither present -> informational notes, NON-AUTHORITATIVE, never warn
# Arms include genuinely-UNSET (env -u) forms, not only empty strings.
# Red control: empty-vs-unset distinction removed in a mutated copy -> suite red.
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname "$0")" && pwd)
DOCTOR="$SCRIPT_DIR/mosaic-doctor"
fail() {
echo "FAIL: $*" >&2
exit 1
}
[ -f "$DOCTOR" ] || fail "missing mosaic-doctor at $DOCTOR"
extract_function() {
local name="$1"
local extracted
extracted=$(sed -n "/^${name}() {/,/^}/p" "$DOCTOR")
[ -n "$extracted" ] || fail "could not extract ${name}() from mosaic-doctor — script reshaped?"
printf '%s\n' "$extracted"
}
for fn in check_structure_anchor_provisioning; do
extract_function "$fn" >/dev/null
done
# run_case LABEL EXPECT(ok|warn|note) [env assignments as args; -u VAR tokens for unset]
run_case() {
local label="$1" expect="$2"
shift 2
local envs=() unsets=()
local a
for a in "$@"; do
case "$a" in
-u:*) unsets+=("${a#-u:}") ;;
*) envs+=("$a") ;;
esac
done
local out warns notes oks
# build the env command with proper -u flags (array expansion must not
# glue '-u VAR' into one word)
local cmd=(env)
local e u
# env(1) parses options only before the first assignment — -u flags FIRST
for u in "${unsets[@]:-}"; do [ -n "$u" ] && cmd+=(-u "$u"); done
for e in "${envs[@]:-}"; do [ -n "$e" ] && cmd+=("$e"); done
cmd+=(bash -c "warn() { echo \"[WARN] \$*\"; }; note() { echo \"[NOTE] \$*\"; return 0; }; pass() { echo \"[OK] \$*\"; return 0; }; $(extract_function check_structure_anchor_provisioning); check_structure_anchor_provisioning")
out=$("${cmd[@]}" 2>&1)
warns=$(printf '%s\n' "$out" | grep -c '^\[WARN\]' || true)
notes=$(printf '%s\n' "$out" | grep -c '^\[NOTE\]' || true)
oks=$(printf '%s\n' "$out" | grep -c '^\[OK\]' || true)
if [[ "$expect" == ok && "$oks" -gt 0 && "$warns" -eq 0 && "$notes" -eq 0 ]]; then
echo "ok - $label"
elif [[ "$expect" == warn && "$warns" -ge 1 && "$notes" -eq 0 ]]; then
echo "ok - $label (warned x$warns)"
elif [[ "$expect" == note && "$notes" -gt 0 && "$warns" -eq 0 ]]; then
echo "ok - $label (noted)"
else
echo "output: $out" >&2
fail "$label: expected $expect (oks=$oks warns=$warns notes=$notes)"
fi
}
ROOT=$(mktemp -d)
trap 'rm -rf "$ROOT"' EXIT
HOST="$ROOT/host"
BRAIN="$ROOT/brain"
# ── state 1: both present + nonempty → pass ────────────────────────────────
run_case "both anchors present passes" ok \
MOSAIC_HOST_ROOT="$HOST" MOSAIC_BRAIN_HOME="$BRAIN"
# ── state 2a: host missing (unset), brain set → exactly one warn ───────────
run_case "unset host root warns" warn \
-u:MOSAIC_HOST_ROOT MOSAIC_BRAIN_HOME="$BRAIN"
# ── state 2b: brain missing (unset), host set → exactly one warn ───────────
run_case "unset brain home warns" warn \
MOSAIC_HOST_ROOT="$HOST" -u:MOSAIC_BRAIN_HOME
# ── state 2c-empty: present-but-empty counts as missing ────────────────────
run_case "empty-string host root warns (empty != set)" warn \
MOSAIC_HOST_ROOT= MOSAIC_BRAIN_HOME="$BRAIN"
run_case "empty-string brain home warns (empty != set)" warn \
MOSAIC_HOST_ROOT="$HOST" MOSAIC_BRAIN_HOME=
# ── state 3: neither present (genuinely unset) → notes, never warn ─────────
run_case "both unset yields non-authoritative notes" note \
-u:MOSAIC_HOST_ROOT -u:MOSAIC_BRAIN_HOME
run_case "both empty-string warns (empty is present, not absent)" warn \
MOSAIC_HOST_ROOT= MOSAIC_BRAIN_HOME=
run_case "host empty + brain unset warns" warn \
MOSAIC_HOST_ROOT= -u:MOSAIC_BRAIN_HOME
run_case "host unset + brain empty warns" warn \
-u:MOSAIC_HOST_ROOT MOSAIC_BRAIN_HOME=
# ── red control (mutation): presence tracking removed → red ────────────────
# Mutant regresses to the reviewed defect shape: presence derived from
# NONEMPTINESS (the `${VAR:-}` collapse) instead of true -v tracking. Both-empty
# then looks genuinely-absent and is mis-filed as informational; the both-empty
# warn arm above finds no WARN and the suite reds.
MUT="$ROOT/mosaic-doctor.mutant"
sed 's/\[\[ -v MOSAIC_HOST_ROOT \]\] \&\& host_set=1/[[ -n "${MOSAIC_HOST_ROOT:-}" ]] \&\& host_set=1/; s/\[\[ -v MOSAIC_BRAIN_HOME \]\] \&\& brain_set=1/[[ -n "${MOSAIC_BRAIN_HOME:-}" ]] \&\& brain_set=1/' \
"$DOCTOR" > "$MUT"
if cmp -s "$DOCTOR" "$MUT"; then
echo "SKIP red control (mutation anchor not found — sed pattern drifted)" >&2
else
mut_fn=$(sed -n "/^check_structure_anchor_provisioning() {/,/^}/p" "$MUT")
outm=$(env MOSAIC_HOST_ROOT= MOSAIC_BRAIN_HOME= bash -c \
"warn() { echo \"[WARN] \$*\"; }; note() { echo \"[NOTE] \$*\"; return 0; }; pass() { echo \"[OK] \$*\"; return 0; }; $mut_fn; check_structure_anchor_provisioning" 2>&1)
if printf '%s\n' "$outm" | grep -q '^\[NOTE\]'; then
echo "ok - red control bites (mutant collapses empty into informational; shipped does not)"
else
fail "red control did not reproduce the regression shape (mutant output unexpected)"
fi
fi
echo "structure anchor doctor check: all arms passed"
@@ -0,0 +1,60 @@
# Authentik Tool Suite
Manage Authentik identity provider (SSO, users, groups, applications, flows) via CLI.
## Prerequisites
- `jq` installed
- Authentik credentials in `~/.config/mosaic/credentials.json` (or `$MOSAIC_CREDENTIALS_FILE`)
- Required fields: `authentik.url`, `authentik.username`, `authentik.password`
## Authentication
Scripts use `auth-token.sh` to auto-authenticate via username/password and cache the API token at `~/.cache/mosaic/authentik-token`. The token is validated on each use and refreshed automatically when expired.
For better security, create a long-lived API token in Authentik admin (Directory > Tokens) and set `$AUTHENTIK_TOKEN` in your environment — the scripts will use it directly.
## Scripts
| Script | Purpose |
| ----------------- | ------------------------------------------ |
| `auth-token.sh` | Authenticate and cache API token |
| `user-list.sh` | List users (search, filter by group) |
| `user-create.sh` | Create user with optional group assignment |
| `group-list.sh` | List groups |
| `app-list.sh` | List OAuth/SAML applications |
| `flow-list.sh` | List authentication flows |
| `admin-status.sh` | System health and version info |
## Common Options
All scripts support:
- `-f json` — JSON output (default: table)
- `-h` — Show help
## API Reference
- Base URL: `https://auth.diversecanvas.com`
- API prefix: `/api/v3/`
- OpenAPI schema: `/api/v3/schema/`
- Auth: Bearer token in `Authorization` header
## Examples
```bash
# List all users
~/.config/mosaic/tools/authentik/user-list.sh
# Search for a user
~/.config/mosaic/tools/authentik/user-list.sh -s "alice"
# Create a user in the admins group
~/.config/mosaic/tools/authentik/user-create.sh -u newuser -n "New User" -e [email protected] -g admins
# List OAuth applications as JSON
~/.config/mosaic/tools/authentik/app-list.sh -f json
# Check system health
~/.config/mosaic/tools/authentik/admin-status.sh
```
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
#
# admin-status.sh — Authentik system health and version info
#
# Usage: admin-status.sh [-f format] [-a instance]
#
# Options:
# -f format Output format: table (default), json
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORMAT="table"
AK_INSTANCE=""
while getopts "f:a:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -13 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
response=$(curl -sk -w "\n%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/admin/system/")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to get system status (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
exit 0
fi
echo "Authentik System Status"
echo "======================="
echo "$body" | jq -r '
" URL: \(.http_host // "unknown")\n" +
" Version: \(.runtime.authentik_version // "unknown")\n" +
" Python: \(.runtime.python_version // "unknown")\n" +
" Workers: \(.runtime.gunicorn_workers // "unknown")\n" +
" Build Hash: \(.runtime.build_hash // "unknown")\n" +
" Embedded Outpost: \(.embedded_outpost_host // "unknown")"
'
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
#
# app-list.sh — List Authentik applications
#
# Usage: app-list.sh [-f format] [-s search] [-a instance]
#
# Options:
# -f format Output format: table (default), json
# -s search Search by application name
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORMAT="table"
SEARCH=""
AK_INSTANCE=""
while getopts "f:s:a:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
s) SEARCH="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -14 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format] [-s search] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
PARAMS="ordering=name"
[[ -n "$SEARCH" ]] && PARAMS="${PARAMS}&search=${SEARCH}"
response=$(curl -sk -w "\n%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/core/applications/?${PARAMS}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list applications (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.results'
exit 0
fi
echo "NAME SLUG PROVIDER LAUNCH URL"
echo "---------------------------- ---------------------------- ----------------- ----------------------------------------"
echo "$body" | jq -r '.results[] | [
.name,
.slug,
(.provider_obj.name // "none"),
(.launch_url // "—")
] | @tsv' | while IFS=$'\t' read -r name slug provider launch_url; do
printf "%-28s %-28s %-17s %s\n" \
"${name:0:28}" "${slug:0:28}" "${provider:0:17}" "$launch_url"
done
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
#
# auth-token.sh — Obtain and cache Authentik API token
#
# Usage: auth-token.sh [-f] [-q] [-a instance]
#
# Returns a valid Authentik API token. Checks in order:
# 1. Cached token at ~/.cache/mosaic/authentik-token-<instance> (if valid)
# 2. Pre-configured token from credentials.json (authentik.<instance>.token)
# 3. Fails with instructions to create a token in the admin UI
#
# Options:
# -f Force re-validation (ignore cached token)
# -q Quiet mode — only output the token
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
#
# Environment variables (or credentials.json):
# AUTHENTIK_URL — Authentik instance URL
# AUTHENTIK_TOKEN — Pre-configured API token (recommended)
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORCE=false
QUIET=false
AK_INSTANCE=""
while getopts "fqa:h" opt; do
case $opt in
f) FORCE=true ;;
q) QUIET=true ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -22 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f] [-q] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
CACHE_DIR="$HOME/.cache/mosaic"
CACHE_FILE="$CACHE_DIR/authentik-token${AUTHENTIK_INSTANCE:+-$AUTHENTIK_INSTANCE}"
_validate_token() {
local token="$1"
local http_code
http_code=$(curl -sk -o /dev/null -w "%{http_code}" \
--connect-timeout 5 --max-time 10 \
-H "Authorization: Bearer $token" \
"${AUTHENTIK_URL}/api/v3/core/users/me/")
[[ "$http_code" == "200" ]]
}
# 1. Check cached token
if [[ "$FORCE" == "false" ]] && [[ -f "$CACHE_FILE" ]]; then
cached_token=$(cat "$CACHE_FILE")
if [[ -n "$cached_token" ]] && _validate_token "$cached_token"; then
[[ "$QUIET" == "false" ]] && echo "Using cached token (valid)" >&2
echo "$cached_token"
exit 0
fi
[[ "$QUIET" == "false" ]] && echo "Cached token invalid, checking credentials..." >&2
fi
# 2. Use pre-configured token from credentials.json
if [[ -n "${AUTHENTIK_TOKEN:-}" ]]; then
if _validate_token "$AUTHENTIK_TOKEN"; then
# Cache it for faster future access
mkdir -p "$CACHE_DIR"
echo "$AUTHENTIK_TOKEN" > "$CACHE_FILE"
chmod 600 "$CACHE_FILE"
[[ "$QUIET" == "false" ]] && echo "Token validated and cached at $CACHE_FILE" >&2
echo "$AUTHENTIK_TOKEN"
exit 0
else
echo "Error: Pre-configured AUTHENTIK_TOKEN is invalid (API returned non-200)" >&2
exit 1
fi
fi
# 3. No token available
echo "Error: No Authentik API token configured" >&2
echo "" >&2
echo "To create one:" >&2
echo " 1. Log into Authentik admin: ${AUTHENTIK_URL}/if/admin/#/core/tokens" >&2
echo " 2. Click 'Create' → set identifier (e.g., 'mosaic-agent')" >&2
echo " 3. Select 'API Token' intent, uncheck 'Expiring'" >&2
echo " 4. Copy the key and add to credentials.json:" >&2
echo " Add token to credentials.json under authentik.<instance>.token" >&2
exit 1
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env bash
#
# flow-list.sh — List Authentik flows
#
# Usage: flow-list.sh [-f format] [-d designation] [-a instance]
#
# Options:
# -f format Output format: table (default), json
# -d designation Filter by designation (authentication, authorization, enrollment, etc.)
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORMAT="table"
DESIGNATION=""
AK_INSTANCE=""
while getopts "f:d:a:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
d) DESIGNATION="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -14 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format] [-d designation] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
PARAMS="ordering=slug"
[[ -n "$DESIGNATION" ]] && PARAMS="${PARAMS}&designation=${DESIGNATION}"
response=$(curl -sk -w "\n%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/flows/instances/?${PARAMS}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list flows (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.results'
exit 0
fi
echo "NAME SLUG DESIGNATION TITLE"
echo "---------------------------- ---------------------------- ---------------- ----------------------------"
echo "$body" | jq -r '.results[] | [
.name,
.slug,
.designation,
(.title // "—")
] | @tsv' | while IFS=$'\t' read -r name slug designation title; do
printf "%-28s %-28s %-16s %s\n" \
"${name:0:28}" "${slug:0:28}" "$designation" "${title:0:28}"
done
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/env bash
#
# group-list.sh — List Authentik groups
#
# Usage: group-list.sh [-f format] [-s search] [-a instance]
#
# Options:
# -f format Output format: table (default), json
# -s search Search by group name
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORMAT="table"
SEARCH=""
AK_INSTANCE=""
while getopts "f:s:a:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
s) SEARCH="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -13 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format] [-s search] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
PARAMS="ordering=name"
[[ -n "$SEARCH" ]] && PARAMS="${PARAMS}&search=${SEARCH}"
response=$(curl -sk -w "\n%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/core/groups/?${PARAMS}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list groups (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.results'
exit 0
fi
echo "NAME PK MEMBERS SUPERUSER"
echo "---------------------------- ------------------------------------ ------- ---------"
echo "$body" | jq -r '.results[] | [
.name,
.pk,
(.users | length | tostring),
(if .is_superuser then "yes" else "no" end)
] | @tsv' | while IFS=$'\t' read -r name pk members superuser; do
printf "%-28s %-36s %-7s %s\n" "${name:0:28}" "$pk" "$members" "$superuser"
done
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env bash
#
# user-create.sh — Create an Authentik user
#
# Usage: user-create.sh -u <username> -n <name> -e <email> [-p password] [-g group] [-a instance]
#
# Options:
# -u username Username (required)
# -n name Display name (required)
# -e email Email address (required)
# -p password Initial password (optional — user gets set-password flow if omitted)
# -g group Group name to add user to (optional)
# -f format Output format: table (default), json
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
#
# Environment variables (or credentials.json):
# AUTHENTIK_URL — Authentik instance URL
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
USERNAME="" NAME="" EMAIL="" PASSWORD="" GROUP="" FORMAT="table" AK_INSTANCE=""
while getopts "u:n:e:p:g:f:a:h" opt; do
case $opt in
u) USERNAME="$OPTARG" ;;
n) NAME="$OPTARG" ;;
e) EMAIL="$OPTARG" ;;
p) PASSWORD="$OPTARG" ;;
g) GROUP="$OPTARG" ;;
f) FORMAT="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -19 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -u <username> -n <name> -e <email> [-p password] [-g group] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
if [[ -z "$USERNAME" || -z "$NAME" || -z "$EMAIL" ]]; then
echo "Error: -u username, -n name, and -e email are required" >&2
exit 1
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
# Build user payload
payload=$(jq -n \
--arg username "$USERNAME" \
--arg name "$NAME" \
--arg email "$EMAIL" \
'{username: $username, name: $name, email: $email, is_active: true}')
# Add password if provided
if [[ -n "$PASSWORD" ]]; then
payload=$(echo "$payload" | jq --arg pw "$PASSWORD" '. + {password: $pw}')
fi
# Add to group if provided
if [[ -n "$GROUP" ]]; then
# Look up group PK by name
group_response=$(curl -sk \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/core/groups/?search=${GROUP}")
group_pk=$(jq -r "first(.results[] | select(.name == \"$GROUP\") | .pk) // empty" <<<"$group_response")
if [[ -n "$group_pk" ]]; then
payload=$(echo "$payload" | jq --arg gk "$group_pk" '. + {groups: [$gk]}')
else
echo "Warning: Group '$GROUP' not found — creating user without group" >&2
fi
fi
response=$(curl -sk -w "\n%{http_code}" -X POST \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "$payload" \
"${AUTHENTIK_URL}/api/v3/core/users/")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "201" ]]; then
echo "Error: Failed to create user (HTTP $http_code)" >&2
echo "$body" | jq -r '.' 2>/dev/null >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
else
echo "User created successfully:"
echo "$body" | jq -r '" Username: \(.username)\n Name: \(.name)\n Email: \(.email)\n PK: \(.pk)"'
fi
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
#
# user-list.sh — List Authentik users
#
# Usage: user-list.sh [-f format] [-s search] [-g group] [-a instance]
#
# Options:
# -f format Output format: table (default), json
# -s search Search term (matches username, name, email)
# -g group Filter by group name
# -a instance Authentik instance name (e.g. usc, mosaic)
# -h Show this help
#
# Environment variables (or credentials.json):
# AUTHENTIK_URL — Authentik instance URL
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
FORMAT="table"
SEARCH=""
GROUP=""
AK_INSTANCE=""
while getopts "f:s:g:a:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
s) SEARCH="$OPTARG" ;;
g) GROUP="$OPTARG" ;;
a) AK_INSTANCE="$OPTARG" ;;
h) head -15 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format] [-s search] [-g group] [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -n "$AK_INSTANCE" ]]; then
load_credentials "authentik-${AK_INSTANCE}"
else
load_credentials authentik
fi
TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})
# Build query params
PARAMS="ordering=username"
[[ -n "$SEARCH" ]] && PARAMS="${PARAMS}&search=${SEARCH}"
[[ -n "$GROUP" ]] && PARAMS="${PARAMS}&groups_by_name=${GROUP}"
response=$(curl -sk -w "\n%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
"${AUTHENTIK_URL}/api/v3/core/users/?${PARAMS}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list users (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.results'
exit 0
fi
# Table output
echo "USERNAME NAME EMAIL ACTIVE LAST LOGIN"
echo "-------------------- ---------------------------- ---------------------------- ------ ----------"
echo "$body" | jq -r '.results[] | [
.username,
.name,
.email,
(if .is_active then "yes" else "no" end),
(.last_login // "never" | split("T")[0])
] | @tsv' | while IFS=$'\t' read -r username name email active last_login; do
printf "%-20s %-28s %-28s %-6s %s\n" \
"${username:0:20}" "${name:0:28}" "${email:0:28}" "$active" "$last_login"
done
+305
View File
@@ -0,0 +1,305 @@
#!/bin/bash
# agent-lint.sh — Audit agent configuration across all coding projects
#
# Usage:
# agent-lint.sh # Scan all projects in ~/src/
# agent-lint.sh --project <path> # Scan single project
# agent-lint.sh --json # Output JSON for machine consumption
# agent-lint.sh --verbose # Show per-check details
# agent-lint.sh --fix-hint # Show fix commands for failures
#
# Checks per project:
# 1. Has runtime context file (CLAUDE.md or RUNTIME.md)?
# 2. Has AGENTS.md?
# 3. Runtime context file references conditional context/guides?
# 4. Runtime context file has quality gates?
# 5. For monorepos: sub-directories have AGENTS.md?
set -euo pipefail
# Defaults
SRC_DIR="$HOME/src"
SINGLE_PROJECT=""
JSON_OUTPUT=false
VERBOSE=false
FIX_HINT=false
# Exclusion patterns (not coding projects)
EXCLUDE_PATTERNS=(
"_worktrees"
".backup"
"_old"
"_bak"
"junk"
"traefik"
"infrastructure"
)
# Parse args
while [[ $# -gt 0 ]]; do
case "$1" in
--project) SINGLE_PROJECT="$2"; shift 2 ;;
--json) JSON_OUTPUT=true; shift ;;
--verbose) VERBOSE=true; shift ;;
--fix-hint) FIX_HINT=true; shift ;;
--src-dir) SRC_DIR="$2"; shift 2 ;;
-h|--help)
echo "Usage: agent-lint.sh [--project <path>] [--json] [--verbose] [--fix-hint] [--src-dir <dir>]"
exit 0
;;
*) echo "Unknown option: $1"; exit 1 ;;
esac
done
# Colors (disabled for JSON mode)
if $JSON_OUTPUT; then
GREEN="" RED="" YELLOW="" NC="" BOLD="" DIM=""
else
GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[0;33m'
NC='\033[0m' BOLD='\033[1m' DIM='\033[2m'
fi
# Determine if a directory is a coding project
is_coding_project() {
local dir="$1"
[[ -f "$dir/package.json" ]] || \
[[ -f "$dir/pyproject.toml" ]] || \
[[ -f "$dir/Cargo.toml" ]] || \
[[ -f "$dir/go.mod" ]] || \
[[ -f "$dir/Makefile" && -f "$dir/src/main.rs" ]] || \
[[ -f "$dir/pom.xml" ]] || \
[[ -f "$dir/build.gradle" ]]
}
# Check if directory should be excluded
is_excluded() {
local dir_name
dir_name=$(basename "$1")
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
if [[ "$dir_name" == *"$pattern"* ]]; then
return 0
fi
done
return 1
}
# Detect if project is a monorepo
is_monorepo() {
local dir="$1"
[[ -f "$dir/pnpm-workspace.yaml" ]] || \
[[ -f "$dir/turbo.json" ]] || \
[[ -f "$dir/lerna.json" ]] || \
(grep -q '"workspaces"' "$dir/package.json" 2>/dev/null)
}
# Resolve runtime context file (CLAUDE.md or RUNTIME.md)
runtime_context_file() {
local dir="$1"
if [[ -f "$dir/CLAUDE.md" ]]; then
echo "$dir/CLAUDE.md"
return
fi
if [[ -f "$dir/RUNTIME.md" ]]; then
echo "$dir/RUNTIME.md"
return
fi
echo ""
}
# Check for runtime context file
check_runtime_context() {
[[ -n "$(runtime_context_file "$1")" ]]
}
# Check for AGENTS.md
check_agents_md() {
[[ -f "$1/AGENTS.md" ]]
}
# Check conditional loading/context (references guides or conditional section)
check_conditional_loading() {
local ctx
ctx="$(runtime_context_file "$1")"
[[ -n "$ctx" ]] && grep -qi "agent-guides\|~/.config/mosaic/guides\|conditional.*loading\|conditional.*documentation\|conditional.*context" "$ctx" 2>/dev/null
}
# Check quality gates
check_quality_gates() {
local ctx
ctx="$(runtime_context_file "$1")"
[[ -n "$ctx" ]] && grep -qi "quality.gates\|must pass before\|lint\|typecheck\|test" "$ctx" 2>/dev/null
}
# Check monorepo sub-AGENTS.md
check_monorepo_sub_agents() {
local dir="$1"
local missing=()
if ! is_monorepo "$dir"; then
echo "N/A"
return
fi
# Check apps/, packages/, services/, plugins/ directories
for subdir_type in apps packages services plugins; do
if [[ -d "$dir/$subdir_type" ]]; then
for subdir in "$dir/$subdir_type"/*/; do
[[ -d "$subdir" ]] || continue
# Only check if it has its own manifest
if [[ -f "$subdir/package.json" ]] || [[ -f "$subdir/pyproject.toml" ]]; then
if [[ ! -f "$subdir/AGENTS.md" ]]; then
missing+=("$(basename "$subdir")")
fi
fi
done
fi
done
if [[ ${#missing[@]} -eq 0 ]]; then
echo "OK"
else
echo "MISS:${missing[*]}"
fi
}
# Lint a single project
lint_project() {
local dir="$1"
local name
name=$(basename "$dir")
local has_runtime has_agents has_guides has_quality mono_status
local score=0 max_score=4
check_runtime_context "$dir" && has_runtime="OK" || has_runtime="MISS"
check_agents_md "$dir" && has_agents="OK" || has_agents="MISS"
check_conditional_loading "$dir" && has_guides="OK" || has_guides="MISS"
check_quality_gates "$dir" && has_quality="OK" || has_quality="MISS"
mono_status=$(check_monorepo_sub_agents "$dir")
[[ "$has_runtime" == "OK" ]] && ((score++)) || true
[[ "$has_agents" == "OK" ]] && ((score++)) || true
[[ "$has_guides" == "OK" ]] && ((score++)) || true
[[ "$has_quality" == "OK" ]] && ((score++)) || true
if $JSON_OUTPUT; then
cat <<JSONEOF
{
"project": "$name",
"path": "$dir",
"runtime_context": "$has_runtime",
"agents_md": "$has_agents",
"conditional_loading": "$has_guides",
"quality_gates": "$has_quality",
"monorepo_sub_agents": "$mono_status",
"score": $score,
"max_score": $max_score
}
JSONEOF
else
# Color-code the status
local c_runtime c_agents c_guides c_quality
[[ "$has_runtime" == "OK" ]] && c_runtime="${GREEN} OK ${NC}" || c_runtime="${RED} MISS ${NC}"
[[ "$has_agents" == "OK" ]] && c_agents="${GREEN} OK ${NC}" || c_agents="${RED} MISS ${NC}"
[[ "$has_guides" == "OK" ]] && c_guides="${GREEN} OK ${NC}" || c_guides="${RED} MISS ${NC}"
[[ "$has_quality" == "OK" ]] && c_quality="${GREEN} OK ${NC}" || c_quality="${RED} MISS ${NC}"
local score_color="$RED"
[[ $score -ge 3 ]] && score_color="$YELLOW"
[[ $score -eq 4 ]] && score_color="$GREEN"
printf " %-35s %b %b %b %b ${score_color}%d/%d${NC}" \
"$name" "$c_runtime" "$c_agents" "$c_guides" "$c_quality" "$score" "$max_score"
# Show monorepo status if applicable
if [[ "$mono_status" != "N/A" && "$mono_status" != "OK" ]]; then
printf " ${YELLOW}(mono: %s)${NC}" "$mono_status"
fi
echo ""
fi
if $VERBOSE && ! $JSON_OUTPUT; then
[[ "$has_runtime" == "MISS" ]] && echo " ${DIM} Runtime context file missing (CLAUDE.md or RUNTIME.md)${NC}"
[[ "$has_agents" == "MISS" ]] && echo " ${DIM} AGENTS.md missing${NC}"
[[ "$has_guides" == "MISS" ]] && echo " ${DIM} No conditional context/loading section detected${NC}"
[[ "$has_quality" == "MISS" ]] && echo " ${DIM} No quality gates section${NC}"
if [[ "$mono_status" == MISS:* ]]; then
echo " ${DIM} Monorepo sub-AGENTS.md missing: ${mono_status#MISS:}${NC}"
fi
fi
if $FIX_HINT && ! $JSON_OUTPUT; then
if [[ "$has_runtime" == "MISS" || "$has_agents" == "MISS" ]]; then
echo " ${DIM}Fix: ~/.config/mosaic/tools/bootstrap/init-project.sh --name \"$name\" --type auto${NC}"
elif [[ "$has_guides" == "MISS" ]]; then
echo " ${DIM}Fix: ~/.config/mosaic/tools/bootstrap/agent-upgrade.sh $dir --section conditional-loading${NC}"
fi
fi
# Return score for summary
echo "$score" > /tmp/agent-lint-score-$$
}
# Main
main() {
local projects=()
local total=0 passing=0 total_score=0
if [[ -n "$SINGLE_PROJECT" ]]; then
projects=("$SINGLE_PROJECT")
else
for dir in "$SRC_DIR"/*/; do
[[ -d "$dir" ]] || continue
is_excluded "$dir" && continue
is_coding_project "$dir" && projects+=("${dir%/}")
done
fi
if [[ ${#projects[@]} -eq 0 ]]; then
echo "No coding projects found."
exit 0
fi
if $JSON_OUTPUT; then
echo '{ "audit_date": "'$(date -I)'", "projects": ['
local first=true
for dir in "${projects[@]}"; do
$first || echo ","
first=false
lint_project "$dir"
done
echo '] }'
else
echo ""
echo -e "${BOLD}Agent Configuration Audit — $(date +%Y-%m-%d)${NC}"
echo "========================================================"
printf " %-35s %s %s %s %s %s\n" \
"Project" "RUNTIME" "AGENTS" "Guides" "Quality" "Score"
echo " -----------------------------------------------------------------------"
for dir in "${projects[@]}"; do
lint_project "$dir"
local score
score=$(cat /tmp/agent-lint-score-$$ 2>/dev/null || echo 0)
((total++)) || true
((total_score += score)) || true
[[ $score -eq 4 ]] && ((passing++)) || true
done
rm -f /tmp/agent-lint-score-$$
echo " -----------------------------------------------------------------------"
local need_attention=$((total - passing))
echo ""
echo -e " ${BOLD}Summary:${NC} $total projects | ${GREEN}$passing pass${NC} | ${RED}$need_attention need attention${NC}"
echo ""
if [[ $need_attention -gt 0 ]] && ! $FIX_HINT; then
echo -e " ${DIM}Run with --fix-hint for suggested fixes${NC}"
echo -e " ${DIM}Run with --verbose for per-check details${NC}"
echo ""
fi
fi
}
main
@@ -0,0 +1,332 @@
#!/bin/bash
# agent-upgrade.sh — Non-destructively upgrade agent configuration in projects
#
# Usage:
# agent-upgrade.sh <project-path> # Upgrade one project
# agent-upgrade.sh --all # Upgrade all projects in ~/src/
# agent-upgrade.sh --all --dry-run # Preview what would change
# agent-upgrade.sh <path> --section conditional-loading # Inject specific section
# agent-upgrade.sh <path> --create-agents # Create AGENTS.md if missing
# agent-upgrade.sh <path> --monorepo-scan # Create sub-AGENTS.md for monorepo dirs
#
# Safety:
# - Creates .bak backup before any modification
# - Append-only — never modifies existing sections
# - --dry-run shows what would change without writing
set -euo pipefail
# Defaults
SRC_DIR="$HOME/src"
FRAGMENTS_DIR="$HOME/.config/mosaic/templates/agent/fragments"
TEMPLATES_DIR="$HOME/.config/mosaic/templates/agent"
DRY_RUN=false
ALL_PROJECTS=false
TARGET_PATH=""
SECTION_ONLY=""
CREATE_AGENTS=false
MONOREPO_SCAN=false
# Exclusion patterns (same as agent-lint.sh)
EXCLUDE_PATTERNS=(
"_worktrees"
".backup"
"_old"
"_bak"
"junk"
"traefik"
"infrastructure"
)
# Colors
GREEN='\033[0;32m' RED='\033[0;31m' YELLOW='\033[0;33m'
NC='\033[0m' BOLD='\033[1m' DIM='\033[2m'
# Parse args
while [[ $# -gt 0 ]]; do
case "$1" in
--all) ALL_PROJECTS=true; shift ;;
--dry-run) DRY_RUN=true; shift ;;
--section) SECTION_ONLY="$2"; shift 2 ;;
--create-agents) CREATE_AGENTS=true; shift ;;
--monorepo-scan) MONOREPO_SCAN=true; shift ;;
--src-dir) SRC_DIR="$2"; shift 2 ;;
-h|--help)
echo "Usage: agent-upgrade.sh [<project-path>|--all] [--dry-run] [--section <name>] [--create-agents] [--monorepo-scan]"
echo ""
echo "Options:"
echo " --all Upgrade all projects in ~/src/"
echo " --dry-run Preview changes without writing"
echo " --section <name> Inject only a specific fragment (conditional-loading, commit-format, secrets, multi-agent, code-review, campsite-rule)"
echo " --create-agents Create AGENTS.md if missing"
echo " --monorepo-scan Create sub-AGENTS.md for monorepo directories"
exit 0
;;
*)
if [[ -d "$1" ]]; then
TARGET_PATH="$1"
else
echo "Unknown option or invalid path: $1"
exit 1
fi
shift
;;
esac
done
if ! $ALL_PROJECTS && [[ -z "$TARGET_PATH" ]]; then
echo "Error: Specify a project path or use --all"
exit 1
fi
# Helpers
is_coding_project() {
local dir="$1"
[[ -f "$dir/package.json" ]] || \
[[ -f "$dir/pyproject.toml" ]] || \
[[ -f "$dir/Cargo.toml" ]] || \
[[ -f "$dir/go.mod" ]] || \
[[ -f "$dir/pom.xml" ]] || \
[[ -f "$dir/build.gradle" ]]
}
is_excluded() {
local dir_name
dir_name=$(basename "$1")
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
[[ "$dir_name" == *"$pattern"* ]] && return 0
done
return 1
}
is_monorepo() {
local dir="$1"
[[ -f "$dir/pnpm-workspace.yaml" ]] || \
[[ -f "$dir/turbo.json" ]] || \
[[ -f "$dir/lerna.json" ]] || \
(grep -q '"workspaces"' "$dir/package.json" 2>/dev/null)
}
has_section() {
local file="$1"
local pattern="$2"
[[ -f "$file" ]] && grep -qi "$pattern" "$file" 2>/dev/null
}
runtime_context_file() {
local project_dir="$1"
if [[ -f "$project_dir/CLAUDE.md" ]]; then
echo "$project_dir/CLAUDE.md"
return
fi
if [[ -f "$project_dir/RUNTIME.md" ]]; then
echo "$project_dir/RUNTIME.md"
return
fi
echo "$project_dir/CLAUDE.md"
}
backup_file() {
local file="$1"
if [[ -f "$file" ]] && ! $DRY_RUN; then
cp "$file" "${file}.bak"
fi
}
# Inject a fragment into CLAUDE.md if the section doesn't exist
inject_fragment() {
local project_dir="$1"
local fragment_name="$2"
local ctx_file
ctx_file="$(runtime_context_file "$project_dir")"
local fragment_file="$FRAGMENTS_DIR/$fragment_name.md"
if [[ ! -f "$fragment_file" ]]; then
echo -e " ${RED}Fragment not found: $fragment_file${NC}"
return 1
fi
# Determine detection pattern for this fragment
local detect_pattern
case "$fragment_name" in
conditional-loading) detect_pattern="agent-guides\|~/.config/mosaic/guides\|Conditional.*Loading\|Conditional.*Documentation\|Conditional.*Context" ;;
commit-format) detect_pattern="<type>.*#issue\|Types:.*feat.*fix" ;;
secrets) detect_pattern="NEVER hardcode secrets\|\.env.example.*committed" ;;
multi-agent) detect_pattern="Multi-Agent Coordination\|pull --rebase.*before" ;;
code-review) detect_pattern="codex-code-review\|codex-security-review\|Code Review" ;;
campsite-rule) detect_pattern="Campsite Rule\|Touching it makes it yours\|was already there.*NEVER" ;;
*) echo "Unknown fragment: $fragment_name"; return 1 ;;
esac
if [[ ! -f "$ctx_file" ]]; then
echo -e " ${YELLOW}No runtime context file (CLAUDE.md/RUNTIME.md) — skipping fragment injection${NC}"
return 0
fi
if has_section "$ctx_file" "$detect_pattern"; then
echo -e " ${DIM}$fragment_name already present${NC}"
return 0
fi
if $DRY_RUN; then
echo -e " ${GREEN}Would inject: $fragment_name${NC}"
else
backup_file "$ctx_file"
echo "" >> "$ctx_file"
cat "$fragment_file" >> "$ctx_file"
echo "" >> "$ctx_file"
echo -e " ${GREEN}Injected: $fragment_name${NC}"
fi
}
# Create AGENTS.md from template
create_agents_md() {
local project_dir="$1"
local agents_md="$project_dir/AGENTS.md"
if [[ -f "$agents_md" ]]; then
echo -e " ${DIM}AGENTS.md already exists${NC}"
return 0
fi
local project_name
project_name=$(basename "$project_dir")
# Detect project type for quality gates
local quality_gates="# Add quality gate commands here"
if [[ -f "$project_dir/package.json" ]]; then
quality_gates="npm run lint && npm run typecheck && npm test"
if grep -q '"pnpm"' "$project_dir/package.json" 2>/dev/null || [[ -f "$project_dir/pnpm-lock.yaml" ]]; then
quality_gates="pnpm lint && pnpm typecheck && pnpm test"
fi
elif [[ -f "$project_dir/pyproject.toml" ]]; then
quality_gates="uv run ruff check src/ tests/ && uv run mypy src/ && uv run pytest --cov"
fi
if $DRY_RUN; then
echo -e " ${GREEN}Would create: AGENTS.md${NC}"
else
# Use generic AGENTS.md template with substitutions
sed -e "s/\${PROJECT_NAME}/$project_name/g" \
-e "s/\${QUALITY_GATES}/$quality_gates/g" \
-e "s/\${TASK_PREFIX}/${project_name^^}/g" \
-e "s|\${SOURCE_DIR}|src|g" \
"$TEMPLATES_DIR/AGENTS.md.template" > "$agents_md"
echo -e " ${GREEN}Created: AGENTS.md${NC}"
fi
}
# Create sub-AGENTS.md for monorepo directories
create_sub_agents() {
local project_dir="$1"
if ! is_monorepo "$project_dir"; then
echo -e " ${DIM}Not a monorepo — skipping sub-AGENTS scan${NC}"
return 0
fi
local created=0
for subdir_type in apps packages services plugins; do
if [[ -d "$project_dir/$subdir_type" ]]; then
for subdir in "$project_dir/$subdir_type"/*/; do
[[ -d "$subdir" ]] || continue
# Only if it has its own manifest
if [[ -f "$subdir/package.json" ]] || [[ -f "$subdir/pyproject.toml" ]]; then
if [[ ! -f "$subdir/AGENTS.md" ]]; then
local dir_name
dir_name=$(basename "$subdir")
if $DRY_RUN; then
echo -e " ${GREEN}Would create: $subdir_type/$dir_name/AGENTS.md${NC}"
else
sed -e "s/\${DIRECTORY_NAME}/$dir_name/g" \
-e "s/\${DIRECTORY_PURPOSE}/Part of the $subdir_type layer./g" \
"$TEMPLATES_DIR/sub-agents.md.template" > "${subdir}AGENTS.md"
echo -e " ${GREEN}Created: $subdir_type/$dir_name/AGENTS.md${NC}"
fi
((created++)) || true
fi
fi
done
fi
done
if [[ $created -eq 0 ]]; then
echo -e " ${DIM}All monorepo sub-AGENTS.md present${NC}"
fi
}
# Upgrade a single project
upgrade_project() {
local dir="$1"
local name
name=$(basename "$dir")
echo -e "\n${BOLD}$name${NC} ${DIM}($dir)${NC}"
if [[ -n "$SECTION_ONLY" ]]; then
inject_fragment "$dir" "$SECTION_ONLY"
return
fi
# Always try conditional-loading (highest impact)
inject_fragment "$dir" "conditional-loading"
# Try other fragments if runtime context exists
if [[ -f "$dir/CLAUDE.md" || -f "$dir/RUNTIME.md" ]]; then
inject_fragment "$dir" "commit-format"
inject_fragment "$dir" "secrets"
inject_fragment "$dir" "multi-agent"
inject_fragment "$dir" "code-review"
inject_fragment "$dir" "campsite-rule"
fi
# Create AGENTS.md if missing (always unless --section was used)
if $CREATE_AGENTS || [[ -z "$SECTION_ONLY" ]]; then
create_agents_md "$dir"
fi
# Monorepo sub-AGENTS.md
if $MONOREPO_SCAN || [[ -z "$SECTION_ONLY" ]]; then
create_sub_agents "$dir"
fi
}
# Main
main() {
local projects=()
if $ALL_PROJECTS; then
for dir in "$SRC_DIR"/*/; do
[[ -d "$dir" ]] || continue
is_excluded "$dir" && continue
is_coding_project "$dir" && projects+=("${dir%/}")
done
else
projects=("$TARGET_PATH")
fi
if [[ ${#projects[@]} -eq 0 ]]; then
echo "No coding projects found."
exit 0
fi
local mode="LIVE"
$DRY_RUN && mode="DRY RUN"
echo -e "${BOLD}Agent Configuration Upgrade — $(date +%Y-%m-%d) [$mode]${NC}"
echo "========================================================"
for dir in "${projects[@]}"; do
upgrade_project "$dir"
done
echo ""
echo -e "${BOLD}Done.${NC}"
if $DRY_RUN; then
echo -e "${DIM}Run without --dry-run to apply changes.${NC}"
else
echo -e "${DIM}Backups saved as .bak files. Run agent-lint.sh to verify.${NC}"
fi
}
main
@@ -0,0 +1,493 @@
#!/bin/bash
# init-project.sh - Bootstrap a project for AI-assisted development
# Usage: init-project.sh [OPTIONS]
#
# Creates CLAUDE.md, AGENTS.md, and standard directories using templates.
# Optionally initializes git labels and milestones.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMPLATE_DIR="$HOME/.config/mosaic/templates/agent"
GIT_SCRIPT_DIR="$HOME/.config/mosaic/tools/git"
SEQUENTIAL_MCP_SCRIPT="$HOME/.config/mosaic/bin/mosaic-ensure-sequential-thinking"
# Defaults
PROJECT_NAME=""
PROJECT_TYPE=""
REPO_URL=""
TASK_PREFIX=""
PROJECT_DESCRIPTION=""
SKIP_LABELS=false
SKIP_CI=false
CICD_DOCKER=false
DRY_RUN=false
declare -a CICD_SERVICES=()
CICD_BRANCHES="main,develop"
show_help() {
cat <<'EOF'
Usage: init-project.sh [OPTIONS]
Bootstrap a project for AI-assisted development.
Options:
-n, --name <name> Project name (required)
-t, --type <type> Project type: nestjs-nextjs, django, generic (default: auto-detect)
-r, --repo <url> Git remote URL
-p, --prefix <prefix> Orchestrator task prefix (e.g., MS, UC)
-d, --description <desc> One-line project description
--skip-labels Skip creating git labels and milestones
--skip-ci Skip copying CI pipeline files
--cicd-docker Generate Docker build/push/link pipeline steps
--cicd-service <name:path> Service for Docker CI (repeatable, requires --cicd-docker)
--cicd-branches <list> Branches for Docker builds (default: main,develop)
--dry-run Show what would be created without creating anything
-h, --help Show this help
Examples:
# Full bootstrap with auto-detection
init-project.sh --name "My App" --description "A web application"
# Specific type
init-project.sh --name "My API" --type django --prefix MA
# Dry run
init-project.sh --name "Test" --type generic --dry-run
# With Docker CI/CD pipeline
init-project.sh --name "My App" --cicd-docker \
--cicd-service "my-api:src/api/Dockerfile" \
--cicd-service "my-web:src/web/Dockerfile"
Project Types:
nestjs-nextjs NestJS + Next.js monorepo (pnpm + TurboRepo)
django Django project (pytest + ruff + mypy)
typescript Standalone TypeScript/Next.js project
python-fastapi Python FastAPI project (pytest + ruff + mypy + uv)
python-library Python library/SDK (pytest + ruff + mypy + uv)
generic Generic project (uses base templates)
auto Auto-detect from project files (default)
EOF
exit 0
}
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
-n|--name)
PROJECT_NAME="$2"
shift 2
;;
-t|--type)
PROJECT_TYPE="$2"
shift 2
;;
-r|--repo)
REPO_URL="$2"
shift 2
;;
-p|--prefix)
TASK_PREFIX="$2"
shift 2
;;
-d|--description)
PROJECT_DESCRIPTION="$2"
shift 2
;;
--skip-labels)
SKIP_LABELS=true
shift
;;
--skip-ci)
SKIP_CI=true
shift
;;
--cicd-docker)
CICD_DOCKER=true
shift
;;
--cicd-service)
CICD_SERVICES+=("$2")
shift 2
;;
--cicd-branches)
CICD_BRANCHES="$2"
shift 2
;;
--dry-run)
DRY_RUN=true
shift
;;
-h|--help)
show_help
;;
*)
echo "Unknown option: $1" >&2
echo "Run with --help for usage" >&2
exit 1
;;
esac
done
# Validate required args
if [[ -z "$PROJECT_NAME" ]]; then
echo "Error: --name is required" >&2
exit 1
fi
# Auto-detect project type if not specified
detect_project_type() {
# Monorepo (pnpm + turbo or npm workspaces with NestJS)
if [[ -f "pnpm-workspace.yaml" ]] || [[ -f "turbo.json" ]]; then
echo "nestjs-nextjs"
return
fi
if [[ -f "package.json" ]] && grep -q '"workspaces"' package.json 2>/dev/null; then
echo "nestjs-nextjs"
return
fi
# Django
if [[ -f "manage.py" ]] && [[ -f "pyproject.toml" ]]; then
echo "django"
return
fi
# FastAPI
if [[ -f "pyproject.toml" ]] && grep -q "fastapi" pyproject.toml 2>/dev/null; then
echo "python-fastapi"
return
fi
# Standalone TypeScript
if [[ -f "tsconfig.json" ]] && [[ -f "package.json" ]]; then
echo "typescript"
return
fi
# Python library/tool
if [[ -f "pyproject.toml" ]]; then
echo "python-library"
return
fi
echo "generic"
}
if [[ -z "$PROJECT_TYPE" || "$PROJECT_TYPE" == "auto" ]]; then
PROJECT_TYPE=$(detect_project_type)
echo "Auto-detected project type: $PROJECT_TYPE"
fi
# Derive defaults
if [[ -z "$REPO_URL" ]]; then
REPO_URL=$(git remote get-url origin 2>/dev/null || echo "")
fi
if [[ -z "$TASK_PREFIX" ]]; then
# Generate prefix from project name initials
TASK_PREFIX=$(echo "$PROJECT_NAME" | sed 's/[^A-Za-z ]//g' | awk '{for(i=1;i<=NF;i++) printf toupper(substr($i,1,1))}')
if [[ -z "$TASK_PREFIX" ]]; then
TASK_PREFIX="PRJ"
fi
fi
if [[ -z "$PROJECT_DESCRIPTION" ]]; then
PROJECT_DESCRIPTION="$PROJECT_NAME"
fi
PROJECT_DIR=$(basename "$(pwd)")
# Detect quality gates, source dir, and stack info based on type
case "$PROJECT_TYPE" in
nestjs-nextjs)
export QUALITY_GATES="pnpm typecheck && pnpm lint && pnpm test"
export SOURCE_DIR="apps"
export BUILD_COMMAND="pnpm build"
export TEST_COMMAND="pnpm test"
export LINT_COMMAND="pnpm lint"
export TYPECHECK_COMMAND="pnpm typecheck"
export FRONTEND_STACK="Next.js + React + TailwindCSS + Shadcn/ui"
export BACKEND_STACK="NestJS + Prisma ORM"
export DATABASE_STACK="PostgreSQL"
export TESTING_STACK="Vitest + Playwright"
export DEPLOYMENT_STACK="Docker + docker-compose"
export CONFIG_FILES="turbo.json, pnpm-workspace.yaml, tsconfig.json"
;;
django)
export QUALITY_GATES="ruff check . && mypy . && pytest tests/"
export SOURCE_DIR="src"
export BUILD_COMMAND="pip install -e ."
export TEST_COMMAND="pytest tests/"
export LINT_COMMAND="ruff check ."
export TYPECHECK_COMMAND="mypy ."
export FRONTEND_STACK="N/A"
export BACKEND_STACK="Django / Django REST Framework"
export DATABASE_STACK="PostgreSQL"
export TESTING_STACK="pytest + pytest-django"
export DEPLOYMENT_STACK="Docker + docker-compose"
export CONFIG_FILES="pyproject.toml"
export PROJECT_SLUG=$(echo "$PROJECT_NAME" | tr '[:upper:]' '[:lower:]' | tr ' ' '_' | sed 's/[^a-z0-9_]//g')
;;
typescript)
PKG_MGR="npm"
[[ -f "pnpm-lock.yaml" ]] && PKG_MGR="pnpm"
[[ -f "yarn.lock" ]] && PKG_MGR="yarn"
export QUALITY_GATES="$PKG_MGR run lint && $PKG_MGR run typecheck && $PKG_MGR test"
export SOURCE_DIR="src"
export BUILD_COMMAND="$PKG_MGR run build"
export TEST_COMMAND="$PKG_MGR test"
export LINT_COMMAND="$PKG_MGR run lint"
export TYPECHECK_COMMAND="npx tsc --noEmit"
export FRAMEWORK="TypeScript"
export PACKAGE_MANAGER="$PKG_MGR"
export FRONTEND_STACK="N/A"
export BACKEND_STACK="N/A"
export DATABASE_STACK="N/A"
export TESTING_STACK="Vitest or Jest"
export DEPLOYMENT_STACK="TBD"
export CONFIG_FILES="tsconfig.json, package.json"
# Detect Next.js
if grep -q '"next"' package.json 2>/dev/null; then
export FRAMEWORK="Next.js"
export FRONTEND_STACK="Next.js + React"
fi
;;
python-fastapi)
export PROJECT_SLUG=$(echo "$PROJECT_NAME" | tr '[:upper:]' '[:lower:]' | tr ' ' '_' | sed 's/[^a-z0-9_]//g')
export QUALITY_GATES="uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov"
export SOURCE_DIR="src"
export BUILD_COMMAND="uv sync --all-extras"
export TEST_COMMAND="uv run pytest --cov"
export LINT_COMMAND="uv run ruff check src/ tests/"
export TYPECHECK_COMMAND="uv run mypy src/"
export FRONTEND_STACK="N/A"
export BACKEND_STACK="FastAPI"
export DATABASE_STACK="TBD"
export TESTING_STACK="pytest + httpx"
export DEPLOYMENT_STACK="Docker"
export CONFIG_FILES="pyproject.toml"
;;
python-library)
export PROJECT_SLUG=$(echo "$PROJECT_NAME" | tr '[:upper:]' '[:lower:]' | tr ' ' '_' | sed 's/[^a-z0-9_]//g')
export QUALITY_GATES="uv run ruff check src/ tests/ && uv run ruff format --check src/ && uv run mypy src/ && uv run pytest --cov"
export SOURCE_DIR="src"
export BUILD_COMMAND="uv sync --all-extras"
export TEST_COMMAND="uv run pytest --cov"
export LINT_COMMAND="uv run ruff check src/ tests/"
export TYPECHECK_COMMAND="uv run mypy src/"
export BUILD_SYSTEM="hatchling"
export FRONTEND_STACK="N/A"
export BACKEND_STACK="N/A"
export DATABASE_STACK="N/A"
export TESTING_STACK="pytest"
export DEPLOYMENT_STACK="PyPI / Gitea Packages"
export CONFIG_FILES="pyproject.toml"
;;
*)
export QUALITY_GATES="echo 'No quality gates configured — update CLAUDE.md'"
export SOURCE_DIR="src"
export BUILD_COMMAND="echo 'No build command configured'"
export TEST_COMMAND="echo 'No test command configured'"
export LINT_COMMAND="echo 'No lint command configured'"
export TYPECHECK_COMMAND="echo 'No typecheck command configured'"
export FRONTEND_STACK="TBD"
export BACKEND_STACK="TBD"
export DATABASE_STACK="TBD"
export TESTING_STACK="TBD"
export DEPLOYMENT_STACK="TBD"
export CONFIG_FILES="TBD"
;;
esac
# Export common variables
export PROJECT_NAME
export PROJECT_DESCRIPTION
export PROJECT_DIR
export REPO_URL
export TASK_PREFIX
echo "=== Project Bootstrap ==="
echo " Name: $PROJECT_NAME"
echo " Type: $PROJECT_TYPE"
echo " Prefix: $TASK_PREFIX"
echo " Description: $PROJECT_DESCRIPTION"
echo " Repo: ${REPO_URL:-'(not set)'}"
echo " Directory: $(pwd)"
echo ""
# Select template directory
STACK_TEMPLATE_DIR="$TEMPLATE_DIR/projects/$PROJECT_TYPE"
if [[ ! -d "$STACK_TEMPLATE_DIR" ]]; then
STACK_TEMPLATE_DIR="$TEMPLATE_DIR"
echo "No stack-specific templates found for '$PROJECT_TYPE', using generic templates."
fi
if [[ "$DRY_RUN" == true ]]; then
echo "[DRY RUN] Would create:"
echo " - Validate sequential-thinking MCP hard requirement"
echo " - CLAUDE.md (from $STACK_TEMPLATE_DIR/CLAUDE.md.template)"
echo " - AGENTS.md (from $STACK_TEMPLATE_DIR/AGENTS.md.template)"
echo " - docs/scratchpads/"
echo " - docs/reports/qa-automation/{pending,in-progress,done,escalated}"
echo " - docs/reports/deferred/"
echo " - docs/tasks/"
echo " - docs/releases/"
echo " - docs/templates/"
if [[ "$SKIP_CI" != true ]]; then
echo " - .woodpecker/codex-review.yml"
echo " - .woodpecker/schemas/*.json"
fi
if [[ "$SKIP_LABELS" != true ]]; then
echo " - Standard git labels (epic, feature, bug, task, documentation, security, breaking)"
echo " - Milestone: 0.0.1 - Pre-MVP Foundation"
echo " - Milestone policy: 0.0.x pre-MVP, 0.1.0 for MVP release"
fi
if [[ "$CICD_DOCKER" == true ]]; then
echo " - Docker build/push/link steps appended to .woodpecker.yml"
for svc in "${CICD_SERVICES[@]}"; do
echo " - docker-build-${svc%%:*}"
done
echo " - link-packages"
fi
exit 0
fi
# Enforce sequential-thinking MCP hard requirement.
if [[ ! -x "$SEQUENTIAL_MCP_SCRIPT" ]]; then
echo "Error: Missing sequential-thinking setup helper: $SEQUENTIAL_MCP_SCRIPT" >&2
echo "Install/repair Mosaic at ~/.config/mosaic before bootstrapping projects." >&2
exit 1
fi
if "$SEQUENTIAL_MCP_SCRIPT" >/dev/null 2>&1; then
echo "Verified sequential-thinking MCP configuration"
else
echo "Error: sequential-thinking MCP setup failed (hard requirement)." >&2
echo "Run: $SEQUENTIAL_MCP_SCRIPT" >&2
exit 1
fi
# Create CLAUDE.md
if [[ -f "CLAUDE.md" ]]; then
echo "CLAUDE.md already exists — skipping (rename or delete to recreate)"
else
if [[ -f "$STACK_TEMPLATE_DIR/CLAUDE.md.template" ]]; then
envsubst < "$STACK_TEMPLATE_DIR/CLAUDE.md.template" > CLAUDE.md
echo "Created CLAUDE.md"
else
echo "Warning: No CLAUDE.md template found at $STACK_TEMPLATE_DIR" >&2
fi
fi
# Create AGENTS.md
if [[ -f "AGENTS.md" ]]; then
echo "AGENTS.md already exists — skipping (rename or delete to recreate)"
else
if [[ -f "$STACK_TEMPLATE_DIR/AGENTS.md.template" ]]; then
envsubst < "$STACK_TEMPLATE_DIR/AGENTS.md.template" > AGENTS.md
echo "Created AGENTS.md"
else
echo "Warning: No AGENTS.md template found at $STACK_TEMPLATE_DIR" >&2
fi
fi
# Create directories
mkdir -p \
docs/scratchpads \
docs/reports/qa-automation/pending \
docs/reports/qa-automation/in-progress \
docs/reports/qa-automation/done \
docs/reports/qa-automation/escalated \
docs/reports/deferred \
docs/tasks \
docs/releases \
docs/templates
echo "Created docs/scratchpads/, docs/reports/*, docs/tasks/, docs/releases/, docs/templates/"
# Set up CI/CD pipeline
if [[ "$SKIP_CI" != true ]]; then
CODEX_DIR="$HOME/.config/mosaic/tools/codex"
if [[ -d "$CODEX_DIR/woodpecker" ]]; then
mkdir -p .woodpecker/schemas
cp "$CODEX_DIR/woodpecker/codex-review.yml" .woodpecker/
cp "$CODEX_DIR/schemas/"*.json .woodpecker/schemas/
echo "Created .woodpecker/ with Codex review pipeline"
else
echo "Codex pipeline templates not found — skipping CI setup"
fi
fi
# Generate Docker build/push/link pipeline steps
if [[ "$CICD_DOCKER" == true ]]; then
CICD_SCRIPT="$HOME/.config/mosaic/tools/cicd/generate-docker-steps.sh"
if [[ -x "$CICD_SCRIPT" ]]; then
# Parse org and repo from git remote
CICD_REGISTRY=""
CICD_ORG=""
CICD_REPO_NAME=""
if [[ -n "$REPO_URL" ]]; then
# Extract host from https://host/org/repo.git or git@host:org/repo.git
CICD_REGISTRY=$(echo "$REPO_URL" | sed -E 's|https?://([^/]+)/.*|\1|; s|git@([^:]+):.*|\1|')
CICD_ORG=$(echo "$REPO_URL" | sed -E 's|https?://[^/]+/([^/]+)/.*|\1|; s|git@[^:]+:([^/]+)/.*|\1|')
CICD_REPO_NAME=$(echo "$REPO_URL" | sed -E 's|\.git$||' | sed -E 's|.*/([^/]+)$|\1|')
fi
if [[ -n "$CICD_REGISTRY" && -n "$CICD_ORG" && -n "$CICD_REPO_NAME" && ${#CICD_SERVICES[@]} -gt 0 ]]; then
# Build service args
SVC_ARGS=""
for svc in "${CICD_SERVICES[@]}"; do
SVC_ARGS="$SVC_ARGS --service $svc"
done
echo ""
echo "Generating Docker CI/CD pipeline steps..."
# Add kaniko_setup anchor to variables section if .woodpecker.yml exists
if [[ -f ".woodpecker.yml" ]]; then
# Append Docker steps to existing pipeline
"$CICD_SCRIPT" \
--registry "$CICD_REGISTRY" \
--org "$CICD_ORG" \
--repo "$CICD_REPO_NAME" \
$SVC_ARGS \
--branches "$CICD_BRANCHES" >> .woodpecker.yml
echo "Appended Docker build/push/link steps to .woodpecker.yml"
else
echo "Warning: No .woodpecker.yml found — generate quality gates first, then re-run with --cicd-docker" >&2
fi
else
if [[ ${#CICD_SERVICES[@]} -eq 0 ]]; then
echo "Warning: --cicd-docker requires at least one --cicd-service" >&2
else
echo "Warning: Could not parse registry/org/repo from git remote — specify --repo" >&2
fi
fi
else
echo "Docker CI/CD generator not found at $CICD_SCRIPT — skipping" >&2
fi
fi
# Initialize labels and milestones
if [[ "$SKIP_LABELS" != true ]]; then
LABEL_SCRIPT="$SCRIPT_DIR/init-repo-labels.sh"
if [[ -x "$LABEL_SCRIPT" ]]; then
echo ""
echo "Initializing git labels and milestones..."
"$LABEL_SCRIPT"
else
echo "Label init script not found — skipping label setup"
fi
fi
echo ""
echo "=== Bootstrap Complete ==="
echo ""
echo "Next steps:"
echo " 1. Review and customize CLAUDE.md"
echo " 2. Review and customize AGENTS.md"
echo " 3. Update quality gate commands if needed"
echo " 4. Commit: git add CLAUDE.md AGENTS.md docs/ .woodpecker/ && git commit -m 'feat: Bootstrap project for AI development'"
if [[ "$SKIP_CI" != true ]]; then
echo " 5. Add 'codex_api_key' secret to Woodpecker CI"
fi
if [[ "$CICD_DOCKER" == true ]]; then
echo " 6. Add 'gitea_username' and 'gitea_token' secrets to Woodpecker CI"
echo " (token needs package:write scope)"
fi
@@ -0,0 +1,123 @@
#!/bin/bash
# init-repo-labels.sh - Create standard labels and initial milestone for a repository
# Usage: init-repo-labels.sh [--skip-milestone]
#
# Works with both Gitea (tea) and GitHub (gh).
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GIT_SCRIPT_DIR="$HOME/.config/mosaic/tools/git"
source "$GIT_SCRIPT_DIR/detect-platform.sh"
SKIP_MILESTONE=false
while [[ $# -gt 0 ]]; do
case $1 in
--skip-milestone)
SKIP_MILESTONE=true
shift
;;
-h|--help)
echo "Usage: $(basename "$0") [--skip-milestone]"
echo ""
echo "Create standard labels and initial milestone for the current repository."
echo ""
echo "Options:"
echo " --skip-milestone Skip creating the 0.0.1 pre-MVP milestone"
echo " -h, --help Show this help"
exit 0
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
PLATFORM=$(detect_platform)
OWNER=$(get_repo_owner)
REPO=$(get_repo_name)
echo "Platform: $PLATFORM"
echo "Repository: $OWNER/$REPO"
echo ""
# Standard labels with colors
# Format: "name|color|description"
LABELS=(
"epic|3E4B9E|Large feature spanning multiple issues"
"feature|0E8A16|New functionality"
"bug|D73A4A|Defect fix"
"task|0075CA|General work item"
"documentation|0075CA|Documentation updates"
"security|B60205|Security-related"
"breaking|D93F0B|Breaking change"
)
create_label_github() {
local name="$1" color="$2" description="$3"
# Check if label already exists
if gh label list --repo "$OWNER/$REPO" --json name -q ".[].name" 2>/dev/null | grep -qx "$name"; then
echo " [skip] '$name' already exists"
return 0
fi
gh label create "$name" \
--repo "$OWNER/$REPO" \
--color "$color" \
--description "$description" 2>/dev/null && \
echo " [created] '$name'" || \
echo " [error] Failed to create '$name'"
}
create_label_gitea() {
local name="$1" color="$2" description="$3"
# Check if label already exists
if tea labels list 2>/dev/null | grep -q "$name"; then
echo " [skip] '$name' already exists"
return 0
fi
tea labels create --name "$name" --color "#$color" --description "$description" 2>/dev/null && \
echo " [created] '$name'" || \
echo " [error] Failed to create '$name'"
}
echo "Creating labels..."
for label_def in "${LABELS[@]}"; do
IFS='|' read -r name color description <<< "$label_def"
case "$PLATFORM" in
github)
create_label_github "$name" "$color" "$description"
;;
gitea)
create_label_gitea "$name" "$color" "$description"
;;
*)
echo "Error: Unsupported platform '$PLATFORM'" >&2
exit 1
;;
esac
done
echo ""
# Create initial pre-MVP milestone
if [[ "$SKIP_MILESTONE" != true ]]; then
echo "Creating initial pre-MVP milestone..."
"$GIT_SCRIPT_DIR/milestone-create.sh" -t "0.0.1" -d "Pre-MVP - Foundation Sprint" 2>/dev/null && \
echo " [created] Milestone '0.0.1 - Pre-MVP'" || \
echo " [skip] Milestone may already exist or creation failed"
echo " [note] Reserve 0.1.0 for MVP release milestone"
echo ""
fi
echo "Label initialization complete."
@@ -0,0 +1,379 @@
#!/bin/bash
# generate-docker-steps.sh - Generate Woodpecker CI pipeline steps for Docker build/push/link
#
# Outputs valid Woodpecker YAML for:
# - Kaniko Docker build & push steps (one per service)
# - Gitea package linking step
# - npm package publish step (optional)
#
# Usage:
# generate-docker-steps.sh \
# --registry git.uscllc.com \
# --org usc \
# --repo uconnect \
# --service backend-api:src/backend-api/Dockerfile \
# --service web-portal:src/web-portal/Dockerfile \
# --branches main,develop \
# [--build-arg backend-api:NEXT_PUBLIC_API_URL=https://api.example.com] \
# [--npm-package @uconnect/schemas:src/schemas] \
# [--npm-registry https://git.uscllc.com/api/packages/usc/npm/] \
# [--depends-on build]
set -e
# Defaults
REGISTRY=""
ORG=""
REPO=""
BRANCHES="main,develop"
DEPENDS_ON="build"
declare -a SERVICES=()
declare -a BUILD_ARGS=()
declare -a NPM_PACKAGES=()
NPM_REGISTRY=""
show_help() {
cat <<'EOF'
Usage: generate-docker-steps.sh [OPTIONS]
Generate Woodpecker CI YAML for Docker build/push/link via Kaniko.
Required:
--registry <host> Gitea hostname (e.g., git.uscllc.com)
--org <name> Gitea organization (e.g., usc)
--repo <name> Repository name (e.g., uconnect)
--service <name:dockerfile> Service to build (repeatable)
Optional:
--branches <list> Comma-separated branches (default: main,develop)
--depends-on <step> Step name Docker builds depend on (default: build)
--build-arg <service:KEY=VAL> Build arg for a service (repeatable)
--npm-package <pkg:path> npm package to publish (repeatable)
--npm-registry <url> npm registry URL for publishing
--kaniko-setup-only Output just the kaniko_setup YAML anchor
-h, --help Show this help
Examples:
# Mosaic Stack pattern
generate-docker-steps.sh \
--registry git.mosaicstack.dev --org mosaic --repo stack \
--service stack-api:apps/api/Dockerfile \
--service stack-web:apps/web/Dockerfile \
--build-arg stack-web:NEXT_PUBLIC_API_URL=https://api.mosaicstack.dev
# U-Connect pattern
generate-docker-steps.sh \
--registry git.uscllc.com --org usc --repo uconnect \
--service uconnect-backend-api:src/backend-api/Dockerfile \
--service uconnect-web-portal:src/web-portal/Dockerfile \
--service uconnect-ingest-api:src/ingest-api/Dockerfile \
--branches main,develop
EOF
exit 0
}
KANIKO_SETUP_ONLY=false
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
--registry) REGISTRY="$2"; shift 2 ;;
--org) ORG="$2"; shift 2 ;;
--repo) REPO="$2"; shift 2 ;;
--service) SERVICES+=("$2"); shift 2 ;;
--branches) BRANCHES="$2"; shift 2 ;;
--depends-on) DEPENDS_ON="$2"; shift 2 ;;
--build-arg) BUILD_ARGS+=("$2"); shift 2 ;;
--npm-package) NPM_PACKAGES+=("$2"); shift 2 ;;
--npm-registry) NPM_REGISTRY="$2"; shift 2 ;;
--kaniko-setup-only) KANIKO_SETUP_ONLY=true; shift ;;
-h|--help) show_help ;;
*) echo "Unknown option: $1" >&2; exit 1 ;;
esac
done
# Validate required args
if [[ -z "$REGISTRY" ]]; then echo "Error: --registry is required" >&2; exit 1; fi
if [[ -z "$ORG" ]]; then echo "Error: --org is required" >&2; exit 1; fi
if [[ -z "$REPO" ]]; then echo "Error: --repo is required" >&2; exit 1; fi
if [[ ${#SERVICES[@]} -eq 0 && "$KANIKO_SETUP_ONLY" != true ]]; then
echo "Error: at least one --service is required" >&2; exit 1
fi
# Parse branches into YAML list
IFS=',' read -ra BRANCH_LIST <<< "$BRANCHES"
BRANCH_YAML="["
for i in "${!BRANCH_LIST[@]}"; do
if [[ $i -gt 0 ]]; then BRANCH_YAML="$BRANCH_YAML, "; fi
BRANCH_YAML="$BRANCH_YAML${BRANCH_LIST[$i]}"
done
BRANCH_YAML="$BRANCH_YAML]"
# Helper: get build args for a specific service
get_build_args_for_service() {
local svc_name="$1"
local args=()
for ba in "${BUILD_ARGS[@]}"; do
local ba_svc="${ba%%:*}"
local ba_val="${ba#*:}"
if [[ "$ba_svc" == "$svc_name" ]]; then
args+=("$ba_val")
fi
done
echo "${args[@]}"
}
# Helper: determine Dockerfile context from path
# e.g., apps/api/Dockerfile -> . (monorepo root)
# docker/postgres/Dockerfile -> docker/postgres
get_context() {
local dockerfile="$1"
local dir
dir=$(dirname "$dockerfile")
# If Dockerfile is at project root or in a top-level apps/src dir, use "."
if [[ "$dir" == "." || "$dir" == apps/* || "$dir" == src/* || "$dir" == packages/* ]]; then
echo "."
else
echo "$dir"
fi
}
# ============================================================
# Output: YAML anchor for kaniko setup
# ============================================================
emit_kaniko_anchor() {
cat <<EOF
# Kaniko base command setup
- &kaniko_setup |
mkdir -p /kaniko/.docker
echo "{\\"auths\\":{\\"${REGISTRY}\\":{\\"username\\":\\"\$GITEA_USER\\",\\"password\\":\\"\$GITEA_TOKEN\\"}}}" > /kaniko/.docker/config.json
EOF
}
if [[ "$KANIKO_SETUP_ONLY" == true ]]; then
emit_kaniko_anchor
exit 0
fi
# ============================================================
# Output: Header comment
# ============================================================
cat <<EOF
# ======================
# Docker Build & Push (${BRANCHES} only)
# ======================
# Generated by: generate-docker-steps.sh
# Registry: ${REGISTRY}/${ORG}
# Requires secrets: gitea_username, gitea_token
#
# Tagging Strategy:
# - Always: commit SHA (first 8 chars)
EOF
for b in "${BRANCH_LIST[@]}"; do
case "$b" in
main) echo " # - main branch: 'latest'" ;;
develop) echo " # - develop branch: 'dev'" ;;
*) echo " # - ${b} branch: '${b}'" ;;
esac
done
echo " # - git tags: version tag (e.g., v1.0.0)"
echo ""
# ============================================================
# Output: Kaniko build step for each service
# ============================================================
for svc in "${SERVICES[@]}"; do
SVC_NAME="${svc%%:*}"
DOCKERFILE="${svc#*:}"
CONTEXT=$(get_context "$DOCKERFILE")
SVC_BUILD_ARGS=$(get_build_args_for_service "$SVC_NAME")
# Build the kaniko command with build args
KANIKO_EXTRA=""
if [[ -n "$SVC_BUILD_ARGS" ]]; then
for arg in $SVC_BUILD_ARGS; do
KANIKO_EXTRA="$KANIKO_EXTRA --build-arg ${arg}"
done
fi
cat <<EOF
# Build and push ${SVC_NAME}
docker-build-${SVC_NAME}:
image: gcr.io/kaniko-project/executor:debug
environment:
GITEA_USER:
from_secret: gitea_username
GITEA_TOKEN:
from_secret: gitea_token
CI_COMMIT_BRANCH: \${CI_COMMIT_BRANCH}
CI_COMMIT_TAG: \${CI_COMMIT_TAG}
CI_COMMIT_SHA: \${CI_COMMIT_SHA}
commands:
- *kaniko_setup
- |
DESTINATIONS="--destination ${REGISTRY}/${ORG}/${SVC_NAME}:\${CI_COMMIT_SHA:0:8}"
EOF
# Branch-specific tags
for b in "${BRANCH_LIST[@]}"; do
case "$b" in
main)
cat <<EOF
if [ "\$CI_COMMIT_BRANCH" = "main" ]; then
DESTINATIONS="\$DESTINATIONS --destination ${REGISTRY}/${ORG}/${SVC_NAME}:latest"
fi
EOF
;;
develop)
cat <<EOF
if [ "\$CI_COMMIT_BRANCH" = "develop" ]; then
DESTINATIONS="\$DESTINATIONS --destination ${REGISTRY}/${ORG}/${SVC_NAME}:dev"
fi
EOF
;;
*)
cat <<EOF
if [ "\$CI_COMMIT_BRANCH" = "${b}" ]; then
DESTINATIONS="\$DESTINATIONS --destination ${REGISTRY}/${ORG}/${SVC_NAME}:${b}"
fi
EOF
;;
esac
done
# Version tag
cat <<EOF
if [ -n "\$CI_COMMIT_TAG" ]; then
DESTINATIONS="\$DESTINATIONS --destination ${REGISTRY}/${ORG}/${SVC_NAME}:\$CI_COMMIT_TAG"
fi
/kaniko/executor --context ${CONTEXT} --dockerfile ${DOCKERFILE}${KANIKO_EXTRA} \$DESTINATIONS
when:
- branch: ${BRANCH_YAML}
event: [push, manual, tag]
depends_on:
- ${DEPENDS_ON}
EOF
done
# ============================================================
# Output: Package linking step
# ============================================================
cat <<EOF
# ======================
# Link Packages to Repository
# ======================
link-packages:
image: alpine:3
environment:
GITEA_TOKEN:
from_secret: gitea_token
commands:
- apk add --no-cache curl
- echo "Waiting 10 seconds for packages to be indexed in registry..."
- sleep 10
- |
set -e
link_package() {
PKG="\$\$1"
echo "Linking \$\$PKG..."
for attempt in 1 2 3; do
STATUS=\$\$(curl -s -o /tmp/link-response.txt -w "%{http_code}" -X POST \\
-H "Authorization: token \$\$GITEA_TOKEN" \\
"https://${REGISTRY}/api/v1/packages/${ORG}/container/\$\$PKG/-/link/${REPO}")
if [ "\$\$STATUS" = "201" ] || [ "\$\$STATUS" = "204" ]; then
echo " Linked \$\$PKG"
return 0
elif [ "\$\$STATUS" = "400" ]; then
echo " \$\$PKG already linked"
return 0
elif [ "\$\$STATUS" = "404" ] && [ \$\$attempt -lt 3 ]; then
echo " \$\$PKG not found yet, waiting 5s (attempt \$\$attempt/3)..."
sleep 5
else
echo " FAILED: \$\$PKG status \$\$STATUS"
cat /tmp/link-response.txt
return 1
fi
done
}
EOF
# List all services to link
for svc in "${SERVICES[@]}"; do
SVC_NAME="${svc%%:*}"
echo " link_package \"${SVC_NAME}\""
done
# Close the link step
cat <<EOF
when:
- branch: ${BRANCH_YAML}
event: [push, manual, tag]
depends_on:
EOF
for svc in "${SERVICES[@]}"; do
SVC_NAME="${svc%%:*}"
echo " - docker-build-${SVC_NAME}"
done
echo ""
# ============================================================
# Output: npm publish step (if requested)
# ============================================================
if [[ ${#NPM_PACKAGES[@]} -gt 0 && -n "$NPM_REGISTRY" ]]; then
cat <<EOF
# ======================
# Publish npm Packages
# ======================
publish-packages:
image: node:20-alpine
environment:
GITEA_TOKEN:
from_secret: gitea_token
commands:
- |
echo "//${NPM_REGISTRY#https://}:_authToken=\$\$GITEA_TOKEN" > .npmrc
EOF
# Detect scope from first package
FIRST_PKG="${NPM_PACKAGES[0]}"
PKG_NAME="${FIRST_PKG%%:*}"
SCOPE="${PKG_NAME%%/*}"
if [[ "$SCOPE" == @* ]]; then
echo " echo \"${SCOPE}:registry=${NPM_REGISTRY}\" >> .npmrc"
fi
for pkg in "${NPM_PACKAGES[@]}"; do
PKG_NAME="${pkg%%:*}"
PKG_PATH="${pkg#*:}"
cat <<EOF
- |
CURRENT=\$\$(node -p "require('./${PKG_PATH}/package.json').version")
PUBLISHED=\$\$(npm view ${PKG_NAME} version 2>/dev/null || echo "0.0.0")
if [ "\$\$CURRENT" = "\$\$PUBLISHED" ]; then
echo "${PKG_NAME}@\$\$CURRENT already published, skipping"
else
echo "Publishing ${PKG_NAME}@\$\$CURRENT (was \$\$PUBLISHED)"
npm publish -w ${PKG_NAME}
fi
EOF
done
cat <<EOF
when:
- branch: [main]
event: [push, manual, tag]
depends_on:
- ${DEPENDS_ON}
EOF
fi
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
#
# _lib.sh — Shared helpers for Cloudflare tool scripts
#
# Usage: source "$(dirname "$0")/_lib.sh"
#
# Provides:
# CF_API — Base API URL
# cf_auth — Authorization header value
# cf_load_instance <instance> — Load credentials for a specific or default instance
# cf_resolve_zone <name_or_id> — Resolves a zone name to its ID (passes IDs through)
CF_API="https://api.cloudflare.com/client/v4"
cf_auth() {
echo "Bearer $CLOUDFLARE_API_TOKEN"
}
# Load credentials for a Cloudflare instance.
# If instance is empty, loads the default.
cf_load_instance() {
local instance="$1"
if [[ -n "$instance" ]]; then
load_credentials "cloudflare-${instance}"
else
load_credentials cloudflare
fi
}
# Resolve a zone name (e.g. "mosaicstack.dev") to its zone ID.
# If the input is already a 32-char hex ID, passes it through.
cf_resolve_zone() {
local input="$1"
# If it looks like a zone ID (32 hex chars), pass through
if [[ "$input" =~ ^[0-9a-f]{32}$ ]]; then
echo "$input"
return 0
fi
# Resolve by name
local response
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
"${CF_API}/zones?name=${input}&status=active")
local http_code
http_code=$(echo "$response" | tail -n1)
local body
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to resolve zone '$input' (HTTP $http_code)" >&2
return 1
fi
local zone_id
zone_id=$(echo "$body" | jq -r '.result[0].id // empty')
if [[ -z "$zone_id" ]]; then
echo "Error: Zone '$input' not found" >&2
return 1
fi
echo "$zone_id"
}
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
#
# record-create.sh — Create a DNS record in a Cloudflare zone
#
# Usage: record-create.sh -z <zone> -t <type> -n <name> -c <content> [-a instance] [-l ttl] [-p] [-P priority]
#
# Options:
# -z zone Zone name or ID (required)
# -t type Record type: A, AAAA, CNAME, MX, TXT, etc. (required)
# -n name Record name, e.g. "app" or "app.example.com" (required)
# -c content Record value/content (required)
# -a instance Cloudflare instance name (default: uses credentials default)
# -l ttl TTL in seconds (default: 1 = auto)
# -p Enable Cloudflare proxy (orange cloud)
# -P priority MX/SRV priority (default: 10)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"
ZONE=""
INSTANCE=""
TYPE=""
NAME=""
CONTENT=""
TTL=1
PROXIED=false
PRIORITY=""
while getopts "z:a:t:n:c:l:pP:h" opt; do
case $opt in
z) ZONE="$OPTARG" ;;
a) INSTANCE="$OPTARG" ;;
t) TYPE="$OPTARG" ;;
n) NAME="$OPTARG" ;;
c) CONTENT="$OPTARG" ;;
l) TTL="$OPTARG" ;;
p) PROXIED=true ;;
P) PRIORITY="$OPTARG" ;;
h) head -18 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -z <zone> -t <type> -n <name> -c <content> [-a instance] [-l ttl] [-p] [-P priority]" >&2; exit 1 ;;
esac
done
if [[ -z "$ZONE" || -z "$TYPE" || -z "$NAME" || -z "$CONTENT" ]]; then
echo "Error: -z, -t, -n, and -c are all required" >&2
exit 1
fi
cf_load_instance "$INSTANCE"
ZONE_ID=$(cf_resolve_zone "$ZONE") || exit 1
# Build JSON payload
payload=$(jq -n \
--arg type "$TYPE" \
--arg name "$NAME" \
--arg content "$CONTENT" \
--argjson ttl "$TTL" \
--argjson proxied "$PROXIED" \
'{type: $type, name: $name, content: $content, ttl: $ttl, proxied: $proxied}')
# Add priority for MX/SRV records
if [[ -n "$PRIORITY" ]]; then
payload=$(echo "$payload" | jq --argjson priority "$PRIORITY" '. + {priority: $priority}')
fi
response=$(curl -s -w "\n%{http_code}" \
-X POST \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
-d "$payload" \
"${CF_API}/zones/${ZONE_ID}/dns_records")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to create record (HTTP $http_code)" >&2
echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
exit 1
fi
record_id=$(echo "$body" | jq -r '.result.id')
echo "Created $TYPE record: $NAME$CONTENT (ID: $record_id)"
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
#
# record-delete.sh — Delete a DNS record from a Cloudflare zone
#
# Usage: record-delete.sh -z <zone> -r <record-id> [-a instance]
#
# Options:
# -z zone Zone name or ID (required)
# -r record-id DNS record ID (required)
# -a instance Cloudflare instance name (default: uses credentials default)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"
ZONE=""
INSTANCE=""
RECORD_ID=""
while getopts "z:a:r:h" opt; do
case $opt in
z) ZONE="$OPTARG" ;;
a) INSTANCE="$OPTARG" ;;
r) RECORD_ID="$OPTARG" ;;
h) head -11 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -z <zone> -r <record-id> [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -z "$ZONE" || -z "$RECORD_ID" ]]; then
echo "Error: -z and -r are both required" >&2
exit 1
fi
cf_load_instance "$INSTANCE"
ZONE_ID=$(cf_resolve_zone "$ZONE") || exit 1
response=$(curl -s -w "\n%{http_code}" \
-X DELETE \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
"${CF_API}/zones/${ZONE_ID}/dns_records/${RECORD_ID}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to delete record (HTTP $http_code)" >&2
echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
exit 1
fi
echo "Deleted DNS record $RECORD_ID from zone $ZONE"
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
#
# record-list.sh — List DNS records for a Cloudflare zone
#
# Usage: record-list.sh -z <zone> [-a instance] [-t type] [-n name] [-f format]
#
# Options:
# -z zone Zone name or ID (required)
# -a instance Cloudflare instance name (default: uses credentials default)
# -t type Filter by record type (A, AAAA, CNAME, MX, TXT, etc.)
# -n name Filter by record name
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"
ZONE=""
INSTANCE=""
TYPE=""
NAME=""
FORMAT="table"
while getopts "z:a:t:n:f:h" opt; do
case $opt in
z) ZONE="$OPTARG" ;;
a) INSTANCE="$OPTARG" ;;
t) TYPE="$OPTARG" ;;
n) NAME="$OPTARG" ;;
f) FORMAT="$OPTARG" ;;
h) head -14 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -z <zone> [-a instance] [-t type] [-n name] [-f format]" >&2; exit 1 ;;
esac
done
if [[ -z "$ZONE" ]]; then
echo "Error: -z zone is required" >&2
exit 1
fi
cf_load_instance "$INSTANCE"
ZONE_ID=$(cf_resolve_zone "$ZONE") || exit 1
# Build query params
params="per_page=100"
[[ -n "$TYPE" ]] && params="${params}&type=${TYPE}"
[[ -n "$NAME" ]] && params="${params}&name=${NAME}"
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
"${CF_API}/zones/${ZONE_ID}/dns_records?${params}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list records (HTTP $http_code)" >&2
echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.result'
exit 0
fi
echo "RECORD ID TYPE NAME CONTENT PROXIED TTL"
echo "-------------------------------- ----- -------------------------------------- ------------------------------- ------- -----"
echo "$body" | jq -r '.result[] | [
.id,
.type,
.name,
.content,
(if .proxied then "yes" else "no" end),
(if .ttl == 1 then "auto" else (.ttl | tostring) end)
] | @tsv' | while IFS=$'\t' read -r id type name content proxied ttl; do
printf "%-32s %-5s %-38s %-31s %-7s %s\n" "$id" "$type" "${name:0:38}" "${content:0:31}" "$proxied" "$ttl"
done
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
#
# record-update.sh — Update a DNS record in a Cloudflare zone
#
# Usage: record-update.sh -z <zone> -r <record-id> -t <type> -n <name> -c <content> [-a instance] [-l ttl] [-p] [-P priority]
#
# Options:
# -z zone Zone name or ID (required)
# -r record-id DNS record ID (required)
# -t type Record type: A, AAAA, CNAME, MX, TXT, etc. (required)
# -n name Record name (required)
# -c content Record value/content (required)
# -a instance Cloudflare instance name (default: uses credentials default)
# -l ttl TTL in seconds (default: 1 = auto)
# -p Enable Cloudflare proxy (orange cloud)
# -P priority MX/SRV priority
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"
ZONE=""
INSTANCE=""
RECORD_ID=""
TYPE=""
NAME=""
CONTENT=""
TTL=1
PROXIED=false
PRIORITY=""
while getopts "z:a:r:t:n:c:l:pP:h" opt; do
case $opt in
z) ZONE="$OPTARG" ;;
a) INSTANCE="$OPTARG" ;;
r) RECORD_ID="$OPTARG" ;;
t) TYPE="$OPTARG" ;;
n) NAME="$OPTARG" ;;
c) CONTENT="$OPTARG" ;;
l) TTL="$OPTARG" ;;
p) PROXIED=true ;;
P) PRIORITY="$OPTARG" ;;
h) head -18 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -z <zone> -r <record-id> -t <type> -n <name> -c <content> [-a instance]" >&2; exit 1 ;;
esac
done
if [[ -z "$ZONE" || -z "$RECORD_ID" || -z "$TYPE" || -z "$NAME" || -z "$CONTENT" ]]; then
echo "Error: -z, -r, -t, -n, and -c are all required" >&2
exit 1
fi
cf_load_instance "$INSTANCE"
ZONE_ID=$(cf_resolve_zone "$ZONE") || exit 1
payload=$(jq -n \
--arg type "$TYPE" \
--arg name "$NAME" \
--arg content "$CONTENT" \
--argjson ttl "$TTL" \
--argjson proxied "$PROXIED" \
'{type: $type, name: $name, content: $content, ttl: $ttl, proxied: $proxied}')
if [[ -n "$PRIORITY" ]]; then
payload=$(echo "$payload" | jq --argjson priority "$PRIORITY" '. + {priority: $priority}')
fi
response=$(curl -s -w "\n%{http_code}" \
-X PUT \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
-d "$payload" \
"${CF_API}/zones/${ZONE_ID}/dns_records/${RECORD_ID}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to update record (HTTP $http_code)" >&2
echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
exit 1
fi
echo "Updated $TYPE record: $NAME$CONTENT (ID: $RECORD_ID)"
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env bash
#
# zone-list.sh — List Cloudflare zones (domains)
#
# Usage: zone-list.sh [-a instance] [-f format]
#
# Options:
# -a instance Cloudflare instance name (default: uses credentials default)
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
source "$(dirname "$0")/_lib.sh"
INSTANCE=""
FORMAT="table"
while getopts "a:f:h" opt; do
case $opt in
a) INSTANCE="$OPTARG" ;;
f) FORMAT="$OPTARG" ;;
h) head -10 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-a instance] [-f format]" >&2; exit 1 ;;
esac
done
cf_load_instance "$INSTANCE"
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: $(cf_auth)" \
-H "Content-Type: application/json" \
"${CF_API}/zones?per_page=50")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list zones (HTTP $http_code)" >&2
echo "$body" | jq -r '.errors[]?.message // empty' 2>/dev/null >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.result'
exit 0
fi
echo "ZONE ID NAME STATUS PLAN"
echo "-------------------------------- ---------------------------- -------- ----------"
echo "$body" | jq -r '.result[] | [
.id,
.name,
.status,
.plan.name
] | @tsv' | while IFS=$'\t' read -r id name status plan; do
printf "%-32s %-28s %-8s %s\n" "$id" "$name" "$status" "$plan"
done
@@ -0,0 +1,281 @@
# Codex CLI Review Scripts
AI-powered code review and security review scripts using OpenAI's Codex CLI.
These scripts provide **independent** code analysis separate from Claude sessions, giving you a second AI perspective on code changes to catch issues that might be missed.
## Prerequisites
```bash
# Install Codex CLI
npm i -g @openai/codex
# Verify installation
codex --version
# Authenticate (first run)
codex # Will prompt for ChatGPT account or API key
# Verify jq is installed (for JSON processing)
jq --version
```
## Scripts
### `codex-code-review.sh`
General code quality review focusing on:
- **Correctness** — logic errors, edge cases, error handling
- **Code Quality** — complexity, duplication, naming, dead code
- **Testing** — coverage, test quality
- **Performance** — N+1 queries, blocking operations, resource cleanup
- **Dependencies** — deprecated packages
- **Documentation** — comments, public API docs
**Output:** Structured JSON with findings categorized as `blocker`, `should-fix`, or `suggestion`.
### `codex-security-review.sh`
Security vulnerability review focusing on:
- **OWASP Top 10** — injection, broken auth, XSS, CSRF, SSRF, etc.
- **Secrets Detection** — hardcoded credentials, API keys, tokens
- **Injection Flaws** — SQL, NoSQL, OS command, LDAP
- **Auth/Authz Gaps** — missing checks, privilege escalation, IDOR
- **Data Exposure** — logging sensitive data, information disclosure
- **Supply Chain** — vulnerable dependencies, typosquatting
**Output:** Structured JSON with findings categorized as `critical`, `high`, `medium`, or `low` with CWE IDs and OWASP categories.
## Usage
### Review Uncommitted Changes
```bash
# Code review
~/.config/mosaic/tools/codex/codex-code-review.sh --uncommitted
# Security review
~/.config/mosaic/tools/codex/codex-security-review.sh --uncommitted
```
### Review a Pull Request
```bash
# Review and post findings as a PR comment
~/.config/mosaic/tools/codex/codex-code-review.sh -n 42
# Security review and post to PR
~/.config/mosaic/tools/codex/codex-security-review.sh -n 42
```
PR mode resolves the provider's PR diff rather than relying on the caller's checked-out branch. On Gitea, it fetches the base and `refs/pull/<number>/head` refs and diffs those explicit refs. If the refs cannot be fetched or the resulting diff is empty, the command exits nonzero before Codex runs or a review is posted.
### Review Against Base Branch
```bash
# Code review changes vs main
~/.config/mosaic/tools/codex/codex-code-review.sh -b main
# Security review changes vs develop
~/.config/mosaic/tools/codex/codex-security-review.sh -b develop
```
### Review a Specific Commit
```bash
~/.config/mosaic/tools/codex/codex-code-review.sh -c abc123f
~/.config/mosaic/tools/codex/codex-security-review.sh -c abc123f
```
### Save Results to File
```bash
# Save JSON output
~/.config/mosaic/tools/codex/codex-code-review.sh --uncommitted -o review-results.json
~/.config/mosaic/tools/codex/codex-security-review.sh --uncommitted -o security-results.json
```
## Options
Both scripts support the same options:
| Option | Description |
| --------------------- | ---------------------------------------------------------- |
| `-n, --pr <number>` | PR number (auto-enables posting to PR) |
| `-b, --base <branch>` | Base branch to diff against (default: main) |
| `-c, --commit <sha>` | Review a specific commit |
| `-o, --output <path>` | Write JSON results to file |
| `--post-to-pr` | Post findings as PR comment (requires -n) |
| `--uncommitted` | Review uncommitted changes (staged + unstaged + untracked) |
| `-h, --help` | Show help |
## Woodpecker CI Integration
Automated PR reviews in CI pipelines.
### Setup
1. **Copy the pipeline template to your repo:**
```bash
cp ~/.config/mosaic/tools/codex/woodpecker/codex-review.yml your-repo/.woodpecker/
```
2. **Copy the schemas directory:**
```bash
cp -r ~/.config/mosaic/tools/codex/schemas your-repo/.woodpecker/
```
3. **Add Codex API key to Woodpecker:**
- Go to your repo in Woodpecker CI
- Settings → Secrets
- Add secret: `codex_api_key` with your OpenAI API key
4. **Commit and push:**
```bash
cd your-repo
git add .woodpecker/
git commit -m "feat: Add Codex AI review pipeline"
git push
```
### Pipeline Behavior
- **Triggers on:** Pull requests
- **Runs:** Code review + Security review in parallel
- **Fails if:**
- Code review finds blockers
- Security review finds critical or high severity issues
- **Outputs:** Structured JSON results in CI logs
## Output Format
### Code Review JSON
```json
{
"summary": "Overall assessment...",
"verdict": "approve|request-changes|comment",
"confidence": 0.85,
"findings": [
{
"severity": "blocker",
"title": "SQL injection vulnerability",
"file": "src/api/users.ts",
"line_start": 42,
"line_end": 45,
"description": "User input directly interpolated into SQL query",
"suggestion": "Use parameterized queries"
}
],
"stats": {
"files_reviewed": 5,
"blockers": 1,
"should_fix": 3,
"suggestions": 8
}
}
```
### Security Review JSON
```json
{
"summary": "Security assessment...",
"risk_level": "high",
"confidence": 0.9,
"findings": [
{
"severity": "high",
"title": "Hardcoded API key",
"file": "src/config.ts",
"line_start": 10,
"description": "API key hardcoded in source",
"cwe_id": "CWE-798",
"owasp_category": "A02:2021-Cryptographic Failures",
"remediation": "Move to environment variables or secrets manager"
}
],
"stats": {
"files_reviewed": 5,
"critical": 0,
"high": 1,
"medium": 2,
"low": 3
}
}
```
## Platform Support
Works with both **GitHub** and **Gitea** via the shared `~/.config/mosaic/tools/git/` infrastructure:
- Auto-detects platform from git remote
- Posts PR comments using `gh` (GitHub) or `tea` (Gitea)
- Unified interface across both platforms
## Architecture
```
codex-code-review.sh
codex-security-review.sh
common.sh
↓ sources
../git/detect-platform.sh (platform detection)
../git/pr-review.sh (post PR comments)
↓ uses
gh (GitHub) or tea (Gitea)
```
## Troubleshooting
### "codex: command not found"
```bash
npm i -g @openai/codex
```
### "jq: command not found"
```bash
# Arch Linux
sudo pacman -S jq
# Debian/Ubuntu
sudo apt install jq
```
### "Error: Not inside a git repository"
Run the script from inside a git repository.
### "No changes found to review"
The specified non-PR mode (`--uncommitted`, `--base`, etc.) found no changes to review. PR mode instead fails closed with an actionable error when it cannot construct a non-empty provider diff; verify the PR number, remote, provider login, and ref access before retrying.
### "Codex produced no output"
Check your Codex API key and authentication:
```bash
codex # Re-authenticate if needed
```
## Model Configuration
By default, scripts use the model configured in `~/.codex/config.toml`:
- **Model:** `gpt-5.3-codex` (recommended for code review)
- **Reasoning effort:** `high`
For best results, use `gpt-5.2-codex` or newer for strongest review accuracy.
## See Also
- `~/.config/mosaic/guides/CODE-REVIEW.md` — Manual code review checklist
- `~/.config/mosaic/tools/git/` — Git helper scripts (issue/PR management)
- OpenAI Codex CLI docs: https://developers.openai.com/codex/cli/
@@ -0,0 +1,238 @@
#!/bin/bash
# codex-code-review.sh - Run an AI-powered code quality review using Codex CLI
# Usage: codex-code-review.sh [OPTIONS]
#
# Runs codex exec in read-only sandbox mode with a structured code review prompt.
# Outputs findings as JSON and optionally posts them to a PR.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Defaults
PR_NUMBER=""
BASE_BRANCH="main"
COMMIT_SHA=""
OUTPUT_FILE=""
POST_TO_PR=false
UNCOMMITTED=false
REVIEW_MODE=""
show_help() {
cat <<'EOF'
Usage: codex-code-review.sh [OPTIONS]
Run an AI-powered code quality review using OpenAI Codex CLI.
Options:
-n, --pr <number> PR number (auto-enables posting findings to PR)
-b, --base <branch> Base branch to diff against (default: main)
-c, --commit <sha> Review a specific commit
-o, --output <path> Write JSON results to file
--post-to-pr Post findings as PR comment (requires -n)
--uncommitted Review uncommitted changes (staged + unstaged + untracked)
-h, --help Show this help
Examples:
# Review uncommitted changes
codex-code-review.sh --uncommitted
# Review a PR and post findings as a comment
codex-code-review.sh -n 42
# Review changes against main, save JSON
codex-code-review.sh -b main -o review.json
# Review a specific commit
codex-code-review.sh -c abc123f
EOF
exit 0
}
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
-n|--pr)
PR_NUMBER="$2"
POST_TO_PR=true
REVIEW_MODE="pr"
shift 2
;;
-b|--base)
BASE_BRANCH="$2"
REVIEW_MODE="base"
shift 2
;;
-c|--commit)
COMMIT_SHA="$2"
REVIEW_MODE="commit"
shift 2
;;
-o|--output)
OUTPUT_FILE="$2"
shift 2
;;
--post-to-pr)
POST_TO_PR=true
shift
;;
--uncommitted)
UNCOMMITTED=true
REVIEW_MODE="uncommitted"
shift
;;
-h|--help)
show_help
;;
*)
echo "Unknown option: $1" >&2
echo "Run with --help for usage" >&2
exit 1
;;
esac
done
# Validate
if [[ -z "$REVIEW_MODE" ]]; then
echo "Error: Specify a review mode: --uncommitted, --base <branch>, --commit <sha>, or --pr <number>" >&2
exit 1
fi
if [[ "$POST_TO_PR" == true && -z "$PR_NUMBER" ]]; then
echo "Error: --post-to-pr requires -n <pr_number>" >&2
exit 1
fi
check_codex
check_jq
# Verify we're in a git repo
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
echo "Error: Not inside a git repository" >&2
exit 1
fi
# Get the diff context
echo "Gathering diff context..." >&2
case "$REVIEW_MODE" in
uncommitted) DIFF_CONTEXT=$(build_diff_context "uncommitted" "") ;;
base) DIFF_CONTEXT=$(build_diff_context "base" "$BASE_BRANCH") ;;
commit) DIFF_CONTEXT=$(build_diff_context "commit" "$COMMIT_SHA") ;;
pr) DIFF_CONTEXT=$(build_diff_context "pr" "$PR_NUMBER") ;;
esac
if [[ -z "$DIFF_CONTEXT" ]]; then
echo "No changes found to review." >&2
exit 0
fi
# Build the review prompt
REVIEW_PROMPT=$(cat <<'PROMPT'
You are an expert code reviewer. Review the following code changes thoroughly.
Focus on issues that are ACTIONABLE and IMPORTANT. Do not flag trivial style issues.
## Review Checklist
### Correctness
- Code does what it claims to do
- Edge cases are handled
- Error conditions are managed properly
- No obvious bugs or logic errors
### Code Quality
- Functions are focused and reasonably sized
- No unnecessary complexity
- DRY - no significant duplication
- Clear naming for variables and functions
- No dead code or commented-out code
### Testing
- Tests exist for new functionality
- Tests cover happy path AND error cases
- No flaky tests introduced
### Performance
- No obvious N+1 queries
- No blocking operations in hot paths
- Resource cleanup (connections, file handles)
### Dependencies
- No deprecated packages
- No unnecessary new dependencies
### Documentation
- Complex logic has explanatory comments
- Public APIs are documented
## Severity Guide
- **blocker**: Must fix before merge (bugs, correctness issues, missing error handling)
- **should-fix**: Important but not blocking (code quality, minor issues)
- **suggestion**: Optional improvements (nice-to-haves)
Only report findings you are confident about (confidence > 0.7).
If the code looks good, say so — don't manufacture issues.
PROMPT
)
# Set up temp files for output and diff
TEMP_OUTPUT=$(mktemp /tmp/codex-review-XXXXXX.json)
TEMP_DIFF=$(mktemp /tmp/codex-diff-XXXXXX.txt)
trap 'rm -f "$TEMP_OUTPUT" "$TEMP_DIFF"' EXIT
SCHEMA_FILE="$SCRIPT_DIR/schemas/code-review-schema.json"
# Write diff to temp file
echo "$DIFF_CONTEXT" > "$TEMP_DIFF"
echo "Running Codex code review..." >&2
echo " Diff size: $(wc -l < "$TEMP_DIFF") lines" >&2
# Build full prompt with diff reference
FULL_PROMPT="${REVIEW_PROMPT}
Here are the code changes to review:
\`\`\`diff
$(cat "$TEMP_DIFF")
\`\`\`"
# Run codex exec with prompt from stdin to avoid arg length limits
echo "$FULL_PROMPT" | codex exec \
--sandbox read-only \
--output-schema "$SCHEMA_FILE" \
-o "$TEMP_OUTPUT" \
- 2>&1 | while IFS= read -r line; do
echo " [codex] $line" >&2
done
# Check output was produced
if [[ ! -s "$TEMP_OUTPUT" ]]; then
echo "Error: Codex produced no output" >&2
exit 1
fi
# Validate JSON
if ! jq empty "$TEMP_OUTPUT" 2>/dev/null; then
echo "Error: Codex output is not valid JSON" >&2
cat "$TEMP_OUTPUT" >&2
exit 1
fi
# Save output if requested
if [[ -n "$OUTPUT_FILE" ]]; then
cp "$TEMP_OUTPUT" "$OUTPUT_FILE"
echo "Results saved to: $OUTPUT_FILE" >&2
fi
# Post to PR if requested
if [[ "$POST_TO_PR" == true && -n "$PR_NUMBER" ]]; then
echo "Posting findings to PR #$PR_NUMBER..." >&2
post_to_pr "$PR_NUMBER" "$TEMP_OUTPUT" "code"
echo "Posted review to PR #$PR_NUMBER" >&2
fi
# Always print results to stdout
print_results "$TEMP_OUTPUT" "code"
@@ -0,0 +1,235 @@
#!/bin/bash
# codex-security-review.sh - Run an AI-powered security vulnerability review using Codex CLI
# Usage: codex-security-review.sh [OPTIONS]
#
# Runs codex exec in read-only sandbox mode with a security-focused review prompt.
# Outputs findings as JSON and optionally posts them to a PR.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/common.sh"
# Defaults
PR_NUMBER=""
BASE_BRANCH="main"
COMMIT_SHA=""
OUTPUT_FILE=""
POST_TO_PR=false
UNCOMMITTED=false
REVIEW_MODE=""
show_help() {
cat <<'EOF'
Usage: codex-security-review.sh [OPTIONS]
Run an AI-powered security vulnerability review using OpenAI Codex CLI.
Options:
-n, --pr <number> PR number (auto-enables posting findings to PR)
-b, --base <branch> Base branch to diff against (default: main)
-c, --commit <sha> Review a specific commit
-o, --output <path> Write JSON results to file
--post-to-pr Post findings as PR comment (requires -n)
--uncommitted Review uncommitted changes (staged + unstaged + untracked)
-h, --help Show this help
Examples:
# Security review uncommitted changes
codex-security-review.sh --uncommitted
# Security review a PR and post findings
codex-security-review.sh -n 42
# Security review against main, save JSON
codex-security-review.sh -b main -o security.json
# Security review a specific commit
codex-security-review.sh -c abc123f
EOF
exit 0
}
# Parse arguments
while [[ $# -gt 0 ]]; do
case $1 in
-n|--pr)
PR_NUMBER="$2"
POST_TO_PR=true
REVIEW_MODE="pr"
shift 2
;;
-b|--base)
BASE_BRANCH="$2"
REVIEW_MODE="base"
shift 2
;;
-c|--commit)
COMMIT_SHA="$2"
REVIEW_MODE="commit"
shift 2
;;
-o|--output)
OUTPUT_FILE="$2"
shift 2
;;
--post-to-pr)
POST_TO_PR=true
shift
;;
--uncommitted)
UNCOMMITTED=true
REVIEW_MODE="uncommitted"
shift
;;
-h|--help)
show_help
;;
*)
echo "Unknown option: $1" >&2
echo "Run with --help for usage" >&2
exit 1
;;
esac
done
# Validate
if [[ -z "$REVIEW_MODE" ]]; then
echo "Error: Specify a review mode: --uncommitted, --base <branch>, --commit <sha>, or --pr <number>" >&2
exit 1
fi
if [[ "$POST_TO_PR" == true && -z "$PR_NUMBER" ]]; then
echo "Error: --post-to-pr requires -n <pr_number>" >&2
exit 1
fi
check_codex
check_jq
# Verify we're in a git repo
if ! git rev-parse --is-inside-work-tree &>/dev/null; then
echo "Error: Not inside a git repository" >&2
exit 1
fi
# Get the diff context
echo "Gathering diff context..." >&2
case "$REVIEW_MODE" in
uncommitted) DIFF_CONTEXT=$(build_diff_context "uncommitted" "") ;;
base) DIFF_CONTEXT=$(build_diff_context "base" "$BASE_BRANCH") ;;
commit) DIFF_CONTEXT=$(build_diff_context "commit" "$COMMIT_SHA") ;;
pr) DIFF_CONTEXT=$(build_diff_context "pr" "$PR_NUMBER") ;;
esac
if [[ -z "$DIFF_CONTEXT" ]]; then
echo "No changes found to review." >&2
exit 0
fi
# Build the security review prompt
REVIEW_PROMPT=$(cat <<'PROMPT'
You are an expert application security engineer performing a security-focused code review.
Your goal is to identify vulnerabilities, security anti-patterns, and data exposure risks.
## Security Review Scope
### OWASP Top 10 (2021)
- A01: Broken Access Control — missing authorization checks, IDOR, privilege escalation
- A02: Cryptographic Failures — weak algorithms, plaintext secrets, missing encryption
- A03: Injection — SQL, NoSQL, OS command, LDAP, XPath injection
- A04: Insecure Design — missing threat modeling, unsafe business logic
- A05: Security Misconfiguration — debug mode, default credentials, unnecessary features
- A06: Vulnerable Components — known CVEs in dependencies
- A07: Authentication Failures — weak auth, missing MFA, session issues
- A08: Data Integrity Failures — deserialization, unsigned updates
- A09: Logging Failures — sensitive data in logs, missing audit trails
- A10: SSRF — unvalidated URLs, internal service access
### Additional Checks
- Hardcoded secrets, API keys, tokens, passwords
- Insecure direct object references
- Missing input validation at trust boundaries
- Cross-Site Scripting (XSS) — reflected, stored, DOM-based
- Cross-Site Request Forgery (CSRF) protection
- Insecure file handling (path traversal, unrestricted upload)
- Race conditions and TOCTOU vulnerabilities
- Information disclosure (stack traces, verbose errors)
- Supply chain risks (typosquatting, dependency confusion)
## Severity Guide
- **critical**: Exploitable vulnerability with immediate impact (RCE, auth bypass, data breach)
- **high**: Significant vulnerability requiring prompt fix (injection, XSS, secrets exposure)
- **medium**: Vulnerability with limited exploitability or impact (missing headers, weak config)
- **low**: Minor security concern or hardening opportunity (informational, defense-in-depth)
## Rules
- Include CWE IDs when applicable
- Include OWASP category when applicable
- Provide specific remediation steps for every finding
- Only report findings you are confident about
- Do NOT flag non-security code quality issues
- If no security issues found, say so clearly
PROMPT
)
# Set up temp files for output and diff
TEMP_OUTPUT=$(mktemp /tmp/codex-security-XXXXXX.json)
TEMP_DIFF=$(mktemp /tmp/codex-diff-XXXXXX.txt)
trap 'rm -f "$TEMP_OUTPUT" "$TEMP_DIFF"' EXIT
SCHEMA_FILE="$SCRIPT_DIR/schemas/security-review-schema.json"
# Write diff to temp file
echo "$DIFF_CONTEXT" > "$TEMP_DIFF"
echo "Running Codex security review..." >&2
echo " Diff size: $(wc -l < "$TEMP_DIFF") lines" >&2
# Build full prompt with diff reference
FULL_PROMPT="${REVIEW_PROMPT}
Here are the code changes to security review:
\`\`\`diff
$(cat "$TEMP_DIFF")
\`\`\`"
# Run codex exec with prompt from stdin to avoid arg length limits
echo "$FULL_PROMPT" | codex exec \
--sandbox read-only \
--output-schema "$SCHEMA_FILE" \
-o "$TEMP_OUTPUT" \
- 2>&1 | while IFS= read -r line; do
echo " [codex] $line" >&2
done
# Check output was produced
if [[ ! -s "$TEMP_OUTPUT" ]]; then
echo "Error: Codex produced no output" >&2
exit 1
fi
# Validate JSON
if ! jq empty "$TEMP_OUTPUT" 2>/dev/null; then
echo "Error: Codex output is not valid JSON" >&2
cat "$TEMP_OUTPUT" >&2
exit 1
fi
# Save output if requested
if [[ -n "$OUTPUT_FILE" ]]; then
cp "$TEMP_OUTPUT" "$OUTPUT_FILE"
echo "Results saved to: $OUTPUT_FILE" >&2
fi
# Post to PR if requested
if [[ "$POST_TO_PR" == true && -n "$PR_NUMBER" ]]; then
echo "Posting findings to PR #$PR_NUMBER..." >&2
post_to_pr "$PR_NUMBER" "$TEMP_OUTPUT" "security"
echo "Posted security review to PR #$PR_NUMBER" >&2
fi
# Always print results to stdout
print_results "$TEMP_OUTPUT" "security"
+200
View File
@@ -0,0 +1,200 @@
#!/bin/bash
# common.sh - Shared utilities for Codex review scripts
# Source this file from review scripts: source "$(dirname "${BASH_SOURCE[0]}")/common.sh"
set -e
CODEX_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GIT_SCRIPT_DIR="$CODEX_SCRIPT_DIR/../git"
# Source platform detection
source "$GIT_SCRIPT_DIR/detect-platform.sh"
# Check codex is installed
check_codex() {
if ! command -v codex &>/dev/null; then
echo "Error: codex CLI not found. Install with: npm i -g @openai/codex" >&2
exit 1
fi
}
# Check jq is installed (needed for JSON processing)
check_jq() {
if ! command -v jq &>/dev/null; then
echo "Error: jq not found. Install with your package manager." >&2
exit 1
fi
}
# Build the codex exec command args for the review mode
# Arguments: $1=mode (--uncommitted|--base|--commit), $2=value (branch/sha)
build_diff_context() {
local mode="$1"
local value="$2"
local diff_text=""
case "$mode" in
uncommitted)
diff_text=$(git diff HEAD 2>/dev/null; git diff --cached 2>/dev/null; git ls-files --others --exclude-standard 2>/dev/null | while read -r f; do echo "=== NEW FILE: $f ==="; cat "$f" 2>/dev/null; done)
;;
base)
diff_text=$(git diff "${value}...HEAD" 2>/dev/null)
;;
commit)
diff_text=$(git show "$value" 2>/dev/null)
;;
pr)
# Provider detection writes its result to stdout; suppress it so it cannot
# be mistaken for diff content when this function is used in a substitution.
detect_platform >/dev/null
if [[ "$PLATFORM" == "github" ]]; then
diff_text=$(gh pr diff "$value" 2>/dev/null) || {
echo "Error: Failed to fetch the diff for PR #${value}." >&2
return 1
}
elif [[ "$PLATFORM" == "gitea" ]]; then
local pr_base base_ref pr_head_ref
pr_base=$(tea pr list --fields index,base --output simple 2>/dev/null | awk -v pr="$value" '$1 == pr { print $2; exit }')
if [[ -z "$pr_base" ]]; then
echo "Error: Could not resolve the base branch for Gitea PR #${value}." >&2
return 1
fi
base_ref="refs/remotes/origin/${pr_base}"
pr_head_ref="refs/remotes/origin/pr/${value}/head"
if ! git fetch --quiet origin \
"+refs/heads/${pr_base}:${base_ref}" \
"+refs/pull/${value}/head:${pr_head_ref}"; then
echo "Error: Failed to fetch the base and head refs for Gitea PR #${value}." >&2
return 1
fi
diff_text=$(git diff "${base_ref}...${pr_head_ref}") || {
echo "Error: Failed to diff the fetched refs for Gitea PR #${value}." >&2
return 1
}
else
echo "Error: Unsupported git platform while resolving PR #${value}." >&2
return 1
fi
;;
esac
if [[ "$mode" == "pr" && -z "${diff_text//[[:space:]]/}" ]]; then
echo "Error: Unable to construct a non-empty diff for PR #${value}; verify the PR refs and provider access." >&2
return 1
fi
printf '%s\n' "$diff_text"
}
# Format JSON findings as markdown for PR comments
# Arguments: $1=json_file, $2=review_type (code|security)
format_findings_as_markdown() {
local json_file="$1"
local review_type="$2"
if [[ ! -f "$json_file" ]]; then
echo "Error: JSON file not found: $json_file" >&2
return 1
fi
local summary verdict confidence
summary=$(jq -r '.summary' "$json_file")
confidence=$(jq -r '.confidence' "$json_file")
if [[ "$review_type" == "code" ]]; then
verdict=$(jq -r '.verdict' "$json_file")
local blockers should_fix suggestions files_reviewed
blockers=$(jq -r '.stats.blockers' "$json_file")
should_fix=$(jq -r '.stats.should_fix' "$json_file")
suggestions=$(jq -r '.stats.suggestions' "$json_file")
files_reviewed=$(jq -r '.stats.files_reviewed' "$json_file")
cat <<EOF
## Codex Code Review
**Verdict:** ${verdict} | **Confidence:** ${confidence} | **Files reviewed:** ${files_reviewed}
**Findings:** ${blockers} blockers, ${should_fix} should-fix, ${suggestions} suggestions
### Summary
${summary}
EOF
else
local risk_level critical high medium low files_reviewed
risk_level=$(jq -r '.risk_level' "$json_file")
critical=$(jq -r '.stats.critical' "$json_file")
high=$(jq -r '.stats.high' "$json_file")
medium=$(jq -r '.stats.medium' "$json_file")
low=$(jq -r '.stats.low' "$json_file")
files_reviewed=$(jq -r '.stats.files_reviewed' "$json_file")
cat <<EOF
## Codex Security Review
**Risk Level:** ${risk_level} | **Confidence:** ${confidence} | **Files reviewed:** ${files_reviewed}
**Findings:** ${critical} critical, ${high} high, ${medium} medium, ${low} low
### Summary
${summary}
EOF
fi
# Output findings
local finding_count
finding_count=$(jq '.findings | length' "$json_file")
if [[ "$finding_count" -gt 0 ]]; then
echo "### Findings"
echo ""
jq -r '.findings[] | "#### [\(.severity | ascii_upcase)] \(.title)\n- **File:** `\(.file)`\(if .line_start then " (L\(.line_start)\(if .line_end and .line_end != .line_start then "-L\(.line_end)" else "" end))" else "" end)\n- \(.description)\(if .suggestion then "\n- **Suggestion:** \(.suggestion)" else "" end)\(if .cwe_id then "\n- **CWE:** \(.cwe_id)" else "" end)\(if .owasp_category then "\n- **OWASP:** \(.owasp_category)" else "" end)\(if .remediation then "\n- **Remediation:** \(.remediation)" else "" end)\n"' "$json_file"
else
echo "*No issues found.*"
fi
echo "---"
echo "*Reviewed by Codex ($(codex --version 2>/dev/null || echo "unknown"))*"
}
# Post review findings to a PR
# Arguments: $1=pr_number, $2=json_file, $3=review_type (code|security)
post_to_pr() {
local pr_number="$1"
local json_file="$2"
local review_type="$3"
local markdown
markdown=$(format_findings_as_markdown "$json_file" "$review_type")
detect_platform
# Determine review action based on findings
local action="comment"
if [[ "$review_type" == "code" ]]; then
local verdict
verdict=$(jq -r '.verdict' "$json_file")
action="$verdict"
else
local risk_level
risk_level=$(jq -r '.risk_level' "$json_file")
case "$risk_level" in
critical|high) action="request-changes" ;;
medium) action="comment" ;;
low|none) action="comment" ;;
esac
fi
# Post the review
"$GIT_SCRIPT_DIR/pr-review.sh" -n "$pr_number" -a "$action" -c "$markdown"
}
# Print review results to stdout
# Arguments: $1=json_file, $2=review_type (code|security)
print_results() {
local json_file="$1"
local review_type="$2"
format_findings_as_markdown "$json_file" "$review_type"
}
@@ -0,0 +1,92 @@
{
"type": "object",
"additionalProperties": false,
"properties": {
"summary": {
"type": "string",
"description": "Brief overall assessment of the code changes"
},
"verdict": {
"type": "string",
"enum": ["approve", "request-changes", "comment"],
"description": "Overall review verdict"
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Confidence score for the review (0-1)"
},
"findings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"severity": {
"type": "string",
"enum": ["blocker", "should-fix", "suggestion"],
"description": "Finding severity: blocker (must fix), should-fix (important), suggestion (optional)"
},
"title": {
"type": "string",
"description": "Short title describing the issue"
},
"file": {
"type": "string",
"description": "File path where the issue was found"
},
"line_start": {
"type": "integer",
"description": "Starting line number"
},
"line_end": {
"type": "integer",
"description": "Ending line number"
},
"description": {
"type": "string",
"description": "Detailed explanation of the issue"
},
"suggestion": {
"type": "string",
"description": "Suggested fix or improvement"
}
},
"required": [
"severity",
"title",
"file",
"line_start",
"line_end",
"description",
"suggestion"
]
}
},
"stats": {
"type": "object",
"additionalProperties": false,
"properties": {
"files_reviewed": {
"type": "integer",
"description": "Number of files reviewed"
},
"blockers": {
"type": "integer",
"description": "Count of blocker findings"
},
"should_fix": {
"type": "integer",
"description": "Count of should-fix findings"
},
"suggestions": {
"type": "integer",
"description": "Count of suggestion findings"
}
},
"required": ["files_reviewed", "blockers", "should_fix", "suggestions"]
}
},
"required": ["summary", "verdict", "confidence", "findings", "stats"]
}
@@ -0,0 +1,106 @@
{
"type": "object",
"additionalProperties": false,
"properties": {
"summary": {
"type": "string",
"description": "Brief overall security assessment of the code changes"
},
"risk_level": {
"type": "string",
"enum": ["critical", "high", "medium", "low", "none"],
"description": "Overall security risk level"
},
"confidence": {
"type": "number",
"minimum": 0,
"maximum": 1,
"description": "Confidence score for the review (0-1)"
},
"findings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"severity": {
"type": "string",
"enum": ["critical", "high", "medium", "low"],
"description": "Vulnerability severity level"
},
"title": {
"type": "string",
"description": "Short title describing the vulnerability"
},
"file": {
"type": "string",
"description": "File path where the vulnerability was found"
},
"line_start": {
"type": "integer",
"description": "Starting line number"
},
"line_end": {
"type": "integer",
"description": "Ending line number"
},
"description": {
"type": "string",
"description": "Detailed explanation of the vulnerability"
},
"cwe_id": {
"type": "string",
"description": "CWE identifier if applicable (e.g., CWE-79)"
},
"owasp_category": {
"type": "string",
"description": "OWASP Top 10 category if applicable (e.g., A03:2021-Injection)"
},
"remediation": {
"type": "string",
"description": "Specific remediation steps to fix the vulnerability"
}
},
"required": [
"severity",
"title",
"file",
"line_start",
"line_end",
"description",
"cwe_id",
"owasp_category",
"remediation"
]
}
},
"stats": {
"type": "object",
"additionalProperties": false,
"properties": {
"files_reviewed": {
"type": "integer",
"description": "Number of files reviewed"
},
"critical": {
"type": "integer",
"description": "Count of critical findings"
},
"high": {
"type": "integer",
"description": "Count of high findings"
},
"medium": {
"type": "integer",
"description": "Count of medium findings"
},
"low": {
"type": "integer",
"description": "Count of low findings"
}
},
"required": ["files_reviewed", "critical", "high", "medium", "low"]
}
},
"required": ["summary", "risk_level", "confidence", "findings", "stats"]
}
@@ -0,0 +1,158 @@
#!/bin/bash
# Hermetic regression coverage for Gitea PR diff construction and fail-closed reviews.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT
fail() {
echo "not ok - $*" >&2
exit 1
}
assert_contains() {
local haystack="$1" needle="$2"
if [[ "$haystack" != *"$needle"* ]]; then
printf 'actual output:\n%s\n' "$haystack" >&2
fail "expected output to contain: $needle"
fi
}
# Prevent CI-provided repository context from leaking into the fixture repositories.
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY \
GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_COMMON_DIR
export GIT_AUTHOR_NAME="Codex Fixture"
export GIT_AUTHOR_EMAIL="[email protected]"
export GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"
export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"
export GITEA_LOGIN="fixture"
export GITEA_TOKEN="fixture-token"
export GITEA_URL="file://$TMP_DIR"
create_pr_fixture() {
local fixture_root="$1" head_mode="$2"
local origin="$fixture_root/origin.git"
local seed="$fixture_root/seed"
local work="$fixture_root/work"
local base_sha head_sha
mkdir -p "$fixture_root"
git init --quiet --bare "$origin"
git init --quiet --initial-branch=release/next "$seed"
printf 'base\n' > "$seed/pr-change.ts"
git -C "$seed" add pr-change.ts
git -C "$seed" commit --quiet -m "fixture base"
base_sha=$(git -C "$seed" rev-parse HEAD)
git -C "$seed" remote add origin "$origin"
git -C "$seed" push --quiet origin release/next
git --git-dir="$origin" symbolic-ref HEAD refs/heads/release/next
if [[ "$head_mode" == "changed" ]]; then
git -C "$seed" switch --quiet -c feature/pr-795
printf 'actual-pr-change\n' > "$seed/pr-change.ts"
git -C "$seed" commit --quiet -am "fixture PR head"
head_sha=$(git -C "$seed" rev-parse HEAD)
git -C "$seed" push --quiet origin HEAD:refs/pull/795/head
else
head_sha="$base_sha"
git --git-dir="$origin" update-ref refs/pull/795/head "$head_sha"
fi
# Gitea's provider-owned PR head ref now exists in the local bare origin.
git clone --quiet "$origin" "$work"
printf '%s\n' "$work"
}
FAKE_BIN="$TMP_DIR/bin"
mkdir -p "$FAKE_BIN"
cat > "$FAKE_BIN/tea" <<'STUB'
#!/bin/bash
if [[ "$*" == "pr list --fields index,base --output simple" ]]; then
printf '795 release/next\n'
exit 0
fi
exit 1
STUB
cat > "$FAKE_BIN/codex" <<'STUB'
#!/bin/bash
printf 'CODEX %s\n' "$*" >> "$CODEX_LOG"
exit 99
STUB
chmod +x "$FAKE_BIN/tea" "$FAKE_BIN/codex"
export PATH="$FAKE_BIN:$PATH"
# The valid fixture is a fresh clone on the non-main base. The PR head exists only
# at refs/pull/795/head, so local HEAD cannot accidentally satisfy the assertion.
if [[ "${1:-all}" != "fail-closed" ]]; then
VALID_WORK=$(create_pr_fixture "$TMP_DIR/valid" changed)
(
cd "$VALID_WORK"
# shellcheck source=common.sh
source "$SCRIPT_DIR/common.sh"
diff_context=$(build_diff_context pr 795)
assert_contains "$diff_context" "actual-pr-change"
base_sha=$(git rev-parse refs/remotes/origin/release/next)
head_sha=$(git rev-parse refs/remotes/origin/pr/795/head)
local_sha=$(git rev-parse HEAD)
[[ "$local_sha" == "$base_sha" ]] || fail "fixture clone is not on the PR base"
[[ "$head_sha" != "$base_sha" ]] || fail "fixture PR head does not differ from its base"
git show-ref --verify --quiet refs/remotes/origin/pr/795/head || \
fail "fetched PR head ref is missing"
[[ "$(git diff --name-only "${base_sha}...${head_sha}")" == "pr-change.ts" ]] || \
fail "explicit PR refs do not contain the fixture change"
if git show-ref --verify --quiet refs/heads/main || \
git show-ref --verify --quiet refs/remotes/origin/main; then
fail "fixture unexpectedly contains a main ref"
fi
)
echo "ok - Gitea PR mode fetches and diffs explicit non-main base and PR head refs"
fi
# Build an empty PR entirely inside another local repository. Both review wrappers
# must emit the PR-numbered error before Codex or the stubbed post path can execute.
if [[ "${1:-all}" != "pr-head" ]]; then
EMPTY_WORK=$(create_pr_fixture "$TMP_DIR/empty" empty)
SANDBOX="$TMP_DIR/sandbox"
mkdir -p "$SANDBOX/tools/codex/schemas" "$SANDBOX/tools/git"
cp "$SCRIPT_DIR/common.sh" \
"$SCRIPT_DIR/codex-code-review.sh" \
"$SCRIPT_DIR/codex-security-review.sh" \
"$SANDBOX/tools/codex/"
cp "$SCRIPT_DIR/schemas/code-review-schema.json" \
"$SCRIPT_DIR/schemas/security-review-schema.json" \
"$SANDBOX/tools/codex/schemas/"
cp "$SCRIPT_DIR/../git/detect-platform.sh" "$SANDBOX/tools/git/"
cat > "$SANDBOX/tools/git/pr-review.sh" <<'STUB'
#!/bin/bash
printf 'POST %s\n' "$*" >> "$POST_LOG"
STUB
chmod +x "$SANDBOX/tools/git/pr-review.sh"
POST_LOG="$TMP_DIR/post.log"
CODEX_LOG="$TMP_DIR/codex.log"
export POST_LOG CODEX_LOG
for review_kind in code security; do
: > "$POST_LOG"
: > "$CODEX_LOG"
review_script="$SANDBOX/tools/codex/codex-${review_kind}-review.sh"
set +e
(
cd "$EMPTY_WORK"
"$review_script" -n 795
) >"$TMP_DIR/${review_kind}.stdout" 2>"$TMP_DIR/${review_kind}.stderr"
review_status=$?
set -e
stderr_text=$(cat "$TMP_DIR/${review_kind}.stderr")
[[ "$review_status" -ne 0 ]] || fail "${review_kind} review returned success for an empty PR diff"
[[ ! -s "$CODEX_LOG" ]] || fail "Codex ran for an empty ${review_kind} PR diff"
[[ ! -s "$POST_LOG" ]] || fail "${review_kind} review auto-post ran for an empty PR diff"
assert_contains "$stderr_text" "Error:"
assert_contains "$stderr_text" "PR #795"
echo "ok - empty ${review_kind} PR diff fails closed before Codex and auto-post"
done
fi
@@ -0,0 +1,90 @@
# Codex AI Review Pipeline for Woodpecker CI
# Drop this into your repo's .woodpecker/ directory to enable automated
# code and security reviews on every pull request.
#
# Required secrets:
# - codex_api_key: OpenAI API key or Codex-compatible key
#
# Optional secrets:
# - gitea_token: Gitea API token for posting PR comments (if not using tea CLI auth)
when:
event: pull_request
variables:
- &node_image 'node:22-slim'
- &install_codex 'npm i -g @openai/codex'
steps:
# --- Code Quality Review ---
code-review:
image: *node_image
environment:
CODEX_API_KEY:
from_secret: codex_api_key
commands:
- *install_codex
- apt-get update -qq && apt-get install -y -qq jq git > /dev/null 2>&1
# Generate the diff
- git fetch origin ${CI_COMMIT_TARGET_BRANCH:-main}
- DIFF=$(git diff origin/${CI_COMMIT_TARGET_BRANCH:-main}...HEAD)
# Run code review with structured output
- |
codex exec \
--sandbox read-only \
--output-schema .woodpecker/schemas/code-review-schema.json \
-o /tmp/code-review.json \
"You are an expert code reviewer. Review the following code changes for correctness, code quality, testing, performance, and documentation issues. Only flag actionable, important issues. Categorize as blocker/should-fix/suggestion. If code looks good, say so.
Changes:
$DIFF"
# Output summary
- echo "=== Code Review Results ==="
- jq '.' /tmp/code-review.json
- |
BLOCKERS=$(jq '.stats.blockers // 0' /tmp/code-review.json)
if [ "$BLOCKERS" -gt 0 ]; then
echo "FAIL: $BLOCKERS blocker(s) found"
exit 1
fi
echo "PASS: No blockers found"
# --- Security Review ---
security-review:
image: *node_image
environment:
CODEX_API_KEY:
from_secret: codex_api_key
commands:
- *install_codex
- apt-get update -qq && apt-get install -y -qq jq git > /dev/null 2>&1
# Generate the diff
- git fetch origin ${CI_COMMIT_TARGET_BRANCH:-main}
- DIFF=$(git diff origin/${CI_COMMIT_TARGET_BRANCH:-main}...HEAD)
# Run security review with structured output
- |
codex exec \
--sandbox read-only \
--output-schema .woodpecker/schemas/security-review-schema.json \
-o /tmp/security-review.json \
"You are an expert application security engineer. Review the following code changes for security vulnerabilities including OWASP Top 10, hardcoded secrets, injection flaws, auth/authz gaps, XSS, CSRF, SSRF, path traversal, and supply chain risks. Include CWE IDs and remediation steps. Only flag real security issues, not code quality.
Changes:
$DIFF"
# Output summary
- echo "=== Security Review Results ==="
- jq '.' /tmp/security-review.json
- |
CRITICAL=$(jq '.stats.critical // 0' /tmp/security-review.json)
HIGH=$(jq '.stats.high // 0' /tmp/security-review.json)
if [ "$CRITICAL" -gt 0 ] || [ "$HIGH" -gt 0 ]; then
echo "FAIL: $CRITICAL critical, $HIGH high severity finding(s)"
exit 1
fi
echo "PASS: No critical or high severity findings"
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# mosaic-context-loader.sh — SessionStart hook for Claude Code
# Injects mandatory Mosaic config files into agent context at session init.
# Stdout from this script is added to Claude's context before processing.
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
# Mandatory load order (per AGENTS.md contract)
MANDATORY_FILES=(
"$MOSAIC_HOME/SOUL.md"
"$MOSAIC_HOME/USER.md"
"$MOSAIC_HOME/STANDARDS.md"
"$MOSAIC_HOME/AGENTS.md"
"$MOSAIC_HOME/TOOLS.md"
)
# E2E delivery guide (canonical uppercase path)
E2E_DELIVERY=""
for candidate in \
"$MOSAIC_HOME/guides/E2E-DELIVERY.md"; do
if [[ -f "$candidate" ]]; then
E2E_DELIVERY="$candidate"
break
fi
done
# Runtime-specific reference
RUNTIME_FILE="$MOSAIC_HOME/runtime/claude/RUNTIME.md"
# Project-local AGENTS.md (cwd at session start)
PROJECT_AGENTS=""
if [[ -f "./AGENTS.md" ]]; then
PROJECT_AGENTS="./AGENTS.md"
fi
emit_file() {
local filepath="$1"
local label="${2:-$(basename "$filepath")}"
if [[ -f "$filepath" ]]; then
echo "=== MOSAIC: $label ==="
cat "$filepath"
echo ""
fi
}
echo "=== MOSAIC CONTEXT INJECTION (SessionStart) ==="
echo ""
for f in "${MANDATORY_FILES[@]}"; do
emit_file "$f"
done
if [[ -n "$E2E_DELIVERY" ]]; then
emit_file "$E2E_DELIVERY" "E2E-DELIVERY.md"
fi
if [[ -n "$PROJECT_AGENTS" ]]; then
emit_file "$PROJECT_AGENTS" "Project AGENTS.md ($(pwd))"
fi
emit_file "$RUNTIME_FILE" "Claude RUNTIME.md"
echo "=== END MOSAIC CONTEXT INJECTION ==="
@@ -0,0 +1,66 @@
# Coolify Tool Suite
Manage Coolify container deployment platform (projects, services, deployments, environment variables).
## Prerequisites
- `jq` and `curl` installed
- Coolify credentials in `~/.config/mosaic/credentials.json` (or `$MOSAIC_CREDENTIALS_FILE`)
- Required fields: `coolify.url`, `coolify.app_token`
## Scripts
| Script | Purpose |
| ------------------- | ------------------------------------- |
| `team-list.sh` | List teams |
| `project-list.sh` | List projects |
| `service-list.sh` | List all services |
| `service-status.sh` | Get service details and status |
| `deploy.sh` | Trigger service deployment |
| `env-set.sh` | Set environment variable on a service |
## Common Options
- `-f json` — JSON output (default: table)
- `-u uuid` — Service UUID (for service-specific operations)
- `-h` — Show help
## API Reference
- Base URL: `http://coolify.example.internal:8000`
- API prefix: `/api/v1/`
- Auth: Bearer token in `Authorization` header
- Rate limit: 200 requests per interval
## Known Limitations
- **FQDN updates on compose sub-apps not supported via API.** Workaround: update directly in Coolify's PostgreSQL DB (`coolify-db` container, `service_applications` table).
- **Compose must be base64-encoded** in `docker_compose_raw` field when creating services via API.
- **Don't send `type` with `docker_compose_raw`** — API rejects payloads with both fields.
## Coolify Magic Variables
Coolify reads special env vars from compose files:
- `SERVICE_FQDN_{NAME}_{PORT}` — assigns a domain to a compose service
- `SERVICE_URL_{NAME}_{PORT}` — internal URL reference
- Must use list-style env syntax (`- SERVICE_FQDN_API_3001`), NOT dict-style.
## Examples
```bash
# List all projects
~/.config/mosaic/tools/coolify/project-list.sh
# List services as JSON
~/.config/mosaic/tools/coolify/service-list.sh -f json
# Check service status
~/.config/mosaic/tools/coolify/service-status.sh -u <uuid>
# Set an env var
~/.config/mosaic/tools/coolify/env-set.sh -u <uuid> -k DATABASE_URL -v "postgres://..."
# Deploy a service
~/.config/mosaic/tools/coolify/deploy.sh -u <uuid>
```
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
#
# deploy.sh — Trigger Coolify service deployment
#
# Usage: deploy.sh -u <uuid> [-f]
#
# Options:
# -u uuid Service UUID (required)
# -f Force restart (stop then start)
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
UUID=""
FORCE=false
while getopts "u:fh" opt; do
case $opt in
u) UUID="$OPTARG" ;;
f) FORCE=true ;;
h) head -11 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -u <uuid> [-f]" >&2; exit 1 ;;
esac
done
if [[ -z "$UUID" ]]; then
echo "Error: -u uuid is required" >&2
exit 1
fi
if [[ "$FORCE" == "true" ]]; then
echo "Stopping service $UUID..."
curl -s -o /dev/null -w "" \
-X POST \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/services/${UUID}/stop"
sleep 2
fi
echo "Starting service $UUID..."
response=$(curl -s -w "\n%{http_code}" \
-X POST \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/services/${UUID}/start")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" && "$http_code" != "201" && "$http_code" != "202" ]]; then
echo "Error: Deployment failed (HTTP $http_code)" >&2
echo "$body" | jq -r '.' 2>/dev/null >&2 || echo "$body" >&2
exit 1
fi
echo "Deployment triggered successfully for service $UUID"
echo "$body" | jq -r '.message // empty' 2>/dev/null || true
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
#
# env-set.sh — Set environment variable on a Coolify service
#
# Usage: env-set.sh -u <uuid> -k <key> -v <value> [--preview]
#
# Options:
# -u uuid Service UUID (required)
# -k key Environment variable name (required)
# -v value Environment variable value (required)
# --preview Set as preview-only variable
# -h Show this help
#
# Note: Changes take effect on next deploy/restart.
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
UUID=""
KEY=""
VALUE=""
IS_PREVIEW="false"
while [[ $# -gt 0 ]]; do
case $1 in
-u) UUID="$2"; shift 2 ;;
-k) KEY="$2"; shift 2 ;;
-v) VALUE="$2"; shift 2 ;;
--preview) IS_PREVIEW="true"; shift ;;
-h) head -15 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -u <uuid> -k <key> -v <value> [--preview]" >&2; exit 1 ;;
esac
done
if [[ -z "$UUID" || -z "$KEY" || -z "$VALUE" ]]; then
echo "Error: -u uuid, -k key, and -v value are required" >&2
exit 1
fi
payload=$(jq -n \
--arg key "$KEY" \
--arg value "$VALUE" \
--argjson preview "$IS_PREVIEW" \
'{key: $key, value: $value, is_preview: $preview}')
response=$(curl -s -w "\n%{http_code}" \
-X PATCH \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
-d "$payload" \
"${COOLIFY_URL}/api/v1/services/${UUID}/envs")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" && "$http_code" != "201" ]]; then
echo "Error: Failed to set environment variable (HTTP $http_code)" >&2
echo "$body" | jq -r '.' 2>/dev/null >&2 || echo "$body" >&2
exit 1
fi
echo "Set $KEY on service $UUID"
echo "Note: Redeploy the service to apply the change"
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
#
# project-list.sh — List Coolify projects
#
# Usage: project-list.sh [-f format]
#
# Options:
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
FORMAT="table"
while getopts "f:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
h) head -10 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format]" >&2; exit 1 ;;
esac
done
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/projects")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list projects (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
exit 0
fi
echo "UUID NAME DESCRIPTION"
echo "------------------------------------ ---------------------------- ----------------------------------------"
echo "$body" | jq -r '.[] | [
.uuid,
.name,
(.description // "—")
] | @tsv' | while IFS=$'\t' read -r uuid name desc; do
printf "%-36s %-28s %s\n" "$uuid" "${name:0:28}" "${desc:0:40}"
done
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
#
# service-list.sh — List Coolify services
#
# Usage: service-list.sh [-f format]
#
# Options:
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
FORMAT="table"
while getopts "f:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
h) head -10 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format]" >&2; exit 1 ;;
esac
done
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/services")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list services (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
exit 0
fi
echo "UUID NAME TYPE STATUS"
echo "------------------------------------ ---------------------------- ------------ ----------"
echo "$body" | jq -r '.[] | [
.uuid,
.name,
(.type // "unknown"),
(.status // "unknown")
] | @tsv' | while IFS=$'\t' read -r uuid name type status; do
printf "%-36s %-28s %-12s %s\n" "$uuid" "${name:0:28}" "${type:0:12}" "$status"
done
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
#
# service-status.sh — Get Coolify service status and details
#
# Usage: service-status.sh -u <uuid> [-f format]
#
# Options:
# -u uuid Service UUID (required)
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
UUID=""
FORMAT="table"
while getopts "u:f:h" opt; do
case $opt in
u) UUID="$OPTARG" ;;
f) FORMAT="$OPTARG" ;;
h) head -12 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 -u <uuid> [-f format]" >&2; exit 1 ;;
esac
done
if [[ -z "$UUID" ]]; then
echo "Error: -u uuid is required" >&2
exit 1
fi
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/services/${UUID}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to get service status (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
exit 0
fi
echo "Service Details"
echo "==============="
echo "$body" | jq -r '
" UUID: \(.uuid)\n" +
" Name: \(.name)\n" +
" Type: \(.type // "unknown")\n" +
" Status: \(.status // "unknown")\n" +
" FQDN: \(.fqdn // "none")\n" +
" Created: \(.created_at // "unknown")\n" +
" Updated: \(.updated_at // "unknown")"
'
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env bash
#
# team-list.sh — List Coolify teams
#
# Usage: team-list.sh [-f format]
#
# Options:
# -f format Output format: table (default), json
# -h Show this help
set -euo pipefail
MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials coolify
FORMAT="table"
while getopts "f:h" opt; do
case $opt in
f) FORMAT="$OPTARG" ;;
h) head -10 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
*) echo "Usage: $0 [-f format]" >&2; exit 1 ;;
esac
done
response=$(curl -s -w "\n%{http_code}" \
-H "Authorization: Bearer $COOLIFY_TOKEN" \
-H "Content-Type: application/json" \
"${COOLIFY_URL}/api/v1/teams")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')
if [[ "$http_code" != "200" ]]; then
echo "Error: Failed to list teams (HTTP $http_code)" >&2
exit 1
fi
if [[ "$FORMAT" == "json" ]]; then
echo "$body" | jq '.'
exit 0
fi
echo "ID NAME DESCRIPTION"
echo "---- ---------------------------- ----------------------------------------"
echo "$body" | jq -r '.[] | [
(.id | tostring),
.name,
(.description // "—")
] | @tsv' | while IFS=$'\t' read -r id name desc; do
printf "%-4s %-28s %s\n" "$id" "${name:0:28}" "${desc:0:40}"
done
@@ -0,0 +1 @@
node_modules/
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# Launcher for Excalidraw MCP stdio server.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec node --loader "$SCRIPT_DIR/loader.mjs" "$SCRIPT_DIR/server.mjs"
@@ -0,0 +1,76 @@
/**
* Custom ESM loader to fix missing .js extensions in @excalidraw/excalidraw deps.
*
* Problems patched:
* 1. excalidraw imports 'roughjs/bin/rough' (and other roughjs/* paths) without .js
* 2. roughjs/* files import sibling modules as './canvas' (relative, no .js)
* 3. JSON files need { type: 'json' } import attribute in Node.js v22+
*
* Usage: node --loader ./loader.mjs server.mjs [args...]
*/
import { fileURLToPath, pathToFileURL } from 'url';
import { dirname, resolve as pathResolve } from 'path';
const __dirname = dirname(fileURLToPath(import.meta.url));
// Modules that have incompatible ESM format — redirect to local stubs
const STUBS = {
'@excalidraw/laser-pointer': pathToFileURL(pathResolve(__dirname, 'stubs/laser-pointer.mjs')).href,
};
export async function resolve(specifier, context, nextResolve) {
// 0. Module stubs (incompatible ESM format packages)
if (STUBS[specifier]) {
return { url: STUBS[specifier], shortCircuit: true };
}
// 1. Bare roughjs/* specifiers without .js extension
if (/^roughjs\/bin\/[a-z-]+$/.test(specifier)) {
return nextResolve(`${specifier}.js`, context);
}
// 2. Relative imports without extension (e.g. './canvas' from roughjs/bin/rough.js)
// These come in as relative paths that resolve to extensionless file URLs.
if (specifier.startsWith('./') || specifier.startsWith('../')) {
// Try resolving first; if it fails with a missing-extension error, add .js
try {
return await nextResolve(specifier, context);
} catch (err) {
if (err.code === 'ERR_MODULE_NOT_FOUND') {
// Try appending .js
try {
return await nextResolve(`${specifier}.js`, context);
} catch {
// Fall through to original error
}
}
throw err;
}
}
// 3. JSON imports need type: 'json' attribute
if (specifier.endsWith('.json')) {
const resolved = await nextResolve(specifier, context);
if (!resolved.importAttributes?.type) {
return {
...resolved,
importAttributes: { ...resolved.importAttributes, type: 'json' },
};
}
return resolved;
}
return nextResolve(specifier, context);
}
export async function load(url, context, nextLoad) {
// Ensure JSON files are loaded with json format
if (url.endsWith('.json')) {
return nextLoad(url, {
...context,
importAttributes: { ...context.importAttributes, type: 'json' },
});
}
return nextLoad(url, context);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
{
"name": "excalidraw-mcp",
"version": "1.0.0",
"type": "module",
"private": true,
"dependencies": {
"@modelcontextprotocol/sdk": "^1.12.0",
"@excalidraw/excalidraw": "^0.18.0",
"jsdom": "^25.0.1"
}
}
@@ -0,0 +1,323 @@
#!/usr/bin/env node
/**
* Excalidraw MCP stdio server
* Provides headless .excalidraw → SVG export via @excalidraw/excalidraw.
* Optional: diagram generation via EXCALIDRAW_GEN_PATH (excalidraw_gen.py).
*/
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod/v3";
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { spawnSync } from 'child_process';
import { JSDOM } from 'jsdom';
// ---------------------------------------------------------------------------
// 1. DOM environment — must be established BEFORE importing excalidraw
// ---------------------------------------------------------------------------
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
url: 'http://localhost/',
pretendToBeVisual: true,
});
const { window } = dom;
// Helper: define a global, overriding read-only getters (e.g. navigator in Node v22)
function defineGlobal(key, value) {
if (value === undefined) return;
try {
Object.defineProperty(global, key, {
value,
writable: true,
configurable: true,
});
} catch {
// Already defined and non-configurable — skip
}
}
// Core DOM globals
defineGlobal('window', window);
defineGlobal('document', window.document);
defineGlobal('navigator', window.navigator);
defineGlobal('location', window.location);
defineGlobal('history', window.history);
defineGlobal('screen', window.screen);
// Element / event interfaces
for (const key of [
'Node', 'Element', 'HTMLElement', 'SVGElement', 'SVGSVGElement',
'HTMLCanvasElement', 'HTMLImageElement', 'Image',
'Event', 'CustomEvent', 'MouseEvent', 'PointerEvent',
'KeyboardEvent', 'TouchEvent', 'WheelEvent', 'InputEvent',
'MutationObserver', 'ResizeObserver', 'IntersectionObserver',
'XMLHttpRequest', 'XMLSerializer',
'DOMParser', 'Range',
'getComputedStyle', 'matchMedia',
]) {
defineGlobal(key, window[key]);
}
// Animation frame stubs (jsdom doesn't implement them)
global.requestAnimationFrame = (fn) => setTimeout(() => fn(Date.now()), 0);
global.cancelAnimationFrame = (id) => clearTimeout(id);
// CSS Font Loading API stub — jsdom doesn't implement FontFace
class FontFaceStub {
constructor(family, source, _descriptors) {
this.family = family;
this.source = source;
this.status = 'loaded';
this.loaded = Promise.resolve(this);
}
load() { return Promise.resolve(this); }
}
defineGlobal('FontFace', FontFaceStub);
// FontFaceSet stub for document.fonts
const fontFaceSet = {
add: () => {},
delete: () => {},
has: () => false,
clear: () => {},
load: () => Promise.resolve([]),
check: () => true,
ready: Promise.resolve(),
status: 'loaded',
forEach: () => {},
[Symbol.iterator]: function*() {},
};
Object.defineProperty(window.document, 'fonts', {
value: fontFaceSet,
writable: true,
configurable: true,
});
// Canvas stub — excalidraw's exportToSvg doesn't need real canvas rendering,
// but the class must exist for isinstance checks.
if (!global.HTMLCanvasElement) {
defineGlobal('HTMLCanvasElement', window.HTMLCanvasElement ?? class HTMLCanvasElement {});
}
// Device pixel ratio
global.devicePixelRatio = 1;
// ---------------------------------------------------------------------------
// 1b. Stub canvas getContext — excalidraw calls this at module init time.
// jsdom throws "Not implemented" by default; we return a no-op 2D stub.
// ---------------------------------------------------------------------------
const _canvasCtx = {
canvas: { width: 800, height: 600 },
fillRect: () => {}, clearRect: () => {}, strokeRect: () => {},
getImageData: (x, y, w, h) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }),
putImageData: () => {}, createImageData: () => ({ data: new Uint8ClampedArray(0) }),
setTransform: () => {}, resetTransform: () => {}, transform: () => {},
drawImage: () => {}, save: () => {}, restore: () => {},
scale: () => {}, rotate: () => {}, translate: () => {},
beginPath: () => {}, closePath: () => {}, moveTo: () => {}, lineTo: () => {},
bezierCurveTo: () => {}, quadraticCurveTo: () => {},
arc: () => {}, arcTo: () => {}, ellipse: () => {}, rect: () => {},
fill: () => {}, stroke: () => {}, clip: () => {},
fillText: () => {}, strokeText: () => {},
measureText: (t) => ({ width: t.length * 8, actualBoundingBoxAscent: 12, actualBoundingBoxDescent: 3, fontBoundingBoxAscent: 14, fontBoundingBoxDescent: 4 }),
createLinearGradient: () => ({ addColorStop: () => {} }),
createRadialGradient: () => ({ addColorStop: () => {} }),
createPattern: () => null,
setLineDash: () => {}, getLineDash: () => [],
isPointInPath: () => false, isPointInStroke: () => false,
getContextAttributes: () => ({ alpha: true, desynchronized: false }),
font: '10px sans-serif', fillStyle: '#000', strokeStyle: '#000',
lineWidth: 1, lineCap: 'butt', lineJoin: 'miter',
textAlign: 'start', textBaseline: 'alphabetic',
globalAlpha: 1, globalCompositeOperation: 'source-over',
shadowOffsetX: 0, shadowOffsetY: 0, shadowBlur: 0, shadowColor: 'transparent',
miterLimit: 10, lineDashOffset: 0, filter: 'none', imageSmoothingEnabled: true,
};
// Patch before excalidraw import so module-level canvas calls get the stub
if (window.HTMLCanvasElement) {
window.HTMLCanvasElement.prototype.getContext = function (type) {
if (type === '2d') return _canvasCtx;
return null;
};
}
// ---------------------------------------------------------------------------
// 2. Load excalidraw (dynamic import so globals are set first)
// ---------------------------------------------------------------------------
let exportToSvg;
try {
const excalidraw = await import('@excalidraw/excalidraw');
exportToSvg = excalidraw.exportToSvg;
if (!exportToSvg) throw new Error('exportToSvg not found in package exports');
} catch (err) {
process.stderr.write(`FATAL: Failed to load @excalidraw/excalidraw: ${err.message}\n`);
process.exit(1);
}
// ---------------------------------------------------------------------------
// 3. SVG export helper
// ---------------------------------------------------------------------------
async function renderToSvg(elements, appState, files) {
const svgEl = await exportToSvg({
elements: elements ?? [],
appState: {
exportWithDarkMode: false,
exportBackground: true,
viewBackgroundColor: '#ffffff',
...appState,
},
files: files ?? {},
});
const serializer = new window.XMLSerializer();
return serializer.serializeToString(svgEl);
}
// ---------------------------------------------------------------------------
// 4. Gen subprocess helper (optional — requires EXCALIDRAW_GEN_PATH)
// ---------------------------------------------------------------------------
function requireGenPath() {
const p = process.env.EXCALIDRAW_GEN_PATH;
if (!p) {
return null;
}
return p;
}
function spawnGen(args) {
const genPath = requireGenPath();
if (!genPath) {
return {
ok: false,
text: 'EXCALIDRAW_GEN_PATH is not set. Set it to the path of excalidraw_gen.py to use diagram generation.',
};
}
const result = spawnSync('python3', [genPath, ...args], { encoding: 'utf8' });
if (result.error) return { ok: false, text: `spawn error: ${result.error.message}` };
if (result.status !== 0) return { ok: false, text: result.stderr || 'subprocess failed' };
return { ok: true, text: result.stdout.trim() };
}
// ---------------------------------------------------------------------------
// 5. MCP Server
// ---------------------------------------------------------------------------
const server = new McpServer({
name: "excalidraw",
version: "1.0.0",
});
// --- Tool: excalidraw_to_svg ---
server.tool(
"excalidraw_to_svg",
"Convert Excalidraw elements JSON to SVG string",
{
elements: z.string().describe("JSON string of Excalidraw elements array"),
app_state: z.string().optional().describe("JSON string of appState overrides"),
},
async ({ elements, app_state }) => {
let parsed;
try {
parsed = JSON.parse(elements);
} catch (err) {
throw new Error(`Invalid elements JSON: ${err.message}`);
}
const appState = app_state ? JSON.parse(app_state) : {};
const svg = await renderToSvg(parsed, appState, {});
return { content: [{ type: "text", text: svg }] };
}
);
// --- Tool: excalidraw_file_to_svg ---
server.tool(
"excalidraw_file_to_svg",
"Convert an .excalidraw file to SVG (writes .svg alongside the input file)",
{
file_path: z.string().describe("Absolute or relative path to .excalidraw file"),
},
async ({ file_path }) => {
const absPath = resolve(file_path);
if (!existsSync(absPath)) {
throw new Error(`File not found: ${absPath}`);
}
const raw = JSON.parse(readFileSync(absPath, 'utf8'));
const svg = await renderToSvg(raw.elements, raw.appState, raw.files);
const outPath = absPath.replace(/\.excalidraw$/, '.svg');
writeFileSync(outPath, svg, 'utf8');
return {
content: [{ type: "text", text: `SVG written to: ${outPath}\n\n${svg}` }],
};
}
);
// --- Tool: list_diagrams ---
server.tool(
"list_diagrams",
"List available diagram templates from the DIAGRAMS registry (requires EXCALIDRAW_GEN_PATH)",
{},
async () => {
const res = spawnGen(['--list']);
return { content: [{ type: "text", text: res.text }] };
}
);
// --- Tool: generate_diagram ---
server.tool(
"generate_diagram",
"Generate an .excalidraw file from a named diagram template (requires EXCALIDRAW_GEN_PATH)",
{
name: z.string().describe("Diagram template name (from list_diagrams)"),
output_path: z.string().optional().describe("Output path for the .excalidraw file"),
},
async ({ name, output_path }) => {
const args = [name];
if (output_path) args.push('--output', output_path);
const res = spawnGen(args);
if (!res.ok) throw new Error(res.text);
return { content: [{ type: "text", text: res.text }] };
}
);
// --- Tool: generate_and_export ---
server.tool(
"generate_and_export",
"Generate an .excalidraw file and immediately export it to SVG (requires EXCALIDRAW_GEN_PATH)",
{
name: z.string().describe("Diagram template name (from list_diagrams)"),
output_path: z.string().optional().describe("Output path for the .excalidraw file (SVG written alongside)"),
},
async ({ name, output_path }) => {
const genArgs = [name];
if (output_path) genArgs.push('--output', output_path);
const genRes = spawnGen(genArgs);
if (!genRes.ok) throw new Error(genRes.text);
const excalidrawPath = genRes.text;
if (!existsSync(excalidrawPath)) {
throw new Error(`Generated file not found: ${excalidrawPath}`);
}
const raw = JSON.parse(readFileSync(excalidrawPath, 'utf8'));
const svg = await renderToSvg(raw.elements, raw.appState, raw.files);
const svgPath = excalidrawPath.replace(/\.excalidraw$/, '.svg');
writeFileSync(svgPath, svg, 'utf8');
return {
content: [{ type: "text", text: `Generated: ${excalidrawPath}\nExported SVG: ${svgPath}` }],
};
}
);
// --- Start ---
const transport = new StdioServerTransport();
await server.connect(transport);
@@ -0,0 +1,7 @@
/**
* Stub for @excalidraw/laser-pointer
* The real package uses a Parcel bundle format that Node.js ESM can't consume.
* For headless SVG export, the laser pointer feature is not needed.
*/
export class LaserPointer {}
export default { LaserPointer };
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
AGENT_NAME=${MOSAIC_AGENT_NAME:-}
RUNTIME=${MOSAIC_AGENT_RUNTIME:-}
MODEL=${MOSAIC_AGENT_MODEL:-}
REASONING=${MOSAIC_AGENT_REASONING:-}
TOOL_POLICY=${MOSAIC_AGENT_TOOL_POLICY:-}
[ -n "$AGENT_NAME" ] || { echo 'ERROR: MOSAIC_AGENT_NAME is required' >&2; exit 64; }
[[ "$AGENT_NAME" =~ ^[A-Za-z0-9_.-]+$ ]] || { echo 'ERROR: invalid agent name' >&2; exit 64; }
[ "$RUNTIME" = 'pi' ] || { echo 'ERROR: invalid runtime policy' >&2; exit 64; }
[ "$MODEL" = 'openai/gpt-5.6-sol' ] || { echo 'ERROR: invalid model policy' >&2; exit 64; }
[ "$REASONING" = 'high' ] || { echo 'ERROR: invalid reasoning policy' >&2; exit 64; }
[ "$TOOL_POLICY" = 'operator-interaction' ] || { echo 'ERROR: invalid tool policy' >&2; exit 64; }
printf '{"agentName":"%s","runtime":"%s","model":"%s","reasoning":"%s","toolPolicy":"%s"}\n' \
"$AGENT_NAME" "$RUNTIME" "$MODEL" "$REASONING" "$TOOL_POLICY"
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env bash
# seat-logins.sh — project seat credentials into tea's login config.
#
# Issue: mosaicstack/stack#1356 (tea login resolution fails open).
#
# WHY THIS EXISTS. tea 0.14.0 has no --token on its operations; it can only use a
# login already stored in ~/.config/tea/config.yml. So the wrappers cannot read the
# seat secrets dir on the tea path. The secrets dir stays authoritative and this
# script projects it into tea's config, which is a DERIVED CACHE: regenerate it,
# never hand-edit it. Same shape as the config-registry projector, same reason —
# a third-party tool that cannot read our store has to be fed.
#
# Canonical login name is "<instance>-<seat>", which is what the identity ladder in
# detect-platform.sh computes from the seat name. A login the ladder cannot compute
# is a fail-open surface, so an ad-hoc name is a defect, not a style.
#
# COLLISIONS. tea refuses to store one token under two names ("token already been
# used, delete login 'X' first"). A hand-made alias holding a seat's token there-
# fore BLOCKS its canonical name. Detected up front by hashing, so a dry run shows
# it; --adopt resolves it by deleting the alias and re-minting canonically. Same
# token, same access, only the label changes.
#
# Tokens are never printed, never logged, and never passed on a visible command
# line beyond tea's own --token, which is unavoidable with this client. tea's
# stderr is echoed on failure with any token-shaped string redacted.
#
# Usage:
# seat-logins.sh # dry run, all seats (default: changes nothing)
# seat-logins.sh --apply # mint/refresh all seats
# seat-logins.sh --seat <seat> # limit to one seat
# seat-logins.sh --apply --adopt # also rename ad-hoc aliases to canonical names
set -euo pipefail
BRAIN_HOME="${MOSAIC_BRAIN_HOME:-$HOME/.mosaic}"
TEA_CONFIG="${TEA_CONFIG:-$HOME/.config/tea/config.yml}"
APPLY=0
ADOPT=0
ONLY_SEAT=""
# Instance -> server URL.
#
# Instances are named here because there is no registry to read them from yet.
# Override per-instance without editing this file, which is how a deployment adds
# its own hosts: MOSAIC_GITEA_URL_<INSTANCE>=https://...
declare -A INSTANCE_URL=(
[mosaicstack]="https://git.mosaicstack.dev"
[usc]="https://git.uscllc.com"
)
while [ $# -gt 0 ]; do
case "$1" in
--apply) APPLY=1; shift ;;
--adopt) ADOPT=1; shift ;;
--seat) ONLY_SEAT="${2:?--seat needs a name}"; shift 2 ;;
-h|--help) sed -n '2,33p' "$0"; exit 0 ;;
*) echo "seat-logins.sh: unknown argument '$1'" >&2; exit 2 ;;
esac
done
command -v tea >/dev/null || { echo "seat-logins.sh: tea not on PATH" >&2; exit 1; }
url_for() {
local inst="$1" ovr
ovr="MOSAIC_GITEA_URL_$(printf '%s' "$inst" | tr '[:lower:]-' '[:upper:]_')"
if [ -n "${!ovr:-}" ]; then printf '%s' "${!ovr}"; return 0; fi
printf '%s' "${INSTANCE_URL[$inst]:-}"
}
# Redact anything token-shaped before any tea output reaches a log.
redact() { sed -E 's/[A-Za-z0-9]{30,}/<REDACTED>/g'; }
# token sha256 -> login name, for every login tea already holds. This is what
# makes collisions visible in a DRY RUN instead of only as an apply-time error.
declare -A TOKEN_OWNER=()
if [ -r "$TEA_CONFIG" ]; then
while read -r sha lname; do
[ -n "${sha:-}" ] && TOKEN_OWNER["$sha"]="$lname"
done < <(python3 - "$TEA_CONFIG" <<'PY'
import sys, yaml, hashlib
try:
cfg = yaml.safe_load(open(sys.argv[1])) or {}
except Exception:
sys.exit(0)
for l in (cfg.get('logins') or []):
t = l.get('token')
if t:
print(hashlib.sha256(t.encode()).hexdigest(), l.get('name'))
PY
)
fi
minted=0; refreshed=0; skipped=0; failed=0; planned=0; adopted=0; blocked=0
existing="$(tea login list --output simple 2>/dev/null | awk '{print $1}' || true)"
shopt -s nullglob
for tokfile in "$BRAIN_HOME"/fleet/agents/*/secrets/gitea-*.token; do
seat="${tokfile#"$BRAIN_HOME"/fleet/agents/}"; seat="${seat%%/*}"
[ -n "$ONLY_SEAT" ] && [ "$seat" != "$ONLY_SEAT" ] && continue
base="$(basename "$tokfile" .token)" # gitea-<instance>-<seat>
inst="${base#gitea-}"; inst="${inst%-"$seat"}"
name="${inst}-${seat}"
url="$(url_for "$inst")"
if [ -z "$url" ]; then
echo " SKIP $name — no URL known for instance '$inst' (set MOSAIC_GITEA_URL_${inst^^})"
skipped=$((skipped+1)); continue
fi
if [ ! -r "$tokfile" ]; then
echo " SKIP $name — token not readable"
skipped=$((skipped+1)); continue
fi
action="mint"
grep -qx "$name" <<<"$existing" && action="refresh"
# Is this exact token already stored under some OTHER name?
tsha="$(sha256sum < "$tokfile" | awk '{print $1}')"
owner="${TOKEN_OWNER[$tsha]:-}"
collision=""
[ -n "$owner" ] && [ "$owner" != "$name" ] && collision="$owner"
if [ "$APPLY" -eq 0 ]; then
if [ -n "$collision" ]; then
if [ "$ADOPT" -eq 1 ]; then
echo " PLAN adopt $collision -> $name ($url)"
else
echo " BLOCK $name — token already stored as '$collision'; re-run with --adopt"
blocked=$((blocked+1)); continue
fi
else
echo " PLAN $action $name -> $url"
fi
planned=$((planned+1)); continue
fi
if [ -n "$collision" ]; then
if [ "$ADOPT" -eq 0 ]; then
echo " BLOCK $name — token already stored as '$collision'; re-run with --adopt"
blocked=$((blocked+1)); continue
fi
tea login delete "$collision" >/dev/null 2>&1 || true
action="adopt"
fi
# tea has no idempotent add; refresh is delete-then-add so a rotated token lands.
[ "$action" = refresh ] && tea login delete "$name" >/dev/null 2>&1 || true
if err="$(tea login add --name "$name" --url "$url" \
--token "$(cat "$tokfile")" --no-version-check 2>&1 >/dev/null)"; then
case "$action" in
mint) minted=$((minted+1)) ;;
refresh) refreshed=$((refreshed+1)) ;;
adopt) adopted=$((adopted+1)) ;;
esac
if [ "$action" = adopt ]; then
echo " OK adopt $collision -> $name ($url)"
else
echo " OK $action $name -> $url"
fi
else
# A failure here is real information: the seat's token is dead, or the server
# refused it. Do not paper over it; the seat cannot act until it is reminted.
# tea's own words, redacted — a summarised FAIL hides whether the cause is the
# credential or the client, which cost a diagnosis on 2026-08-21.
echo " FAIL $action $name -> $url"
echo " tea: $(printf '%s' "$err" | redact | head -1)"
failed=$((failed+1))
fi
done
echo
if [ "$APPLY" -eq 0 ]; then
echo "dry run: $planned login(s) would be written, $skipped skipped, $blocked blocked."
[ "$blocked" -gt 0 ] && echo "re-run with --adopt to rename ad-hoc aliases to canonical names."
echo "no changes made. re-run with --apply."
else
echo "minted=$minted adopted=$adopted refreshed=$refreshed skipped=$skipped blocked=$blocked failed=$failed"
fi
[ "$failed" -eq 0 ] && [ "$blocked" -eq 0 ]
@@ -0,0 +1,519 @@
#!/usr/bin/env bash
set -euo pipefail
# FCM-M2-001 boundary: only a roster-derived .env.generated projection and a
# separately parsed data-only .env.local can influence launch. Never source an
# environment file and never accept a command string from either file.
MODE=launch
case "${1:-}" in
--stop)
MODE=stop
AGENT_NAME=${2:-}
;;
--interaction)
MODE=interaction
AGENT_NAME=${2:-}
;;
*) AGENT_NAME=${1:-${MOSAIC_AGENT_NAME:-}} ;;
esac
MOSAIC_HOME=${MOSAIC_HOME:-$HOME/.config/mosaic}
fail() {
echo "ERROR: $*" >&2
exit 64
}
hash_value() {
printf '%s' "$1" | sha256sum | awk '{print $1}'
}
fail_env() {
local code="$1"
local key="$2"
local value="$3"
echo "ERROR: agent environment rejected: code=${code} key=${key} sha256=$(hash_value "$value")" >&2
exit 64
}
safe_agent_name() {
[[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]*$ ]]
}
safe_policy_name() {
[[ "$1" =~ ^[a-z][a-z0-9-]*$ ]]
}
safe_path() {
[[ "$1" == /* ]] || return 1
[[ "$1" != *".."* ]] || return 1
[[ ! "$1" =~ [[:space:]\"\'\`\$\\\;\|\&\<\>\(\)\{\}] ]]
}
assert_private_regular_file() {
local file="$1"
[ -f "$file" ] && [ ! -L "$file" ] || fail_env unsafe-file '(file)' "$file"
local mode
mode=$(stat -c '%a' -- "$file") || fail_env unsafe-file '(file)' "$file"
(( (8#$mode & 8#077) == 0 )) || fail_env unsafe-permissions '(file)' "$file"
}
assert_managed_directory() {
local directory="$1"
[ -d "$directory" ] && [ ! -L "$directory" ] || fail_env unsafe-directory '(directory)' "$directory"
local mode
mode=$(stat -c '%a' -- "$directory") || fail_env unsafe-directory '(directory)' "$directory"
(( (8#$mode & 8#022) == 0 )) || fail_env unsafe-permissions '(directory)' "$directory"
}
assert_private_directory() {
local directory="$1"
assert_managed_directory "$directory"
local mode
mode=$(stat -c '%a' -- "$directory") || fail_env unsafe-directory '(directory)' "$directory"
(( (8#$mode & 8#077) == 0 )) || fail_env unsafe-permissions '(directory)' "$directory"
}
[ -n "$AGENT_NAME" ] || fail "agent name argument or MOSAIC_AGENT_NAME is required"
safe_agent_name "$AGENT_NAME" || fail_env unsafe-agent-name MOSAIC_AGENT_NAME "$AGENT_NAME"
safe_path "$MOSAIC_HOME" || fail_env unsafe-path MOSAIC_HOME "$MOSAIC_HOME"
FLEET_DIR="$MOSAIC_HOME/fleet"
AGENT_ENV_DIR="$FLEET_DIR/agents"
# Brain-home split (canon docs/STRUCTURE-CANON.md §2): seat launch envs live
# under the brain home's fleet/agents when a brain is active; roster, roles
# baseline, and runtime state (fleet/run) stay under MOSAIC_HOME.
# Resolution mirrors packages/mosaic/src/fleet/brain-home.ts:
# 1. MOSAIC_BRAIN_HOME env (explicit, always wins)
# 2. ~/.mosaic — adopted only when MOSAIC_HOME is the default config home AND
# ~/.mosaic/fleet/agents exists
# 3. MOSAIC_HOME (legacy single-tree)
BRAIN_HOME="${MOSAIC_BRAIN_HOME:-}"
if [ -z "$BRAIN_HOME" ]; then
BRAIN_HOME="$MOSAIC_HOME"
if [ "$(cd "$MOSAIC_HOME" 2>/dev/null && pwd -P)" = "$HOME/.config/mosaic" ] \
&& [ -d "$HOME/.mosaic/fleet/agents" ]; then
BRAIN_HOME="$HOME/.mosaic"
fi
fi
if [ "$BRAIN_HOME" != "$MOSAIC_HOME" ]; then
AGENT_ENV_DIR="$BRAIN_HOME/fleet/agents"
fi
assert_managed_directory "$MOSAIC_HOME"
assert_managed_directory "$FLEET_DIR"
assert_private_directory "$AGENT_ENV_DIR"
GENERATED_ENV="$AGENT_ENV_DIR/$AGENT_NAME.env.generated"
LOCAL_ENV="$AGENT_ENV_DIR/$AGENT_NAME.env.local"
declare -A GENERATED_VALUES=()
declare -A LOCAL_VALUES=()
declare -A SEEN_KEYS=()
is_sensitive_key() {
[[ "$1" =~ (API[_-]?KEY|AUTH|CREDENTIAL|PASSWORD|PRIVATE|SECRET|TOKEN) ]]
}
is_generated_key() {
case "$1" in
MOSAIC_AGENT_NAME|MOSAIC_GIT_IDENTITY|MOSAIC_AGENT_CLASS|MOSAIC_AGENT_RUNTIME|MOSAIC_AGENT_MODEL|MOSAIC_AGENT_REASONING|MOSAIC_AGENT_TOOL_POLICY|MOSAIC_AGENT_WORKDIR|MOSAIC_TMUX_SOCKET) return 0 ;;
*) return 1 ;;
esac
}
is_local_key() {
case "$1" in
MOSAIC_RUNTIME_BIN|MOSAIC_HEARTBEAT_RUN_DIR|MOSAIC_HEARTBEAT_INTERVAL|MOSAIC_CLAUDE_JSON|CLAUDE_CONFIG_DIR) return 0 ;;
*) return 1 ;;
esac
}
validate_generated_value() {
local key="$1"
local value="$2"
case "$key" in
MOSAIC_AGENT_NAME) safe_agent_name "$value" || fail_env unsafe-agent-name "$key" "$value" ;;
MOSAIC_GIT_IDENTITY) safe_agent_name "$value" || fail_env unsafe-git-identity "$key" "$value" ;;
MOSAIC_AGENT_CLASS) safe_policy_name "$value" || fail_env unsafe-class "$key" "$value" ;;
MOSAIC_AGENT_RUNTIME)
case "$value" in claude|codex|opencode|pi) ;; *) fail_env unsupported-runtime "$key" "$value" ;; esac
;;
MOSAIC_AGENT_MODEL) [[ "$value" =~ ^[A-Za-z0-9._/:+-]*$ ]] || fail_env unsafe-model "$key" "$value" ;;
MOSAIC_AGENT_REASONING)
case "$value" in ''|low|medium|high) ;; *) fail_env unsupported-reasoning "$key" "$value" ;; esac
;;
MOSAIC_AGENT_TOOL_POLICY) [ -z "$value" ] || safe_policy_name "$value" || fail_env unsafe-tool-policy "$key" "$value" ;;
MOSAIC_AGENT_WORKDIR) safe_path "$value" || fail_env unsafe-path "$key" "$value" ;;
MOSAIC_TMUX_SOCKET) [[ "$value" =~ ^[A-Za-z0-9_.-]*$ ]] || fail_env unsafe-socket "$key" "$value" ;;
esac
}
validate_local_value() {
local key="$1"
local value="$2"
if [ "$key" = MOSAIC_HEARTBEAT_INTERVAL ]; then
[[ "$value" =~ ^[1-9][0-9]*$ ]] || fail_env invalid-interval "$key" "$value"
else
safe_path "$value" || fail_env unsafe-path "$key" "$value"
fi
}
load_environment_file() {
local file="$1"
local kind="$2"
[ -e "$file" ] || {
[ "$kind" = generated ] && fail_env missing-file '(generated)' "$file"
return 0
}
assert_private_regular_file "$file"
SEEN_KEYS=()
local line key value
while IFS= read -r line || [ -n "$line" ]; do
[ -z "$line" ] && continue
if [[ ! "$line" =~ ^([A-Z][A-Z0-9_]*)=(.*)$ ]]; then
fail_env malformed-line '(malformed)' "$line"
fi
key=${BASH_REMATCH[1]}
value=${BASH_REMATCH[2]}
[ -z "${SEEN_KEYS[$key]+set}" ] || fail_env duplicate-key "$key" "$value"
SEEN_KEYS[$key]=1
is_sensitive_key "$key" && fail_env sensitive-key "$key" "$value"
if [ "$kind" = generated ]; then
is_generated_key "$key" || fail_env unknown-key "$key" "$value"
validate_generated_value "$key" "$value"
GENERATED_VALUES[$key]=$value
else
is_generated_key "$key" && fail_env generated-key-shadow "$key" "$value"
is_local_key "$key" || fail_env unknown-key "$key" "$value"
validate_local_value "$key" "$value"
LOCAL_VALUES[$key]=$value
fi
done < "$file"
}
load_environment_file "$GENERATED_ENV" generated
for required_key in \
MOSAIC_AGENT_NAME MOSAIC_GIT_IDENTITY MOSAIC_AGENT_CLASS MOSAIC_AGENT_RUNTIME MOSAIC_AGENT_MODEL \
MOSAIC_AGENT_REASONING MOSAIC_AGENT_TOOL_POLICY MOSAIC_AGENT_WORKDIR MOSAIC_TMUX_SOCKET; do
[ -n "${GENERATED_VALUES[$required_key]+set}" ] || fail_env missing-key "$required_key" ''
done
load_environment_file "$LOCAL_ENV" local
[ "${GENERATED_VALUES[MOSAIC_AGENT_NAME]}" = "$AGENT_NAME" ] || \
fail_env agent-name-mismatch MOSAIC_AGENT_NAME "${GENERATED_VALUES[MOSAIC_AGENT_NAME]}"
[ "${GENERATED_VALUES[MOSAIC_GIT_IDENTITY]}" = "$AGENT_NAME" ] || \
fail_env git-identity-mismatch MOSAIC_GIT_IDENTITY "${GENERATED_VALUES[MOSAIC_GIT_IDENTITY]}"
MOSAIC_TMUX_SOCKET=${GENERATED_VALUES[MOSAIC_TMUX_SOCKET]}
MOSAIC_AGENT_RUNTIME=${GENERATED_VALUES[MOSAIC_AGENT_RUNTIME]}
MOSAIC_AGENT_MODEL=${GENERATED_VALUES[MOSAIC_AGENT_MODEL]}
MOSAIC_AGENT_REASONING=${GENERATED_VALUES[MOSAIC_AGENT_REASONING]}
MOSAIC_AGENT_WORKDIR=${GENERATED_VALUES[MOSAIC_AGENT_WORKDIR]}
MOSAIC_GIT_IDENTITY=${GENERATED_VALUES[MOSAIC_GIT_IDENTITY]}
MOSAIC_AGENT_CLASS=${GENERATED_VALUES[MOSAIC_AGENT_CLASS]}
MOSAIC_AGENT_TOOL_POLICY=${GENERATED_VALUES[MOSAIC_AGENT_TOOL_POLICY]}
MOSAIC_RUNTIME_BIN=${LOCAL_VALUES[MOSAIC_RUNTIME_BIN]:-}
MOSAIC_HEARTBEAT_RUN_DIR=${LOCAL_VALUES[MOSAIC_HEARTBEAT_RUN_DIR]:-$MOSAIC_HOME/fleet/run}
MOSAIC_HEARTBEAT_INTERVAL=${LOCAL_VALUES[MOSAIC_HEARTBEAT_INTERVAL]:-15}
MOSAIC_CLAUDE_JSON=${LOCAL_VALUES[MOSAIC_CLAUDE_JSON]:-}
CLAUDE_CONFIG_DIR=${LOCAL_VALUES[CLAUDE_CONFIG_DIR]:-}
if ! command -v tmux >/dev/null 2>&1; then
echo "ERROR: tmux is required" >&2
exit 69
fi
_tmux() {
if [ -n "$MOSAIC_TMUX_SOCKET" ]; then
tmux -L "$MOSAIC_TMUX_SOCKET" "$@"
else
tmux "$@"
fi
}
assert_owned_tmux_server() {
local owner_file="$MOSAIC_HOME/fleet/run/holder-owner"
[ -f "$owner_file" ] && [ ! -L "$owner_file" ] || fail "private tmux ownership identity is missing"
local owner_mode
owner_mode=$(stat -c '%a' -- "$owner_file") || fail "private tmux ownership identity is unreadable"
(( (8#$owner_mode & 8#077) == 0 )) || fail "private tmux ownership identity has unsafe permissions"
local owner
owner=$(tr -d '\n' < "$owner_file")
[[ "$owner" =~ ^[a-f0-9-]{36}$ ]] || fail "private tmux ownership identity is malformed"
_tmux has-session -t '=_holder:0.0' 2>/dev/null || fail "owned tmux holder session is absent"
local environment expected
environment=$(_tmux show-environment -g 2>/dev/null) || fail "owned tmux global environment is unreadable"
expected=$(printf '%s\n' \
"HOME=$HOME" \
'PATH=/usr/bin:/bin' \
"PWD=$HOME" \
"MOSAIC_FLEET_OWNER=$owner" \
'MOSAIC_TMUX_HOLDER=_holder' \
"MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET" | sort)
[ "$(printf '%s\n' "$environment" | sort)" = "$expected" ] || \
fail "tmux server ownership or environment validation failed"
}
# Lease-broker socket preflight (#1292). The gated runtime (`mosaic yolo …` →
# launch-runtime.py) registers with the broker or dies ~4 seconds in, with the
# diagnostic invisible because tmux destroys the dead pane. This check runs
# BEFORE any tmux effect — including the ownership probe below — so a host
# without a broker produces a named, surviving refusal instead of a doomed
# pane. Exit 75 (EX_TEMPFAIL), distinct from 64 (bad projection) and 69 (host
# not ready for other reasons); the agent@ unit is Type=oneshot with no
# Restart=, so the failed unit keeps its message instead of looping. Socket
# resolution matches launch.ts's defaultLeaseBrokerSocket precedence exactly.
# This preflight DETECTS and REFUSES — it never starts the broker (activation
# belongs to the fleet control plane; a component that both detects and fixes
# cannot be used to measure whether the fix worked).
broker_socket_path() {
if [ -n "${MOSAIC_LEASE_BROKER_SOCKET:-}" ]; then
printf '%s\n' "$MOSAIC_LEASE_BROKER_SOCKET"
return 0
fi
local runtime_dir="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
printf '%s\n' "${runtime_dir}/mosaic-lease/broker.sock"
}
if [ "$MODE" = "launch" ]; then
_broker_socket=$(broker_socket_path)
if [ ! -S "$_broker_socket" ]; then
echo "[fleet] FAIL_LAUNCH broker-absent: lease broker socket ${_broker_socket} missing; runtime launch denied (#1292)." >&2
echo "[fleet] remedy: systemctl --user enable --now mosaic-lease-broker.service (or reinstall via: mosaic fleet install)" >&2
exit 75
fi
fi
assert_owned_tmux_server
if [ "$MODE" = interaction ]; then
[ "$MOSAIC_AGENT_RUNTIME" = pi ] || fail "operator interaction service requires runtime pi"
[ "$MOSAIC_AGENT_MODEL" = openai/gpt-5.6-sol ] || \
fail "operator interaction service requires the pinned model"
[ "$MOSAIC_AGENT_REASONING" = high ] || \
fail "operator interaction service requires high reasoning"
[ "$MOSAIC_AGENT_TOOL_POLICY" = operator-interaction ] || \
fail "operator interaction service requires the operator-interaction tool policy"
fi
if [ "$MODE" = stop ]; then
_tmux kill-session -t "=${AGENT_NAME}" >/dev/null 2>&1 || true
exit 0
fi
# #1408 hazard: a seat still living on the DEFAULT tmux socket is invisible to the
# declared-socket guard below, and launching over it creates a same-name duplicate that
# name-addressed comms delivery cannot tell apart. Refuse with a distinct code (76,
# after 75 broker-absent) so a cutover wave script can branch on "seat still on legacy
# socket" vs "already running" (0) vs "broker absent" (75). Stopping the legacy session
# belongs to the cutover procedure, never to this launcher.
if [ -n "$MOSAIC_TMUX_SOCKET" ] && tmux has-session -t "=${AGENT_NAME}" 2>/dev/null; then
echo "[fleet] FAIL_LAUNCH seat-on-legacy-socket: session '${AGENT_NAME}' exists on the DEFAULT tmux socket; stop it before launching on '${MOSAIC_TMUX_SOCKET}'." >&2
exit 76
fi
if _tmux has-session -t "=${AGENT_NAME}:0.0" 2>/dev/null; then
echo "Mosaic agent session already running: $AGENT_NAME on socket ${MOSAIC_TMUX_SOCKET:-(default)}"
exit 0
fi
# Systemd passes HOME as %h, and the installed service fixes MOSAIC_HOME under
# that home. Derive the pane home from the canonical path when available so an
# inherited pane/session HOME cannot become runtime authority.
PANE_HOME=$HOME
case "$MOSAIC_HOME" in
*/.config/mosaic) PANE_HOME=${MOSAIC_HOME%/.config/mosaic} ;;
esac
_build_runtime_bin_prefix() {
local candidates=()
if [ -n "$MOSAIC_RUNTIME_BIN" ]; then candidates+=("$MOSAIC_RUNTIME_BIN"); fi
# A host with no system Node gets one bootstrapped here by tools/install.sh, which
# records it in ~/.profile. The fleet unit runs `env -i ... bash --noprofile --norc`
# by design, so ~/.profile is never read and the directory has to be named here.
# The npm probe below cannot cover this: it reports a package prefix
# (~/.npm-global), never a Node runtime directory. It sits ahead of the npm probe so
# the bootstrapped runtime wins on a host that has both — that is the one the installer
# verified — while an explicit MOSAIC_RUNTIME_BIN still outranks it.
# Runtime binaries are `#!/usr/bin/env node`, so without this the pane resolves the
# binary and then dies on `env: 'node': No such file or directory`.
candidates+=("$PANE_HOME/.mosaic/node/current/bin")
if command -v npm >/dev/null 2>&1; then
local npm_prefix
npm_prefix=$(npm config get prefix 2>/dev/null) || true
if [ -n "$npm_prefix" ]; then candidates+=("${npm_prefix}/bin"); fi
fi
candidates+=("$PANE_HOME/.npm-global/bin" "$PANE_HOME/.local/bin")
local prefix="" dir
for dir in "${candidates[@]}"; do
[ -d "$dir" ] || continue
case ":${prefix}:" in *":${dir}:"*) ;; *) prefix="${prefix:+$prefix:}$dir" ;; esac
done
printf '%s' "$prefix"
}
MOSAIC_RUNTIME_BIN_PREFIX=$(_build_runtime_bin_prefix)
PANE_PATH=${MOSAIC_RUNTIME_BIN_PREFIX:+${MOSAIC_RUNTIME_BIN_PREFIX}:}/usr/local/bin:/usr/bin:/bin
# #1241. The pane runs `mosaic yolo <runtime>` under PANE_PATH with a cleared
# environment. A binary missing from *that* path is a pane that dies in under a
# second, inside a session nobody is attached to, with its diagnostic scrolled
# into a pane tmux then destroys. Resolve both here, before any effect, where
# the failure is still attributable to the thing that caused it.
#
# `mosaic yolo <runtime>` runs checkRuntime(runtime) and the binary it looks for
# is named exactly like the runtime, so resolving the runtime name is the same
# question the pane will ask a moment later — asked while an operator can still
# see the answer.
_resolve_in_pane_path() {
PATH="$PANE_PATH" command -v -- "$1" 2>/dev/null
}
# Exit 69 (EX_UNAVAILABLE): the seat cannot be provided. Distinguished from the
# 64 (EX_USAGE) rejections above, which mean the projection itself was bad —
# here the data is fine and the host is not ready. Callers tell the individual
# cases apart by `code=`, the same way fail_env's many codes share exit 64.
fail_launch() {
local code="$1"
shift
echo "ERROR: agent launch aborted: code=${code} agent=${AGENT_NAME} $*" >&2
exit 69
}
for required_binary in mosaic "$MOSAIC_AGENT_RUNTIME"; do
_resolve_in_pane_path "$required_binary" >/dev/null ||
fail_launch missing-binary "'${required_binary}' is not on the pane PATH (${PANE_PATH})"
done
_ensure_claude_workdir_trusted() {
local workdir="$1"
local resolved
resolved=$(cd "$workdir" 2>/dev/null && pwd -P) || resolved="$workdir"
local claude_json="${MOSAIC_CLAUDE_JSON:-${CLAUDE_CONFIG_DIR:+$CLAUDE_CONFIG_DIR/.claude.json}}"
claude_json="${claude_json:-$HOME/.claude.json}"
command -v python3 >/dev/null 2>&1 || return 1
MOSAIC_CJ="$claude_json" MOSAIC_TRUST_DIR="$resolved" python3 - <<'PY'
import json, os, sys, tempfile
cj = os.environ["MOSAIC_CJ"]
d = os.environ["MOSAIC_TRUST_DIR"]
try:
data = json.load(open(cj)) if os.path.exists(cj) else {}
if not isinstance(data, dict):
data = {}
except Exception:
sys.exit(2)
projects = data.setdefault("projects", {})
entry = projects.get(d)
if not isinstance(entry, dict):
entry = {}
projects[d] = entry
entry["hasTrustDialogAccepted"] = True
tmp_dir = os.path.dirname(cj) or "."
fd, tmp = tempfile.mkstemp(dir=tmp_dir, prefix=".claude.json.mosaic.")
try:
with os.fdopen(fd, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp, cj)
except Exception:
try:
os.unlink(tmp)
except OSError:
pass
sys.exit(3)
PY
}
if [ "$MOSAIC_AGENT_RUNTIME" = claude ]; then
_ensure_claude_workdir_trusted "$MOSAIC_AGENT_WORKDIR" || \
echo "WARNING: could not pre-trust workdir for claude agent $AGENT_NAME" >&2
fi
# #1408 hazard: prefer the seat's own launch.sh when the brain provides one. It is the
# path that binds the auth profile (CLAUDE_SECURESTORAGE_CONFIG_DIR) and seeds the seat
# config; `mosaic yolo` relocates CLAUDE_CONFIG_DIR to the seat dir (launch.ts
# activeSeatDir/harnessEnv) but performs neither, so a yolo-launched seat points its
# config at a directory holding no credentials. The env -i allowlist below still
# applies: launch.sh reads its own launch.env.
SEAT_LAUNCH="${BRAIN_HOME}/fleet/agents/${AGENT_NAME}/launch.sh"
if [ -x "$SEAT_LAUNCH" ]; then
LAUNCH_COMMAND=("$SEAT_LAUNCH")
echo "[fleet] launch path: seat launch.sh ($SEAT_LAUNCH)"
else
LAUNCH_COMMAND=(mosaic yolo "$MOSAIC_AGENT_RUNTIME")
if [ -n "$MOSAIC_AGENT_MODEL" ]; then LAUNCH_COMMAND+=(--model "$MOSAIC_AGENT_MODEL"); fi
if [ -n "$MOSAIC_AGENT_REASONING" ]; then LAUNCH_COMMAND+=(--thinking "$MOSAIC_AGENT_REASONING"); fi
echo "[fleet] launch path: mosaic yolo (no executable seat launch.sh)"
fi
# The tmux holder owns a named server. Explicitly clear the pane environment
# so server/session variables cannot cross the launch boundary; retain only
# trusted bootstrap, generated, and approved local data as argv assignments.
LAUNCH_ENV=(
/usr/bin/env
-i
"HOME=$PANE_HOME"
"PATH=$PANE_PATH"
"MOSAIC_HOME=$MOSAIC_HOME"
"MOSAIC_AGENT_NAME=$AGENT_NAME"
"MOSAIC_GIT_IDENTITY=$MOSAIC_GIT_IDENTITY"
"MOSAIC_AGENT_CLASS=$MOSAIC_AGENT_CLASS"
"MOSAIC_AGENT_RUNTIME=$MOSAIC_AGENT_RUNTIME"
"MOSAIC_AGENT_MODEL=$MOSAIC_AGENT_MODEL"
"MOSAIC_AGENT_REASONING=$MOSAIC_AGENT_REASONING"
"MOSAIC_AGENT_TOOL_POLICY=$MOSAIC_AGENT_TOOL_POLICY"
"MOSAIC_AGENT_WORKDIR=$MOSAIC_AGENT_WORKDIR"
"MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET"
"MOSAIC_HEARTBEAT_RUN_DIR=$MOSAIC_HEARTBEAT_RUN_DIR"
)
mkdir -p "$MOSAIC_AGENT_WORKDIR"
_tmux new-session -d -s "$AGENT_NAME" -c "$MOSAIC_AGENT_WORKDIR" \
"${LAUNCH_ENV[@]}" "${LAUNCH_COMMAND[@]}"
PANE_PID=""
for _retry in 1 2 3 4 5; do
PANE_PID=$(_tmux list-panes -t "=${AGENT_NAME}:0.0" -F '#{pane_pid}' 2>/dev/null || true)
[ -n "$PANE_PID" ] && break
sleep 0.2
done
_start_heartbeat_sidecar() {
local agent="$1" pane_pid="$2" run_dir="$3" interval="$4"
local hb_file="${run_dir}/${agent}.hb"
mkdir -p "$run_dir"
local sidecar_script
sidecar_script=$(printf \
'hb=%q; pid=%q; iv=%q; native="$hb.native"; mkdir -p "$(dirname "$hb")"; while kill -0 "$pid" 2>/dev/null; do now=$(date +%%s); marker=$(stat -c %%Y -- "$native" 2>/dev/null || true); if [ -z "$marker" ] || [ -L "$native" ] || (( now - marker > iv * 2 + 1 )); then tmp="$hb.tmp.$$"; printf "ts=%%s\npid=%%s\nstatus=ok\n" "$(date +%%Y-%%m-%%dT%%H:%%M:%%S%%z)" "$pid" > "$tmp" && mv "$tmp" "$hb"; fi; sleep "$iv"; done' \
"$hb_file" "$pane_pid" "$interval")
if command -v setsid >/dev/null 2>&1; then
setsid bash -c "$sidecar_script" </dev/null >/dev/null 2>&1 &
else
bash -c "$sidecar_script" </dev/null >/dev/null 2>&1 &
fi
disown $! 2>/dev/null || true
}
if [ -n "$PANE_PID" ]; then
_start_heartbeat_sidecar "$AGENT_NAME" "$PANE_PID" \
"$MOSAIC_HEARTBEAT_RUN_DIR" "$MOSAIC_HEARTBEAT_INTERVAL" || \
echo "WARNING: heartbeat sidecar could not be started for $AGENT_NAME" >&2
elif _tmux has-session -t "=${AGENT_NAME}:0.0" 2>/dev/null; then
# #1241. Session present, no pane PID after a second of retries. Whatever this
# is, it is not a seat an operator can use, so it is not a success either.
fail_launch pane-pid-unresolved \
"tmux reports the session but no pane PID after 5 attempts"
else
# #1241. This branch used to print a WARNING about the heartbeat sidecar and
# exit 0. It is not a heartbeat problem: tmux destroys a session when its pane
# command exits, so an absent session one second after new-session means the
# runtime died on startup. Reporting it as success is what let `fleet start`
# return 0 over three dead panes — the launcher knew, and said the wrong thing
# at the wrong severity to the wrong layer.
fail_launch pane-did-not-survive \
"the pane exited immediately and tmux destroyed the session;" \
"run 'mosaic yolo ${MOSAIC_AGENT_RUNTIME}' in ${MOSAIC_AGENT_WORKDIR} to see why"
fi
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
AGENT_NAME=${1:-}
fail() {
echo "ERROR: $*" >&2
exit 64
}
[ -n "$AGENT_NAME" ] || fail "agent name argument is required"
# The shared launcher strictly validates the generated/local data boundary
# before it applies this interaction service's pinned profile checks.
exec "$(cd -- "$(dirname -- "$0")" && pwd)/start-agent-session.sh" --interaction "$AGENT_NAME"
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
set -euo pipefail
# A holder may create only the configured named socket. Existing servers are
# accepted only when their private install-derived ownership identity, exact
# holder session, and complete approved global environment all match.
MOSAIC_HOME=${MOSAIC_HOME:-$HOME/.config/mosaic}
MOSAIC_TMUX_SOCKET=${MOSAIC_TMUX_SOCKET:-mosaic-fleet}
MOSAIC_TMUX_HOLDER=${MOSAIC_TMUX_HOLDER:-_holder}
OWNER_FILE="$MOSAIC_HOME/fleet/run/holder-owner"
TMUX_BIN=/usr/bin/tmux
fail() {
echo "ERROR: refusing unmanaged Mosaic tmux server on socket ${MOSAIC_TMUX_SOCKET}: $1" >&2
exit 64
}
[ -x "$TMUX_BIN" ] || fail "tmux binary is unavailable"
[ -f "$OWNER_FILE" ] && [ ! -L "$OWNER_FILE" ] || fail "private ownership identity is missing"
owner_mode=$(stat -c '%a' -- "$OWNER_FILE") || fail "private ownership identity is unreadable"
(( (8#$owner_mode & 8#077) == 0 )) || fail "private ownership identity has unsafe permissions"
MOSAIC_FLEET_OWNER=$(tr -d '\n' < "$OWNER_FILE")
[[ "$MOSAIC_FLEET_OWNER" =~ ^[a-f0-9-]{36}$ ]] || fail "private ownership identity is malformed"
_tmux() {
"$TMUX_BIN" -L "$MOSAIC_TMUX_SOCKET" "$@"
}
server_running() {
_tmux list-sessions >/dev/null 2>&1
}
assert_owned_server() {
_tmux has-session -t "=${MOSAIC_TMUX_HOLDER}:0.0" 2>/dev/null || fail "exact holder session is absent"
local environment
environment=$(_tmux show-environment -g 2>/dev/null) || fail "global environment is unreadable"
local expected
expected=$(printf '%s\n' \
"HOME=$HOME" \
'PATH=/usr/bin:/bin' \
"PWD=$HOME" \
"MOSAIC_FLEET_OWNER=$MOSAIC_FLEET_OWNER" \
"MOSAIC_TMUX_HOLDER=$MOSAIC_TMUX_HOLDER" \
"MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET" | sort)
[ "$(printf '%s\n' "$environment" | sort)" = "$expected" ] || \
fail "global environment does not match the owned-server contract"
}
if server_running; then
assert_owned_server
else
cd "$HOME" || fail "trusted home is unavailable"
# Start the tmux server itself under the approved environment. The holder pane
# receives the same closed environment rather than arbitrary server globals.
/usr/bin/env -i \
"HOME=$HOME" \
PATH=/usr/bin:/bin \
"MOSAIC_FLEET_OWNER=$MOSAIC_FLEET_OWNER" \
"MOSAIC_TMUX_HOLDER=$MOSAIC_TMUX_HOLDER" \
"MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET" \
"$TMUX_BIN" -L "$MOSAIC_TMUX_SOCKET" new-session -d -s "$MOSAIC_TMUX_HOLDER" \
/usr/bin/env -i "HOME=$HOME" PATH=/usr/bin:/bin /bin/sh -c 'while true; do sleep 3600; done'
fi
@@ -0,0 +1,222 @@
#!/usr/bin/env bash
# CI-fit regression suite for the #1292 lease-broker socket preflight in
# start-agent-session.sh.
#
# WHY THIS SUITE IS CI-FIT WHERE test-start-agent-session.sh IS NOT (#1017/#1270
# context): that older suite's precondition is "the host does not have the pi
# binary", which a CI image that ships pi violates — its guard correctly
# refuses to report a pass there, so it is excluded from the chain. THIS suite
# controls its own preconditions instead of inheriting them from the host: a
# fake tmux on PATH, a fake mosaic on PATH, a real unix socket created in a
# tmpdir, a hermetic env (env -i, fake HOME, GIT_CONFIG_GLOBAL severed). It
# never depends on what the host has installed, so a green here means the same
# thing on every host. Anyone adding cases: keep that property — no case may
# depend on host state.
#
# The failure this suite is written down to catch (#1292): a seat launched on a
# host with no lease broker dies ~4 seconds in at registration, with the
# diagnostic invisible because tmux destroys the dead pane. The preflight runs
# BEFORE any tmux effect and refuses with a NAMED code (exit 75, EX_TEMPFAIL)
# so the message survives. The agent@ unit is Type=oneshot with no Restart=,
# so a failed unit keeps its output instead of looping.
#
# Cases:
# 1. absent socket -> exit 75, message names broker-absent + socket path +
# remedy, and NO tmux session was ever created (the doomed-pane half).
# 2. present socket (real unix socket in tmpdir) -> proceeds PAST the
# preflight (the suite then stops at the next precondition, proving the
# preflight was not the refusal).
# 3. explicit MOSAIC_LEASE_BROKER_SOCKET wins over XDG_RUNTIME_DIR default.
# 4. --stop mode does NOT require the broker (teardown must not be fenced on
# a component whose absence is exactly what teardown may follow).
#
# Sabotage control, run by the developer (not in-suite): remove the preflight
# block from start-agent-session.sh, re-run — case 1 fails (a tmux session is
# created / exit is not 75), cases 2-4 still pass; restore byte-identically.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/agent-session-broker-preflight}"
FAKE_HOME="$WORK_DIR/home"
BIN_DIR="$WORK_DIR/bin"
ENV_DIR="$WORK_DIR/env"
SOCK_DIR="$WORK_DIR/sockets"
LOG_FILE="$WORK_DIR/tmux-calls.log"
rm -rf "$WORK_DIR"
# The script asserts a managed directory tree under MOSAIC_HOME: mosaic/,
# mosaic/fleet/, mosaic/fleet/agents/ — private (0700/0750-style) modes, no
# symlinks — plus a per-agent env projection. Build the full tree the launcher
# expects so the suite reaches the BROKER preflight rather than dying at
# environment validation.
mkdir -p "$FAKE_HOME/.config/mosaic/fleet/agents" "$BIN_DIR" "$SOCK_DIR"
chmod 700 "$FAKE_HOME/.config/mosaic" "$FAKE_HOME/.config/mosaic/fleet/agents"
chmod 750 "$FAKE_HOME/.config/mosaic/fleet"
cat > "$FAKE_HOME/.config/mosaic/fleet/agents/preflight-test.env.generated" <<'ENVEOF'
MOSAIC_AGENT_NAME=preflight-test
MOSAIC_GIT_IDENTITY=preflight-test
MOSAIC_AGENT_CLASS=worker
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=
MOSAIC_AGENT_REASONING=
MOSAIC_AGENT_TOOL_POLICY=code
MOSAIC_AGENT_WORKDIR=/tmp
MOSAIC_TMUX_SOCKET=mosaic-fleet
ENVEOF
chmod 600 "$FAKE_HOME/.config/mosaic/fleet/agents/preflight-test.env.generated"
# ─── Fake tmux: records every invocation; new-session marks the marker. ────
: > "$LOG_FILE"
cat > "$BIN_DIR/tmux" <<SH
#!/usr/bin/env bash
printf 'tmux %s\n' "\$*" >> "$LOG_FILE"
if [[ "\$*" == *new-session* ]]; then
echo "TMUX-NEW-SESSION-INVOKED" >> "$LOG_FILE"
fi
exit 0
SH
chmod +x "$BIN_DIR/tmux"
# ─── Fake mosaic/pi binaries so the script proceeds past its own lookups. ───
for bin in mosaic pi claude; do
printf '#!/usr/bin/env bash\nexit 0\n' > "$BIN_DIR/$bin"
chmod +x "$BIN_DIR/$bin"
done
# ─── Minimal launch environment the script expects. ────────────────────────
# (Enough for the preflight to be reached; later stages will still fail in
# case 2 — that is expected and asserted.)
run_session_script() {
local mode="$1"; shift
(
cd "$WORK_DIR"
env -i HOME="$FAKE_HOME" PATH="$BIN_DIR:/usr/bin:/bin" \
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \
MOSAIC_HOME="$FAKE_HOME/.config/mosaic" \
AGENT_NAME=preflight-test \
"$@" \
bash "$SCRIPT_DIR/start-agent-session.sh" $mode preflight-test
)
}
fail=0
assert() {
local desc="$1" expected="$2" actual="$3"
if [[ "$expected" != "$actual" ]]; then
echo "FAIL: $desc — expected '$expected', got '$actual'" >&2
fail=1
fi
}
assert_contains() {
local desc="$1" haystack="$2" needle="$3"
[[ "$haystack" == *"$needle"* ]] || { echo "FAIL: $desc — missing '$needle' in: $haystack" >&2; fail=1; }
}
assert_not_contains() {
local desc="$1" haystack="$2" needle="$3"
if [[ "$haystack" == *"$needle"* ]]; then
echo "FAIL: $desc — must not contain '$needle'" >&2
fail=1
fi
return 0
}
# ─── 1. Absent socket → named refusal, NO tmux session. ────────────────────
: > "$LOG_FILE"
stderr_file="$WORK_DIR/stderr-1.tmp"
set +e
out=$(run_session_script "" MOSAIC_LEASE_BROKER_SOCKET="$SOCK_DIR/absent.sock" 2>"$stderr_file")
rc=$?
set -e
assert "absent socket exit code" "75" "$rc"
err=$(cat "$stderr_file")
assert_contains "absent socket names the failure" "$err" "FAIL_LAUNCH broker-absent"
assert_contains "absent socket names the socket path" "$err" "$SOCK_DIR/absent.sock"
assert_contains "absent socket names a remedy" "$err" "mosaic fleet install"
log1=$(cat "$LOG_FILE")
assert_not_contains "absent socket must not create a tmux session" "$log1" "TMUX-NEW-SESSION-INVOKED"
# ─── 2. Present socket → passes the preflight. ─────────────────────────────
# Expected: ownership/env checks AFTER the preflight may refuse (fixture is
# minimal by design); the assertion is only that the refusal is NOT
# broker-absent and the exit is NOT 75.
# Create a REAL unix socket: a detached python holder binds it and stays alive
# for the duration (bash cannot create sockets; a foreground python would
# close the socket on exit and -S on a closed-but-unlinked path fails). Written
# as a script file + setsid nohup so no job-control/heredoc interaction with
# set -e can silently kill the suite.
# AF_UNIX binds cap at 108 path bytes; the suite's workdir exceeds that, so
# the live socket lives at a SHORT path under /tmp (unique per run, cleaned
# with the suite). The preflight takes its socket path explicitly, so this
# stays fully controlled.
# A real unix socket at a SHORT absolute path (AF_UNIX limit is 108 bytes,
# so the repo-deep SOCK_DIR cannot host it). The name is composed, not
# `mktemp -u`: the CI image's mktemp dialect rejects that invocation
# (pipeline 2562: "mktemp: : Invalid argument"), and no pre-existing file is
# wanted anyway — the holder binds it fresh.
LIVE_SOCK="/tmp/mosaic-preflight-$RANDOM-$$.sock"
trap 'rm -f "$LIVE_SOCK"' EXIT
rm -f "$SOCK_DIR/live.sock" "$LIVE_SOCK"
cat > "$SOCK_DIR/holder.py" <<'PY'
import socket, sys, time
path = sys.argv[1]
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(path)
s.listen(1)
time.sleep(120)
PY
python3 "$SOCK_DIR/holder.py" "$LIVE_SOCK" >/dev/null 2>"$SOCK_DIR/holder.err" &
HOLDER_PID=$!
# Wait for the socket object to exist (bind is near-instant, but do not race it).
for _ in $(seq 1 50); do
[ -S "$LIVE_SOCK" ] && break
sleep 0.1
done
if [ ! -S "$LIVE_SOCK" ]; then
echo "FAIL: could not create live socket fixture (holder pid $HOLDER_PID)" >&2
ps -p "$HOLDER_PID" -o pid,stat,cmd --no-headers >&2 || echo "(holder exited)" >&2
cat "$SOCK_DIR/holder.err" >&2 || true
exit 1
fi
: > "$LOG_FILE"
set +e
out=$(run_session_script "" MOSAIC_LEASE_BROKER_SOCKET="$LIVE_SOCK" 2>"$WORK_DIR/stderr-2.tmp")
rc=$?
set -e
# The preflight PASSED if the failure (whatever later stage refused) is NOT
# the broker refusal, and tmux was reached or a later precondition named
# something else.
err2=$(cat "$WORK_DIR/stderr-2.tmp")
assert_not_contains "live socket must not refuse broker-absent" "$err2" "broker-absent"
if [[ "$rc" == "75" ]]; then
echo "FAIL: live socket — preflight still refused (exit 75) with a live socket" >&2
fail=1
fi
# ─── 3. Explicit socket env wins over XDG default. ─────────────────────────
set +e
out=$(run_session_script "" XDG_RUNTIME_DIR="$SOCK_DIR/no-runtime-here" MOSAIC_LEASE_BROKER_SOCKET="$SOCK_DIR/absent2.sock" 2>"$WORK_DIR/stderr-3.tmp")
rc=$?
set -e
assert "explicit env wins (exit 75)" "75" "$rc"
assert_contains "explicit env path named" "$(cat "$WORK_DIR/stderr-3.tmp")" "$SOCK_DIR/absent2.sock"
# ─── 4. --stop is not fenced on the broker. ────────────────────────────────
: > "$LOG_FILE"
set +e
out=$(run_session_script "--stop" MOSAIC_LEASE_BROKER_SOCKET="$SOCK_DIR/absent3.sock" 2>"$WORK_DIR/stderr-4.tmp")
rc=$?
set -e
err4=$(cat "$WORK_DIR/stderr-4.tmp")
assert_not_contains "--stop must not refuse broker-absent" "$err4" "broker-absent"
if [[ "$rc" == "75" ]]; then
echo "FAIL: --stop — exit 75 means teardown was fenced on the broker" >&2
fail=1
fi
kill "$HOLDER_PID" 2>/dev/null || true
if [[ "$fail" -eq 0 ]]; then
echo "start-agent-session lease-broker preflight regression passed"
fi
exit "$fail"
@@ -0,0 +1,216 @@
#!/usr/bin/env bash
# CI-fit regression suite for the #1408 legacy-socket guard in
# start-agent-session.sh.
#
# Same hermeticity contract as test-agent-session-broker-preflight.sh: a fake
# tmux on PATH that scripts its own answers, a real unix socket in a tmpdir so
# the broker preflight passes, env -i with a fake HOME. No case depends on host
# state.
#
# The failure this suite is written down to catch: during a socket cutover a
# seat's session still lives on the DEFAULT tmux socket while the launcher
# targets the named one. The declared-socket has-session check cannot see the
# legacy session (measured 2026-08-24: rc=1, script proceeds), so launch
# creates a same-name duplicate — and comms delivery, which addresses sessions
# by NAME, cannot tell the two apart. The guard refuses with its own code
# (exit 76, after 75 broker-absent) BEFORE any tmux mutation.
#
# Cases:
# 1. legacy session present -> exit 76, message names seat-on-legacy-socket
# + both sockets' roles, and NO tmux session was created.
# 2. legacy session absent -> proceeds PAST the guard (the run then stops at
# a later precondition; asserted: exit != 76, stderr lacks the guard's
# code, proving the guard was not the refusal).
# 3. MOSAIC_TMUX_SOCKET empty (single-socket host) -> guard is inert: the
# default-socket probe must not fire at all.
#
# Sabotage control, run by the developer (not in-suite): remove the guard
# block, re-run — case 1 fails (exit is not 76), cases 2-3 still pass;
# restore byte-identically.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORK_DIR="${MOSAIC_TEST_WORK_DIR:-$PWD/.mosaic-test-work/agent-session-legacy-socket-guard}"
FAKE_HOME="$WORK_DIR/home"
BIN_DIR="$WORK_DIR/bin"
SOCK_DIR="$WORK_DIR/sockets"
LOG_FILE="$WORK_DIR/tmux-calls.log"
LEGACY_FLAG="$WORK_DIR/legacy-session-present"
rm -rf "$WORK_DIR"
mkdir -p "$FAKE_HOME/.config/mosaic/fleet/agents" "$BIN_DIR" "$SOCK_DIR"
chmod 700 "$FAKE_HOME/.config/mosaic" "$FAKE_HOME/.config/mosaic/fleet/agents"
chmod 750 "$FAKE_HOME/.config/mosaic/fleet"
cat > "$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-test.env.generated" <<'ENVEOF'
MOSAIC_AGENT_NAME=lsguard-test
MOSAIC_GIT_IDENTITY=lsguard-test
MOSAIC_AGENT_CLASS=worker
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=
MOSAIC_AGENT_REASONING=
MOSAIC_AGENT_TOOL_POLICY=code
MOSAIC_AGENT_WORKDIR=/tmp
MOSAIC_TMUX_SOCKET=mosaic-fleet
ENVEOF
chmod 600 "$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-test.env.generated"
# A projection with NO named socket, for case 3. Same file minus the socket line.
sed '/^MOSAIC_TMUX_SOCKET=/d; s/lsguard-test/lsguard-nosock/' \
"$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-test.env.generated" \
> "$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-nosock.env.generated"
echo 'MOSAIC_TMUX_SOCKET=' >> "$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-nosock.env.generated"
chmod 600 "$FAKE_HOME/.config/mosaic/fleet/agents/lsguard-nosock.env.generated"
# Ownership identity the launcher validates before anything touches tmux:
# a 0600 uuid file plus a tmux global environment that matches it exactly.
mkdir -p "$FAKE_HOME/.config/mosaic/fleet/run"
chmod 750 "$FAKE_HOME/.config/mosaic/fleet/run"
OWNER_UUID="aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
printf '%s' "$OWNER_UUID" > "$FAKE_HOME/.config/mosaic/fleet/run/holder-owner"
chmod 600 "$FAKE_HOME/.config/mosaic/fleet/run/holder-owner"
# The exact env block assert_owned_tmux_server expects; the socket value differs
# per case, so cases rewrite it via write_tmux_env before each run.
write_tmux_env() {
printf '%s\n' \
"HOME=$FAKE_HOME" \
'PATH=/usr/bin:/bin' \
"PWD=$FAKE_HOME" \
"MOSAIC_FLEET_OWNER=$OWNER_UUID" \
'MOSAIC_TMUX_HOLDER=_holder' \
"MOSAIC_TMUX_SOCKET=$1" > "$WORK_DIR/tmux-env"
}
# ─── Fake tmux ──────────────────────────────────────────────────────────────
# Scripted answers: a DEFAULT-socket has-session (argv carries no -L) answers
# by the flag file; every named-socket call succeeds (holder present, no
# existing session is fine for these cases since refusal happens first).
cat > "$BIN_DIR/tmux" <<SH
#!/usr/bin/env bash
printf 'tmux %s\n' "\$*" >> "$LOG_FILE"
if [[ "\$*" == *new-session* ]]; then
echo "TMUX-NEW-SESSION-INVOKED" >> "$LOG_FILE"
fi
if [[ "\$*" == *show-environment* ]]; then
cat "$WORK_DIR/tmux-env"
exit 0
fi
if [[ "\$*" == *has-session* ]]; then
# holder session always present; the seat's DEFAULT-socket presence is the
# flag file; the seat is never already-running on the NAMED socket.
[[ "\$*" == *_holder* ]] && exit 0
if [[ "\$1" == "-L" ]]; then exit 1; fi
[[ -e "$LEGACY_FLAG" ]] && exit 0 || exit 1
fi
exit 0
SH
chmod +x "$BIN_DIR/tmux"
for bin in mosaic pi claude; do
printf '#!/usr/bin/env bash\nexit 0\n' > "$BIN_DIR/$bin"
chmod +x "$BIN_DIR/$bin"
done
# Real socket so the #1292 broker preflight passes and the run reaches the guard.
# Same idiom as the broker-preflight suite: AF_UNIX binds cap at 108 path bytes,
# so the socket lives at a SHORT /tmp path held by a detached python holder (a
# foreground bind would close on exit; -S on a closed-but-unlinked path fails).
LIVE_SOCK="/tmp/mosaic-lsguard-$RANDOM-$$.sock"
trap 'rm -f "$LIVE_SOCK"' EXIT
rm -f "$LIVE_SOCK"
cat > "$SOCK_DIR/holder.py" <<'PY'
import socket, sys, time
path = sys.argv[1]
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.bind(path)
s.listen(1)
time.sleep(120)
PY
python3 "$SOCK_DIR/holder.py" "$LIVE_SOCK" >/dev/null 2>"$SOCK_DIR/holder.err" &
for _ in $(seq 1 50); do
[ -S "$LIVE_SOCK" ] && break
sleep 0.1
done
[ -S "$LIVE_SOCK" ] || { echo "FAIL: could not create live socket" >&2; exit 1; }
run_session_script() {
local agent="$1"; shift
(
cd "$WORK_DIR"
env -i HOME="$FAKE_HOME" PATH="$BIN_DIR:/usr/bin:/bin" \
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \
MOSAIC_HOME="$FAKE_HOME/.config/mosaic" \
MOSAIC_LEASE_BROKER_SOCKET="$LIVE_SOCK" \
"$@" \
bash "$SCRIPT_DIR/start-agent-session.sh" "$agent"
)
}
fail=0
assert() {
local desc="$1" expected="$2" actual="$3"
[[ "$expected" == "$actual" ]] || { echo "FAIL: $desc — expected '$expected', got '$actual'" >&2; fail=1; }
}
assert_contains() {
local desc="$1" haystack="$2" needle="$3"
[[ "$haystack" == *"$needle"* ]] || { echo "FAIL: $desc — missing '$needle'" >&2; fail=1; }
}
assert_not_contains() {
local desc="$1" haystack="$2" needle="$3"
if [[ "$haystack" == *"$needle"* ]]; then
echo "FAIL: $desc — must not contain '$needle'" >&2
fail=1
fi
return 0
}
# ─── 1. Legacy session present → exit 76, no tmux mutation. ─────────────────
write_tmux_env "mosaic-fleet"
: > "$LOG_FILE"; touch "$LEGACY_FLAG"
stderr_file="$WORK_DIR/stderr-1.tmp"
set +e
run_session_script lsguard-test >/dev/null 2>"$stderr_file"
rc=$?
set -e
err=$(cat "$stderr_file")
assert "legacy present exit code" "76" "$rc"
assert_contains "names the failure" "$err" "FAIL_LAUNCH seat-on-legacy-socket"
assert_contains "names the agent" "$err" "lsguard-test"
assert_contains "names the target socket" "$err" "mosaic-fleet"
assert_not_contains "no session created" "$(cat "$LOG_FILE")" "TMUX-NEW-SESSION-INVOKED"
# ─── 2. Legacy session absent → guard is not the refusal. ───────────────────
write_tmux_env "mosaic-fleet"
: > "$LOG_FILE"; rm -f "$LEGACY_FLAG"
stderr_file="$WORK_DIR/stderr-2.tmp"
set +e
run_session_script lsguard-test >/dev/null 2>"$stderr_file"
rc=$?
set -e
err=$(cat "$stderr_file")
if [[ "$rc" == "76" ]]; then
echo "FAIL: legacy absent must not exit 76" >&2; fail=1
fi
assert_not_contains "guard code absent from stderr" "$err" "seat-on-legacy-socket"
# ─── 3. Empty MOSAIC_TMUX_SOCKET → guard inert, no default-socket probe. ────
write_tmux_env ""
: > "$LOG_FILE"; touch "$LEGACY_FLAG" # even with a legacy session present
stderr_file="$WORK_DIR/stderr-3.tmp"
set +e
run_session_script lsguard-nosock >/dev/null 2>"$stderr_file"
rc=$?
set -e
err=$(cat "$stderr_file")
if [[ "$rc" == "76" ]]; then
echo "FAIL: empty socket must never exit 76 (single-socket host)" >&2; fail=1
fi
assert_not_contains "guard code absent on single-socket host" "$err" "seat-on-legacy-socket"
rm -f "$LEGACY_FLAG"
if [[ "$fail" -ne 0 ]]; then
echo "start-agent-session legacy-socket guard regression FAILED" >&2
exit 1
fi
echo "start-agent-session legacy-socket guard regression passed"
@@ -0,0 +1,812 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
START="$SCRIPT_DIR/start-agent-session.sh"
INTERACTION_START="$SCRIPT_DIR/start-interaction-service.sh"
ROOT=$(mktemp -d)
FAKE_BIN=$(mktemp -d)
TMUX_CALLS=$(mktemp)
trap 'rm -rf "$ROOT" "$FAKE_BIN" "$TMUX_CALLS"' EXIT
fail() {
echo "FAIL: $*" >&2
exit 1
}
pane_command_clears_environment() {
local calls_file="$1"
local -a argv=()
local index
mapfile -d '' -t argv < "$calls_file"
for ((index = 0; index + 1 < ${#argv[@]}; index++)); do
if [ "${argv[$index]}" = /usr/bin/env ] && [ "${argv[$((index + 1))]}" = -i ]; then
return 0
fi
done
return 1
}
print_pane_argv() {
local calls_file="$1"
local -a argv=()
local bytes index
mapfile -d '' -t argv < "$calls_file"
bytes=$(wc -c < "$calls_file")
printf 'observed pane argv: records=%s bytes=%s\n' "${#argv[@]}" "$bytes" >&2
for ((index = 0; index < ${#argv[@]}; index++)); do
printf ' [%03d] %q\n' "$index" "${argv[$index]}" >&2
done
}
check_pane_environment_boundary() {
local calls_file="$1"
if pane_command_clears_environment "$calls_file"; then
return 0
fi
print_pane_argv "$calls_file"
return 1
}
contains_literal() {
grep -F -- "$2" <<< "$1" >/dev/null
}
contains_line() {
grep -xF -- "$2" <<< "$1" >/dev/null
}
# Portability regression: inspect the authoritative NUL-delimited argv instead
# of piping a newline reconstruction through `grep -q` under pipefail. The old
# pipeline could report failure after a successful match when an upstream
# producer received SIGPIPE. A large trailing argument keeps that failure class
# covered without making stream size part of the semantic contract.
PORTABILITY_CALLS="$ROOT/portability-calls"
printf -v PORTABILITY_PADDING '%*s' 32768 ''
PORTABILITY_PADDING=${PORTABILITY_PADDING// /x}
printf '%s\0' /usr/bin/env -i "$PORTABILITY_PADDING" > "$PORTABILITY_CALLS"
pane_command_clears_environment "$PORTABILITY_CALLS" || \
fail "valid large pane argv was rejected by the environment-boundary assertion"
assert_pane_boundary_rejected() {
local case_name="$1"
local expected_records="$2"
local diagnostic
if diagnostic=$(check_pane_environment_boundary "$PORTABILITY_CALLS" 2>&1); then
fail "pane boundary accepted invalid $case_name fixture"
fi
contains_literal "$diagnostic" "records=$expected_records bytes=" || \
fail "pane argv diagnostic omitted counts for $case_name fixture"
contains_literal "$diagnostic" '[000]' || \
fail "pane argv diagnostic omitted indexed arguments for $case_name fixture"
}
printf '%s\0' tmux -i > "$PORTABILITY_CALLS"
assert_pane_boundary_rejected missing-env 2
printf '%s\0' /usr/bin/env HOME=/untrusted > "$PORTABILITY_CALLS"
assert_pane_boundary_rejected missing-i 2
printf '%s\0' /usr/bin/env HOME=/untrusted -i > "$PORTABILITY_CALLS"
assert_pane_boundary_rejected non-adjacent-i 3
printf '%s\0' -i /usr/bin/env > "$PORTABILITY_CALLS"
assert_pane_boundary_rejected reversed-boundary 2
cat > "$FAKE_BIN/tmux" <<'SHIM'
#!/usr/bin/env bash
set -euo pipefail
printf '%s\0' "$@" >> "${MOSAIC_TEST_TMUX_CALLS:?}"
args=("$@")
index=0
if [ "${args[0]:-}" = -L ]; then index=2; fi
case "${args[$index]:-}" in
has-session)
# The holder always answers. MOSAIC_TEST_HELD_SESSIONS lets a case add
# other targets that should answer too — without it there is no way to
# model "tmux still reports the session" for a non-holder agent, and the
# launcher's pane-pid-unresolved branch is unreachable from this harness.
#
# A listed target answers only AFTER new-session, because the launcher asks
# this question twice about the same name: once before launching, where a
# yes means "already running, nothing to do, exit 0", and once after, where
# a yes means "the session survived". A shim that answered yes to both
# would short-circuit at the first and never reach the branch under test —
# it would look like coverage and measure the idempotency path instead.
for argument in "${args[@]}"; do
[ "$argument" = '=_holder:0.0' ] && exit 0
case " ${MOSAIC_TEST_HELD_SESSIONS:-} " in
*" $argument "*)
if tr '\0' '\n' < "${MOSAIC_TEST_TMUX_CALLS:?}" | grep -qxF new-session; then
exit 0
fi
;;
esac
done
exit 1
;;
show-environment)
printf '%s\n' \
"HOME=${MOSAIC_TEST_HOME:?}" \
'PATH=/usr/bin:/bin' \
"PWD=${MOSAIC_TEST_HOME:?}" \
"MOSAIC_FLEET_OWNER=${MOSAIC_TEST_FLEET_OWNER:?}" \
'MOSAIC_TMUX_HOLDER=_holder' \
'MOSAIC_TMUX_SOCKET=mosaic-test'
exit 0
;;
list-panes) printf '%s\n' "${MOSAIC_TEST_PANE_PID:-}"; exit 0 ;;
new-session)
if [ "${MOSAIC_TEST_EXECUTE_PANE:-}" = 1 ]; then
for ((index = 0; index < ${#args[@]}; index++)); do
if [ "${args[$index]}" = /usr/bin/env ]; then
"${args[@]:$index}"
break
fi
done
fi
exit 0
;;
*) exit 0 ;;
esac
SHIM
chmod +x "$FAKE_BIN/tmux"
cat > "$FAKE_BIN/mosaic" <<'SHIM'
#!/usr/bin/env bash
set -euo pipefail
env -0 > "${MOSAIC_HOME:?}/fleet/pane-environment"
SHIM
chmod +x "$FAKE_BIN/mosaic"
# The runtime the rosters below name. The launcher resolves it against PANE_PATH
# before spawning (#1241), so it has to exist somewhere the pane would find it —
# not merely on the launcher's own PATH.
printf '#!/usr/bin/env bash\nexit 0\n' > "$FAKE_BIN/pi"
chmod +x "$FAKE_BIN/pi"
# PANE_PATH is derived partly from `npm config get prefix`. Left to the real npm
# it would splice whatever the host has installed into the path under test, and
# the missing-binary cases below would pass or fail by accident of the machine.
cat > "$FAKE_BIN/npm" <<'SHIM'
#!/usr/bin/env bash
printf '%s\n' "${MOSAIC_TEST_NPM_PREFIX:-/nonexistent}"
SHIM
chmod +x "$FAKE_BIN/npm"
# PANE_PATH always ends in the system path. A host that installs these there can
# not measure the missing-binary cases at all, and a green run would mean
# nothing — so say so instead of passing.
for host_binary in mosaic pi; do
if PATH=/usr/local/bin:/usr/bin:/bin command -v "$host_binary" >/dev/null 2>&1; then
fail "host provides '$host_binary' in the system path; missing-binary cases are not measurable here"
fi
done
write_generated() {
local home="$1"
local agent="$2"
mkdir -p "$home/fleet/agents" "$home/fleet/run"
chmod 700 "$home" "$home/fleet" "$home/fleet/agents" "$home/fleet/run"
printf '123e4567-e89b-12d3-a456-426614174000\n' > "$home/fleet/run/holder-owner"
chmod 600 "$home/fleet/run/holder-owner"
cat > "$home/fleet/agents/$agent.env.generated" <<EOF
MOSAIC_AGENT_NAME=$agent
MOSAIC_GIT_IDENTITY=$agent
MOSAIC_AGENT_CLASS=code
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=openai-codex/gpt-5.6-sol
MOSAIC_AGENT_REASONING=high
MOSAIC_AGENT_TOOL_POLICY=code
MOSAIC_AGENT_WORKDIR=$home/work
MOSAIC_TMUX_SOCKET=mosaic-test
EOF
chmod 600 "$home/fleet/agents/$agent.env.generated"
mkdir -p "$home/work"
install_pane_binaries "$home"
}
# `$PANE_HOME/.npm-global/bin` is one of the prefixes the launcher folds into
# PANE_PATH, so this is the pane's own view of "installed", distinct from the
# launcher's PATH. Tests that need a binary *absent* remove it from here.
install_pane_binaries() {
local pane_home="$1"
mkdir -p "$pane_home/.npm-global/bin"
local binary
for binary in mosaic pi; do
ln -sf "$FAKE_BIN/$binary" "$pane_home/.npm-global/bin/$binary"
done
}
run_start() {
local home="$1"
local agent="$2"
HOME="$home" PATH="$FAKE_BIN:$PATH" MOSAIC_TEST_TMUX_CALLS="$TMUX_CALLS" \
MOSAIC_TEST_PANE_PID="${MOSAIC_TEST_PANE_PID:-}" \
MOSAIC_TEST_HELD_SESSIONS="${MOSAIC_TEST_HELD_SESSIONS:-}" \
MOSAIC_TEST_FIXED_EPOCH="${MOSAIC_TEST_FIXED_EPOCH:-}" \
MOSAIC_TEST_HOME="$home" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_HOME="$home" "$START" "$agent"
}
# Valid generated data launches only the fixed runtime argument array. It never
# reads an agent-command string or constructs a bash -c pane payload.
HOME_VALID="$ROOT/valid"
AGENT_VALID="coder0"
write_generated "$HOME_VALID" "$AGENT_VALID"
# A live pane PID is part of what "valid launch" means. Until #1241 this case
# ran with none, so the suite's one success path was itself a dead pane the
# launcher reported as fine.
MOSAIC_TEST_PANE_PID=$$ run_start "$HOME_VALID" "$AGENT_VALID"
valid_args=$(tr '\0' '\n' < "$TMUX_CALLS")
contains_literal "$valid_args" new-session || fail "valid generated projection did not reach tmux"
contains_literal "$valid_args" mosaic || fail "fixed mosaic launcher command missing"
contains_literal "$valid_args" yolo || fail "fixed yolo launcher command missing"
contains_literal "$valid_args" pi || fail "roster runtime missing"
if contains_literal "$valid_args" 'bash -c'; then
fail "launcher constructed a shell command payload"
fi
# ── Brain-home split (canon §2) ─────────────────────────────────────────
# When MOSAIC_HOME is the default config home under $HOME and the host carries
# $HOME/.mosaic/fleet/agents, seat envs resolve from the brain tree; the config
# home still owns fleet/run (holder-owner) and remains a managed boundary.
: > "$TMUX_CALLS"
HOME_BRAIN="$ROOT/brain-home"
CONFIG_HOME="$HOME_BRAIN/.config/mosaic"
BRAIN="$HOME_BRAIN/.mosaic"
mkdir -p "$CONFIG_HOME/fleet/run" "$BRAIN/fleet/agents" "$HOME_BRAIN/work"
chmod 700 "$CONFIG_HOME" "$CONFIG_HOME/fleet" "$CONFIG_HOME/fleet/run" \
"$BRAIN/fleet/agents" "$HOME_BRAIN/work"
printf '123e4567-e89b-12d3-a456-426614174000\n' > "$CONFIG_HOME/fleet/run/holder-owner"
chmod 600 "$CONFIG_HOME/fleet/run/holder-owner"
cat > "$BRAIN/fleet/agents/coder-brain.env.generated" <<EOF
MOSAIC_AGENT_NAME=coder-brain
MOSAIC_AGENT_CLASS=code
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=openai-codex/gpt-5.6-sol
MOSAIC_AGENT_REASONING=high
MOSAIC_AGENT_TOOL_POLICY=code
MOSAIC_AGENT_WORKDIR=$HOME_BRAIN/work
MOSAIC_TMUX_SOCKET=mosaic-test
EOF
chmod 600 "$BRAIN/fleet/agents/coder-brain.env.generated"
install_pane_binaries "$HOME_BRAIN"
HOME="$HOME_BRAIN" PATH="$FAKE_BIN:$PATH" MOSAIC_TEST_TMUX_CALLS="$TMUX_CALLS" \
MOSAIC_TEST_PANE_PID=$$ MOSAIC_TEST_HOME="$HOME_BRAIN" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_HOME="$CONFIG_HOME" "$START" coder-brain
brain_args=$(tr '\0' '\n' < "$TMUX_CALLS")
echo "$brain_args" | grep -qF new-session || fail "brain-home generated projection did not reach tmux"
echo "$brain_args" | grep -qF 'coder-brain' || fail "brain-home agent env was not the launch source"
[ -f "$BRAIN/fleet/agents/coder-brain.env.generated" ] || fail "brain generated env vanished"
# Negative control: the SAME default-config-home shape but without
# ~/.mosaic/fleet/agents — the config-home env tree is used directly (legacy).
: > "$TMUX_CALLS"
HOME_NOBRAIN="$ROOT/brainless-home"
CONFIG_HOME_NOBRAIN="$HOME_NOBRAIN/.config/mosaic"
write_generated "$CONFIG_HOME_NOBRAIN" "coder-legacy"
install_pane_binaries "$HOME_NOBRAIN"
HOME="$HOME_NOBRAIN" PATH="$FAKE_BIN:$PATH" MOSAIC_TEST_TMUX_CALLS="$TMUX_CALLS" \
MOSAIC_TEST_PANE_PID=$$ MOSAIC_TEST_HOME="$HOME_NOBRAIN" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_HOME="$CONFIG_HOME_NOBRAIN" "$START" coder-legacy
legacy_args=$(tr '\0' '\n' < "$TMUX_CALLS")
echo "$legacy_args" | grep -qF new-session || fail "legacy single-tree launch regressed"
# The pane must start through an absolute clean-environment boundary. Its
# runtime command remains an argv vector, but no holder/session environment
# control variable can pass through the pane command.
check_pane_environment_boundary "$TMUX_CALLS" || \
fail "pane command did not use an adjacent /usr/bin/env -i boundary"
# Git identity is generated authority, not an optional or independently mutable
# local value. Each invalid form must fail before fake tmux receives a call.
assert_git_identity_rejected() {
local case_name="$1"
local expected_code="$2"
local home="$ROOT/git-identity-$case_name"
local agent="coder-git-identity-$case_name"
local generated="$home/fleet/agents/$agent.env.generated"
write_generated "$home" "$agent"
case "$case_name" in
missing) grep -v '^MOSAIC_GIT_IDENTITY=' "$generated" > "$generated.next" && mv "$generated.next" "$generated" ;;
unsafe) sed -i 's|^MOSAIC_GIT_IDENTITY=.*$|MOSAIC_GIT_IDENTITY=bad/identity|' "$generated" ;;
mismatch) sed -i 's|^MOSAIC_GIT_IDENTITY=.*$|MOSAIC_GIT_IDENTITY=other-agent|' "$generated" ;;
local-shadow)
printf 'MOSAIC_GIT_IDENTITY=%s\n' "$agent" > "$home/fleet/agents/$agent.env.local"
chmod 600 "$home/fleet/agents/$agent.env.local"
;;
*) fail "unknown Git identity rejection case: $case_name" ;;
esac
chmod 600 "$generated"
: > "$TMUX_CALLS"
if output=$(run_start "$home" "$agent" 2>&1); then
fail "Git identity case $case_name was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before Git identity $case_name rejection"
contains_literal "$output" "code=$expected_code" || \
fail "Git identity $case_name diagnostic omitted code $expected_code"
}
assert_git_identity_rejected missing missing-key
assert_git_identity_rejected unsafe unsafe-git-identity
assert_git_identity_rejected mismatch git-identity-mismatch
assert_git_identity_rejected local-shadow generated-key-shadow
# The generated-file parent is a security boundary too: even a private regular
# file is untrusted if its parent can be replaced or written by another user.
# Validation must happen before fake tmux receives even a has-session call.
: > "$TMUX_CALLS"
HOME_UNSAFE_PARENT="$ROOT/unsafe-parent"
write_generated "$HOME_UNSAFE_PARENT" "coder-parent"
chmod 777 "$HOME_UNSAFE_PARENT/fleet/agents"
if output=$(run_start "$HOME_UNSAFE_PARENT" coder-parent 2>&1); then
fail "generated file under a world-writable parent was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before unsafe parent rejection"
contains_literal "$output" 'code=unsafe-permissions' || fail "unsafe parent diagnostic missing"
: > "$TMUX_CALLS"
HOME_SYMLINK_PARENT="$ROOT/symlink-parent"
write_generated "$HOME_SYMLINK_PARENT" "coder-symlink-parent"
mv "$HOME_SYMLINK_PARENT/fleet/agents" "$HOME_SYMLINK_PARENT/private-agents"
ln -s "$HOME_SYMLINK_PARENT/private-agents" "$HOME_SYMLINK_PARENT/fleet/agents"
if output=$(run_start "$HOME_SYMLINK_PARENT" coder-symlink-parent 2>&1); then
fail "generated file under a symlinked parent was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before symlinked parent rejection"
contains_literal "$output" 'code=unsafe-directory' || fail "symlinked parent diagnostic missing"
# Every managed ancestor is a boundary: MOSAIC_HOME, fleet, and agents. A
# symlink or group/world-writable ancestor must fail before environment parsing,
# workdir creation, or tmux effects. The malformed local input proves parsing
# was not reached when the ancestor rejection is reported.
assert_managed_ancestor_rejected() {
local ancestor="$1"
local hazard="$2"
local home="$ROOT/managed-${ancestor//\//-}-${hazard}"
local agent="coder-managed-${ancestor//\//-}-${hazard}"
local node
write_generated "$home" "$agent"
printf 'MOSAIC_AGENT_COMMAND=must-not-be-parsed\n' > "$home/fleet/agents/$agent.env.local"
chmod 600 "$home/fleet/agents/$agent.env.local"
rm -rf "$home/work"
case "$ancestor" in
MOSAIC_HOME) node="$home" ;;
MOSAIC_HOME/fleet) node="$home/fleet" ;;
MOSAIC_HOME/fleet/agents) node="$home/fleet/agents" ;;
*) fail "unknown managed ancestor: $ancestor" ;;
esac
if [ "$hazard" = symlink ]; then
local target="${node}-target"
mv "$node" "$target"
ln -s "$target" "$node"
else
chmod 777 "$node"
fi
: > "$TMUX_CALLS"
if output=$(run_start "$home" "$agent" 2>&1); then
fail "${hazard} $ancestor was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before $hazard $ancestor rejection"
[ ! -e "$home/work" ] || fail "workdir was created before $hazard $ancestor rejection"
contains_literal "$output" 'code=unsafe-' || fail "managed ancestor diagnostic missing"
if contains_literal "$output" 'key=MOSAIC_AGENT_COMMAND'; then
fail "environment parsing ran before $hazard $ancestor rejection"
fi
}
for managed_ancestor in MOSAIC_HOME MOSAIC_HOME/fleet MOSAIC_HOME/fleet/agents; do
assert_managed_ancestor_rejected "$managed_ancestor" symlink
assert_managed_ancestor_rejected "$managed_ancestor" group-world-writable
done
# A local file cannot shadow any roster-derived generated key. Validation must
# happen before fake tmux receives even a has-session call.
: > "$TMUX_CALLS"
HOME_SHADOW="$ROOT/shadow"
write_generated "$HOME_SHADOW" "coder1"
printf 'MOSAIC_AGENT_RUNTIME=codex\n' > "$HOME_SHADOW/fleet/agents/coder1.env.local"
chmod 600 "$HOME_SHADOW/fleet/agents/coder1.env.local"
if output=$(run_start "$HOME_SHADOW" coder1 2>&1); then
fail "generated-key shadow was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before generated-key shadow rejection"
contains_literal "$output" 'key=MOSAIC_AGENT_RUNTIME' || fail "shadow diagnostic omitted key"
contains_literal "$output" 'sha256=' || fail "shadow diagnostic omitted hash"
if contains_literal "$output" codex; then
fail "shadow diagnostic leaked value"
fi
# Arbitrary command compatibility is quarantined/rejected as data. Diagnostics
# may name the key and hash but must never echo the privileged command text.
: > "$TMUX_CALLS"
HOME_COMMAND="$ROOT/command"
write_generated "$HOME_COMMAND" "coder2"
COMMAND_VALUE='mosaic yolo codex --dangerous'
printf 'MOSAIC_AGENT_COMMAND=%s\n' "$COMMAND_VALUE" > "$HOME_COMMAND/fleet/agents/coder2.env.local"
chmod 600 "$HOME_COMMAND/fleet/agents/coder2.env.local"
if output=$(run_start "$HOME_COMMAND" coder2 2>&1); then
fail "arbitrary command override was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before command rejection"
contains_literal "$output" 'key=MOSAIC_AGENT_COMMAND' || fail "command diagnostic omitted key"
contains_literal "$output" 'sha256=' || fail "command diagnostic omitted hash"
if contains_literal "$output" "$COMMAND_VALUE"; then
fail "command diagnostic leaked command value"
fi
# Group/world-readable local input is not trusted even when its syntax is safe.
: > "$TMUX_CALLS"
HOME_PERMS="$ROOT/perms"
write_generated "$HOME_PERMS" "coder3"
printf 'MOSAIC_RUNTIME_BIN=/opt/mosaic/bin\n' > "$HOME_PERMS/fleet/agents/coder3.env.local"
chmod 644 "$HOME_PERMS/fleet/agents/coder3.env.local"
if output=$(run_start "$HOME_PERMS" coder3 2>&1); then
fail "world-readable local input was accepted"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before permissions rejection"
contains_literal "$output" 'code=unsafe-permissions' || fail "permission diagnostic missing"
# A unit/holder-like clean bootstrap must yield a pane with trusted HOME and
# computed PATH only. The pane command itself must not carry loader, shell
# control, arbitrary sentinel, or stale bootstrap variables.
: > "$TMUX_CALLS"
HOME_PANE_BOUNDARY="$ROOT/pane-boundary/.config/mosaic"
write_generated "$HOME_PANE_BOUNDARY" "coder-pane-boundary"
PANE_TRUSTED_HOME="${HOME_PANE_BOUNDARY%/.config/mosaic}"
PANE_STALE_HOME="$ROOT/stale-home"
PANE_STALE_PATH="$ROOT/stale-bin"
PANE_BASH_ENV="$ROOT/pane-boundary.bash-env"
printf 'MOSAIC_RUNTIME_BIN=%s\n' "$FAKE_BIN" > \
"$HOME_PANE_BOUNDARY/fleet/agents/coder-pane-boundary.env.local"
chmod 600 "$HOME_PANE_BOUNDARY/fleet/agents/coder-pane-boundary.env.local"
# This case does not go through run_start, so its pane binaries come from
# MOSAIC_RUNTIME_BIN=$FAKE_BIN in the env.local written above — not from the
# symlinks install_pane_binaries planted under the generated home, which this
# launcher never consults because HOME here is the trusted parent. That is a
# legitimate resolution path, but it means dropping MOSAIC_RUNTIME_BIN from
# this case on the belief that the symlinks cover it would break the #1241
# binary check rather than exercise it.
LD_PRELOAD='/not/loaded/by-clean-bootstrap.so' \
BASH_ENV="$PANE_BASH_ENV" \
MOSAIC_UNTRUSTED_SENTINEL='must-not-reach-pane' \
HOME="$PANE_STALE_HOME" \
PATH="$PANE_STALE_PATH" \
/usr/bin/env -i \
"HOME=$PANE_TRUSTED_HOME" \
"PATH=$FAKE_BIN:/usr/bin:/bin" \
"MOSAIC_HOME=$HOME_PANE_BOUNDARY" \
"MOSAIC_TEST_TMUX_CALLS=$TMUX_CALLS" \
"MOSAIC_TEST_HOME=$PANE_TRUSTED_HOME" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_TEST_EXECUTE_PANE=1 \
"MOSAIC_TEST_PANE_PID=$$" \
"$START" coder-pane-boundary
pane_args=$(tr '\0' '\n' < "$TMUX_CALLS")
contains_line "$pane_args" "HOME=$PANE_TRUSTED_HOME" || \
fail "pane did not restore trusted HOME"
contains_literal "$pane_args" "HOME=$PANE_STALE_HOME" && \
fail "pane inherited stale HOME"
contains_literal "$pane_args" "$PANE_STALE_PATH" && fail "pane inherited stale PATH"
for blocked in LD_PRELOAD= BASH_ENV= MOSAIC_UNTRUSTED_SENTINEL=; do
contains_literal "$pane_args" "$blocked" && fail "pane inherited $blocked"
done
check_pane_environment_boundary "$TMUX_CALLS" || \
fail "pane command did not use an adjacent /usr/bin/env -i boundary"
pane_environment=$(tr '\0' '\n' < "$HOME_PANE_BOUNDARY/fleet/pane-environment")
# Exercise the repository launcher at $START, not the independently installed
# host copy. Set-compare every declared generated projection entry with the
# launched process environment so a newly declared identity cannot be omitted
# by a hand-maintained per-variable assertion.
declared_generated_environment=$(sort "$HOME_PANE_BOUNDARY/fleet/agents/coder-pane-boundary.env.generated")
missing_or_changed_generated_environment=$(comm -23 \
<(printf '%s\n' "$declared_generated_environment") \
<(printf '%s\n' "$pane_environment" | sort))
if [ -n "$missing_or_changed_generated_environment" ]; then
missing_or_changed_keys=$(printf '%s\n' "$missing_or_changed_generated_environment" | cut -d= -f1 | paste -sd, -)
fail "runtime pane omitted or changed generated environment keys: $missing_or_changed_keys"
fi
contains_line "$pane_environment" "HOME=$PANE_TRUSTED_HOME" || \
fail "runtime pane did not receive trusted HOME"
contains_literal "$pane_environment" "$PANE_STALE_PATH" && fail "runtime pane received stale PATH"
for blocked in LD_PRELOAD= BASH_ENV= MOSAIC_UNTRUSTED_SENTINEL=; do
contains_literal "$pane_environment" "$blocked" && fail "runtime pane received $blocked"
done
# #1256. On a host with no system Node, tools/install.sh bootstraps one into
# ~/.mosaic/node/ and writes that directory to ~/.profile. The fleet unit runs
# `env -i ... bash --noprofile --norc`, so ~/.profile is never read — correctly, by
# design — and _build_runtime_bin_prefix does not list the bootstrap directory. Its
# `npm config get prefix` branch cannot cover the gap either: the installer points
# npm's prefix at ~/.npm-global, so that branch contributes the npm-global directory
# and never the Node one, however it resolves.
#
# The property under test is not "the string is in PATH". It is that the pane can
# EXECUTE a Node-shebang runtime binary — which is what `mosaic` is
# (`#!/usr/bin/env node`) and what actually failed: measured on a greenfield VM as
# `env: 'node': No such file or directory` after a clean install that reported success.
#
# So this case runs the pane for real and requires it to have run. A PATH-substring
# assertion would pass on a fix that put the directory in the wrong position, and it
# would keep passing if the pane later stopped running for some unrelated reason.
: > "$TMUX_CALLS"
HOME_NODE="$ROOT/bootstrap-node/.config/mosaic"
write_generated "$HOME_NODE" "coder-node"
NODE_PANE_HOME="${HOME_NODE%/.config/mosaic}"
NODE_BOOTSTRAP_BIN="$NODE_PANE_HOME/.mosaic/node/current/bin"
mkdir -p "$NODE_BOOTSTRAP_BIN"
# The bootstrapped runtime. It records that it ran, which is the evidence this case
# turns on: no node reachable from the pane means no marker.
cat > "$NODE_BOOTSTRAP_BIN/node" <<'SHIM'
#!/usr/bin/env bash
set -euo pipefail
env -0 > "${MOSAIC_HOME:?}/fleet/pane-environment"
SHIM
chmod +x "$NODE_BOOTSTRAP_BIN/node"
# write_generated plants its symlinks under the MOSAIC_HOME it is given; here the
# pane's HOME is the trusted parent, so the pane's view of "installed" is this
# directory instead. `pi` is what #1241 resolves against PANE_PATH; `mosaic` is what
# the pane then executes, and it is a Node script — not a bash script that would run
# anywhere and quietly hide the defect.
mkdir -p "$NODE_PANE_HOME/.npm-global/bin"
ln -sf "$FAKE_BIN/pi" "$NODE_PANE_HOME/.npm-global/bin/pi"
printf '#!/usr/bin/env node\n' > "$NODE_PANE_HOME/.npm-global/bin/mosaic"
chmod +x "$NODE_PANE_HOME/.npm-global/bin/mosaic"
# The npm branch is modelled ALIVE and still cannot close the gap, which is the
# stronger statement. An earlier draft of this case tried to model npm as absent —
# true on a real bootstrap host, where npm lives only in the Node directory — and it
# refused to run anywhere npm is in the system path, i.e. most machines. It was also
# the weaker claim: it would have proven only that a dead branch supplies nothing.
#
# On a bootstrap host the installer sets npm's prefix to ~/.npm-global. So even with
# `command -v npm` true and the branch executing, `npm config get prefix` yields the
# npm-global directory and never the Node one. The gap does not depend on whether
# that branch runs.
NODE_LAUNCHER_BIN="$ROOT/bootstrap-node-launcher-bin"
mkdir -p "$NODE_LAUNCHER_BIN"
ln -sf "$FAKE_BIN/tmux" "$NODE_LAUNCHER_BIN/tmux"
ln -sf "$FAKE_BIN/npm" "$NODE_LAUNCHER_BIN/npm"
/usr/bin/env -i \
"HOME=$NODE_PANE_HOME" \
"PATH=$NODE_LAUNCHER_BIN:/usr/bin:/bin" \
"MOSAIC_HOME=$HOME_NODE" \
"MOSAIC_TEST_TMUX_CALLS=$TMUX_CALLS" \
"MOSAIC_TEST_HOME=$NODE_PANE_HOME" \
"MOSAIC_TEST_NPM_PREFIX=$NODE_PANE_HOME/.npm-global" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_TEST_EXECUTE_PANE=1 \
"MOSAIC_TEST_PANE_PID=$$" \
"$START" coder-node
[ -f "$HOME_NODE/fleet/pane-environment" ] || \
fail "pane could not execute a Node-shebang runtime: $NODE_BOOTSTRAP_BIN is absent from PANE_PATH (#1256)"
node_pane_environment=$(tr '\0' '\n' < "$HOME_NODE/fleet/pane-environment")
# Colon-pad and match a whole element. A regex with `(^|:)` after `.*` looks like it
# does this and does not: an anchor cannot match mid-pattern, so it silently requires
# a leading colon and rejects the directory in FIRST position — which is where THIS
# FIXTURE puts it: it runs under `env -i` with no MOSAIC_RUNTIME_BIN, so the bootstrap
# directory leads. That is a property of the fixture, not of the fix — in general the
# directory sits second, after MOSAIC_RUNTIME_BIN. The colon padding makes the
# assertion position-independent either way, which is why it is written this way and
# not with an anchor. That produced a failure reading "pane ran but PANE_PATH does not
# carry <dir>" against a PATH whose first element was that dir.
node_pane_path=":$(printf '%s\n' "$node_pane_environment" | sed -n 's/^PATH=//p' | head -1):"
case "$node_pane_path" in
*":$NODE_BOOTSTRAP_BIN:"*) ;;
*) fail "pane ran but PANE_PATH does not carry $NODE_BOOTSTRAP_BIN (PATH=$node_pane_path)" ;;
esac
write_interaction_generated() {
local home="$1"
local agent="$2"
mkdir -p "$home/fleet/agents" "$home/fleet/run" "$home/work"
chmod 700 "$home" "$home/fleet" "$home/fleet/agents" "$home/fleet/run"
printf '123e4567-e89b-12d3-a456-426614174000\n' > "$home/fleet/run/holder-owner"
chmod 600 "$home/fleet/run/holder-owner"
cat > "$home/fleet/agents/$agent.env.generated" <<EOF
MOSAIC_AGENT_NAME=$agent
MOSAIC_GIT_IDENTITY=$agent
MOSAIC_AGENT_CLASS=operator-interaction
MOSAIC_AGENT_RUNTIME=pi
MOSAIC_AGENT_MODEL=openai/gpt-5.6-sol
MOSAIC_AGENT_REASONING=high
MOSAIC_AGENT_TOOL_POLICY=operator-interaction
MOSAIC_AGENT_WORKDIR=$home/work
MOSAIC_TMUX_SOCKET=mosaic-test
EOF
chmod 600 "$home/fleet/agents/$agent.env.generated"
}
run_interaction() {
local home="$1"
local agent="$2"
HOME="$home" PATH="$FAKE_BIN:$PATH" MOSAIC_TEST_TMUX_CALLS="$TMUX_CALLS" \
MOSAIC_TEST_HOME="$home" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_HOME="$home" "$INTERACTION_START" "$agent"
}
write_heartbeat_local() {
local home="$1"
local agent="$2"
mkdir -p "$home/run"
cat > "$home/fleet/agents/$agent.env.local" <<EOF
MOSAIC_HEARTBEAT_RUN_DIR=$home/run
MOSAIC_HEARTBEAT_INTERVAL=1
EOF
chmod 600 "$home/fleet/agents/$agent.env.local"
}
wait_for_sidecar_status() {
local file="$1"
for _retry in $(seq 1 30); do
grep -qF 'status=ok' "$file" 2>/dev/null && return 0
sleep 0.1
done
fail "heartbeat sidecar did not resume after native marker became stale or absent"
}
# A fresh Pi-native marker is authoritative: the shell sidecar may start but
# must not overwrite Pi's busy/ok/model heartbeat. It must resume only when
# the marker is stale or absent.
HOME_NATIVE_FRESH="$ROOT/native-fresh"
write_generated "$HOME_NATIVE_FRESH" "coder-native-fresh"
write_heartbeat_local "$HOME_NATIVE_FRESH" "coder-native-fresh"
FRESH_HB="$HOME_NATIVE_FRESH/run/coder-native-fresh.hb"
printf 'ts=native\npid=1\nstatus=busy\nmodel=authoritative-model\n' > "$FRESH_HB"
touch "$FRESH_HB.native"
MOSAIC_TEST_PANE_PID=$$ run_start "$HOME_NATIVE_FRESH" coder-native-fresh
sleep 0.3
fresh_content=$(cat "$FRESH_HB")
[ "$fresh_content" = 'ts=native
pid=1
status=busy
model=authoritative-model' ] || fail "fresh native heartbeat was overwritten"
HOME_NATIVE_STALE="$ROOT/native-stale"
write_generated "$HOME_NATIVE_STALE" "coder-native-stale"
write_heartbeat_local "$HOME_NATIVE_STALE" "coder-native-stale"
STALE_HB="$HOME_NATIVE_STALE/run/coder-native-stale.hb"
printf 'ts=native\npid=1\nstatus=busy\nmodel=stale-model\n' > "$STALE_HB"
touch -t 200001010000.00 "$STALE_HB.native"
# Hold the sidecar's observation epoch constant: assertion runtime must not age
# a fresh-marker mutant into the stale state that this fixture must distinguish.
STALE_OBSERVATION_EPOCH=$(date +%s)
MOSAIC_TEST_FIXED_EPOCH="$STALE_OBSERVATION_EPOCH" \
MOSAIC_TEST_PANE_PID=$$ run_start "$HOME_NATIVE_STALE" coder-native-stale
wait_for_sidecar_status "$STALE_HB"
HOME_NATIVE_ABSENT="$ROOT/native-absent"
write_generated "$HOME_NATIVE_ABSENT" "coder-native-absent"
write_heartbeat_local "$HOME_NATIVE_ABSENT" "coder-native-absent"
ABSENT_HB="$HOME_NATIVE_ABSENT/run/coder-native-absent.hb"
printf 'ts=native\npid=1\nstatus=busy\nmodel=absent-model\n' > "$ABSENT_HB"
MOSAIC_TEST_PANE_PID=$$ run_start "$HOME_NATIVE_ABSENT" coder-native-absent
wait_for_sidecar_status "$ABSENT_HB"
# The interaction wrapper delegates to the shared strict parser before applying
# its pinned policy, so malformed projection data wins over profile diagnostics.
: > "$TMUX_CALLS"
HOME_INTERACTION_MALFORMED="$ROOT/interaction-malformed"
write_interaction_generated "$HOME_INTERACTION_MALFORMED" "interaction-malformed"
printf 'UNTRUSTED_BOOTSTRAP=value\n' >> "$HOME_INTERACTION_MALFORMED/fleet/agents/interaction-malformed.env.generated"
if output=$(run_interaction "$HOME_INTERACTION_MALFORMED" interaction-malformed 2>&1); then
fail "interaction wrapper accepted malformed generated data"
fi
[ ! -s "$TMUX_CALLS" ] || fail "tmux ran before interaction strict-parser rejection"
contains_literal "$output" 'code=unknown-key' || fail "interaction did not use shared strict parser first"
# A syntactically valid but policy-incompatible projection reaches the pinned
# interaction policy check only after strict parsing and never starts tmux.
: > "$TMUX_CALLS"
HOME_INTERACTION_POLICY="$ROOT/interaction-policy"
write_interaction_generated "$HOME_INTERACTION_POLICY" "interaction-policy"
sed -i 's|^MOSAIC_AGENT_RUNTIME=pi$|MOSAIC_AGENT_RUNTIME=codex|' \
"$HOME_INTERACTION_POLICY/fleet/agents/interaction-policy.env.generated"
if output=$(run_interaction "$HOME_INTERACTION_POLICY" interaction-policy 2>&1); then
fail "interaction wrapper accepted a policy-incompatible projection"
fi
interaction_policy_args=$(tr '\0' '\n' < "$TMUX_CALLS")
contains_literal "$interaction_policy_args" new-session && \
fail "interaction pinned-policy rejection created a tmux session"
contains_literal "$output" 'operator interaction service requires runtime pi' || \
fail "interaction pinned-policy check did not follow strict parsing"
# #1241. The pane runs `mosaic yolo <runtime>` against PANE_PATH. A binary
# missing from that path is a launch failure, and it has to be named before the
# session is created — after it, the diagnostic dies with the pane.
assert_missing_pane_binary_rejected() {
local binary="$1"
local home="$ROOT/missing-$binary"
local agent="coder-missing-$binary"
write_generated "$home" "$agent"
rm -f "$home/.npm-global/bin/$binary"
: > "$TMUX_CALLS"
local output
if output=$(MOSAIC_TEST_PANE_PID=$$ run_start "$home" "$agent" 2>&1); then
fail "launch succeeded with '$binary' absent from the pane PATH"
fi
echo "$output" | grep -qF 'code=missing-binary' || fail "missing '$binary' diagnostic missing"
echo "$output" | grep -qF "'$binary'" || fail "missing-binary diagnostic did not name $binary"
if tr '\0' '\n' < "$TMUX_CALLS" | grep -qF new-session; then
fail "launcher created a session it knew would die ($binary absent)"
fi
}
assert_missing_pane_binary_rejected mosaic
assert_missing_pane_binary_rejected pi
# #1241. tmux destroys a session when its pane command exits, so no pane PID a
# second after new-session means the runtime died on startup. This used to be a
# WARNING about the heartbeat sidecar followed by exit 0 — three layers above it
# then reported a fleet that was not running.
: > "$TMUX_CALLS"
HOME_DEAD_PANE="$ROOT/dead-pane"
write_generated "$HOME_DEAD_PANE" "coder-dead-pane"
if output=$(MOSAIC_TEST_PANE_PID='' run_start "$HOME_DEAD_PANE" coder-dead-pane 2>&1); then
fail "launcher reported success over a pane that did not survive"
fi
echo "$output" | grep -qF 'code=pane-did-not-survive' || fail "dead-pane diagnostic missing"
if echo "$output" | grep -qiF 'heartbeat'; then
fail "dead pane is still being reported as a heartbeat-sidecar problem"
fi
tr '\0' '\n' < "$TMUX_CALLS" | grep -qF new-session || \
fail "dead-pane case did not reach the launch it is measuring"
# #1241, the other way a pane fails. Above, tmux destroyed the session and
# has-session said so. Here the session is still there and no PID comes back
# after the retries — a different fault (the pane is alive but unusable, or
# tmux is answering inconsistently) that an operator has to be told apart from
# a runtime that died on startup.
#
# This case exists because the branch that handles it shipped with nothing able
# to reach it: the shim answered has-session only for the holder, so every
# non-holder agent landed in the session-is-gone branch no matter what. A
# defensive branch nothing exercises is the same shape as the bug this whole
# change is about, one layer down.
: > "$TMUX_CALLS"
HOME_NO_PID="$ROOT/pane-no-pid"
write_generated "$HOME_NO_PID" "coder-no-pid"
if output=$(MOSAIC_TEST_PANE_PID='' MOSAIC_TEST_HELD_SESSIONS='=coder-no-pid:0.0' \
run_start "$HOME_NO_PID" coder-no-pid 2>&1); then
fail "launcher reported success over a session with no resolvable pane PID"
fi
echo "$output" | grep -qF 'code=pane-pid-unresolved' || \
fail "session-present/no-PID was not reported as pane-pid-unresolved: $output"
if echo "$output" | grep -qF 'code=pane-did-not-survive'; then
fail "a session tmux still reports was diagnosed as a destroyed session"
fi
if echo "$output" | grep -qiF 'heartbeat'; then
fail "an unresolvable pane PID is still being reported as a heartbeat-sidecar problem"
fi
# Exact stop derives the socket exclusively from the validated generated
# projection and ignores an ambient socket supplied by the caller.
: > "$TMUX_CALLS"
HOME_STOP="$ROOT/stop"
write_generated "$HOME_STOP" "coder-stop"
HOME="$HOME_STOP" PATH="$FAKE_BIN:$PATH" MOSAIC_TEST_TMUX_CALLS="$TMUX_CALLS" \
MOSAIC_TEST_HOME="$HOME_STOP" \
MOSAIC_TEST_FLEET_OWNER=123e4567-e89b-12d3-a456-426614174000 \
MOSAIC_HOME="$HOME_STOP" MOSAIC_TMUX_SOCKET=ambient-socket "$START" --stop coder-stop
stop_args=$(tr '\0' '\n' < "$TMUX_CALLS")
contains_line "$stop_args" mosaic-test || fail "exact stop did not use the validated generated socket"
contains_line "$stop_args" kill-session || fail "exact stop did not request session termination"
contains_line "$stop_args" '=coder-stop' || fail "exact stop did not exact-match the generated agent name"
if contains_literal "$stop_args" ambient-socket; then
fail "exact stop trusted an ambient socket"
fi
echo 'ok - start-agent-session generated environment boundary'
@@ -0,0 +1,196 @@
# Git provider wrappers
These scripts provide host-aware GitHub and Gitea issue, pull-request, milestone, and CI operations.
## Durable review provenance
A successful provider write command—or a wrapper message based only on that command's exit code—is **not** durable review provenance. Review comments, approvals, and change requests count as durable provenance only after the wrapper reads the created provider record back and verifies that it was created by _this_ write.
**The write is a direct Gitea REST `POST` that returns the created record's id.** Neither wrapper writes through `tea` — tea 0.11.1 can silently no-op while exiting 0 and cannot emit the id of a record it creates, so its exit code is worthless as proof of a durable write (#865). Instead:
- Comments (`issue-comment.sh`, and the `comment` action of `pr-review.sh`) `POST /api/v1/repos/{owner}/{repo}/issues/{index}/comments`, requiring a `201` and parsing the created comment's `id` from the response body.
- Reviews (`approve` / `request-changes`) `POST /api/v1/repos/{owner}/{repo}/pulls/{index}/reviews` with the `event` (`APPROVED` / `REQUEST_CHANGES`), the review `body`, and `commit_id` pinned to the PR's current head, then parse the created review's `id`. The review body travels _in the review submit itself_ — there is no separate detached comment to reconcile (a Gitea `REQUEST_CHANGES` review requires a non-empty body, which the submit carries).
**Verification keys on that exact provider-returned id.** The wrapper then `GET`s that one record directly — `GET /issues/comments/{id}` or `GET /pulls/{n}/reviews/{id}` — and requires that its `id` equals the created id, its **author login equals the acting identity** (resolved via `GET /api/v1/user` for the token in use), and, for comments, its body exactly matches what was submitted **and its returned web URL belongs to this exact provider and repository** (the `issue_url` / `pull_request_url` origin — scheme, host, and effective port — and full path, i.e. deployment prefix + exact `owner/repo` + kind + number, must match; a suffix/`endsWith` test would accept a look-alike host or a decoy path prefix, so the whole normalized URL is compared). The `comment` action of `pr-review.sh` additionally requires the returned resource be a **pull request** (a populated `pull_request_url`); a bare `issue_url` is rejected, so if issue `#N` exists but PR `#N` does not, an issue comment cannot be reported as a verified PR comment. (`issue-comment.sh` legitimately keeps the broader issue-or-PR acceptance.) For reviews, its state matches the requested action, its reviewed `commit_id` equals the PR head, **and its persisted body equals the submitted body** — an exact, presence- and type-checked equality (a missing/`null` persisted body no longer counts as an empty match), because Gitea can finalize/reuse a pending review id whose stored content was authored elsewhere, so the body is bound too. The write, the `/user` identity lookup, and the read-back all use the **same** credential — the effective login's token, or the host credential when no login is named — so the write is verified against the identity that actually performed it.
**A review's pinned head is re-checked after verification (current-head TOCTOU).** The `commit_id` is pinned to the PR head read _before_ the submit; between that read and the read-back the branch could advance (a force-push or a new commit), leaving a verified review attached to a now-superseded commit while the live tip carries unreviewed code. After the exact-id read-back succeeds, the wrapper re-reads the live PR head (`GET …/pulls/{n}`) and requires it still equals the submitted SHA; if the head advanced it fails closed (non-zero, no success line) rather than reporting a review that no longer covers the PR's current commit.
**This closes the concurrency window rather than documenting it.** Because verification keys on the id the create returned, a no-op create yields no id and fails closed with no list-scan fallback, and a _concurrent_ record — even one written by the _same_ identity with an identical body/state — has a _different_ id and cannot be mistaken for this write. There is no residual same-identity window: the earlier boundary-and-author heuristic (accept any `id > pre-write-max` with a matching author) is replaced entirely by exact-id attribution.
**Exact-id read-back is the sole authority.** Verification is a direct `GET` of the one record the create returned; there is no follow-up list enumeration. An earlier redundant pass that re-listed the record's page (`?limit=&page=1,2,…`) was removed: server-capped page sizes and list-pagination quirks made it a false-failure source (a durable, exact-id-verified record could be missed by a non-exhaustive enumeration), and it added nothing over the authoritative exact-id `GET`.
## Credential handling
The Gitea API token is **never passed on a curl command line.** An `Authorization: token <value>` argument would be visible to any local process that can read the process table (`ps` / `/proc/<pid>/cmdline`) for the lifetime of the request. Instead, every authenticated curl call writes the header into a private, mode-`0600` config file under `$TMPDIR` and passes it with `curl --config <file>` (`gitea_write_auth_config`), so only the file _path_ — never the token — appears in argv. Each such file is unlinked on every exit path (success and failure) by the caller's `RETURN` trap.
## `tea` invocation notes (Gitea)
- tea v0.11.1 has **no `comment` subcommand under `tea pr` or `tea issue`** — the `tea pr comment` / `tea issue comment` forms don't error, they silently fall through to a no-op and still exit 0, producing a false-success write (#865). tea's write subcommands (`tea comment`, `tea pr approve`/`reject`) also cannot report the id of the record they create, so their exit code cannot prove a durable write. These wrappers therefore do **not** write reviews or comments through `tea` at all; they use direct Gitea REST `POST`s that return the created record's id (see "Durable review provenance" above). `tea` is consulted only to enumerate the login list for host→login resolution.
- Because the review body is carried in the `POST …/reviews` submit itself, there is no separate detached review comment, and the historical `tea pr approve`/`reject` trailing-positional-argument vs. nonexistent `--comment`/`-comment` flag hazard (#835) no longer applies to these wrappers — no review comment is ever passed to `tea`.
### `--login` override
Both `pr-review.sh` and `issue-comment.sh` accept an optional `--login <name>` flag that overrides the automatically detected Gitea login for that single invocation. The override selects **which credential the REST write, the `/user` identity lookup, and the read-back all use** — its token is resolved from the tea config for that login name (`get_gitea_token_for_login`).
**With no `--login`, there is no tea lookup at all.** The acting credential is the calling identity's own, resolved by `get_gitea_token` (see "Per-agent Gitea identity" below), and there is deliberately no fallback from it. These wrappers previously _guessed_ a login from the repo host and looked that guess up in the tea config; on a shared-account host the guess resolved to the shared login, so an unqualified call authored its write as that account rather than as the caller. Since `get_gitea_token_for_login` matches by login **name** and performs no authentication check, a dead shared credential still resolved at rc=0 and the identity-aware resolver was never reached. A caller passing no `--login` is asking to act as itself, so `--login` is now the only route to the tea store (#1351). The resolved login is **host- and port-bound**: the login's configured URL host **and effective port** (the scheme's default port — 80 for `http`, 443 for `https` — applies when a port is omitted, symmetrically on both sides) must match the repo remote's, so a login name shared across hosts (or an override configured for a different Gitea, including one on a different port of the same host) can never send one host's credential to another — a host or port mismatch fails closed rather than leaking a cross-host token. Resolving the acting identity and the read-back from the _same_ login that performs the write is essential: a write performed under an overridden login must be verified against that login's identity, not the host default's. Callers who need a different login than the host default should pass `--login <reviewer-login>`.
As a durable successor to this mechanism, consider giving each reviewer/approver slot its own dedicated Gitea login credential, so that author≠reviewer holds at the credential level rather than relying on wrapper-level `--login` bookkeeping. This is a recommendation for future hardening, not something implemented by this flag.
## Per-agent Gitea identity (Gate-16 author≠reviewer)
By default, git push/fetch (via `git-credential-mosaic`) and the API wrappers above (via
`detect-platform.sh`'s `get_gitea_token`) all authenticate as the single shared Gitea
account/token configured through `tools/_lib/credentials.sh`. That means every agent in a
fleet commits, pushes, and opens PRs under one identity — with no cryptographic
separation between an author and a reviewer.
Both `git-credential-mosaic` and `get_gitea_token()` resolve an optional **per-agent
identity**:
1. `MOSAIC_GIT_IDENTITY` environment variable, or
2. `git config --get mosaic.gitIdentity` (set per-worktree; persists on disk across
non-persistent shells — `git config mosaic.gitIdentity <agent-id>`), or
3. (git-credential-mosaic only) the username git itself supplies for the credential
request.
### Which store a credential is read from
The store is chosen by what the identity **is**, not by which file happens to exist first:
| The identity | Its credential is read from |
| ------------------------------------------------------------------ | -------------------------------------------------------------------------- |
| has a directory at `<brain>/fleet/agents/<id>/` — it is a **seat** | `<brain>/fleet/agents/<id>/secrets/gitea-{usc,mosaicstack}-<id>.token` |
| does not — it is a **service identity** | `~/.config/mosaic/secrets/gitea-tokens/gitea-{usc,mosaicstack}-<id>.token` |
`<brain>` is `MOSAIC_BRAIN_HOME` if set, else `~/.mosaic` — the same resolution
`packages/mosaic/src/fleet/brain-home.ts` performs.
**There is no precedence between the two stores and no fallback from one to the other.**
A seat whose slot is empty is refused even when a same-named token sits in the framework
store. One credential lives in exactly one location: a second copy is drift rather than
redundancy, and the way drift surfaces is a stale copy returning 401, which reads as a
revoked token and sends whoever debugs it to the wrong place.
### What happens when nothing resolves
| identity resolves | token in its store | host runs a fleet | result |
| ----------------- | ------------------ | ----------------- | ------------------------- |
| yes | yes | — | that identity + token |
| yes | no | — | **fail closed** |
| no | — | yes | **fail closed** |
| no | — | no | shared account, unchanged |
A host "runs a fleet" when `<brain>/fleet/agents` exists — the same signal `brain-home.ts`
uses to decide a brain is active.
Failing closed means: nothing is emitted, the exit status is nonzero, a stderr diagnostic
names the identity, its source, the store it resolved to and the path that was expected,
and `git-credential-mosaic` additionally appends a record (identity, host, reason, cwd —
never a token value) to `${MOSAIC_CREDENTIAL_SPOOL:-~/.local/state/mosaic-credential-escalations}`.
The git operation fails; nothing is attributed to anyone.
The shared-account fallback that used to cover these two cases is why a PR could be
authored, commented and merged under an account whose owner did not open it — every seat
shared one identity, so the record could not be traced back afterwards. An
under-provisioned agent is refused rather than handed the most privileged account
available.
**On a host with no fleet, nothing changes**: no `fleet/agents` directory means the shared
account still answers, so this is a no-op for an operator who has not provisioned per-slot
tokens. On a host that does run a fleet, a human doing manual git work needs an identity
of their own — `MOSAIC_GIT_IDENTITY=<id>` with a provisioned slot. There is deliberately no
environment variable that restores the fallback; one would reintroduce exactly the
substitution this removes.
### The tea path: login resolution (#1356)
The wrappers that go through `tea` (`issue-list.sh`, `pr-list.sh`, `pr-view.sh`,
`lane-brief.sh`, and the tea half of `issue-close.sh`) cannot use a token directly: tea
0.14 only acts as a **login** already stored in `~/.config/tea/config.yml`. Those wrappers
therefore resolve a login name, not a token, and the resolution follows the same identity
as above:
1. Resolve the identity (`MOSAIC_GIT_IDENTITY`, then `git config mosaic.gitIdentity`).
2. Derive the Gitea instance from the repo host (`git.mosaicstack.dev``mosaicstack`,
`git.uscllc.com``usc`), or from the owner when `--repo owner/name` is given.
3. The canonical login is `<instance>-<identity>`. If tea has it, that login acts.
4. If the identity is set but that login is missing, the wrapper **fails closed**: nonzero
exit, empty stdout, and a stderr line naming the login it wanted and the source of the
identity. When `tea` itself is not installed the message says so instead, since "no such
login" would send the reader to create a login they cannot create.
5. With **no identity set**, the old host-default behaviour is unchanged (first login
configured for that host, else the API fallback).
Step 4 replaced a fallback that picked any login configured for the host, which meant a
seat with no login of its own silently acted as whichever seat had configured one. That
satisfied the author≠reviewer gate on paper while one actor held both names.
**Provisioning the logins.** `tools/fleet/seat-logins.sh` projects each seat's token from
its secrets store into tea's config under the canonical name. tea's config is a derived
cache of the secrets store: regenerate it with the script, never hand-edit it. Run it with
`--seat <seat>` for one seat (all seats when omitted), dry-run by default, `--apply` to write. A hand-made
alias holding a seat's token blocks its canonical name (tea refuses one token under two
names); `--adopt` renames it.
### Enabling it for a clone
The framework installer syncs `git-credential-mosaic` to
`~/.config/mosaic/tools/git/git-credential-mosaic` (executable) on every install/update,
but does **not** register it as git's credential helper automatically. Registration is a
one-time, explicit step:
```bash
# Per-repo (recommended — scopes the helper to this clone only):
git config credential.helper "$HOME/.config/mosaic/tools/git/git-credential-mosaic"
# Per-worktree identity pin (Gate-16 separation):
git config mosaic.gitIdentity <agent-id>
```
This is deliberately **not** auto-registered on install/update: `credential.helper` is
global, order-sensitive git config (`~/.gitconfig`) that can already hold an
operator-chosen credential manager (keychain, `store`, `manager-core`, …) for
repositories unrelated to Mosaic. Silently inserting an entry on every framework
install/upgrade risks reordering or shadowing that operator-owned surface across the
whole host — the same operator-owned config the installer's manifest system is
otherwise careful never to touch. Because identity is already resolved per-worktree
(`mosaic.gitIdentity`), the correct granularity for registering the helper is per-clone
too, so a documented manual step is the right shape here, not a global auto-write.
### Running these tests
`MOSAIC_GIT_IDENTITY` is inherited into each test's sandbox `HOME`, and **the tests disagree
about which value they need**, so no single ambient value passes all 29. Measured on `next` at
`a480ee83`, two full passes differing only in that variable:
| tests | identity exported | identity unset |
| ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | -------------- |
| `gitea-login-resolution`, `issue-comment-readback`, `issue-create-interactive-auth`, `pr-edit`, `pr-merge-gitea-empty-uid`, `pr-metadata-gitea` | **fail** | pass |
| `issue-close-fail-closed` | pass | **fail** |
| remaining 22 | pass | pass |
The six fail because inside a sandbox `HOME` the identity has no `fleet/agents/<id>/`
directory, so it is classified as a **service identity**, its store is unpopulated, and the
resolver correctly refuses with `Refusing to borrow another slot's token`. That is the
documented fail-closed behaviour above, reached from a state the test never intended.
`issue-close-fail-closed` is the mirror image: it asserts that no comment POST is attempted, so
it needs an identity resolving to an empty slot, and with the variable unset the shared account
answers and the POST goes through.
These read as wrapper regressions rather than as environment. Two seats independently
misdiagnosed them as a patch defect while reviewing #1352. Until each test controls its own
value (#1353), `env -u MOSAIC_GIT_IDENTITY` is the closest thing to a clean run at 28/29, with
`issue-close-fail-closed` the expected failure — and **"the suite passes" is not a statement
anyone can make here without naming the ambient value that produced it.**
### PowerShell parity
`detect-platform.ps1`'s Gitea wrappers authenticate through `tea` CLI logins
(`Get-GiteaLoginForHost`), not a raw-token `get_gitea_token`-equivalent function — there
is nothing to prepend the identity-resolution block to on the PowerShell side. A native
PowerShell git-credential helper is also unnecessary: `git-credential-mosaic` is invoked
by git's credential-helper protocol (stdin/stdout), which works identically under Git for
Windows' bundled `bash`/`sh` when configured via `credential.helper`, without a `.ps1`
counterpart. A `tea`-login-based per-agent identity for the PowerShell wrappers is a
separate, larger design (mapping identities to `tea login` profiles) and is out of scope
here.
@@ -0,0 +1,261 @@
# ci-queue-wait.ps1 - Wait until project CI queue is clear (no running/queued pipeline on branch head)
# Usage: .\ci-queue-wait.ps1 [-Branch main] [-TimeoutSeconds 900] [-IntervalSeconds 15] [-Purpose merge] [-RequireStatus]
[CmdletBinding()]
param(
[Alias("B")]
[string]$Branch = "main",
[Alias("t")]
[int]$TimeoutSeconds = 900,
[Alias("i")]
[int]$IntervalSeconds = 15,
[ValidateSet("push", "merge")]
[string]$Purpose = "merge",
[switch]$RequireStatus,
[Alias("h")]
[switch]$Help
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$ScriptDir\detect-platform.ps1"
function Show-Usage {
@"
Usage: ci-queue-wait.ps1 [-Branch main] [-TimeoutSeconds 900] [-IntervalSeconds 15] [-Purpose push|merge] [-RequireStatus]
Options:
-Branch, -B BRANCH Branch head to inspect (default: main)
-TimeoutSeconds, -t SECONDS Max wait time (default: 900)
-IntervalSeconds, -i SECONDS Poll interval (default: 15)
-Purpose VALUE push or merge (default: merge)
-RequireStatus Fail if no CI status contexts are present
-Help, -h Show help
"@
}
if ($Help) {
Show-Usage
exit 0
}
if ($TimeoutSeconds -lt 1 -or $IntervalSeconds -lt 1) {
Write-Error "TimeoutSeconds and IntervalSeconds must be positive integers."
exit 1
}
function Get-RemoteHost {
$remoteUrl = git remote get-url origin 2>$null
if ([string]::IsNullOrEmpty($remoteUrl)) { return $null }
if ($remoteUrl -match "^https?://([^/]+)/") { return $Matches[1] }
if ($remoteUrl -match "^git@([^:]+):") { return $Matches[1] }
return $null
}
function Get-GiteaToken {
param([string]$Host)
if ($env:GITEA_TOKEN) { return $env:GITEA_TOKEN }
$credPath = Join-Path $HOME ".git-credentials"
if (-not (Test-Path $credPath)) { return $null }
$line = Get-Content $credPath | Where-Object { $_ -like "*$Host*" } | Select-Object -First 1
if (-not $line) { return $null }
if ($line -match 'https?://[^@]*:([^@/]+)@') {
return $Matches[1]
}
return $null
}
function Get-QueueState {
param([object]$Payload)
$pending = @("pending", "queued", "running", "waiting")
$failure = @("failure", "error", "failed")
$success = @("success")
$state = ""
if ($null -ne $Payload.state) {
$state = "$($Payload.state)".ToLowerInvariant()
}
$values = @()
$statuses = @()
if ($null -ne $Payload.statuses) { $statuses = @($Payload.statuses) }
foreach ($s in $statuses) {
if ($null -eq $s) { continue }
$v = ""
if ($null -ne $s.status) { $v = "$($s.status)".ToLowerInvariant() }
elseif ($null -ne $s.state) { $v = "$($s.state)".ToLowerInvariant() }
if (-not [string]::IsNullOrEmpty($v)) { $values += $v }
}
# Zero contexts is classified FIRST: Gitea reports a synthetic aggregate
# state of "pending" alongside statuses:null / total_count:0 (a commit
# with no CI at all), and honoring that aggregate would poll to the
# timeout. With zero contexts there is nothing to wait on.
if ($values.Count -eq 0) { return "no-status" }
if ($pending -contains $state) { return "pending" }
if ($failure -contains $state) { return "terminal-failure" }
if ($success -contains $state) { return "terminal-success" }
if (($values | Where-Object { $pending -contains $_ }).Count -gt 0) { return "pending" }
if (($values | Where-Object { $failure -contains $_ }).Count -gt 0) { return "terminal-failure" }
if ($values.Count -gt 0 -and ($values | Where-Object { -not ($success -contains $_) }).Count -eq 0) { return "terminal-success" }
return "unknown"
}
function Print-PendingContexts {
param([object]$Payload)
$pending = @("pending", "queued", "running", "waiting")
$statuses = @()
if ($null -ne $Payload.statuses) { $statuses = @($Payload.statuses) }
if ($statuses.Count -eq 0) {
Write-Host "[ci-queue-wait] no status contexts reported"
return
}
$found = $false
foreach ($s in $statuses) {
if ($null -eq $s) { continue }
$name = if ($s.context) { $s.context } elseif ($s.name) { $s.name } else { "unknown-context" }
$value = if ($s.status) { "$($s.status)".ToLowerInvariant() } elseif ($s.state) { "$($s.state)".ToLowerInvariant() } else { "unknown" }
$target = if ($s.target_url) { $s.target_url } elseif ($s.url) { $s.url } else { "" }
if ($pending -contains $value) {
$found = $true
if ($target) {
Write-Host "[ci-queue-wait] pending: $name=$value ($target)"
}
else {
Write-Host "[ci-queue-wait] pending: $name=$value"
}
}
}
if (-not $found) {
Write-Host "[ci-queue-wait] no pending contexts"
}
}
$platform = Get-GitPlatform
$owner = Get-GitRepoOwner
$repo = Get-GitRepoName
if ([string]::IsNullOrEmpty($owner) -or [string]::IsNullOrEmpty($repo)) {
Write-Error "Could not determine repository owner/name from git remote."
exit 1
}
$headSha = $null
$host = $null
$giteaToken = $null
switch ($platform) {
"github" {
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
Write-Error "gh CLI is required for GitHub CI queue guard."
exit 1
}
$headSha = (& gh api "repos/$owner/$repo/branches/$Branch" --jq ".commit.sha").Trim()
if ([string]::IsNullOrEmpty($headSha)) {
Write-Error "Could not resolve $Branch head SHA."
exit 1
}
Write-Host "[ci-queue-wait] platform=github purpose=$Purpose branch=$Branch sha=$headSha"
}
"gitea" {
$host = Get-RemoteHost
if ([string]::IsNullOrEmpty($host)) {
Write-Error "Could not determine remote host."
exit 1
}
$giteaToken = Get-GiteaToken -Host $host
if ([string]::IsNullOrEmpty($giteaToken)) {
Write-Error "Gitea token not found. Set GITEA_TOKEN or configure ~/.git-credentials."
exit 1
}
try {
$branchUrl = "https://$host/api/v1/repos/$owner/$repo/branches/$Branch"
$branchPayload = Invoke-RestMethod -Method Get -Uri $branchUrl -Headers @{ Authorization = "token $giteaToken" }
$headSha = ($branchPayload.commit.id | Out-String).Trim()
}
catch {
# A not-yet-pushed feature branch has no in-flight pipeline, so the
# pre-push queue guard must treat 404 as "queue clear", not crash.
$statusCode = $null
if ($_.Exception.Response) {
$statusCode = [int]$_.Exception.Response.StatusCode
}
if ($statusCode -eq 404) {
Write-Host "[ci-queue-wait] branch $Branch not yet on remote — no in-flight pipeline; queue clear."
exit 0
}
Write-Error "Could not resolve $Branch head SHA from Gitea API."
exit 1
}
if ([string]::IsNullOrEmpty($headSha)) {
Write-Error "Could not resolve $Branch head SHA."
exit 1
}
Write-Host "[ci-queue-wait] platform=gitea purpose=$Purpose branch=$Branch sha=$headSha"
}
default {
Write-Error "Unsupported platform '$platform'."
exit 1
}
}
$deadline = (Get-Date).AddSeconds($TimeoutSeconds)
while ($true) {
if ((Get-Date) -gt $deadline) {
Write-Error "Timed out waiting for CI queue to clear on $Branch after ${TimeoutSeconds}s."
exit 124
}
try {
if ($platform -eq "github") {
$statusJson = & gh api "repos/$owner/$repo/commits/$headSha/status"
$payload = $statusJson | ConvertFrom-Json
}
else {
$statusUrl = "https://$host/api/v1/repos/$owner/$repo/commits/$headSha/status"
$payload = Invoke-RestMethod -Method Get -Uri $statusUrl -Headers @{ Authorization = "token $giteaToken" }
}
}
catch {
Write-Error "Failed to query commit status for queue guard."
exit 1
}
$state = Get-QueueState -Payload $payload
Write-Host "[ci-queue-wait] state=$state purpose=$Purpose branch=$Branch"
switch ($state) {
"pending" {
Print-PendingContexts -Payload $payload
Start-Sleep -Seconds $IntervalSeconds
}
"no-status" {
if ($RequireStatus) {
Write-Error "No CI status contexts found while -RequireStatus is set."
exit 1
}
Write-Host "[ci-queue-wait] no status contexts present; proceeding."
exit 0
}
"terminal-success" { exit 0 }
"terminal-failure" { exit 0 }
"unknown" { exit 0 }
default { exit 0 }
}
}
+678
View File
@@ -0,0 +1,678 @@
#!/bin/bash
# ci-queue-wait.sh - Wait until project CI queue is clear (no running/queued pipeline on branch head)
# Usage: ci-queue-wait.sh [-B branch] [-t timeout_sec] [-i interval_sec] [--purpose push|merge] [--require-status] [--no-ci-expected]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"
BRANCH=""
TARGET_REPO=""
HEAD_SHA=""
TIMEOUT_SEC=900
INTERVAL_SEC=15
PURPOSE="merge"
REQUIRE_STATUS=0
NO_CI_EXPECTED=0
usage() {
cat <<EOF
Usage: $(basename "$0") [-B branch] [-R owner/repo] [--sha full-40] [-t timeout_sec] [-i interval_sec] [--purpose push|merge] [--require-status] [--no-ci-expected]
Options:
-B, --branch BRANCH Branch head to inspect (default: current branch)
-R, --repo OWNER/REPO Repository containing the branch (default: origin repo)
--sha FULL_SHA Inspect this exact 40-character commit instead of resolving the branch
-t, --timeout SECONDS Max wait time in seconds (default: 900)
-i, --interval SECONDS Poll interval in seconds (default: 15)
--purpose VALUE Log context: push|merge (default: merge)
--require-status Fail if no CI status contexts are present
--no-ci-expected Assert this repository has no CI configured: a merge guard on a zero-context head becomes queue-clear (requires the acting token to hold repository admin); refused with exit 78 when MOSAIC_GIT_IDENTITY is unset or empty
-h, --help Show this help
Examples:
$(basename "$0")
$(basename "$0") --purpose push -t 600 -i 10
EOF
}
# get_remote_host and get_gitea_token are provided by detect-platform.sh
get_state_from_status_json() {
# Python source comes from -c so the provider payload remains on stdin.
# Never move the payload to argv: commit-status responses can exceed ARG_MAX.
python3 -c '
import json
import sys
try:
payload = json.load(sys.stdin)
if not isinstance(payload, dict):
raise ValueError("status payload is not an object")
except Exception:
print("malformed")
raise SystemExit(0)
# Gitea returns "statuses": null (not []) for a commit with zero status
# contexts -- e.g. any repo with no CI configured. Treat null as empty.
raw_statuses = payload.get("statuses", [])
if raw_statuses is None:
raw_statuses = []
raw_state = payload.get("state", "")
if not isinstance(raw_statuses, list) or not isinstance(raw_state, str):
print("malformed")
raise SystemExit(0)
statuses = raw_statuses
state = raw_state.lower()
pending_values = {"pending", "queued", "running", "waiting"}
failure_values = {"failure", "error", "failed"}
success_values = {"success"}
values = []
for item in statuses:
if not isinstance(item, dict):
print("malformed")
raise SystemExit(0)
raw_value = item.get("status") or item.get("state")
if not isinstance(raw_value, str) or not raw_value:
print("malformed")
raise SystemExit(0)
values.append(raw_value.lower())
# Zero contexts is classified FIRST: Gitea reports a synthetic aggregate
# state of "pending" alongside total_count:0, and an aggregate with no
# contexts behind it must not read as an in-flight pipeline (it would poll
# to the timeout). With zero contexts there is nothing to wait on.
if not values:
print("no-status")
elif any(value in pending_values for value in values) or state in pending_values:
print("pending")
elif any(value in failure_values for value in values) or state in failure_values:
print("terminal-failure")
elif all(value in success_values for value in values) and state in {"", "success"}:
print("terminal-success")
else:
print("unknown")
'
}
print_pending_contexts() {
python3 -c '
import json
import sys
try:
payload = json.load(sys.stdin)
except Exception:
print("[ci-queue-wait] unable to decode status payload")
raise SystemExit(0)
statuses = payload.get("statuses") or []
if not statuses:
print("[ci-queue-wait] no status contexts reported")
raise SystemExit(0)
pending_values = {"pending", "queued", "running", "waiting"}
found = False
for item in statuses:
if not isinstance(item, dict):
continue
name = item.get("context") or item.get("name") or "unknown-context"
value = str(item.get("status") or item.get("state") or "unknown").lower()
target = item.get("target_url") or item.get("url") or ""
if value in pending_values:
found = True
suffix = f" ({target})" if target else ""
print(f"[ci-queue-wait] pending: {name}={value}{suffix}")
if not found:
print("[ci-queue-wait] no pending contexts")
'
}
record_cannot_assert() {
local reason="$1"
local audit_log="${MOSAIC_CI_QUEUE_AUDIT_LOG:-${XDG_STATE_HOME:-${HOME:-}/.local/state}/mosaic/audit/ci-queue-wait.jsonl}"
if [[ -z "$audit_log" ]] || ! mkdir -p "$(dirname "$audit_log")"; then
echo "Error: CANNOT_ASSERT and audit directory is unavailable; refusing degraded pass." >&2
return 70
fi
if ! python3 - "$audit_log" "$reason" "${PLATFORM:-unknown}" "$PURPOSE" "${BRANCH:-unknown}" "${OWNER:-unknown}/${REPO:-unknown}" <<'PY'
import datetime
import json
import os
import sys
path, reason, platform, purpose, branch, repo = sys.argv[1:]
record = {
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"outcome": "CANNOT_ASSERT",
"reason": reason,
"platform": platform,
"purpose": purpose,
"disposition": "hold" if purpose == "merge" else "degraded-pass",
"branch": branch,
"repo": repo,
}
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
try:
os.write(fd, (json.dumps(record, separators=(",", ":")) + "\n").encode())
finally:
os.close(fd)
PY
then
echo "Error: CANNOT_ASSERT and audit write failed at ${audit_log}; refusing degraded pass." >&2
return 70
fi
if [[ "$PURPOSE" == "merge" ]]; then
echo "[ci-queue-wait] CANNOT_ASSERT reason=${reason} purpose=merge branch=${BRANCH:-unknown}; audited=${audit_log}; HOLD (exit 75). Retry after provider recovery; no manual reset is required." >&2
return 75
fi
echo "[ci-queue-wait] CANNOT_ASSERT reason=${reason} purpose=push branch=${BRANCH:-unknown}; audited=${audit_log}; push may proceed in degraded mode." >&2
return 0
}
# Durable audit record for an explicit no-CI assertion event (granted or
# refused). Same JSONL sink and field shape as record_cannot_assert so one
# reader covers all three outcomes; the outcome value distinguishes them.
# rc 70 on an unwritable sink: a merge pass that cannot be audited must not
# be reachable, mirroring record_cannot_assert's refusal of a degraded pass.
record_assertion_event() {
local outcome="$1" reason="$2" asserted_by="$3"
local audit_log="${MOSAIC_CI_QUEUE_AUDIT_LOG:-${XDG_STATE_HOME:-${HOME:-}/.local/state}/mosaic/audit/ci-queue-wait.jsonl}"
if [[ -z "$audit_log" ]] || ! mkdir -p "$(dirname "$audit_log")"; then
echo "Error: could not write ${outcome} audit record (audit directory unavailable at ${audit_log})." >&2
return 70
fi
if ! python3 - "$audit_log" "$outcome" "$reason" "$asserted_by" "${PLATFORM:-unknown}" "$PURPOSE" "${BRANCH:-unknown}" "${OWNER:-unknown}/${REPO:-unknown}" <<'PY'
import datetime
import json
import os
import sys
path, outcome, reason, asserted_by, platform, purpose, branch, repo = sys.argv[1:]
record = {
"timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"outcome": outcome,
"reason": reason,
"platform": platform,
"purpose": purpose,
"branch": branch,
"repo": repo,
"asserted_by": asserted_by,
}
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
try:
os.write(fd, (json.dumps(record, separators=(",", ":")) + "\n").encode())
finally:
os.close(fd)
PY
then
echo "Error: could not write ${outcome} audit record at ${audit_log}; refusing to proceed unaudited." >&2
return 70
fi
return 0
}
github_get_branch_head_sha() {
local owner="$1"
local repo="$2"
local branch="$3"
gh api "repos/${owner}/${repo}/branches/${branch}" --jq '.commit.sha'
}
# Repository-admin state for the acting credential, GitHub flavor. The
# repository object's permissions.admin is the field; read through the same
# gh CLI the guard already authenticates with. rc 0 = admin, 1 = not admin
# (or field absent), 2 = indeterminate (transport/API failure).
github_repo_admin_state() {
local owner="$1"
local repo="$2"
local perm
if ! perm=$(gh api "repos/${owner}/${repo}" --jq '.permissions.admin' 2>/dev/null); then
return 2
fi
case "$perm" in
true) return 0 ;;
false|null|"") return 1 ;;
*) return 2 ;;
esac
}
github_get_commit_status_json() {
local owner="$1"
local repo="$2"
local sha="$3"
local work_root status_file checks_file
work_root="${AGENT_WORK_ROOT:-${HOME:-}/.cache/mosaic/ci-queue-wait}"
mkdir -p "$work_root" || return 1
status_file=$(mktemp "$work_root/github-status.XXXXXX") || return 1
checks_file=$(mktemp "$work_root/github-checks.XXXXXX") || {
rm -f "$status_file"
return 1
}
if ! gh api --paginate --slurp "repos/${owner}/${repo}/commits/${sha}/statuses?per_page=100" > "$status_file" ||
! gh api --paginate --slurp "repos/${owner}/${repo}/commits/${sha}/check-runs?per_page=100&filter=latest" > "$checks_file"; then
rm -f "$status_file" "$checks_file"
return 1
fi
python3 - "$status_file" "$checks_file" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as handle:
status_pages = json.load(handle)
with open(sys.argv[2], encoding="utf-8") as handle:
check_pages = json.load(handle)
if not isinstance(status_pages, list) or not isinstance(check_pages, list):
raise SystemExit(1)
# The statuses endpoint is newest-first and can contain retries for one context.
# Keep only the newest entry per context after flattening every page.
combined = []
seen_contexts = set()
for page in status_pages:
if not isinstance(page, list):
raise SystemExit(1)
for status in page:
if not isinstance(status, dict):
raise SystemExit(1)
context = status.get("context")
if not isinstance(context, str) or not context or context in seen_contexts:
continue
seen_contexts.add(context)
combined.append(status)
check_runs = []
reported_total = 0
for page in check_pages:
if not isinstance(page, dict):
raise SystemExit(1)
page_runs = page.get("check_runs") or []
total_count = page.get("total_count")
if not isinstance(page_runs, list) or not isinstance(total_count, int):
raise SystemExit(1)
reported_total = max(reported_total, total_count)
check_runs.extend(page_runs)
if len(check_runs) < reported_total:
raise SystemExit(1)
for run in check_runs:
if not isinstance(run, dict):
raise SystemExit(1)
status = run.get("status")
conclusion = run.get("conclusion")
if status != "completed":
value = "pending"
elif conclusion == "success":
value = "success"
elif conclusion in {"failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale"}:
value = "failure"
else:
value = "unknown"
combined.append({
"context": run.get("name") or "github-check",
"status": value,
"target_url": run.get("html_url") or run.get("details_url") or "",
})
json.dump({"state": "", "statuses": combined}, sys.stdout)
PY
local status=$?
rm -f "$status_file" "$checks_file"
return "$status"
}
gitea_get_branch_head_sha() {
local host="$1"
local repo="$2"
local branch="$3"
local token="$4"
local url="https://${host}/api/v1/repos/${repo}/branches/${branch}"
# Capture HTTP status so an absent branch (404) is distinguished from an API
# error. A not-yet-pushed feature branch has no in-flight pipeline, so the
# pre-push queue guard must treat 404 as "queue clear", not crash.
local resp code body
resp=$(curl -sS -H "User-Agent: curl/8" -H "Authorization: token ${token}" -w $'\n%{http_code}' "$url")
code="${resp##*$'\n'}"
body="${resp%$'\n'*}"
if [[ "$code" == "404" ]]; then
echo "__BRANCH_ABSENT__"
return 0
fi
if [[ "$code" != "200" ]]; then
return 1
fi
printf '%s' "$body" | python3 -c '
import json, sys
data = json.load(sys.stdin)
commit = data.get("commit") or {}
print((commit.get("id") or "").strip())
'
}
gitea_get_commit_status_json() {
local host="$1"
local repo="$2"
local sha="$3"
local token="$4"
local url="https://${host}/api/v1/repos/${repo}/commits/${sha}/status"
curl -fsSL -H "User-Agent: curl/8" -H "Authorization: token ${token}" "$url"
}
# Repository-admin state for the acting credential, Gitea flavor. The guard's
# existing fetches (branch head, combined status) carry no permissions object
# (measured: neither response includes one), so the elevation check reads the
# repository object's permissions.admin, the one documented carrier of that
# field. rc 0 = admin, 1 = not admin (or field absent), 2 = indeterminate
# (non-200 or unparseable).
gitea_repo_admin_state() {
local host="$1"
local repo="$2"
local token="$3"
local url="https://${host}/api/v1/repos/${repo}"
local resp code body
resp=$(curl -sS -H "User-Agent: curl/8" -H "Authorization: token ${token}" -w $'\n%{http_code}' "$url") || return 2
code="${resp##*$'\n'}"
body="${resp%$'\n'*}"
if [[ "$code" != "200" ]]; then
return 2
fi
printf '%s' "$body" | python3 -c '
import json
import sys
try:
payload = json.load(sys.stdin)
except Exception:
raise SystemExit(2)
if not isinstance(payload, dict):
raise SystemExit(2)
permissions = payload.get("permissions")
if not isinstance(permissions, dict) or permissions.get("admin") is not True:
raise SystemExit(1)
raise SystemExit(0)
'
}
while [[ $# -gt 0 ]]; do
case "$1" in
-B|--branch)
BRANCH="$2"
shift 2
;;
-R|--repo)
TARGET_REPO="$2"
shift 2
;;
--sha)
HEAD_SHA="$2"
shift 2
;;
-t|--timeout)
TIMEOUT_SEC="$2"
shift 2
;;
-i|--interval)
INTERVAL_SEC="$2"
shift 2
;;
--purpose)
PURPOSE="$2"
shift 2
;;
--require-status)
REQUIRE_STATUS=1
shift
;;
--no-ci-expected)
NO_CI_EXPECTED=1
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
usage >&2
exit 1
;;
esac
done
if ! [[ "$TIMEOUT_SEC" =~ ^[0-9]+$ ]] || ! [[ "$INTERVAL_SEC" =~ ^[0-9]+$ ]]; then
echo "Error: timeout and interval must be integer seconds." >&2
exit 1
fi
if [[ -n "$HEAD_SHA" && ! "$HEAD_SHA" =~ ^[0-9a-fA-F]{40}$ ]]; then
echo "Error: --sha must be a full 40-character hexadecimal commit SHA." >&2
exit 1
fi
if [[ -n "$TARGET_REPO" && ! "$TARGET_REPO" =~ ^[^/[:space:]]+/[^/[:space:]]+$ ]]; then
echo "Error: --repo must be OWNER/REPO." >&2
exit 1
fi
if [[ "$PURPOSE" != "push" && "$PURPOSE" != "merge" ]]; then
echo "Error: --purpose must be push or merge." >&2
exit 1
fi
if [[ "$NO_CI_EXPECTED" -eq 1 && "$REQUIRE_STATUS" -eq 1 ]]; then
echo "Error: --no-ci-expected and --require-status contradict each other: one asserts the repository has no CI, the other demands status contexts. Pass at most one." >&2
exit 1
fi
OWNER="unknown"
REPO="unknown"
PLATFORM="unknown"
if ! OWNER=$(get_repo_owner) || [[ -z "$OWNER" ]]; then
record_cannot_assert "repository-owner-unresolvable"
exit $?
fi
if ! REPO=$(get_repo_name) || [[ -z "$REPO" ]]; then
record_cannot_assert "repository-name-unresolvable"
exit $?
fi
if ! detect_platform > /dev/null; then
PLATFORM="${PLATFORM:-unknown}"
record_cannot_assert "unsupported-platform"
exit $?
fi
PLATFORM="${PLATFORM:-unknown}"
if [[ -n "$TARGET_REPO" ]]; then
OWNER="${TARGET_REPO%%/*}"
REPO="${TARGET_REPO##*/}"
fi
if [[ -z "$BRANCH" ]]; then
if ! BRANCH=$(git symbolic-ref --quiet --short HEAD) || [[ -z "$BRANCH" ]]; then
record_cannot_assert "current-branch-unresolvable"
exit $?
fi
fi
# T51 WP5b (spec 4.1, review ruling C4/F8): the declaration adds ROUTE CONTEXT only.
# Branch-selection semantics are UNCHANGED — the guard keeps inspecting the
# exact head above. No declaration dependency gates the wait (4.3/DR2 R9:
# blocking here adds a blocker with no safety gain); absence is silent.
# shellcheck source=packages/mosaic/framework/tools/git/ci-queue-wait.sh
if git rev-parse --show-toplevel >/dev/null 2>&1 \
&& [ -f "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/repo-decl.sh" ]; then
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/repo-decl.sh"
repo_decl_load
if [[ "$DECL_STATE" == invalid ]]; then
repo_decl_report_invalid
elif [[ "$DECL_STATE" == valid && "$DECL_SCHEMA" == 2 ]]; then
route="feature"
if [[ "$BRANCH" == "$DECL_TRUNK" ]]; then
route="trunk (integration head)"
elif [[ "$BRANCH" == "$DECL_RELEASE" ]]; then
route="release branch"
fi
echo "repo-decl: route context flow=$DECL_FLOW trunk=$DECL_TRUNK release=$DECL_RELEASE; guarded head '$BRANCH' is a $route head (spec 4.1)" >&2
fi
fi
if [[ "$PLATFORM" == "github" ]]; then
if ! command -v gh >/dev/null 2>&1; then
record_cannot_assert "github-cli-unavailable"
exit $?
fi
if [[ -z "$HEAD_SHA" ]]; then
if ! HEAD_SHA=$(github_get_branch_head_sha "$OWNER" "$REPO" "$BRANCH") || [[ -z "$HEAD_SHA" ]]; then
record_cannot_assert "branch-head-unavailable"
exit $?
fi
fi
echo "[ci-queue-wait] platform=github purpose=${PURPOSE} branch=${BRANCH} sha=${HEAD_SHA}"
elif [[ "$PLATFORM" == "gitea" ]]; then
if ! HOST=$(get_remote_host) || [[ -z "$HOST" ]]; then
record_cannot_assert "remote-host-unresolvable"
exit $?
fi
if ! TOKEN=$(get_gitea_token "$HOST") || [[ -z "$TOKEN" ]]; then
record_cannot_assert "credential-unresolvable"
exit $?
fi
if [[ -z "$HEAD_SHA" ]]; then
if ! HEAD_SHA=$(gitea_get_branch_head_sha "$HOST" "$OWNER/$REPO" "$BRANCH" "$TOKEN"); then
record_cannot_assert "branch-head-unavailable"
exit $?
fi
if [[ "$HEAD_SHA" == "__BRANCH_ABSENT__" ]]; then
echo "[ci-queue-wait] branch ${BRANCH} not yet on remote — no in-flight pipeline; queue clear."
exit 0
fi
if [[ -z "$HEAD_SHA" ]]; then
record_cannot_assert "branch-head-unavailable"
exit $?
fi
fi
echo "[ci-queue-wait] platform=gitea purpose=${PURPOSE} branch=${BRANCH} sha=${HEAD_SHA}"
else
record_cannot_assert "unsupported-platform"
exit $?
fi
START_TS=$(date +%s)
DEADLINE_TS=$((START_TS + TIMEOUT_SEC))
while true; do
NOW_TS=$(date +%s)
if (( NOW_TS > DEADLINE_TS )); then
echo "Error: ASSERTED_NOT_READY state=pending; timed out waiting for CI queue to clear on ${BRANCH} after ${TIMEOUT_SEC}s." >&2
exit 124
fi
if [[ "$PLATFORM" == "github" ]]; then
if ! STATUS_JSON=$(github_get_commit_status_json "$OWNER" "$REPO" "$HEAD_SHA"); then
record_cannot_assert "status-provider-unreachable"
exit $?
fi
else
if ! STATUS_JSON=$(gitea_get_commit_status_json "$HOST" "$OWNER/$REPO" "$HEAD_SHA" "$TOKEN"); then
record_cannot_assert "status-provider-unreachable"
exit $?
fi
fi
STATE=$(printf '%s' "$STATUS_JSON" | get_state_from_status_json)
echo "[ci-queue-wait] state=${STATE} purpose=${PURPOSE} branch=${BRANCH}"
case "$STATE" in
pending)
printf '%s' "$STATUS_JSON" | print_pending_contexts
sleep "$INTERVAL_SEC"
;;
terminal-success)
exit 0
;;
no-status)
if [[ "$REQUIRE_STATUS" -eq 1 ]]; then
echo "Error: ASSERTED_NOT_READY state=no-status; --require-status was set for ${BRANCH}." >&2
exit 3
fi
# A head with zero status contexts has no CI queue to wait on.
# For push, that is queue-clear (a repo with no CI must remain
# pushable) -- mirroring record_cannot_assert's dispositions
# (push=degraded-pass, merge=hold). Merge stays fail-closed:
# no-status there may just mean CI has not reported yet.
if [[ "$PURPOSE" == "push" ]]; then
echo "[ci-queue-wait] queue-clear state=no-status purpose=push branch=${BRANCH}; no queued or running CI."
exit 0
fi
if [[ "$NO_CI_EXPECTED" -eq 1 ]]; then
# Explicit, elevated, audit-visible assertion that this
# repository has no CI to wait on. The zero-context case is
# the ONLY state the flag reclassifies: a pending or failed
# context still holds or fails exactly as without it, and a
# non-admin token is refused rather than trusted.
# The assertion must name an asserting identity: "unknown"
# attributes nothing, so a caller with MOSAIC_GIT_IDENTITY
# unset or empty is refused (exit 78) BEFORE the permission
# lookup -- an unattributable caller never triggers that
# network call.
if [[ -z "${MOSAIC_GIT_IDENTITY:-}" ]]; then
record_assertion_event "ASSERTION_UNATTRIBUTABLE" "actor-unattributable" "unknown" \
|| echo "Warning: could not write the ASSERTION_UNATTRIBUTABLE audit record; the refusal itself stands." >&2
echo "Error: ASSERTION_UNATTRIBUTABLE state=no-status purpose=merge asserted-by=unknown reason=no-ci-expected branch=${BRANCH}; --no-ci-expected requires MOSAIC_GIT_IDENTITY to name the asserting identity and it is unset or empty (exit 78)." >&2
exit 78
fi
ASSERTED_BY="${MOSAIC_GIT_IDENTITY}"
ADMIN_STATE=2
if [[ "$PLATFORM" == "github" ]]; then
if github_repo_admin_state "$OWNER" "$REPO"; then ADMIN_STATE=0; else ADMIN_STATE=$?; fi
else
if gitea_repo_admin_state "$HOST" "$OWNER/$REPO" "$TOKEN"; then ADMIN_STATE=0; else ADMIN_STATE=$?; fi
fi
case "$ADMIN_STATE" in
0)
record_assertion_event "NO_CI_ASSERTED" "no-ci-expected" "$ASSERTED_BY" || exit $?
echo "[ci-queue-wait] queue-clear state=no-status purpose=merge asserted-by=${ASSERTED_BY} reason=no-ci-expected branch=${BRANCH}"
exit 0
;;
1)
record_assertion_event "ASSERTION_REFUSED" "actor-not-repo-admin" "$ASSERTED_BY" \
|| echo "Warning: could not write the ASSERTION_REFUSED audit record; the refusal itself stands." >&2
echo "Error: ASSERTION_REFUSED state=no-status purpose=merge asserted-by=${ASSERTED_BY} reason=no-ci-expected branch=${BRANCH}; --no-ci-expected requires repository admin and the acting token is not an admin of ${OWNER}/${REPO} (exit 77)." >&2
exit 77
;;
*)
record_cannot_assert "repo-permissions-unavailable"
exit $?
;;
esac
fi
echo "Error: ASSERTED_NOT_READY state=no-status purpose=${PURPOSE} branch=${BRANCH}." >&2
exit 3
;;
terminal-failure)
if [[ "$PURPOSE" == "push" ]]; then
echo "[ci-queue-wait] queue-clear state=terminal-failure purpose=push branch=${BRANCH}; no queued or running CI."
exit 0
fi
echo "Error: ASSERTED_NOT_READY state=terminal-failure purpose=${PURPOSE} branch=${BRANCH}." >&2
exit 3
;;
malformed|unknown)
echo "Error: ASSERTED_NOT_READY state=${STATE} purpose=${PURPOSE} branch=${BRANCH}." >&2
exit 3
;;
*)
echo "Error: ASSERTED_NOT_READY unrecognized-state=${STATE} purpose=${PURPOSE} branch=${BRANCH}." >&2
exit 3
;;
esac
done
@@ -0,0 +1,231 @@
# detect-platform.ps1 - Detect git platform (Gitea or GitHub) for current repo
# Usage: . .\detect-platform.ps1; Get-GitPlatform
# or: .\detect-platform.ps1 (prints platform name)
function Get-GitPlatform {
[CmdletBinding()]
param()
$remoteUrl = git remote get-url origin 2>$null
if ([string]::IsNullOrEmpty($remoteUrl)) {
Write-Error "Not a git repository or no origin remote"
return $null
}
# Check for GitHub
if ($remoteUrl -match "github\.com") {
return "github"
}
# Check for common Gitea indicators
# Gitea URLs typically don't contain github.com, gitlab.com, bitbucket.org
if ($remoteUrl -notmatch "gitlab\.com" -and $remoteUrl -notmatch "bitbucket\.org") {
# Assume Gitea for self-hosted repos
return "gitea"
}
return "unknown"
}
function Get-GitRepoInfo {
[CmdletBinding()]
param()
$remoteUrl = git remote get-url origin 2>$null
if ([string]::IsNullOrEmpty($remoteUrl)) {
Write-Error "Not a git repository or no origin remote"
return $null
}
# Extract owner/repo from URL
# Handles: git@host:owner/repo.git, https://host/owner/repo.git, https://host/owner/repo
$repoPath = $remoteUrl
if ($remoteUrl -match "^git@") {
$repoPath = ($remoteUrl -split ":")[1]
} else {
# Remove protocol and host
$repoPath = $remoteUrl -replace "^https?://[^/]+/", ""
}
# Remove .git suffix if present
$repoPath = $repoPath -replace "\.git$", ""
return $repoPath
}
function Get-GitRemoteHost {
[CmdletBinding()]
param()
$remoteUrl = git remote get-url origin 2>$null
if ([string]::IsNullOrEmpty($remoteUrl)) {
Write-Error "Not a git repository or no origin remote"
return $null
}
if ($remoteUrl -match "^https?://([^/]+)/") {
$remoteHost = $Matches[1]
return ($remoteHost -replace "^.*@", "")
}
if ($remoteUrl -match "^git@([^:]+):") {
return $Matches[1]
}
return $null
}
function Get-TeaLoginList {
[CmdletBinding()]
param()
$json = tea login list --output json 2>$null
if (-not $json) {
return @()
}
try {
$items = $json | ConvertFrom-Json
} catch {
return @()
}
if ($null -eq $items) {
return @()
}
return @($items)
}
function Test-GiteaUrlMatchesHost {
[CmdletBinding()]
param(
[string]$Url,
[string]$GiteaHost
)
if ([string]::IsNullOrEmpty($Url) -or [string]::IsNullOrEmpty($GiteaHost)) {
return $false
}
try {
$uri = [Uri]$Url
return $uri.Host -eq $GiteaHost
} catch {
return $false
}
}
function Find-TeaLoginForHost {
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string]$GiteaHost)
foreach ($login in Get-TeaLoginList) {
$name = if ($login.name) { [string]$login.name } elseif ($login.Name) { [string]$login.Name } else { "" }
$url = if ($login.url) { [string]$login.url } elseif ($login.URL) { [string]$login.URL } else { "" }
if ([string]::IsNullOrEmpty($name) -or [string]::IsNullOrEmpty($url)) {
continue
}
try {
$uri = [Uri]$url
if ($uri.Host -eq $GiteaHost) {
return $name
}
} catch {
continue
}
}
return $null
}
function Test-TeaLoginMatchesHost {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)][string]$LoginName,
[Parameter(Mandatory=$true)][string]$GiteaHost
)
foreach ($login in Get-TeaLoginList) {
$name = if ($login.name) { [string]$login.name } elseif ($login.Name) { [string]$login.Name } else { "" }
$url = if ($login.url) { [string]$login.url } elseif ($login.URL) { [string]$login.URL } else { "" }
if ($name -ne $LoginName -or [string]::IsNullOrEmpty($url)) {
continue
}
try {
$uri = [Uri]$url
return $uri.Host -eq $GiteaHost
} catch {
return $false
}
}
return $false
}
function Get-GiteaLoginForHost {
[CmdletBinding()]
param([string]$GiteaHost)
if ([string]::IsNullOrEmpty($GiteaHost)) {
$GiteaHost = Get-GitRemoteHost
}
if ([string]::IsNullOrEmpty($GiteaHost)) {
return $null
}
if ($env:GITEA_LOGIN) {
if (Test-TeaLoginMatchesHost -LoginName $env:GITEA_LOGIN -GiteaHost $GiteaHost) {
return $env:GITEA_LOGIN
}
}
return Find-TeaLoginForHost -GiteaHost $GiteaHost
}
function Get-GiteaRepoArgs {
[CmdletBinding()]
param()
$repo = Get-GitRepoInfo
$hostName = Get-GitRemoteHost
$login = Get-GiteaLoginForHost -GiteaHost $hostName
if ([string]::IsNullOrEmpty($repo) -or [string]::IsNullOrEmpty($login)) {
return @()
}
return @("--repo", $repo, "--login", $login)
}
function Get-GitRepoOwner {
[CmdletBinding()]
param()
$repoInfo = Get-GitRepoInfo
if ($repoInfo) {
return ($repoInfo -split "/")[0]
}
return $null
}
function Get-GitRepoName {
[CmdletBinding()]
param()
$repoInfo = Get-GitRepoInfo
if ($repoInfo) {
return ($repoInfo -split "/")[-1]
}
return $null
}
# If script is run directly (not dot-sourced), output the platform
if ($MyInvocation.InvocationName -ne ".") {
Get-GitPlatform
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,64 @@
#!/usr/bin/python3
# git-credential-mosaic — production entrypoint (P0-SEC R4, rev-code-02 B1).
#
# WHY THIS IS NOT BASH: three review rounds falsified every in-bash startup
# guard. A non-interactive bash sources $BASH_ENV and imports exported
# functions BEFORE the first script line, so read(), unset(), exit(),
# declare(), printf() — every callable — can be shadows that fake the
# ancestry, defeat the scrub, or forge diagnostics (rev-code-02 probes 1 and
# 2, artifacts fc49e9d9 lineage). No in-language dispatch survives that.
#
# This entrypoint is unshapable at the bash level: python does not read
# BASH_ENV and imports no bash functions, and the interpreter is pinned by
# absolute shebang (no PATH resolution). It builds the child environment BY
# ALLOWLIST and execve's the bash implementation directly — the child bash
# starts with no BASH_ENV, no BASH_FUNC_*, no SHELLOPTS/BASHOPTS, and exactly
# the variables the credential protocol needs. stdin/stdout/stderr and argv
# pass through untouched.
#
# The implementation file (git-credential-mosaic.impl) refuses to run without
# the clean-mode marker, so it cannot be invoked directly as a shaped-entry
# bypass of this wrapper.
import os
import sys
IMPL = os.path.join(os.path.dirname(os.path.realpath(__file__)), "git-credential-mosaic.impl")
# Absolute-path candidates ONLY — never PATH resolution (an attacker-shaped
# PATH must not choose the interpreter). /usr/bin/bash is the fleet-host
# layout; /bin/bash is alpine and other FHS variants (found by the T125
# gateway-image verification: the hardcoded /usr/bin/bash made every call
# exit 127 inside node:22-alpine).
BASH_CANDIDATES = ("/usr/bin/bash", "/bin/bash")
BASH = next((p for p in BASH_CANDIDATES if os.access(p, os.X_OK)), None)
# Allowlist: everything else in the environment dies at this boundary. Adding
# a variable here is a security decision — it crosses into a shell that no
# longer has any startup shaping, but it also becomes the only context the
# implementation can see.
KEEP = (
"HOME",
"PATH",
"LANG",
"MOSAIC_GIT_IDENTITY",
"MOSAIC_AGENT_NAME",
"MOSAIC_BRAIN_HOME",
"MOSAIC_CREDENTIAL_SPOOL",
"MOSAIC_CREDENTIAL_LINEAGE_FENCE",
)
env = {"_MOSAIC_HELPER_CLEAN": "1"}
for name in KEEP:
value = os.environ.get(name)
if value is not None:
env[name] = value
argv = [BASH, IMPL] + sys.argv[1:]
if BASH is None:
sys.stderr.write("git-credential-mosaic: no executable bash at " + " or ".join(BASH_CANDIDATES) + "\n")
sys.exit(127)
try:
os.execve(BASH, argv, env)
except OSError as exc:
sys.stderr.write(f"git-credential-mosaic: entrypoint exec failed: {exc}\n")
sys.exit(127)
@@ -0,0 +1,480 @@
#!/bin/bash
# git-credential-mosaic — git credential helper. Resolves a Gitea token from the
# Mosaic credential store at runtime so remote URLs never embed secrets.
#
# Install (one-time, per clone or globally):
# git config credential.helper "$HOME/.config/mosaic/tools/git/git-credential-mosaic"
#
# Per-agent identity (Gate-16 author != reviewer separation):
# git config mosaic.gitIdentity <agent-id> # per-worktree, persists on disk
# # or: export MOSAIC_GIT_IDENTITY=<agent-id>
#
# ── WHY THIS FAILS CLOSED ──────────────────────────────────────────────────────
# This helper used to end by emitting the shared account's token for any request
# it could not resolve to an identity. A seat with no identity, or with an
# identity whose token was never provisioned, therefore received the most
# privileged credential configured on the host — silently, and indistinguishably
# from correct operation. Every record it then created (commit, push, PR, review)
# was attributed to that shared account, so author != reviewer separation was
# unenforceable and the true actor was unrecoverable after the fact.
#
# Under-provisioning must fail loudly, not impersonate. A refused git operation
# is recoverable in one command; a merged pull request attributed to the wrong
# principal is not.
#
# ── CONTRACT ───────────────────────────────────────────────────────────────────
# identity : MOSAIC_GIT_IDENTITY > git config mosaic.gitIdentity > the
# username git supplies on stdin
# ownership: a FLEET SEAT caller may resolve ONLY its own identity, where
# the CALLER is established by process ANCESTRY, not by the
# current environment: every ancestor's /proc/<pid>/environ is
# frozen at exec, so a child can rewrite its own MOSAIC_AGENT_NAME
# but can never make an ancestor disagree with what the launcher
# gave it (P5-RM-006; the dual-variable override was measured by
# rev-code-02 F1). An anonymous caller (no lineage, no consensus)
# may resolve NOTHING on a fleet host — seat or service
# (rev-code-02 F2). Non-fleet hosts keep the documented legacy
# paths below.
# perms : a slot whose mode lets group or other read it (anything but
# ?00) is refused — a loose slot is provisioning drift, and
# serving from it silently widens every seat's exposure on a
# single-account host.
# store : chosen by what the identity IS, with no precedence and no
# cross-store fallback (see "Credential store selection" below)
# hit : emit username + password, exit 0
# miss : emit NOTHING, spool a durable escalation record, explain on
# stderr, exit 1 — git surfaces the failure and nothing is attributed
# unknown host : exit 0 with no output, no record (passthrough for non-Mosaic
# remotes handled by another helper)
#
# Backward compatibility is preserved for exactly one case: a host with no fleet
# and no identity requested still gets the shared account, because on such a host
# the shared account is the operator's own and there is no attribution to lose.
# A host that HAS a fleet has agents whose records must be distinguishable, so
# the shared fallback is refused there.
#
# A token is never written to stderr, to the escalation record, or to any log.
[ "$1" = "get" ] || exit 0
# ── The shared refusal path ──────────────────────────────────────────────────
# Every fail-closed exit funnels through refuse(): a durable escalation record
# (deduped, JSON-escaped), a stderr diagnostic naming host/identity/reason,
# caller-supplied guidance when the refusing site has specific advice, exit 1.
# Defined here because the ownership gate below must be able to reach it.
refuse() {
local guidance="${1:-}"
local seat ts spool spool_record spoolfile dedupe
seat="${MOSAIC_AGENT_NAME:-unknown}"
ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# A record field is arbitrary operator-supplied text: an identity comes from git
# config or the environment, and cwd is whatever directory git ran in. Either can
# contain a quote or a backslash, which would make the line unparseable JSON --
# and a spool that silently stops parsing is worse than no spool, because the
# operator only discovers it while reading the record that explains an outage.
json_escape() {
local s=$1
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\t'/\\t}
s=${s//$'\r'/\\r}
s=${s//$'\n'/\\n}
printf '%s' "$s"
}
spool="${MOSAIC_CREDENTIAL_SPOOL:-$HOME/.local/state/mosaic-credential-escalations}"
spool_record=""
if mkdir -p "$spool" 2>/dev/null; then
chmod 700 "$spool" 2>/dev/null
spoolfile="$spool/$(date -u +%Y%m%d).jsonl"
dedupe="$spool/.spooled-${seat}-${ident:-none}-${reason}-$(date -u +%Y%m%d%H%M)"
if [ ! -e "$dedupe" ]; then
: > "$dedupe" 2>/dev/null
printf '{"ts":"%s","reason":"%s","identity":"%s","identity_source":"%s","kind":"%s","seat":"%s","host":"%s","cwd":"%s"}\n' \
"$(json_escape "$ts")" "$(json_escape "$reason")" \
"$(json_escape "${ident:-<unset>}")" "$(json_escape "$ident_src")" \
"$(json_escape "${ident_kind:-none}")" "$(json_escape "$seat")" \
"$(json_escape "$host")" "$(json_escape "$PWD")" \
>> "$spoolfile" 2>/dev/null
chmod 600 "$spoolfile" 2>/dev/null
fi
# Name the record only if one is actually on disk. Printing the path
# unconditionally sends the operator to a file that does not exist on exactly
# the hosts where the spool could not be created.
[ -s "$spoolfile" ] && spool_record="$spoolfile"
find "$spool" -maxdepth 1 -name '.spooled-*' -mmin +120 -delete 2>/dev/null
fi
while IFS= builtin read -r _diag_line; do builtin printf '%s\n' "$_diag_line" >&2; done <<EOF
git-credential-mosaic: REFUSED (fail-closed).
host : ${host}
identity : ${ident:-<unset>}${ident:+ (from ${ident_src}; resolved as a ${ident_kind})}
reason : ${reason}
EOF
if [ -n "$ident" ]; then
while IFS= builtin read -r _diag_line; do builtin printf '%s\n' "$_diag_line" >&2; done <<EOF
expected : ${idtok}
EOF
fi
while IFS= builtin read -r _diag_line; do builtin printf '%s\n' "$_diag_line" >&2; done <<EOF
${guidance}
EOF
if [ -n "$spool_record" ]; then
echo " record: ${spool_record}" >&2
else
echo " record: NOT WRITTEN — spool unavailable at ${spool}" >&2
fi
exit 1
}
# ── Bash environment injection guard (rev-code-02 R3, B1) ───────────────────
# Non-interactive bash sources $BASH_ENV at startup and imports exported
# functions from BASH_FUNC_* environment entries; either can define a read()
# or printf() that shadows the builtin the ancestry walker and diagnostics
# rely on — measured live by the reviewer's fixture (BASH_ENV read() rewrote
# every ancestry entry). A legitimate fleet seat environment carries neither
# (verified: zero BASH_FUNC_* in seat envs), so their presence in a helper
# request is an injection attempt: scrub the shadows first (so even the
# refusal machinery cannot be subverted), then refuse fail-closed.
# Imported functions are detected by ENUMERATION, not env-var names: bash
# consumes BASH_FUNC_* variables while importing the functions, so the
# environment no longer shows them (measured). At this point the script has
# defined exactly one function of its own (refuse); anything else in the
# function table arrived from the caller's environment. BASH_ENV is checked
# directly (it remains visible after sourcing).
_injected=0
_inj_names=""
while IFS=' ' builtin read -r _decl _kind _fn; do
[ -n "$_fn" ] || continue
case "$_fn" in
refuse) ;;
*) _injected=1; _inj_names="$_inj_names $_fn";;
esac
done < <(declare -F)
_inj_vars="${!BASH_FUNC_@}"
if [ -n "$_inj_vars" ]; then
_injected=1
for _iv in $_inj_vars; do
case "$_iv" in
BASH_FUNC_*%%) _ifn="${_iv#BASH_FUNC_}"; _ifn="${_ifn%%%}";;
BASH_FUNC_*) _ifn="${_iv#BASH_FUNC_}";;
*) _ifn="";;
esac
[ -n "$_ifn" ] && { unset -f "$_ifn" 2>/dev/null; _inj_names="$_inj_names $_ifn"; }
done
fi
if [ "$_injected" = 1 ] || [ -n "${BASH_ENV:-}" ]; then
while IFS=' ' builtin read -r _decl _kind _fn; do
[ "$_fn" = refuse ] || unset -f "$_fn" 2>/dev/null
done < <(declare -F)
unset BASH_ENV 2>/dev/null
reason="bash-environment-injection-refused"
refuse "The helper's bash startup state was externally shaped: BASH_ENV is
set and/or exported BASH_FUNC_* functions are present in the request
environment. Non-interactive bash sources BASH_ENV and imports those
functions BEFORE any script line runs, so builtins this helper's security
decisions rely on could be shadowed. Nothing resolves from a shaped request
environment. If this surprised a legitimate workflow, the caller environment
must be cleaned (no BASH_ENV, no exported functions) before invoking git."
fi
host=""; username_in=""
while IFS= builtin read -r line; do
[ -z "$line" ] && break
case "$line" in
host=*) host=${line#host=};;
username=*) username_in=${line#username=};;
esac
done
# Recognized Gitea hosts carry the per-identity token scheme. Anything else is
# declined quietly — another helper owns it, and refusing would break it.
case "$host" in
git.uscllc.com) idpfx=gitea-usc;;
git.mosaicstack.dev) idpfx=gitea-mosaicstack;;
*) exit 0;;
esac
# ── Clean-entrypoint assert (P0-SEC R4) ─────────────────────────────────────
# This implementation only runs behind the python entrypoint
# (git-credential-mosaic), which execve's it with an allowlist environment:
# no BASH_ENV, no imported functions, nothing shapable at bash startup. A
# direct invocation without the marker is a bypass attempt on that boundary
# and refuses. Placed after refuse() and the host parse so the refusal path
# exists when it fires (an earlier placement died on 'refuse: command not
# found' — the failure mode is real, keep this after every definition it
# calls).
if [ "${_MOSAIC_HELPER_CLEAN:-}" != "1" ]; then
reason="direct-entrypoint-refused"
refuse "This implementation refuses to run outside the production
entrypoint. git-credential-mosaic (the python wrapper in this directory)
execve's it with a hand-built, unshapable environment; invoking the .impl
directly bypasses that boundary. Credential requests go through git, which
invokes the wrapper named in gitconfig."
fi
ident="$MOSAIC_GIT_IDENTITY"; ident_src="MOSAIC_GIT_IDENTITY"
if [ -z "$ident" ]; then
ident=$(git config --get mosaic.gitIdentity 2>/dev/null)
ident_src="git config mosaic.gitIdentity"
fi
if [ -z "$ident" ]; then
ident="$username_in"
ident_src="the username git supplied"
fi
# ── Credential store selection ────────────────────────────────────────────────
# An identity is a SEAT or it is a SERVICE, and which one it is determines where
# its credential lives. There is no precedence rule between the two stores and no
# fallback from one to the other: a seat whose slot is empty fails closed rather
# than reading a service credential that happens to share its name.
#
# seat — <brain>/fleet/agents/<ident>/ exists
# credential at <brain>/fleet/agents/<ident>/secrets/<idpfx>-<ident>.token
# service — it does not
# credential at ~/.config/mosaic/secrets/gitea-tokens/<idpfx>-<ident>.token
#
# One credential, one location. Two copies of one credential diverge, and the
# stale copy fails in a way that reads as a revoked token rather than as drift.
#
# Brain-home resolution mirrors packages/mosaic/src/fleet/brain-home.ts and
# tools/fleet/start-agent-session.sh: MOSAIC_BRAIN_HOME wins, else ~/.mosaic.
brain_home="${MOSAIC_BRAIN_HOME:-$HOME/.mosaic}"
svc_store="$HOME/.config/mosaic/secrets/gitea-tokens"
# ── Caller-identity ownership (P5-RM-006) ──────────────────────────────────────
# A credential request is honourable only when the CALLER owns the identity it
# asks for. On a fleet host every seat shares one unix account, so the
# launcher-established MOSAIC_AGENT_NAME is the only attribution signal the
# helper has. Two measured paths made the old contract unsafe:
#
# - a seat exporting MOSAIC_GIT_IDENTITY=<another-seat> resolved that seat's
# token through the normal precedence chain (T97 G2, jarvis V2 probe), and
# - an anonymous caller (no seat name) inherited the host gitconfig's
# username=jarvis line and resolved jarvis's slot (T94: five watcher units
# flapping on exactly this class).
#
# Ownership rules, fail-closed on fleet hosts only; a host with no fleet keeps
# the legacy contract unchanged:
# 1. a SEAT caller may resolve only its own identity;
# 2. an anonymous caller may not resolve any SEAT identity (service
# identities remain available to non-seat automation such as CI).
# [P5-RM-006r1 ancestry binding begin]
# ── Caller identity from exec-frozen ancestry (rev-code-02 F1/F2) ───────────
# Walk /proc self->root collecting MOSAIC_AGENT_NAME from each ancestor's
# frozen environ. Rules:
# - any DISAGREEMENT (an ancestor value != the current value, or ancestors
# disagreeing among themselves) is a rewrite -> spoof-refused, nothing
# resolves. A child can inject variables downward but cannot alter an
# ancestor's exec-frozen environ, so the launcher-established value always
# participates in the comparison.
# - consensus (all ancestors that carry the var agree with the current env,
# or with each other when the current env is empty) -> caller = that value.
# - no ancestor carries it -> the current claim is unlineaged: caller is
# anonymous regardless of what the environment says. A name with no
# lineage is a claim, not an identity.
# The walk stops at PID 1, at a missing /proc entry, or INCLUSIVE at an
# ancestor that carries MOSAIC_CREDENTIAL_LINEAGE_FENCE with an EMPTY agent
# name — the test-suite lineage root. A fence beside a non-empty name is
# IGNORED and the walk continues, so an attacker cannot fence off the true
# ancestry by planting the marker next to a victim name.
trusted_caller() {
# PATH-HARDENED (rev-code-02 R1 F1): every /proc read below uses ONLY bash
# builtins (read/case/parameter expansion). The first implementation piped
# through PATH-resolved tr/sed/head/grep, and a caller that prepends hostile
# utilities to PATH in the same invocation that overrides the identity
# variables could forge the ancestry itself. Builtins cannot be shadowed.
local pid ppid v entry line fence
local -a vals=()
pid=$$
while :; do
v=""
fence=0
if [ -r "/proc/$pid/environ" ]; then
# Read inside a captured subshell whose stderr is closed: opening
# /proc/<pid>/environ can fail with EACCES on ancestors that are
# readable-by-mode but not openable (session managers), and that open
# failure prints from the SHELL, immune to loop-level 2>/dev/null
# (measured). The subshell makes the skip silent; NUL separators are
# converted to newlines for the parent's builtin parse.
_env_text=$( { while IFS= builtin read -r -d '' _e; do builtin printf '%s\n' "$_e"; done < "/proc/$pid/environ"; } 2>/dev/null )
while IFS= builtin read -r entry; do
[ -n "$entry" ] || continue
case "$entry" in
MOSAIC_AGENT_NAME=*) v="${entry#MOSAIC_AGENT_NAME=}";;
MOSAIC_CREDENTIAL_LINEAGE_FENCE=*) fence=1;;
esac
done <<EOF_ENV
$_env_text
EOF_ENV
fi
if [ "$pid" != "$$" ]; then
[ -n "$v" ] && vals+=("$v")
if [ "$fence" = 1 ] && [ -z "$v" ]; then
break
fi
fi
ppid=""
if [ -r "/proc/$pid/status" ]; then
while IFS= builtin read -r line; do
case "$line" in
PPid:*) ppid="${line#PPid:}"; ppid="${ppid//[[:space:]]/}";;
esac
done < "/proc/$pid/status"
fi
case "$ppid" in ''|0|1) break;; esac
pid=$ppid
done
local self="${MOSAIC_AGENT_NAME:-}" i consensus=""
if [ "${#vals[@]}" -gt 0 ]; then
consensus="${vals[0]}"
for i in "${vals[@]}"; do
if [ "$i" != "$consensus" ]; then
printf 'SPOOF'
return
fi
done
if [ -n "$self" ] && [ "$self" != "$consensus" ]; then
printf 'SPOOF'
return
fi
fi
printf '%s' "$consensus"
}
if [ -d "$brain_home/fleet/agents" ]; then
caller="$(trusted_caller)"
if [ "$caller" = "SPOOF" ]; then
reason="caller-identity-spoof-refused"
refuse "The MOSAIC_AGENT_NAME lineage disagrees within this process tree:
an ancestor established by exec carries a different value than the request.
A child process can rewrite its own environment but never an ancestor's
frozen environ, so disagreement is a rewrite, not a race. Nothing resolves
under a rewritten caller identity. If this surprised a legitimate workflow,
run git from the seat's own session, not from a rewritten environment."
fi
if [ -n "$caller" ] && [ -d "$brain_home/fleet/agents/$caller" ]; then
if [ -n "$ident" ] && [ "$ident" != "$caller" ]; then
reason="cross-seat-identity-refused"
refuse "A seat may resolve only its own credential slot. Caller seat is
'$caller' (ancestry-established); the request names '$ident'. Overriding
MOSAIC_GIT_IDENTITY (or a git config / URL username) to another seat's name is
exactly the path this refusal exists to close. If '$ident' auth is genuinely
required, that seat runs the operation itself or the orchestrator provisions
an explicit grant."
fi
else
# Anonymous caller on a fleet host (no lineage, or the lineage root is not
# a seat): NOTHING resolves — seat slots (T94 jarvis@ class) or legacy
# service credentials (rev-code-02 F2: credentialed services are seats;
# the legacy store is vestigial and not anonymously reachable).
if [ -n "$ident" ]; then
ident_kind="${ident_kind:-}"
[ -d "$brain_home/fleet/agents/$ident" ] && ident_kind="seat" || ident_kind="service identity"
reason="anonymous-credential-refused"
refuse "This caller has no seat lineage on a fleet host and asked for
'$ident' (a ${ident_kind}). Anonymous callers resolve nothing on fleet hosts:
seat credentials must never serve an unattributable caller, and credentialed
services are seats with their own sessions (the legacy service store is
vestigial). Run from the owning seat's session."
fi
fi
fi
# [P5-RM-006r1 ancestry binding end]
idtok=""; ident_kind=""
if [ -n "$ident" ]; then
if [ -d "$brain_home/fleet/agents/$ident" ]; then
ident_kind="seat"
idtok="$brain_home/fleet/agents/$ident/secrets/${idpfx}-${ident}.token"
else
ident_kind="service identity"
idtok="$svc_store/${idpfx}-${ident}.token"
fi
if [ -r "$idtok" ]; then
# P5-RM-006 seat permissions: a SEAT slot readable by group or other is
# provisioning drift, and on a single-account fleet host it widens every
# seat's exposure at once. Refuse rather than serve from a loose slot; the
# record names the path so the provisioning fix is one chmod away.
# Scoped to seat slots: the framework service store is operator-managed
# and outside this work unit's permission surface.
if [ "${ident_kind:-}" = "seat" ]; then
# command -p resolves stat from the POSIX default PATH (system
# directories), never the caller's PATH (rev-code-02 R3 B2: a shadowed
# stat reported a 0644 slot as 600 and the helper served it). Output is
# shape-validated: anything that is not 3-4 octal digits refuses.
slot_mode="$(command -p stat -c '%a' "$idtok" 2>/dev/null || true)"
case "$slot_mode" in
[0-7][0-7][0-7]|[0-7][0-7][0-7][0-7]) ;;
*) slot_mode="unverifiable";;
esac
if [ "${slot_mode:1:2}" != "00" ]; then
reason="slot-permission-violation"
refuse "Slot $idtok has mode ${slot_mode:-unknown}; expected owner-only
(0600 or stricter). Tighten it: chmod 600 '$idtok'. This refusal is the seat
permissions half of P5-RM-006: a loose slot on a shared-account host is every
seat's exposure, so the helper declines to serve from it. Mode inspection uses
command -p (trusted PATH) and fails closed on unverifiable output."
fi
fi
echo "username=${ident}"
echo "password=$(<"$idtok")"
exit 0
fi
fi
# ── Shared-account fallback: ONLY on a host with no fleet and no identity ──────
# `fleet/agents` existing is the same signal brain-home.ts uses to decide a brain
# is active. Where there are seats, records must be attributable, so an
# unresolvable request is refused instead of borrowing the shared account.
fleet_present=0
[ -d "$brain_home/fleet/agents" ] && fleet_present=1
if [ -z "$ident" ] && [ "$fleet_present" -eq 0 ]; then
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=../_lib/credentials.sh
source "$script_dir/../_lib/credentials.sh"
load_credentials "$idpfx" >/dev/null 2>&1 || exit 0
# GITEA_USER is not populated by load_credentials (it exports GITEA_URL and
# GITEA_TOKEN only). Gitea's git-over-HTTP auth authenticates from the token in
# the password field, not from the username string, so any non-empty
# placeholder works — deliberately NOT a real account name, since framework
# files stay operator-agnostic (tools/quality/scripts/verify-sanitized.sh).
echo "username=${GITEA_USER:-git}"
echo "password=$GITEA_TOKEN"
exit 0
fi
# ── FAIL CLOSED ───────────────────────────────────────────────────────────────
# The escalation RECORD is durable and unconditional; any notification built on
# top of it is best-effort (see refuse()). Record and alert are deduplicated
# separately — a cap on the alert alone lets the spool grow without bound
# exactly while the operator is being told nothing, so the louder the failure
# the quieter it gets.
if [ -z "$ident" ]; then
reason="no-identity"
else
reason="no-token-for-identity"
fi
refuse "No per-identity credential resolved. This helper does NOT fall back to the shared
account: that fallback makes every record it creates attributable to one
principal, which is unrecoverable once a pull request has merged under it.
Fix (pick one):
export MOSAIC_GIT_IDENTITY=<agent-id> # process-scoped
git config mosaic.gitIdentity <agent-id> # per-repo/worktree, persists
Then provision that identity's credential at the path named above. An identity
with a directory under \${MOSAIC_BRAIN_HOME:-\$HOME/.mosaic}/fleet/agents/ is a
seat and is read ONLY from its own secrets/ slot; any other identity is read from
~/.config/mosaic/secrets/gitea-tokens/. There is no fallback between the two.
If this identity legitimately needs git access and has none, ask the orchestrator
to provision one."
+343
View File
@@ -0,0 +1,343 @@
#!/bin/bash
# grant-reviewer.sh - Grant a reviewer read + review access to an org-owned
# Gitea repository via an org team (default: fleet-reviewers).
#
# Usage: grant-reviewer.sh -u <user> [-r <owner>/<repo>] [-t <team>]
#
# The team carries `permission: read` with per-unit overrides
# {repo.code: read, repo.issues: write, repo.pulls: write}: the reviewer can
# read code and write issues/PR reviews, but cannot push. The grant is
# idempotent — the team is looked up before it is created, and member/repo
# additions are PUTs.
#
# KNOWN LIMITATION — branch protection counts these reviews as UNOFFICIAL.
# Gitea computes a review's `official` flag at SUBMISSION time, from write
# permission on the repo or from membership in the protected branch's
# approvals whitelist (disabled by default). A team granted through this
# script has read permission on code, so under branch protection with
# required_approvals the reviewer's approval shows but does NOT count toward
# the required total — the merge still fails with "not enough approvals".
# Enabling the approvals whitelist and adding this team to it is review
# policy (who counts as an official approver), an operator decision made in
# the repo's branch-protection settings, deliberately NOT automated here.
# Because `official` is fixed at submission, whitelisting after the fact
# requires the review to be re-submitted before it counts.
#
# Platform: Gitea only. On a GitHub-remoted repo this script refuses to run —
# GitHub review access is granted through collaborator/team facilities that
# have no equivalent to Gitea's org-team unit map.
#
# Identity: the acting credential resolves exactly as in issue-comment.sh —
# GITEA_LOGIN (when set) names a tea login whose token MUST resolve for the
# remote host (fail closed, never downgrade to the host default identity);
# otherwise the per-seat identity ladder in detect-platform.sh applies
# (MOSAIC_GIT_IDENTITY / git config mosaic.gitIdentity → per-slot token,
# fail-loud on fleet hosts). Managing org teams requires org owner/admin:
# an HTTP 403 from any step is reported as "org admin required on <org>",
# never as a silent partial grant.
#
# Verification is fail-closed: after the member and repo PUTs, the script
# GETs the single resources back (GET /teams/{id}/members/{user} and
# GET /teams/{id}/repos/{owner}/{repo}) and refuses to report success unless
# both confirm the grant. A PUT that returns success without persisting
# (the #865 defect class: an exit code is not evidence of a durable write)
# therefore fails the run instead of reporting a grant that does not exist.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/detect-platform.sh"
usage() {
echo "Usage: grant-reviewer.sh -u <user> [-r <owner>/<repo>] [-t <team>]"
echo ""
echo "Options:"
echo " -u, --user Gitea username to grant reviewer access (required)"
echo " -r, --repo Target repository as <owner>/<repo>; defaults to the"
echo " current repository's origin. The owner must be an"
echo " organization."
echo " -t, --team Org team to use/create (default: fleet-reviewers)"
echo " -h, --help Show this help"
echo ""
echo "Environment:"
echo " GITEA_LOGIN Override the acting identity with a named tea login"
echo " (must resolve for the remote host; fails closed)."
echo ""
echo "Grants: code read + issues/pulls write via an org team. Gitea only."
echo ""
echo "LIMITATION: under branch protection with required approvals, reviews"
echo "from a read-permission team are official=false and do not count"
echo "toward the required total. Making them count means enabling the"
echo "protected branch's approvals whitelist and adding the team — an"
echo "operator review-policy decision this script does not automate. The"
echo "official flag is computed at review submission, so a review made"
echo "before whitelisting must be re-submitted afterwards."
}
REVIEWER=""
REPO_OVERRIDE=""
TEAM="fleet-reviewers"
while [[ $# -gt 0 ]]; do
case $1 in
-u|--user)
REVIEWER="$2"
shift 2
;;
-r|--repo)
REPO_OVERRIDE="$2"
shift 2
;;
-t|--team)
TEAM="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unknown option: $1" >&2
exit 1
;;
esac
done
if [[ -z "$REVIEWER" ]]; then
echo "Error: reviewer username is required (-u)" >&2
exit 1
fi
# Gitea usernames and team names are AlphaDashDot. Validating here keeps the
# values safe to interpolate into API paths without URL-encoding.
NAME_RE='^[A-Za-z0-9][A-Za-z0-9._-]*$'
if ! [[ "$REVIEWER" =~ $NAME_RE ]]; then
echo "Error: invalid reviewer username '$REVIEWER'" >&2
exit 1
fi
if ! [[ "$TEAM" =~ $NAME_RE ]]; then
echo "Error: invalid team name '$TEAM'" >&2
exit 1
fi
if [[ -n "$REPO_OVERRIDE" ]] && ! [[ "$REPO_OVERRIDE" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
echo "Error: -r expects <owner>/<repo>, got '$REPO_OVERRIDE'" >&2
exit 1
fi
detect_platform >/dev/null
if [[ "$PLATFORM" != "gitea" ]]; then
echo "Error: grant-reviewer.sh is Gitea only (detected platform: $PLATFORM)." >&2
echo " On GitHub, grant review access via repository collaborators or org teams in the GitHub UI/CLI." >&2
exit 1
fi
HOST=$(get_remote_host) || {
echo "Error: could not resolve the remote host from origin" >&2
exit 1
}
# Acting credential: GITEA_LOGIN (explicit, fail closed) or the identity
# ladder. Same ordering contract as issue-comment.sh — an explicit override is
# never silently downgraded to the host default identity.
if [[ -n "${GITEA_LOGIN:-}" ]]; then
GITEA_API_TOKEN=$(get_gitea_token_for_login "$GITEA_LOGIN" "$HOST") || {
echo "Error: could not resolve a host-matched Gitea token for GITEA_LOGIN '$GITEA_LOGIN' on host '$HOST'; refusing to fall back to the host default identity (reviewer grant)" >&2
exit 1
}
else
GITEA_API_TOKEN=$(get_gitea_token "$HOST") || {
echo "Error: no Gitea credential resolved for the acting identity on host '$HOST' (reviewer grant). Set MOSAIC_GIT_IDENTITY=<agent-id>, or set GITEA_LOGIN=<name> to use a named tea credential." >&2
exit 1
}
fi
CONFIGURED_URL=$(get_gitea_url_for_host "$HOST") || {
echo "Error: configured Gitea URL not found for host '$HOST'" >&2
exit 1
}
GITEA_API_ROOT="${CONFIGURED_URL%/}/api/v1"
if [[ -n "$REPO_OVERRIDE" ]]; then
REPO_SLUG="$REPO_OVERRIDE"
else
REPO_SLUG=$(get_gitea_repo_slug_for_url "$CONFIGURED_URL") || {
echo "Error: could not resolve <owner>/<repo> from origin; pass -r <owner>/<repo>" >&2
exit 1
}
fi
ORG="${REPO_SLUG%%/*}"
REPO_NAME="${REPO_SLUG#*/}"
RESPONSE_FILE=$(mktemp "${TMPDIR:-/tmp}/mosaic-grant-reviewer-resp.XXXXXX")
AUTH_CONFIG=$(gitea_write_auth_config "$GITEA_API_TOKEN") || {
rm -f "$RESPONSE_FILE"
echo "Error: could not stage Gitea credential for reviewer grant" >&2
exit 1
}
trap 'rm -f "$RESPONSE_FILE" "$AUTH_CONFIG"' EXIT
# gitea_api <step> <method> <path> [json-payload]
# Runs one API call with the staged credential (token never in argv). Sets
# GITEA_API_STATUS and leaves the body in $RESPONSE_FILE. Transport failure
# and HTTP 403 are terminal here: 403 on ANY step means the acting identity
# cannot manage org teams, and the run must stop rather than continue into a
# partial grant.
gitea_api() {
local step="$1" method="$2" path="$3" payload="${4:-}"
local -a payload_args=()
if [[ -n "$payload" ]]; then
payload_args=(-H 'Content-Type: application/json' -d "$payload")
fi
if ! GITEA_API_STATUS=$(curl -sS -o "$RESPONSE_FILE" -w '%{http_code}' \
-X "$method" \
--config "$AUTH_CONFIG" \
"${payload_args[@]}" \
"$GITEA_API_ROOT$path"); then
echo "Error: Gitea transport failed during $step" >&2
return 1
fi
if [[ "$GITEA_API_STATUS" == "403" ]]; then
echo "Error: HTTP 403 during $step: org admin required on '$ORG' — managing org teams needs owner/admin on the organization. No grant was completed." >&2
return 1
fi
return 0
}
# json_field <file> <key> — print a top-level scalar field or fail.
json_field() {
python3 - "$1" "$2" <<'PY'
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as response:
data = json.load(response)
value = data.get(sys.argv[2]) if isinstance(data, dict) else None
if value is None or isinstance(value, (dict, list, bool)):
raise ValueError(f"missing or non-scalar field {sys.argv[2]!r}")
except (OSError, json.JSONDecodeError, ValueError) as error:
print(f"Error: unusable Gitea response: {error}", file=sys.stderr)
raise SystemExit(1)
print(value)
PY
}
# 1. The owner must be an organization: teams are an org facility, and a
# user-owned repo would fail later with a misleading team error.
gitea_api "organization check" GET "/orgs/$ORG"
if [[ "$GITEA_API_STATUS" == "404" ]]; then
echo "Error: owner '$ORG' is not an organization on '$HOST'; grant-reviewer requires an org-owned repository" >&2
exit 1
fi
if [[ "$GITEA_API_STATUS" != "200" ]]; then
echo "Error: organization check for '$ORG' failed with HTTP $GITEA_API_STATUS" >&2
exit 1
fi
# 2. Idempotent team resolution: exact-name lookup first, create only on miss.
# The search endpoint substring-matches, so the exact-name filter is done
# on the response, not trusted to the query.
gitea_api "team lookup" GET "/orgs/$ORG/teams/search?q=$TEAM"
if [[ "$GITEA_API_STATUS" != "200" ]]; then
echo "Error: team lookup for '$TEAM' on '$ORG' failed with HTTP $GITEA_API_STATUS" >&2
exit 1
fi
TEAM_ID=$(TEAM_NAME="$TEAM" python3 - "$RESPONSE_FILE" <<'PY'
import json
import os
import sys
wanted = os.environ["TEAM_NAME"]
try:
with open(sys.argv[1], encoding="utf-8") as response:
result = json.load(response)
teams = result.get("data") if isinstance(result, dict) else None
if not isinstance(teams, list):
raise ValueError("team search response carried no data list")
except (OSError, json.JSONDecodeError, ValueError) as error:
print(f"Error: unusable team search response: {error}", file=sys.stderr)
raise SystemExit(1)
for team in teams:
if isinstance(team, dict) and team.get("name") == wanted:
team_id = team.get("id")
if not isinstance(team_id, int) or team_id <= 0:
print("Error: matched team carried no positive id", file=sys.stderr)
raise SystemExit(1)
print(team_id)
raise SystemExit(0)
print("")
PY
)
if [[ -z "$TEAM_ID" ]]; then
CREATE_PAYLOAD=$(TEAM_NAME="$TEAM" python3 -c '
import json
import os
print(json.dumps({
"name": os.environ["TEAM_NAME"],
"description": "review seats: code read + issues/pulls write",
"permission": "read",
"includes_all_repositories": False,
"can_create_org_repo": False,
"units_map": {
"repo.code": "read",
"repo.issues": "write",
"repo.pulls": "write",
},
}))
')
gitea_api "team create" POST "/orgs/$ORG/teams" "$CREATE_PAYLOAD"
if [[ "$GITEA_API_STATUS" != "201" ]]; then
echo "Error: team create for '$TEAM' on '$ORG' failed with HTTP $GITEA_API_STATUS" >&2
exit 1
fi
TEAM_ID=$(json_field "$RESPONSE_FILE" id) || {
echo "Error: team create returned no usable team id" >&2
exit 1
}
echo "Created team '$TEAM' (id $TEAM_ID) on org '$ORG'"
else
echo "Found existing team '$TEAM' (id $TEAM_ID) on org '$ORG'"
fi
# 3. Membership and repo attachment — both PUTs, both idempotent in Gitea.
gitea_api "member add" PUT "/teams/$TEAM_ID/members/$REVIEWER"
if [[ "$GITEA_API_STATUS" != "204" ]]; then
echo "Error: adding '$REVIEWER' to team '$TEAM' failed with HTTP $GITEA_API_STATUS" >&2
exit 1
fi
gitea_api "repo add" PUT "/teams/$TEAM_ID/repos/$ORG/$REPO_NAME"
if [[ "$GITEA_API_STATUS" != "204" ]]; then
echo "Error: adding repo '$REPO_SLUG' to team '$TEAM' failed with HTTP $GITEA_API_STATUS" >&2
exit 1
fi
# 4. Fail-closed read-back: a 204 from a PUT is an exit code, not evidence the
# grant persisted. GET the single resources back and require both.
gitea_api "member read-back" GET "/teams/$TEAM_ID/members/$REVIEWER"
if [[ "$GITEA_API_STATUS" != "200" ]]; then
echo "Error: reviewer grant NOT verified — GET /teams/$TEAM_ID/members/$REVIEWER returned HTTP $GITEA_API_STATUS after a successful PUT. Treat the grant as not made." >&2
exit 1
fi
READBACK_LOGIN=$(json_field "$RESPONSE_FILE" login) || exit 1
if [[ "${READBACK_LOGIN,,}" != "${REVIEWER,,}" ]]; then
echo "Error: reviewer grant NOT verified — member read-back returned login '$READBACK_LOGIN', expected '$REVIEWER'" >&2
exit 1
fi
gitea_api "repo read-back" GET "/teams/$TEAM_ID/repos/$ORG/$REPO_NAME"
if [[ "$GITEA_API_STATUS" != "200" ]]; then
echo "Error: reviewer grant NOT verified — GET /teams/$TEAM_ID/repos/$ORG/$REPO_NAME returned HTTP $GITEA_API_STATUS after a successful PUT. Treat the grant as not made." >&2
exit 1
fi
READBACK_FULL_NAME=$(json_field "$RESPONSE_FILE" full_name) || exit 1
if [[ "${READBACK_FULL_NAME,,}" != "${REPO_SLUG,,}" ]]; then
echo "Error: reviewer grant NOT verified — repo read-back returned '$READBACK_FULL_NAME', expected '$REPO_SLUG'" >&2
exit 1
fi
echo "Granted: '$REVIEWER' is a member of team '$TEAM' (id $TEAM_ID) with access to '$REPO_SLUG' (code read, issues/pulls write) — verified by read-back"
echo "Note: under branch protection with required approvals this reviewer's approvals are official=false unless the branch's approvals whitelist includes the team (operator decision; reviews submitted before whitelisting must be re-submitted)."
@@ -0,0 +1,117 @@
# issue-assign.ps1 - Assign issues on Gitea or GitHub
# Usage: .\issue-assign.ps1 -Issue ISSUE_NUMBER [-Assignee assignee] [-Labels labels] [-Milestone milestone]
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[Alias("i")]
[int]$Issue,
[Alias("a")]
[string]$Assignee,
[Alias("l")]
[string]$Labels,
[Alias("m")]
[string]$Milestone,
[Alias("r")]
[switch]$RemoveAssignee,
[Alias("h")]
[switch]$Help
)
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$ScriptDir\detect-platform.ps1"
function Show-Usage {
@"
Usage: issue-assign.ps1 [OPTIONS]
Assign or update an issue on the current repository (Gitea or GitHub).
Options:
-Issue, -i NUMBER Issue number (required)
-Assignee, -a USER Assign to user (use @me for self)
-Labels, -l LABELS Add comma-separated labels
-Milestone, -m NAME Set milestone
-RemoveAssignee, -r Remove current assignee
-Help, -h Show this help message
Examples:
.\issue-assign.ps1 -i 42 -a "username"
.\issue-assign.ps1 -i 42 -l "in-progress" -m "0.2.0"
.\issue-assign.ps1 -i 42 -a @me
"@
exit 1
}
if ($Help) {
Show-Usage
}
$platform = Get-GitPlatform
switch ($platform) {
"github" {
if ($Assignee) {
gh issue edit $Issue --add-assignee $Assignee
}
if ($RemoveAssignee) {
$current = gh issue view $Issue --json assignees -q '.assignees[].login' 2>$null
if ($current) {
$assignees = ($current -split "`n") -join ","
gh issue edit $Issue --remove-assignee $assignees
}
}
if ($Labels) {
gh issue edit $Issue --add-label $Labels
}
if ($Milestone) {
gh issue edit $Issue --milestone $Milestone
}
Write-Host "Issue #$Issue updated successfully"
}
"gitea" {
$repoArgs = @(Get-GiteaRepoArgs)
if ($repoArgs.Length -eq 0) {
Write-Error "Could not resolve Gitea repo/login for remote host"
exit 1
}
$needsEdit = $false
$cmd = @("tea", "issue", "edit", $Issue)
if ($Assignee) {
$cmd += @("--assignees", $Assignee)
$needsEdit = $true
}
if ($Labels) {
$cmd += @("--labels", $Labels)
$needsEdit = $true
}
if ($Milestone) {
$milestoneList = tea milestones list @repoArgs 2>$null
$milestoneId = ($milestoneList | Select-String "^\s*(\d+).*$Milestone" | ForEach-Object { $_.Matches.Groups[1].Value } | Select-Object -First 1)
if ($milestoneId) {
$cmd += @("--milestone", $milestoneId)
$needsEdit = $true
} else {
Write-Warning "Could not find milestone '$Milestone'"
}
}
if ($needsEdit) {
$cmd += $repoArgs
& $cmd[0] $cmd[1..($cmd.Length-1)]
Write-Host "Issue #$Issue updated successfully"
} else {
Write-Host "No changes specified"
}
}
default {
Write-Error "Could not detect git platform"
exit 1
}
}

Some files were not shown because too many files have changed in this diff Show More