diff --git a/README.md b/README.md index 3e1b708d16..936a19019b 100644 --- a/README.md +++ b/README.md @@ -621,6 +621,8 @@ Data is stored in [Supabase](https://supabase.com) (open source Firebase alterna **Stale install?** Run `/gstack-upgrade` — or set `auto_upgrade: true` in `~/.gstack/config.yaml` +**State in the wrong place, or a setting that won't stick?** `~/.claude/skills/gstack/bin/gstack-paths --explain` shows which directory gstack uses for its state and why. See [docs/state-root.md](docs/state-root.md). + **Want shorter commands?** `cd ~/.claude/skills/gstack && ./setup --no-prefix` — switches from `/gstack-qa` to `/qa`. Your choice is remembered for future upgrades. **Want namespaced commands?** `cd ~/.claude/skills/gstack && ./setup --prefix` — switches from `/qa` to `/gstack-qa`. Useful if you run other skill packs alongside gstack. diff --git a/autoplan/SKILL.md b/autoplan/SKILL.md index 95763b3933..d80aa2f09b 100644 --- a/autoplan/SKILL.md +++ b/autoplan/SKILL.md @@ -255,7 +255,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -365,7 +366,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -725,7 +727,7 @@ bun -e 'console.log(require("fs").realpathSync(process.argv[1]))' "$HOME/.claude Fresh external RESTORE_PATH: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-') DATETIME=$(date +%Y%m%d-%H%M%S) diff --git a/autoplan/SKILL.md.tmpl b/autoplan/SKILL.md.tmpl index 6d0f624fb0..f9b6df70c7 100644 --- a/autoplan/SKILL.md.tmpl +++ b/autoplan/SKILL.md.tmpl @@ -204,7 +204,7 @@ Resolve SNAPSHOT_TOOL once: Fresh external RESTORE_PATH: ```bash {{SLUG_EVAL}} -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null | tr '/' '-') DATETIME=$(date +%Y%m%d-%H%M%S) diff --git a/autoplan/sections/tasks-aggregator.md b/autoplan/sections/tasks-aggregator.md index fca58d8ac4..33ce339df8 100644 --- a/autoplan/sections/tasks-aggregator.md +++ b/autoplan/sections/tasks-aggregator.md @@ -6,8 +6,9 @@ Before rendering the Final Approval Gate output block below, aggregate the per-phase task lists each review skill wrote. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="${HOME}/.gstack/projects/${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" BRANCH=$(git branch --show-current 2>/dev/null || echo unknown) # Commit window: last 5 commits on this branch. Drops stale standalone reviews. COMMITS_RECENT=$(git log --format=%H -n 5 2>/dev/null | tr '\n' '|' | sed 's/|$//') diff --git a/bin/gstack-analytics b/bin/gstack-analytics index ad06edd167..8e814bcc92 100755 --- a/bin/gstack-analytics +++ b/bin/gstack-analytics @@ -8,10 +8,12 @@ # gstack-analytics all # all time # # Env overrides (for testing): -# GSTACK_STATE_DIR — override ~/.gstack state directory +# GSTACK_HOME — relocate the state root (chain: bin/gstack-state-root.sh) set -uo pipefail -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" JSONL_FILE="$STATE_DIR/analytics/skill-usage.jsonl" # ─── Parse time window ─────────────────────────────────────── diff --git a/bin/gstack-artifacts-init b/bin/gstack-artifacts-init index d2c1a8cf3c..a82f9e7a47 100755 --- a/bin/gstack-artifacts-init +++ b/bin/gstack-artifacts-init @@ -46,7 +46,9 @@ BASH_COMPAT=50 set -euo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" URL_BIN="$SCRIPT_DIR/gstack-artifacts-url" REMOTE_FILE="$HOME/.gstack-artifacts-remote.txt" diff --git a/bin/gstack-brain-cache b/bin/gstack-brain-cache index 5ced064c0d..038ef63c07 100755 --- a/bin/gstack-brain-cache +++ b/bin/gstack-brain-cache @@ -23,6 +23,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, statSyn import { join, dirname } from 'path'; import { homedir, hostname } from 'os'; import { spawnSync } from 'child_process'; +import { resolveStateRoot } from '../lib/state-root'; import { execGbrainJson, spawnGbrain } from '../lib/gbrain-exec'; import { BRAIN_CACHE_ENTITIES, @@ -37,7 +38,7 @@ import { // Paths + meta // ────────────────────────────────────────────────────────────────────────── -const GSTACK_HOME = process.env.GSTACK_HOME || join(homedir(), '.gstack'); +const GSTACK_HOME = resolveStateRoot(); interface CacheMeta { /** Version of the schema pack the cache was built against. Mismatch → full rebuild. */ diff --git a/bin/gstack-brain-context-load.ts b/bin/gstack-brain-context-load.ts index 647ceb9d4f..4e41b49527 100644 --- a/bin/gstack-brain-context-load.ts +++ b/bin/gstack-brain-context-load.ts @@ -38,6 +38,7 @@ import { existsSync, readFileSync, statSync, readdirSync, accessSync, constants import { join, dirname, basename, resolve, delimiter } from "path"; import { spawnSync } from "child_process"; import { homedir } from "os"; +import { resolveStateRoot } from "../lib/state-root"; import { parseSkillManifest, type GbrainManifest, type GbrainManifestQuery, withErrorContext } from "../lib/gstack-memory-helpers"; @@ -67,7 +68,7 @@ interface QueryResult { // ── Constants ────────────────────────────────────────────────────────────── const HOME = homedir(); -const GSTACK_HOME = process.env.GSTACK_HOME || join(HOME, ".gstack"); +const GSTACK_HOME = resolveStateRoot(); // 500ms hard cap per Section 1C; overridable for slow/loaded environments // (test harnesses under CI load, cold CLI starts). const MCP_TIMEOUT_MS = Math.max(1, parseInt(process.env.GSTACK_BRAIN_TIMEOUT_MS || "", 10) || 500); diff --git a/bin/gstack-brain-enqueue b/bin/gstack-brain-enqueue index 815eff31bf..e0e97fb8bd 100755 --- a/bin/gstack-brain-enqueue +++ b/bin/gstack-brain-enqueue @@ -31,7 +31,9 @@ set -uo pipefail FILE="${1:-}" [ -z "$FILE" ] && exit 0 -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" SPOOL="$GSTACK_HOME/.brain-queue.d" SKIP_FILE="$GSTACK_HOME/.brain-skip.txt" diff --git a/bin/gstack-brain-restore b/bin/gstack-brain-restore index 781ba700ad..f81a14d137 100755 --- a/bin/gstack-brain-restore +++ b/bin/gstack-brain-restore @@ -37,7 +37,9 @@ BASH_COMPAT=50 set -euo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" CONFIG_BIN="$SCRIPT_DIR/gstack-config" diff --git a/bin/gstack-brain-sync b/bin/gstack-brain-sync index fcdd48b946..c203937f67 100755 --- a/bin/gstack-brain-sync +++ b/bin/gstack-brain-sync @@ -29,7 +29,9 @@ BASH_COMPAT=50 set -uo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" # Maildir-style spool: one FILE per record, --.json. # Writers (gstack-brain-enqueue, --discover-new) create records via tmp-file # + atomic rename; the drain deletes exactly the files it snapshotted. No diff --git a/bin/gstack-brain-uninstall b/bin/gstack-brain-uninstall index a240a855e9..cb2a289c93 100755 --- a/bin/gstack-brain-uninstall +++ b/bin/gstack-brain-uninstall @@ -41,7 +41,9 @@ set -euo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" CONFIG_BIN="$SCRIPT_DIR/gstack-config" # v1.27.0.0+ canonical name; brain-remote is the legacy fallback during migration. diff --git a/bin/gstack-codex-probe b/bin/gstack-codex-probe index 2c372b02e5..4c58ebe08c 100755 --- a/bin/gstack-codex-probe +++ b/bin/gstack-codex-probe @@ -63,8 +63,11 @@ _gstack_codex_model_probe() { # Only call this AFTER _gstack_codex_auth_probe passes — probing without # auth just measures the auth failure again. local _codex_home="${CODEX_HOME:-$HOME/.codex}" - local _gstack_home="${GSTACK_HOME:-$HOME/.gstack}" - local _cache="$_gstack_home/.codex-model-probe" + # State root from the shared twin (sourced in a subshell, so the caller's + # shell is untouched). A missing twin only disables the cache. + local _gstack_home _cache="" + _gstack_home="$(. "${BASH_SOURCE[0]%/*}/gstack-state-root.sh" 2>/dev/null && gstack_state_root)" || _gstack_home="" + [ -n "$_gstack_home" ] && _cache="$_gstack_home/.codex-model-probe" local _model="${GSTACK_CODEX_MODEL:-gpt-6-astra}" # Cache signature: config.toml + auth.json mtimes + gstack model selection. # Editing the model env/config or re-logging-in invalidates the cached result @@ -83,7 +86,7 @@ _gstack_codex_model_probe() { _sig="${_cfg_m}-${_auth_m}-${_model_sig}" local _now _now=$(date +%s 2>/dev/null || echo 0) - if [ -f "$_cache" ]; then + if [ -n "$_cache" ] && [ -f "$_cache" ]; then local _c_line _c_status _c_ts _c_sig _c_line=$(head -1 "$_cache" 2>/dev/null) _c_status=$(printf '%s' "$_c_line" | cut -d' ' -f1) @@ -105,14 +108,12 @@ _gstack_codex_model_probe() { _out=$(_gstack_codex_timeout_wrapper 30 codex exec --skip-git-repo-check -s read-only -c "model=\"$_model\"" "reply OK" &1) _code=$? if [ "$_code" -eq 0 ]; then - mkdir -p "$_gstack_home" 2>/dev/null || true - printf 'MODEL_OK %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null || true + [ -n "$_cache" ] && { mkdir -p "$_gstack_home" 2>/dev/null; printf 'MODEL_OK %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null; } echo "MODEL_OK" return 0 fi if printf '%s' "$_out" | grep -qiE 'model.{0,40}is not supported|"status":[[:space:]]*400'; then - mkdir -p "$_gstack_home" 2>/dev/null || true - printf 'MODEL_UNUSABLE %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null || true + [ -n "$_cache" ] && { mkdir -p "$_gstack_home" 2>/dev/null; printf 'MODEL_UNUSABLE %s %s\n' "$_now" "$_sig" > "$_cache" 2>/dev/null; } echo "MODEL_UNUSABLE" printf '%s\n' "$_out" | grep -i "model" | head -3 echo "HINT: gstack requested model '$_model'." @@ -221,12 +222,15 @@ _gstack_codex_log_event() { local _event="$1" local _duration="${2:-0}" [ "${_TEL:-off}" = "off" ] && return 0 - mkdir -p "$HOME/.gstack/analytics" 2>/dev/null || return 0 + local _root + _root="$(. "${BASH_SOURCE[0]%/*}/gstack-state-root.sh" 2>/dev/null && gstack_state_root)" || return 0 + [ -n "$_root" ] || return 0 + mkdir -p "$_root/analytics" 2>/dev/null || return 0 local _ts _ts=$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || echo unknown) printf '{"skill":"codex","event":"%s","duration_s":"%s","ts":"%s"}\n' \ "$_event" "$_duration" "$_ts" \ - >> "$HOME/.gstack/analytics/skill-usage.jsonl" 2>/dev/null || true + >> "$_root/analytics/skill-usage.jsonl" 2>/dev/null || true } # --- Learnings log on hang -------------------------------------------------- diff --git a/bin/gstack-codex-session-import b/bin/gstack-codex-session-import index 7b1c5f07c5..b4236202e8 100755 --- a/bin/gstack-codex-session-import +++ b/bin/gstack-codex-session-import @@ -21,7 +21,9 @@ # derive all apply uniformly. set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" CODEX_SESSIONS_ROOT="${CODEX_SESSIONS_ROOT:-$HOME/.codex/sessions}" MODE="latest" diff --git a/bin/gstack-config b/bin/gstack-config index a73e0d67ed..c394718e70 100755 --- a/bin/gstack-config +++ b/bin/gstack-config @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# gstack-config — read/write ~/.gstack/config.yaml +# gstack-config — read/write /config.yaml (default ~/.gstack/config.yaml) # # Usage: # gstack-config get — read a config value (falls back to DEFAULTS) @@ -10,14 +10,20 @@ # gstack-config list — show all config (values + defaults) # gstack-config defaults — show just the defaults table # -# Env overrides (for testing): -# GSTACK_STATE_ROOT — override ~/.gstack state directory (highest priority, -# matches D16 cathedral isolation convention) -# GSTACK_HOME — override ~/.gstack state directory (aligns with writer scripts) -# GSTACK_STATE_DIR — legacy alias for GSTACK_HOME (kept for backwards compat) +# State root: GSTACK_STATE_ROOT → GSTACK_HOME → GSTACK_STATE_DIR → +# CLAUDE_PLUGIN_DATA (only when CLAUDE_PLUGIN_ROOT contains "gstack") → +# ~/.gstack (bin/gstack-state-root.sh). Set GSTACK_HOME to relocate state; +# GSTACK_STATE_ROOT is gstack-paths' output, also honored as input; +# GSTACK_STATE_DIR is a legacy alias. +# Privacy keys (telemetry, memorable_recall, codex_reviews, update_check) take +# the most restrictive value across the resolved root and ~/.gstack; `set` +# reports which root received the value and which root still overrides it. +# Docs: https://github.com/garrytan/gstack/blob/main/docs/state-root.md set -euo pipefail -STATE_DIR="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" CONFIG_FILE="$STATE_DIR/config.yaml" # Swap a freshly-rendered tmp dir into the live render location (#2569 @@ -329,14 +335,27 @@ resolve_user_slug() { printf '%s' "$_slug" } +# The one reader (bin/gstack-state-root.sh): last `key:` line in the resolved +# root, except privacy keys, which take the most restrictive value across roots. read_config_value() { - local key="$1" - if [ ! -f "$CONFIG_FILE" ]; then - return 0 - fi - grep -E "^${key}:" "$CONFIG_FILE" 2>/dev/null \ - | tail -1 \ - | sed -E "s/^${key}:[[:space:]]*//; s/[[:space:]]+$//" + gstack_read_config_key "$1" +} + +_STATE_DOC="https://github.com/garrytan/gstack/blob/main/docs/state-root.md" +_SELF="$(cd "$(dirname "$0")" && pwd)/gstack-config" + +# One line when the root-selecting variables name different directories. +report_root_disagreement() { + local _v _val _set="" _distinct="" + for _v in GSTACK_STATE_ROOT GSTACK_HOME GSTACK_STATE_DIR; do + eval "_val=\${$_v:-}" + [ -n "$_val" ] || continue + _set="$_set $_v=$_val" + case " $_distinct " in *" $_val "*) ;; *) _distinct="$_distinct $_val" ;; esac + done + set -- $_distinct + [ "$#" -gt 1 ] || return 0 + echo "# note: root-selecting variables disagree:$_set; using $STATE_DIR ($_gstack_sr_var wins). Explain: $(dirname "$_SELF")/gstack-paths --explain ($_STATE_DOC)" } case "${1:-}" in @@ -470,6 +489,12 @@ case "${1:-}" in else echo "${KEY}: ${SAFE_VALUE}" >> "$CONFIG_FILE" fi + # Report only when another root still overrides the value just written. + gstack_config_select "$KEY" + if [ -n "$_gstack_cfg_root" ] && [ "$_gstack_cfg_root" != "$STATE_DIR" ] && [ "$_gstack_cfg_value" != "$SAFE_VALUE" ]; then + echo "gstack-config: set $KEY in $CONFIG_FILE, but $KEY is still '$_gstack_cfg_value': $_gstack_cfg_root/config.yaml sets that more restrictive value, and for privacy keys the most restrictive value across state roots wins." >&2 + echo "fix: GSTACK_STATE_ROOT='$_gstack_cfg_root' $_SELF set $KEY $SAFE_VALUE ($_STATE_DOC)" >&2 + fi # Auto-relink skills when prefix setting changes (skip during setup to avoid recursive call) if [ "$KEY" = "skill_prefix" ] && [ -z "${GSTACK_SETUP_RUNNING:-}" ]; then GSTACK_RELINK="$(dirname "$0")/gstack-relink" @@ -482,15 +507,19 @@ case "${1:-}" in fi echo "" echo "# ─── Active values (including defaults for unset keys) ───" + report_root_disagreement for KEY in proactive routing_declined telemetry auto_upgrade update_check \ skill_prefix explain_level \ codex_reviews gstack_contributor skip_eng_review workspace_root \ artifacts_sync_mode artifacts_sync_mode_prompted plan_tune_hooks \ timeline_stop_hook design_detector design_detector_install_prompted memorable_recall; do - VALUE=$(read_config_value "$KEY" || true) + gstack_config_select "$KEY" + VALUE="$_gstack_cfg_value" SOURCE="default" if [ -n "$VALUE" ]; then SOURCE="set" + _gstack_config_rank "$KEY" x + [ -n "$_gstack_cfg_rank" ] && SOURCE="set, $_gstack_cfg_root" else VALUE=$(lookup_default "$KEY") fi @@ -569,7 +598,7 @@ case "${1:-}" in # worktree — bin/dev-setup owns that flow), and look like a real # gstack clone. INSTALL_DIR="$HOME/.claude/skills/gstack" - RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}" + RENDER_DIR="${GSTACK_USER_RENDER_DIR:-$STATE_DIR/render/claude}" if [ ! -d "$INSTALL_DIR" ]; then echo "No global install at $INSTALL_DIR — nothing to render. (Dev workspaces get blocks via bin/dev-setup.)" elif [ -L "$INSTALL_DIR" ]; then diff --git a/bin/gstack-design-detect.ts b/bin/gstack-design-detect.ts index 079ac37a22..76a24224ab 100755 --- a/bin/gstack-design-detect.ts +++ b/bin/gstack-design-detect.ts @@ -57,7 +57,7 @@ * * Scan hardening: every target, explicit or derived from `--changed`, must be an * existing regular file or directory whose realpath lies under the repo root (or - * cwd) or under ${GSTACK_HOME:-~/.gstack}/projects//designs/ (where design- + * cwd) or under /projects//designs/ (where design- * review keeps rendered-DOM dumps: `designs//dom/**` are page dumps and * scan with --no-inline-ignores, because an `impeccable-disable` comment there is * page-controlled; other designs/ files are gstack-authored artifacts and keep @@ -77,7 +77,7 @@ * whose realpath lies inside the repo or cwd are ignored (IMPECCABLE_ENV_IGNORED). * * Observability: one content-free JSON line per probe/scan appended to - * ${GSTACK_HOME:-~/.gstack}/analytics/design-detector.jsonl (local file, no egress). + * /analytics/design-detector.jsonl (local file, no egress). * * Non-sink: this spawns a third-party binary the user installed over local * paths; gstack does not audit that engine's network behavior (NOTICE.md). @@ -94,6 +94,7 @@ import { ENGINE_RELEASE_BASE, ENGINE_ASSETS, ENGINE_PINS, } from '../lib/design-detect-contract'; import { writeReceipt, writeOutcome } from '../lib/egress-receipt'; +import { readConfigKey, resolveStateRoot } from '../lib/state-root'; import { DESIGN_SLOP_CATALOG, entryForImpeccableId } from '../lib/design-catalog'; import { isFrontendPath } from '../lib/frontend-scope'; @@ -104,14 +105,9 @@ const HOME = os.homedir(); const REAL_HOME = realpathOrNull(HOME) ?? HOME; const ENV = process.env; -/** Where config.yaml lives: the same precedence bin/gstack-config uses. */ -function gstackStateDir(): string { - return ENV.GSTACK_STATE_ROOT || ENV.GSTACK_HOME || ENV.GSTACK_STATE_DIR || path.join(HOME, '.gstack'); -} - -/** Existing local analytics location; design artifacts resolve separately below. */ +/** Config, analytics and design artifacts share the one state root (lib/state-root.ts). */ function gstackHome(): string { - return ENV.GSTACK_HOME || path.join(HOME, '.gstack'); + return resolveStateRoot(ENV); } function realpathOrNull(p: string): string | null { @@ -130,23 +126,10 @@ function gitTopLevel(cwd: string): string | null { return top ? realpathOrNull(top) : null; } -/** One flat key from config.yaml, read the way bin/gstack-config resolves it (same STATE_DIR precedence); '' when unset. */ +/** One flat key from config.yaml via readConfigKey (the bin/gstack-config reader); '' when unset. */ function configValue(key: string): string { - const file = path.join(gstackStateDir(), 'config.yaml'); - try { - const text = fs.readFileSync(file, 'utf-8'); - let value = ''; - const re = new RegExp(`^${key}:\\s*(.*?)\\s*$`); - for (const line of text.split('\n')) { - const m = line.match(re); - if (!m) continue; - // flat YAML: drop a trailing comment and surrounding quotes - value = m[1].replace(/\s+#.*$/, '').trim().replace(/^["'](.*)["']$/, '$1'); - } - return value; - } catch { - return ''; - } + // flat YAML: drop a trailing comment and surrounding quotes + return (readConfigKey(key, ENV) ?? '').replace(/\s+#.*$/, '').trim().replace(/^["'](.*)["']$/, '$1'); } /** design_detector: `Off` by hand must not silently re-enable a third-party binary. */ @@ -785,12 +768,7 @@ function refuse(target: string, why: string) { } function designsRoot(): string { - // Match the artifact producer's bin/gstack-paths precedence without changing - // config or analytics roots. Plugin data belongs to gstack only with its marker. - const stateRoot = ENV.GSTACK_HOME - || (ENV.CLAUDE_PLUGIN_DATA && /gstack/i.test(ENV.CLAUDE_PLUGIN_ROOT || '') ? ENV.CLAUDE_PLUGIN_DATA : '') - || (ENV.HOME ? path.join(ENV.HOME, '.gstack') : '.gstack'); - return path.join(stateRoot, 'projects'); + return path.join(resolveStateRoot(ENV), 'projects'); } type TargetClass = 'project' | 'artifact' | 'dom-dump'; diff --git a/bin/gstack-developer-profile b/bin/gstack-developer-profile index 57ba9adb9d..e5f4197f84 100755 --- a/bin/gstack-developer-profile +++ b/bin/gstack-developer-profile @@ -29,7 +29,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" # GSTACK_STATE_ROOT takes precedence over GSTACK_HOME (test isolation per D16). -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" # Windows git-bash: GSTACK_HOME resolves to an MSYS path (/c/Users/...), which # Bun on Windows cannot open as a filesystem path (bites --derive). Normalize # once, here, before PROFILE_FILE/LEGACY_FILE are derived from it below — diff --git a/bin/gstack-distill-apply b/bin/gstack-distill-apply index 5b97da0aaa..d87128d405 100755 --- a/bin/gstack-distill-apply +++ b/bin/gstack-distill-apply @@ -24,7 +24,9 @@ # gstack-distill-apply --list # show pending proposals set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null || true)" SLUG="${SLUG:-unknown}" PROJECT_DIR="$GSTACK_HOME/projects/$SLUG" diff --git a/bin/gstack-distill-free-text b/bin/gstack-distill-free-text index a7e997c0a5..86cbd8918a 100755 --- a/bin/gstack-distill-free-text +++ b/bin/gstack-distill-free-text @@ -32,7 +32,9 @@ set -euo pipefail BASH_COMPAT=50 SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null || true)" SLUG="${SLUG:-unknown}" PROJECT_DIR="$GSTACK_HOME/projects/$SLUG" diff --git a/bin/gstack-egress b/bin/gstack-egress index 4ff92ad0fc..bb87037543 100755 --- a/bin/gstack-egress +++ b/bin/gstack-egress @@ -24,19 +24,13 @@ */ import path from 'node:path'; -import { spawnSync } from 'node:child_process'; import { egressLedgerPath, listReceipts, resolveEgressHome, verifyLedger, } from '../lib/egress-receipt'; - -// import.meta.dir is Windows-safe; new URL(import.meta.url).pathname yields -// '/C:/...' with percent-encoded spaces there, which would make the -// gstack-config spawn silently fail and grants report every default. Matches -// the sibling bin/*.ts convention. -const BIN_DIR = import.meta.dir; +import { readConfigKey } from '../lib/state-root'; /** * Strip control characters (incl. ANSI escapes) from ledger-derived strings @@ -64,11 +58,9 @@ function usage(message: string): never { process.exit(2); } +/** The shared config reader (lib/state-root.ts); '' when unset (callers apply gstack-config's defaults). */ function configGet(key: string): string { - const result = spawnSync(path.join(BIN_DIR, 'gstack-config'), ['get', key], { - encoding: 'utf-8', - }); - return (result.stdout || '').trim(); + return readConfigKey(key) ?? ''; } function egressList(args: string[], home: string): number { diff --git a/bin/gstack-egress-lib.sh b/bin/gstack-egress-lib.sh index 37fe045a7d..4cb50dbfb3 100644 --- a/bin/gstack-egress-lib.sh +++ b/bin/gstack-egress-lib.sh @@ -43,13 +43,13 @@ case "${BASH_SOURCE[0]}" in *) _gstack_egress_lib_dir="$(pwd)" ;; esac +# State root from the shared twin (bin/gstack-state-root.sh, builtins only), +# sourced lazily on first use. _gstack_egress_home() { - if [ -n "${GSTACK_HOME:-}" ]; then - printf '%s' "$GSTACK_HOME" - elif [ -n "${GSTACK_STATE_DIR:-}" ]; then - printf '%s' "$GSTACK_STATE_DIR" + if command -v gstack_state_root >/dev/null 2>&1 || { [ -f "$_gstack_egress_lib_dir/gstack-state-root.sh" ] && . "$_gstack_egress_lib_dir/gstack-state-root.sh"; }; then + gstack_state_root else - printf '%s' "$HOME/.gstack" + printf '%s' "" fi } diff --git a/bin/gstack-evidence b/bin/gstack-evidence index 8343fe9cf5..878c385572 100755 --- a/bin/gstack-evidence +++ b/bin/gstack-evidence @@ -39,6 +39,7 @@ import { mkdirpSync } from "../lib/fs-utils"; import { join, dirname } from "path"; import { spawnSync } from "child_process"; import { appendJsonl, readJsonl } from "../lib/jsonl-store"; +import { resolveStateRoot } from "../lib/state-root"; import { scan, applyRedactions } from "../lib/redact-engine"; const BIN_DIR = dirname(Bun.fileURLToPath(import.meta.url)); @@ -93,10 +94,10 @@ function currentWtree(): string | undefined { } function ledgerPath(): { dir: string; file: string; logsDir: string } { - const home = process.env.GSTACK_HOME || (process.env.HOME ? join(process.env.HOME, ".gstack") : undefined); - // No resolvable home: skip bookkeeping (a literal "~" dir in cwd would land - // inside the repo and perturb the fingerprint it exists to compute). - if (!home) throw new Error("no GSTACK_HOME/HOME — bookkeeping skipped"); + const home = resolveStateRoot(); + // No resolvable home: skip bookkeeping (the relative ".gstack" fallback would + // land inside the repo and perturb the fingerprint it exists to compute). + if (home === ".gstack") throw new Error("no GSTACK_HOME/HOME — bookkeeping skipped"); // ONE gstack-slug spawn: its output carries both SLUG= and BRANCH= lines // (same branch→filename sanitization as reviews.jsonl). const slugOut = spawnSync(join(BIN_DIR, "gstack-slug"), { encoding: "utf-8" }); diff --git a/bin/gstack-gbrain-detect b/bin/gstack-gbrain-detect index 3774f6bacc..ece1d7c87d 100755 --- a/bin/gstack-gbrain-detect +++ b/bin/gstack-gbrain-detect @@ -44,8 +44,9 @@ import { readGbrainVersion, } from "../lib/gbrain-local-status"; import { gbrainConfigDir, isTransactionModePooler } from "../lib/gbrain-exec"; +import { resolveStateRoot } from "../lib/state-root"; -const STATE_DIR = process.env.GSTACK_HOME || join(userHome(), ".gstack"); +const STATE_DIR = resolveStateRoot(); const SCRIPT_DIR = __dirname; const CONFIG_BIN = join(SCRIPT_DIR, "gstack-config"); // Honors GBRAIN_HOME with gbrain's own configDir() semantics (#2521: diff --git a/bin/gstack-gbrain-read-capability.ts b/bin/gstack-gbrain-read-capability.ts index 4850d04090..6cdee19cbd 100644 --- a/bin/gstack-gbrain-read-capability.ts +++ b/bin/gstack-gbrain-read-capability.ts @@ -1,10 +1,10 @@ #!/usr/bin/env bun import { readFileSync, realpathSync, statSync } from 'node:fs'; -import { homedir } from 'node:os'; import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; import { gbrainInvocation, buildGbrainEnv } from '../lib/gbrain-exec'; import { parseSourcesList } from '../lib/gbrain-sources'; +import { resolveStateRoot } from '../lib/state-root'; type Verdict = { status: 'ready' | 'unknown' | 'skipped' | 'source'; reason: string; source_id?: string; page_count?: number }; @@ -20,7 +20,7 @@ function readCapability(): Verdict { try { root = realpathSync(repo.stdout.trim()); const pinPath = join(root, '.gbrain-source'); - const statePath = join(process.env.GSTACK_HOME || join(homedir(), '.gstack'), '.gbrain-sync-state.json'); + const statePath = join(resolveStateRoot(), '.gbrain-sync-state.json'); if (statSync(pinPath).size > 512 || statSync(statePath).size > 64 * 1024) return unknown('sync state or source pin exceeds the read limit'); pin = readFileSync(pinPath, 'utf8').trim(); diff --git a/bin/gstack-gbrain-repo-policy b/bin/gstack-gbrain-repo-policy index 845297a6dd..5b23caa9a6 100755 --- a/bin/gstack-gbrain-repo-policy +++ b/bin/gstack-gbrain-repo-policy @@ -50,12 +50,22 @@ # migration actually changes anything. Idempotent: running twice is safe. # # Env: -# GSTACK_HOME — override ~/.gstack state directory (aligns with other -# gstack-* bins; used heavily in tests). +# GSTACK_HOME — override the state root (the shared chain in +# bin/gstack-state-root.sh; used heavily in tests). +# +# Deny tiers merge across state roots: when the resolved root is not +# ~/.gstack, `get` also reads ~/.gstack/gbrain-repo-policy.json and returns +# its deny or read-only tier when that is more restrictive. Nothing is written +# there. Docs: https://github.com/garrytan/gstack/blob/main/docs/state-root.md set -euo pipefail -STATE_DIR="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" POLICY_FILE="$STATE_DIR/gbrain-repo-policy.json" +gstack_legacy_root_select +LEGACY_POLICY_FILE="" +[ -n "$_gstack_legacy_root" ] && [ -f "$_gstack_legacy_root/gbrain-repo-policy.json" ] && LEGACY_POLICY_FILE="$_gstack_legacy_root/gbrain-repo-policy.json" SCHEMA_VERSION=2 die() { echo "gstack-gbrain-repo-policy: $*" >&2; exit 2; } @@ -177,6 +187,23 @@ ensure_file() { fi } +_tier_rank() { + case "$1" in deny) echo 0 ;; read-only) echo 1 ;; read-write) echo 2 ;; *) echo 3 ;; esac +} + +# merge_legacy_tier KEY TIER — TIER, or the other root's deny/read-only tier +# when that is more restrictive. Never more permissive than TIER. +merge_legacy_tier() { + local key="$1" tier="$2" other + if [ -z "$LEGACY_POLICY_FILE" ]; then printf '%s\n' "$tier"; return 0; fi + other=$(jq -r --arg key "$key" '.[$key] // "none"' "$LEGACY_POLICY_FILE" 2>/dev/null) || other="none" + case "$other" in + deny|read-only) + if [ "$(_tier_rank "$other")" -lt "$(_tier_rank "$tier")" ]; then tier="$other"; fi ;; + esac + printf '%s\n' "$tier" +} + # get --batch — bulk lookup for ingest gates. One URL per stdin line, one # tier per stdout line, input order preserved. Reuses normalize() (the same # code path single `get` uses) per line. Prints `none` where single `get` @@ -190,6 +217,18 @@ ensure_file() { # fails hard (exit 2) instead and names the recovery path. cmd_get_batch() { require_jq + if [ -n "$LEGACY_POLICY_FILE" ] && ! jq empty "$LEGACY_POLICY_FILE" 2>/dev/null; then + die "policy store $LEGACY_POLICY_FILE is corrupt (invalid JSON) — refusing batch read. Inspect or remove it; its deny tiers apply to every state root." + fi + if [ ! -f "$POLICY_FILE" ] && [ -n "$LEGACY_POLICY_FILE" ]; then + local url key + while IFS= read -r url || [ -n "$url" ]; do + key=$(normalize "$url") + if [ -z "$key" ]; then printf 'none\n'; continue; fi + merge_legacy_tier "$key" none + done + return 0 + fi if [ ! -f "$POLICY_FILE" ]; then # No store = no policy was ever set. Every URL is `none`; don't create # the file just for a read (matches cmd_list). @@ -211,7 +250,7 @@ cmd_get_batch() { printf 'none\n' continue fi - jq -r --arg key "$key" '.[$key] // "none"' "$POLICY_FILE" + merge_legacy_tier "$key" "$(jq -r --arg key "$key" '.[$key] // "none"' "$POLICY_FILE")" done } @@ -235,7 +274,13 @@ cmd_get() { return 0 fi ensure_file - jq -r --arg key "$key" '.[$key] // "unset"' "$POLICY_FILE" + local tier + tier=$(jq -r --arg key "$key" '.[$key] // "unset"' "$POLICY_FILE") + if [ -n "$LEGACY_POLICY_FILE" ] && ! jq empty "$LEGACY_POLICY_FILE" 2>/dev/null; then + echo "gstack-gbrain-repo-policy: ignoring corrupt $LEGACY_POLICY_FILE (inspect or remove it)" >&2 + LEGACY_POLICY_FILE="" + fi + merge_legacy_tier "$key" "$tier" } cmd_set() { diff --git a/bin/gstack-gbrain-source-wireup b/bin/gstack-gbrain-source-wireup index 7947fd5871..05e50b1df7 100755 --- a/bin/gstack-gbrain-source-wireup +++ b/bin/gstack-gbrain-source-wireup @@ -43,7 +43,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" CONFIG_BIN="$SCRIPT_DIR/gstack-config" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" WORKTREE="${GSTACK_BRAIN_WORKTREE:-$HOME/.gstack-brain-worktree}" # v1.27.0.0+ canonical name; brain-remote is the legacy fallback during migration. if [ -f "$HOME/.gstack-artifacts-remote.txt" ]; then diff --git a/bin/gstack-gbrain-sync.ts b/bin/gstack-gbrain-sync.ts index 9b0b67ed82..29d644c6c8 100644 --- a/bin/gstack-gbrain-sync.ts +++ b/bin/gstack-gbrain-sync.ts @@ -44,6 +44,7 @@ import { localEngineStatus, type LocalEngineStatus } from "../lib/gbrain-local-s import { buildGbrainEnv, spawnGbrain, execGbrainJson, NEEDS_SHELL_ON_WINDOWS, bashScriptInvocation } from "../lib/gbrain-exec"; import { repoPolicyTier as sharedRepoPolicyTier } from "../lib/gbrain-repo-policy-client"; import { checkOwnedStagingDir } from "../lib/staging-guard"; +import { resolveStateRoot } from "../lib/state-root"; // ── Types ────────────────────────────────────────────────────────────────── @@ -98,7 +99,7 @@ interface StageResult { // ── Constants ────────────────────────────────────────────────────────────── const HOME = homedir(); -const GSTACK_HOME = process.env.GSTACK_HOME || join(HOME, ".gstack"); +const GSTACK_HOME = resolveStateRoot(); const STATE_PATH = join(GSTACK_HOME, ".gbrain-sync-state.json"); const LOCK_PATH = join(GSTACK_HOME, ".sync-gbrain.lock"); const STALE_LOCK_MS = 5 * 60 * 1000; @@ -118,7 +119,7 @@ const DREAM_MARKER_STALE_MS = DEFAULT_DREAM_TIMEOUT_MS; * module-load-time const captures the real ~/.gstack before a test can redirect. */ export function dreamMarkerPath(): string { - return join(process.env.GSTACK_HOME || join(homedir(), ".gstack"), ".dream-in-progress"); + return join(resolveStateRoot(), ".dream-in-progress"); } // Default 35-minute timeout for code-walk + memory-ingest stages. Override via diff --git a/bin/gstack-learnings-log b/bin/gstack-learnings-log index 3c47ebb80a..fd0efaa56f 100755 --- a/bin/gstack-learnings-log +++ b/bin/gstack-learnings-log @@ -14,7 +14,9 @@ case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) command -v cygpath >/dev/null 2>&1 && SCRIPT_DIR="$(cygpath -m "$SCRIPT_DIR")" ;; esac eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" mkdir -p "$GSTACK_HOME/projects/$SLUG" INPUT="$1" diff --git a/bin/gstack-learnings-search b/bin/gstack-learnings-search index d7038e8218..4e3d8ba467 100755 --- a/bin/gstack-learnings-search +++ b/bin/gstack-learnings-search @@ -8,7 +8,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" TYPE="" QUERY="" diff --git a/bin/gstack-memorable b/bin/gstack-memorable index 31b1a1dfd1..993f163db6 100755 --- a/bin/gstack-memorable +++ b/bin/gstack-memorable @@ -36,7 +36,9 @@ set -uo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" GSTACK_CONFIG="$SCRIPT_DIR/gstack-config" -STATE_DIR="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" SETTINGS_FILE="${GSTACK_SETTINGS_FILE:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}/settings.json}" HOOK_SOURCE="gstack-memorable" @@ -380,9 +382,9 @@ status_bridge() { n="unknown (gstack-egress list failed; run it yourself)" fi echo "receipts: $n for sink $SINK (gstack-egress list --sink $SINK)" - # Same resolution as lib/egress-receipt.ts resolveEgressHome: GSTACK_HOME, GSTACK_STATE_DIR, ~/.gstack. + # Same root lib/egress-receipt.ts resolveEgressHome uses (the shared state-root chain). local ledger size - ledger="${GSTACK_HOME:-${GSTACK_STATE_DIR:-$HOME/.gstack}}/security/egress.jsonl" + ledger="$STATE_DIR/security/egress.jsonl" if [ -f "$ledger" ]; then size="$(wc -c < "$ledger" | tr -d ' ')" if [ "${size:-0}" -gt 26214400 ]; then diff --git a/bin/gstack-memory-ingest.ts b/bin/gstack-memory-ingest.ts index 412ee48f96..a94adf4fc5 100644 --- a/bin/gstack-memory-ingest.ts +++ b/bin/gstack-memory-ingest.ts @@ -72,6 +72,7 @@ import { execGbrainText, spawnGbrainAsync } from "../lib/gbrain-exec"; import { writeReceipt } from "../lib/egress-receipt"; import { checkOwnedStagingDir, STAGING_MARKER } from "../lib/staging-guard"; import { hasRepoPolicyStore, repoPolicyTierBatch } from "../lib/gbrain-repo-policy-client"; +import { resolveStateRoot } from "../lib/state-root"; // ── Types ────────────────────────────────────────────────────────────────── @@ -186,7 +187,7 @@ interface BulkResult { // ── Constants ────────────────────────────────────────────────────────────── const HOME = homedir(); -const GSTACK_HOME = process.env.GSTACK_HOME || join(HOME, ".gstack"); +const GSTACK_HOME = resolveStateRoot(); const STATE_PATH = join(GSTACK_HOME, ".transcript-ingest-state.json"); const DEFAULT_INCREMENTAL_BUDGET_MS = 50; diff --git a/bin/gstack-paths b/bin/gstack-paths index 5b66e3102f..2b4da7f385 100755 --- a/bin/gstack-paths +++ b/bin/gstack-paths @@ -2,6 +2,7 @@ # gstack-paths — output portable state-root paths for skill bash blocks # Usage: eval "$(gstack-paths)" → sets GSTACK_STATE_ROOT, PLAN_ROOT, TMP_ROOT # Or: gstack-paths → prints GSTACK_STATE_ROOT=... etc. +# gstack-paths --explain → which variable selected the state root, and why # # Resolves three roots with explicit fallback chains so skills work the same # whether installed as a Claude Code plugin (CLAUDE_PLUGIN_DATA / CLAUDE_PLANS_DIR @@ -9,9 +10,18 @@ # CI / container env where HOME may be unset. # # Chains: -# GSTACK_STATE_ROOT: GSTACK_HOME -> CLAUDE_PLUGIN_DATA (only when CLAUDE_PLUGIN_ROOT=*gstack*) -> $HOME/.gstack -> .gstack +# GSTACK_STATE_ROOT: GSTACK_STATE_ROOT -> GSTACK_HOME -> GSTACK_STATE_DIR +# -> CLAUDE_PLUGIN_DATA (only when CLAUDE_PLUGIN_ROOT=*gstack*) +# -> $HOME/.gstack -> .gstack +# (one rule, owned by bin/gstack-state-root.sh; set GSTACK_HOME +# to relocate state; GSTACK_STATE_ROOT is this script's output, +# also honored as input; GSTACK_STATE_DIR is a legacy alias) # PLAN_ROOT: GSTACK_PLAN_DIR -> CLAUDE_PLANS_DIR -> $HOME/.claude/plans -> .claude/plans # TMP_ROOT: TMPDIR -> TMP -> .gstack/tmp (and mkdir -p, best-effort) +# Docs: https://github.com/garrytan/gstack/blob/main/docs/state-root.md +# +# Callers guard the eval, because eval "$(f)" succeeds even when f fails: +# eval "$(gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" # # Output: values are emitted shell-quoted (printf %q) so `eval` round-trips them # byte-for-byte. This matters on Windows, where $TMP is a backslash path like @@ -24,19 +34,67 @@ # reason any path variable needs quoting. set -u +_GSTACK_DOC="https://github.com/garrytan/gstack/blob/main/docs/state-root.md" +_GSTACK_TWIN="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)/gstack-state-root.sh" + +# Fail stop: never print a payload that would set an empty GSTACK_STATE_ROOT. +_gstack_paths_fail() { + echo "gstack-paths: cannot resolve the gstack state root: $1" >&2 + echo "fix: reinstall gstack with ./setup (in the gstack checkout) or /gstack-upgrade. Docs: $_GSTACK_DOC" >&2 + exit 1 +} +if [ ! -f "$_GSTACK_TWIN" ] || ! . "$_GSTACK_TWIN" 2>/dev/null || ! command -v gstack_state_root_select >/dev/null 2>&1; then + _gstack_paths_fail "missing or broken $_GSTACK_TWIN" +fi + # State root: where gstack writes projects/, sessions/, analytics/. -if [ -n "${GSTACK_HOME:-}" ]; then - _state_root="$GSTACK_HOME" -elif [ -n "${CLAUDE_PLUGIN_DATA:-}" ] && echo "${CLAUDE_PLUGIN_ROOT:-}" | grep -qi "gstack"; then - # Guard: only trust CLAUDE_PLUGIN_DATA when CLAUDE_PLUGIN_ROOT confirms we are - # running as the gstack plugin. Without this, a CLAUDE_PLUGIN_DATA from another - # plugin (e.g. codex) that leaked into the session env via CLAUDE_ENV_FILE would - # be picked up, writing all gstack state into the wrong directory. - _state_root="$CLAUDE_PLUGIN_DATA" -elif [ -n "${HOME:-}" ]; then - _state_root="$HOME/.gstack" -else - _state_root=".gstack" +gstack_state_root_select +_state_root="$_gstack_sr_root" +[ -n "$_state_root" ] || _gstack_paths_fail "the resolver in $_GSTACK_TWIN returned an empty root" + +if [ "${1:-}" = "--explain" ]; then + echo "state root: $_state_root (selected by $_gstack_sr_var)" + echo "chain (first non-empty wins):" + _gstack_sel_seen=0 + for _v in GSTACK_STATE_ROOT GSTACK_HOME GSTACK_STATE_DIR CLAUDE_PLUGIN_DATA; do + eval "_val=\${$_v:-}" + if [ -z "$_val" ]; then + printf ' %-20s unset\n' "$_v" + elif [ "$_v" = "$_gstack_sr_var" ]; then + printf ' %-20s %s selected\n' "$_v" "$_val" + elif [ "$_v" = CLAUDE_PLUGIN_DATA ] && [ "$_gstack_sr_var" = default ]; then + printf ' %-20s %s ignored (CLAUDE_PLUGIN_ROOT does not contain "gstack")\n' "$_v" "$_val" + else + printf ' %-20s %s ignored\n' "$_v" "$_val" + fi + done + _gstack_user_home + if [ -n "$_gstack_home_val" ]; then + _gstack_default="$_gstack_home_val/.gstack" + else + _gstack_default=".gstack" + fi + if [ "$_gstack_sr_var" = default ]; then + printf ' %-20s %s selected\n' "default" "$_gstack_default" + else + printf ' %-20s %s ignored\n' "default" "$_gstack_default" + _gstack_has_state=no + for _e in "$_gstack_default"/* "$_gstack_default"/.[!.]*; do + [ -e "$_e" ] && { _gstack_has_state=yes; break; } + done + echo "default root $_gstack_default also holds gstack state: $_gstack_has_state" + fi + echo "merged privacy keys (most restrictive value across roots wins):" + for _k in telemetry memorable_recall codex_reviews update_check; do + gstack_config_select "$_k" + if [ -n "$_gstack_cfg_value" ]; then + printf ' %-17s %s (from %s/config.yaml)\n' "$_k:" "$_gstack_cfg_value" "$_gstack_cfg_root" + else + printf ' %-17s not set (default applies)\n' "$_k:" + fi + done + echo "docs: $_GSTACK_DOC" + exit 0 fi # Plan root: where /context-save and /codex consult write plan files. diff --git a/bin/gstack-question-log b/bin/gstack-question-log index ea1afe1e33..d769bf371c 100755 --- a/bin/gstack-question-log +++ b/bin/gstack-question-log @@ -35,7 +35,9 @@ case "$(uname -s)" in esac eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" # GSTACK_STATE_ROOT takes precedence over GSTACK_HOME (test isolation per D16). -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" mkdir -p "$GSTACK_HOME/projects/$SLUG" INPUT="$1" diff --git a/bin/gstack-question-preference b/bin/gstack-question-preference index f78d4b269c..51de1347e9 100755 --- a/bin/gstack-question-preference +++ b/bin/gstack-question-preference @@ -32,7 +32,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" # GSTACK_STATE_ROOT takes precedence over GSTACK_HOME (test isolation per D16). -GSTACK_HOME="${GSTACK_STATE_ROOT:-${GSTACK_HOME:-$HOME/.gstack}}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null || true)" SLUG="${SLUG:-unknown}" PREF_FILE="$GSTACK_HOME/projects/$SLUG/question-preferences.json" diff --git a/bin/gstack-redact-prepush b/bin/gstack-redact-prepush index 8ca1fa0f55..af3eebbec0 100755 --- a/bin/gstack-redact-prepush +++ b/bin/gstack-redact-prepush @@ -27,10 +27,10 @@ */ import { spawnSync } from "child_process"; import * as fs from "fs"; -import * as os from "os"; import * as path from "path"; import { normalizeWithMap, scan, type Finding } from "../lib/redact-engine"; import { mkdirpSync } from "../lib/fs-utils"; +import { resolveStateRoot } from "../lib/state-root"; const ZERO = /^0+$/; let emptyTree: string | undefined; @@ -416,7 +416,7 @@ function scanAddedLines(added: string, opts: Parameters[1]): Findin function logSkip(reason: string): void { try { - const home = process.env.GSTACK_HOME || path.join(os.homedir(), ".gstack"); + const home = resolveStateRoot(); const dir = path.join(home, "security"); // mkdirpSync, not bare mkdirSync: bun-on-Windows EEXIST (#2635). This site // is try-wrapped by the caller, so the old failure was a silent skip-log diff --git a/bin/gstack-relink b/bin/gstack-relink index ecc609caef..bafd24ef6f 100755 --- a/bin/gstack-relink +++ b/bin/gstack-relink @@ -5,7 +5,7 @@ # gstack-relink # # Env overrides (for testing): -# GSTACK_STATE_DIR — override ~/.gstack state directory +# GSTACK_HOME — relocate the state root (chain: bin/gstack-state-root.sh) # GSTACK_INSTALL_DIR — override gstack install directory # GSTACK_SKILLS_DIR — override target skills directory set -euo pipefail @@ -40,7 +40,9 @@ PREFIX=$("$GSTACK_CONFIG" get skill_prefix 2>/dev/null || echo "false") # out-dir instead of the tracked install checkout. When a render exists for a # skill, relink serves it — otherwise a config change would silently flip # every skill back to the canonical (blockless) source. -RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}" +. "$SCRIPT_DIR/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $SCRIPT_DIR/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_STATE_ROOT="$_gstack_sr_root" +RENDER_DIR="${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}" # ─── Ownership gate ─────────────────────────────────────────────────────────── # relink runs on every ./setup and used to `rm -rf` any same-name entry with a @@ -58,7 +60,7 @@ RENDER_DIR="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claud # refreshed in place. WEAK (byte-identity with our source, or gen-skill-docs' # two-line banner on a real file) proves only that the SKILL.md came from us: # it authorizes touching that one file, never deleting the directory, and a -# differing file is moved to ${GSTACK_HOME:-~/.gstack}/backups/skills// +# differing file is moved to $GSTACK_STATE_ROOT/backups/skills// # before we link over it (a user who started their own skill from a gstack # SKILL.md looks exactly like a pre-marker legacy copy). # @@ -183,7 +185,7 @@ _report_foreign() { # Weakly-proven real files we would otherwise overwrite go here, one summary # line at the end. mv, not cp: the link that follows needs the path free. -BACKUP_ROOT="${GSTACK_HOME:-$HOME/.gstack}/backups/skills/$(date +%Y%m%dT%H%M%S)" +BACKUP_ROOT="$GSTACK_STATE_ROOT/backups/skills/$(date +%Y%m%dT%H%M%S)" BACKED_UP=() _backup_skill_md() { # Non-zero when the file could NOT be moved: the caller leaves the entry alone. diff --git a/bin/gstack-repo-mode b/bin/gstack-repo-mode index a5c5a6ba64..7b1dd901e7 100755 --- a/bin/gstack-repo-mode +++ b/bin/gstack-repo-mode @@ -41,7 +41,9 @@ if [ -n "$OVERRIDE" ] && [ "$OVERRIDE" != "null" ]; then fi # Check cache (7-day TTL) -CACHE_DIR="$HOME/.gstack/projects/$SLUG" +. "$SCRIPT_DIR/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $SCRIPT_DIR/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_STATE_ROOT="$_gstack_sr_root" +CACHE_DIR="$GSTACK_STATE_ROOT/projects/$SLUG" CACHE_FILE="$CACHE_DIR/repo-mode.json" if [ -f "$CACHE_FILE" ]; then # GNU first (#2195): on GNU coreutils `stat -f` SUCCEEDS with filesystem diff --git a/bin/gstack-retro-metrics b/bin/gstack-retro-metrics index 58c2c05180..e04f84a400 100755 --- a/bin/gstack-retro-metrics +++ b/bin/gstack-retro-metrics @@ -12,7 +12,7 @@ # # Conventions mirror bin/gstack-skill-start: # - Paths resolve $0-relative (works for every host + install layout). -# - State paths honor ${GSTACK_HOME:-$HOME/.gstack}. +# - State paths honor the shared state root (bin/gstack-paths). # - Error style: per-line `|| true`, never `set -e` — a mid-script failure # must not drop later METRIC lines. # - No heredocs (nothing to BASH_COMPAT-guard; see @@ -45,7 +45,9 @@ done # sibling-bin call must go through $_BIN, never bare PATH lookup). _SCRIPT_DIR=$(cd "$(dirname "$0")" 2>/dev/null && pwd) _BIN="$_SCRIPT_DIR" -_GH="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +_GH="$_gstack_sr_root" echo "RETRO_METRICS_PROTO: 1" diff --git a/bin/gstack-review-log b/bin/gstack-review-log index c9f6149a0d..c1bdab2642 100755 --- a/bin/gstack-review-log +++ b/bin/gstack-review-log @@ -13,7 +13,9 @@ export GIT_OPTIONAL_LOCKS=0 export GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }'core.fsmonitor=false' 'core.untrackedCache=false'" SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" mkdir -p "$GSTACK_HOME/projects/$SLUG" INPUT="${1:-}" diff --git a/bin/gstack-review-read b/bin/gstack-review-read index 16139f1d8e..3725c3e723 100755 --- a/bin/gstack-review-read +++ b/bin/gstack-review-read @@ -14,7 +14,9 @@ case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) command -v cygpath >/dev/null 2>&1 && SCRIPT_DIR="$(cygpath -m "$SCRIPT_DIR")" ;; esac eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" WTREE=$("$SCRIPT_DIR/gstack-wtree" 2>/dev/null || echo "unknown") if [ -f "$GSTACK_HOME/projects/$SLUG/$BRANCH-reviews.jsonl" ]; then GSTACK_REVIEW_LIB="$SCRIPT_DIR/../lib/review-evidence.ts" GSTACK_REVIEW_WTREE="$WTREE" bun -e ' diff --git a/bin/gstack-session-update b/bin/gstack-session-update index 15f8caa872..fdb2ce873f 100755 --- a/bin/gstack-session-update +++ b/bin/gstack-session-update @@ -10,7 +10,10 @@ set +e GSTACK_DIR="${GSTACK_DIR:-$HOME/.claude/skills/gstack}" -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +# Hook: source the state-root twin (never spawn gstack-paths); a broken +# install exits 0 silently, like every other error here. +. "$(cd "$(dirname "$0")" && pwd)/gstack-state-root.sh" 2>/dev/null || exit 0 +STATE_DIR="$(gstack_state_root; printf x)"; STATE_DIR="${STATE_DIR%x}" # Egress receipt helpers (_receipted_git): fail-open — an update pull must # never block a session over a receipt hiccup. diff --git a/bin/gstack-skill-end b/bin/gstack-skill-end index b4b3b01744..b270b8f3ac 100755 --- a/bin/gstack-skill-end +++ b/bin/gstack-skill-end @@ -30,7 +30,9 @@ done _SCRIPT_DIR=$(cd "$(dirname "$0")" 2>/dev/null && pwd) _BIN="$_SCRIPT_DIR" -_GH="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +_GH="$_gstack_sr_root" _TEL=$("$_BIN/gstack-config" get telemetry 2>/dev/null || echo off) _TEL_END=$(date +%s) diff --git a/bin/gstack-skill-start b/bin/gstack-skill-start index 941e3b994f..44eaac5b95 100755 --- a/bin/gstack-skill-start +++ b/bin/gstack-skill-start @@ -51,7 +51,9 @@ done _SCRIPT_DIR=$(cd "$(dirname "$0")" 2>/dev/null && pwd) _BIN="$_SCRIPT_DIR" -_GH="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +_GH="$_gstack_sr_root" # OV4: strip instruction markers from any passthrough text before echoing it # into the blessed tool result. Prior-session/repo content must not be able to diff --git a/bin/gstack-slug b/bin/gstack-slug index 12f0ed3972..49cd56dc8f 100755 --- a/bin/gstack-slug +++ b/bin/gstack-slug @@ -46,11 +46,13 @@ # injection when consumed via source or eval. set -euo pipefail -# GSTACK_HOME-aware, matching lib/bin-context.ts's native port (#2561): the +# State-root aware (bin/gstack-state-root.sh), matching lib/bin-context.ts (#2561): the # bash writer and the TS reader must key the SAME cache, and a test running # with GSTACK_HOME= must write its cache junk there, not into the real # home (observed: 2,528 stale temp-cwd entries accumulated in ~/.gstack). -CACHE_DIR="${GSTACK_HOME:-$HOME/.gstack}/slug-cache" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_STATE_ROOT="$_gstack_sr_root" +CACHE_DIR="$GSTACK_STATE_ROOT/slug-cache" PROJECT_DIR="$(pwd)" # Encode absolute path as cache key: /Users/j/foo → _Users_j_foo CACHE_KEY=$(printf '%s' "$PROJECT_DIR" | tr '/' '_') diff --git a/bin/gstack-specialist-stats b/bin/gstack-specialist-stats index 3349c2b715..1b1d1eafb9 100755 --- a/bin/gstack-specialist-stats +++ b/bin/gstack-specialist-stats @@ -8,7 +8,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" PROJECT_DIR="$GSTACK_HOME/projects/$SLUG" if [ ! -d "$PROJECT_DIR" ]; then diff --git a/bin/gstack-state-root.sh b/bin/gstack-state-root.sh new file mode 100644 index 0000000000..1ce264fda4 --- /dev/null +++ b/bin/gstack-state-root.sh @@ -0,0 +1,135 @@ +# shellcheck shell=bash +# gstack-state-root.sh — the one bash owner of where gstack keeps its state +# (twin of lib/state-root.ts; test/state-root-parity.test.ts keeps them equal). +# Sourced, never executed: bin/gstack-paths and the careful/freeze hooks source +# it; other executables run `eval "$(/gstack-paths)"` plus the +# `: "${GSTACK_STATE_ROOT:?...}"` guard. Chain: GSTACK_STATE_ROOT → GSTACK_HOME → +# GSTACK_STATE_DIR → CLAUDE_PLUGIN_DATA (only when CLAUDE_PLUGIN_ROOT contains +# "gstack") → $HOME/.gstack → .gstack. Bash builtins only (bash 3.2, no +# subprocess): hooks run it on every tool call. Enforced by +# test/state-root-ratchet.test.ts. Generalizes careful/bin/hook-extract.sh's +# former gstack_hook_state_root. Docs: docs/state-root.md. + +# _gstack_user_home — HOME, or USERPROFILE on Windows shells when HOME is unset. +_gstack_user_home() { + _gstack_home_val="${HOME:-}" + if [ -z "$_gstack_home_val" ]; then + case "${OSTYPE:-}" in + msys*|cygwin*|win32*) _gstack_home_val="${USERPROFILE:-}" ;; + esac + fi +} + +# gstack_state_root_select — sets _gstack_sr_root and _gstack_sr_var (the +# variable that selected it, or "default") without printing. +gstack_state_root_select() { + _gstack_user_home + if [ -n "${GSTACK_STATE_ROOT:-}" ]; then + _gstack_sr_root="$GSTACK_STATE_ROOT"; _gstack_sr_var="GSTACK_STATE_ROOT" + elif [ -n "${GSTACK_HOME:-}" ]; then + _gstack_sr_root="$GSTACK_HOME"; _gstack_sr_var="GSTACK_HOME" + elif [ -n "${GSTACK_STATE_DIR:-}" ]; then + _gstack_sr_root="$GSTACK_STATE_DIR"; _gstack_sr_var="GSTACK_STATE_DIR" + else + _gstack_sr_root="" + if [ -n "${CLAUDE_PLUGIN_DATA:-}" ]; then + case "${CLAUDE_PLUGIN_ROOT:-}" in + *[gG][sS][tT][aA][cC][kK]*) _gstack_sr_root="$CLAUDE_PLUGIN_DATA"; _gstack_sr_var="CLAUDE_PLUGIN_DATA" ;; + esac + fi + if [ -z "$_gstack_sr_root" ]; then + if [ -n "$_gstack_home_val" ]; then + _gstack_sr_root="$_gstack_home_val/.gstack"; _gstack_sr_var="default" + else + _gstack_sr_root=".gstack"; _gstack_sr_var="default" + fi + fi + fi +} + +# gstack_state_root — print the state root WITHOUT a trailing newline. Capture +# with a sentinel so a root ending in a newline round-trips exactly: +# r="$(gstack_state_root; printf x)"; r="${r%x}" +gstack_state_root() { + gstack_state_root_select + printf '%s' "$_gstack_sr_root" +} + +# _gstack_config_from_root ROOT KEY — sets _gstack_cfg_one to the value of the +# last `KEY:` line in ROOT/config.yaml, trimmed ("" when absent). Same parse as +# `gstack-config get`. +_gstack_config_from_root() { + _gstack_cfg_one="" + [ -f "$1/config.yaml" ] || return 0 + while IFS= read -r _gstack_cfg_line || [ -n "$_gstack_cfg_line" ]; do + case "$_gstack_cfg_line" in + "$2":*) + _gstack_cfg_one="${_gstack_cfg_line#"$2":}" + _gstack_cfg_one="${_gstack_cfg_one#"${_gstack_cfg_one%%[![:space:]]*}"}" + _gstack_cfg_one="${_gstack_cfg_one%"${_gstack_cfg_one##*[![:space:]]}"}" + ;; + esac + done < "$1/config.yaml" +} + +# _gstack_config_rank KEY VALUE — sets _gstack_cfg_rank: position in the key's +# most-restrictive-first order, -1 for an unrecognized value, "" when KEY is +# not a merged key. +_gstack_config_rank() { + case "$1" in + telemetry) case "$2" in off) _gstack_cfg_rank=0 ;; anonymous) _gstack_cfg_rank=1 ;; community) _gstack_cfg_rank=2 ;; *) _gstack_cfg_rank=-1 ;; esac ;; + memorable_recall) case "$2" in off) _gstack_cfg_rank=0 ;; on) _gstack_cfg_rank=1 ;; *) _gstack_cfg_rank=-1 ;; esac ;; + codex_reviews) case "$2" in disabled) _gstack_cfg_rank=0 ;; enabled) _gstack_cfg_rank=1 ;; *) _gstack_cfg_rank=-1 ;; esac ;; + update_check) case "$2" in false) _gstack_cfg_rank=0 ;; true) _gstack_cfg_rank=1 ;; *) _gstack_cfg_rank=-1 ;; esac ;; + *) _gstack_cfg_rank="" ;; + esac +} + +# gstack_legacy_root_select — sets _gstack_legacy_root to the second candidate +# root merged privacy settings are also read from: $HOME/.gstack +# (GSTACK_TEST_LEGACY_ROOT in tests), or "" when there is none or it is the +# resolved root. Call after gstack_state_root_select. +gstack_legacy_root_select() { + _gstack_legacy_root="" + if [ -n "${GSTACK_TEST_LEGACY_ROOT:-}" ]; then + _gstack_legacy_root="$GSTACK_TEST_LEGACY_ROOT" + elif [ -n "$_gstack_home_val" ]; then + _gstack_legacy_root="$_gstack_home_val/.gstack" + fi + [ "$_gstack_legacy_root" = "$_gstack_sr_root" ] && _gstack_legacy_root="" + return 0 +} + +# gstack_config_select KEY — sets _gstack_cfg_value and _gstack_cfg_root (the +# root that supplied it; both "" when unset). Merged privacy keys (telemetry, +# memorable_recall, codex_reviews, update_check) take the most restrictive +# value across the resolved root and $HOME/.gstack; every other key reads the +# resolved root only. GSTACK_TEST_LEGACY_ROOT replaces $HOME/.gstack in tests. +gstack_config_select() { + gstack_state_root_select + _gstack_config_from_root "$_gstack_sr_root" "$1" + _gstack_cfg_value="$_gstack_cfg_one"; _gstack_cfg_root="" + [ -n "$_gstack_cfg_value" ] && _gstack_cfg_root="$_gstack_sr_root" + _gstack_config_rank "$1" "x" + [ -n "$_gstack_cfg_rank" ] || return 0 + gstack_legacy_root_select + [ -n "$_gstack_legacy_root" ] || return 0 + _gstack_cfg_legacy="$_gstack_legacy_root" + _gstack_config_from_root "$_gstack_cfg_legacy" "$1" + [ -n "$_gstack_cfg_one" ] || return 0 + if [ -z "$_gstack_cfg_value" ]; then + _gstack_cfg_value="$_gstack_cfg_one"; _gstack_cfg_root="$_gstack_cfg_legacy" + return 0 + fi + _gstack_config_rank "$1" "$_gstack_cfg_value"; _gstack_cfg_best="$_gstack_cfg_rank" + _gstack_config_rank "$1" "$_gstack_cfg_one" + if [ "$_gstack_cfg_rank" -lt "$_gstack_cfg_best" ]; then + _gstack_cfg_value="$_gstack_cfg_one"; _gstack_cfg_root="$_gstack_cfg_legacy" + fi +} + +# gstack_read_config_key KEY — print the (merged) value, no trailing newline. +gstack_read_config_key() { + gstack_config_select "$1" + printf '%s' "$_gstack_cfg_value" +} diff --git a/bin/gstack-taste-update b/bin/gstack-taste-update index 4782552d22..7510a8bbfd 100755 --- a/bin/gstack-taste-update +++ b/bin/gstack-taste-update @@ -32,8 +32,9 @@ import * as fs from 'fs'; import * as path from 'path'; import { execSync } from 'child_process'; +import { resolveStateRoot } from '../lib/state-root'; -const STATE_DIR = process.env.GSTACK_STATE_DIR || path.join(process.env.HOME || '/', '.gstack'); +const STATE_DIR = resolveStateRoot(); const SCHEMA_VERSION = 1; const SESSION_CAP = 50; const DECAY_PER_WEEK = 0.05; diff --git a/bin/gstack-telemetry-log b/bin/gstack-telemetry-log index 7b95e5ea75..f75fe76230 100755 --- a/bin/gstack-telemetry-log +++ b/bin/gstack-telemetry-log @@ -16,7 +16,7 @@ # epilogue may sweep. # # Env overrides (for testing): -# GSTACK_STATE_DIR — override ~/.gstack state directory +# GSTACK_HOME — relocate the state root (chain: bin/gstack-state-root.sh) # GSTACK_DIR — override auto-detected gstack root # # NOTE: Uses set -uo pipefail (no -e) — telemetry must never exit non-zero @@ -29,7 +29,9 @@ SCRIPT_DIR="$GSTACK_DIR/bin" case "$(uname -s)" in MINGW*|MSYS*|CYGWIN*) command -v cygpath >/dev/null 2>&1 && SCRIPT_DIR="$(cygpath -m "$SCRIPT_DIR")" ;; esac -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" ANALYTICS_DIR="$STATE_DIR/analytics" JSONL_FILE="$ANALYTICS_DIR/skill-usage.jsonl" PENDING_DIR="$ANALYTICS_DIR" # .pending-* files live here @@ -148,7 +150,7 @@ fi # can't be guessed or correlated by someone who knows your machine identity. INSTALL_ID="" if [ "$TIER" = "community" ]; then - ID_FILE="$HOME/.gstack/installation-id" + ID_FILE="$STATE_DIR/installation-id" if [ -f "$ID_FILE" ]; then INSTALL_ID="$(cat "$ID_FILE" 2>/dev/null)" fi diff --git a/bin/gstack-telemetry-sync b/bin/gstack-telemetry-sync index 1a4ac02b88..9ad5d62f3e 100755 --- a/bin/gstack-telemetry-sync +++ b/bin/gstack-telemetry-sync @@ -6,13 +6,15 @@ # Posts to the telemetry-ingest edge function (not PostgREST directly). # # Env overrides (for testing): -# GSTACK_STATE_DIR — override ~/.gstack state directory +# GSTACK_HOME — relocate the state root (chain: bin/gstack-state-root.sh) # GSTACK_DIR — override auto-detected gstack root # GSTACK_SUPABASE_URL — override Supabase project URL set -uo pipefail GSTACK_DIR="${GSTACK_DIR:-$(cd "$(dirname "$0")/.." && pwd)}" -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" # Egress receipt helpers (_receipted_curl): receipt-before-send, fail-closed. . "$GSTACK_DIR/bin/gstack-egress-lib.sh" diff --git a/bin/gstack-timeline-log b/bin/gstack-timeline-log index 6b7dc7e4e6..0f24f8a230 100755 --- a/bin/gstack-timeline-log +++ b/bin/gstack-timeline-log @@ -12,7 +12,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" mkdir -p "$GSTACK_HOME/projects/$SLUG" INPUT="$1" diff --git a/bin/gstack-timeline-read b/bin/gstack-timeline-read index 5c1b6bb6f8..be2dc1d60b 100755 --- a/bin/gstack-timeline-read +++ b/bin/gstack-timeline-read @@ -8,7 +8,9 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" eval "$("$SCRIPT_DIR/gstack-slug" 2>/dev/null)" -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +GSTACK_HOME="$_gstack_sr_root" SINCE="" LIMIT=20 diff --git a/bin/gstack-uninstall b/bin/gstack-uninstall index eaa30a013a..8adad56001 100755 --- a/bin/gstack-uninstall +++ b/bin/gstack-uninstall @@ -4,7 +4,15 @@ # Usage: # gstack-uninstall — interactive uninstall (prompts before removing) # gstack-uninstall --force — remove everything without prompting -# gstack-uninstall --keep-state — remove skills but keep ~/.gstack/ data +# gstack-uninstall --keep-state — remove skills but keep all gstack state +# +# State: only the default root ~/.gstack/ is ever deleted. A state root +# selected elsewhere (GSTACK_HOME, GSTACK_STATE_ROOT, GSTACK_STATE_DIR or +# plugin data; chain in bin/gstack-state-root.sh) is left in place and the +# exact removal command is printed. Uninstall refuses (exit 2) when ~/.gstack +# resolves to /, $HOME or an ancestor, the gstack checkout, the current git +# repository, or an ancestor of either. +# Docs: https://github.com/garrytan/gstack/blob/main/docs/state-root.md # # What gets REMOVED: # ~/.claude/skills/gstack — global Claude skill install (git clone or vendored) @@ -28,7 +36,6 @@ # # Env overrides (for testing): # GSTACK_DIR — override auto-detected gstack root -# GSTACK_STATE_DIR — override ~/.gstack state directory # # NOTE: Uses set -uo pipefail (no -e) — uninstall must never abort partway. set -uo pipefail @@ -39,7 +46,14 @@ if [ -z "${HOME:-}" ]; then fi GSTACK_DIR="${GSTACK_DIR:-$(cd "$(dirname "$0")/.." && pwd)}" -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +# Only the default root is ever deleted; RESOLVED_ROOT (the full chain) is +# used read-only (daemon discovery) and reported when it is elsewhere. +STATE_DIR="$HOME/.gstack" +_STATE_DOC="https://github.com/garrytan/gstack/blob/main/docs/state-root.md" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade ($_STATE_DOC)" >&2; exit 1; } +gstack_state_root_select +RESOLVED_ROOT="$_gstack_sr_root" +RESOLVED_VAR="$_gstack_sr_var" _GIT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || true)" # ─── Parse flags ───────────────────────────────────────────── @@ -61,6 +75,53 @@ while [ $# -gt 0 ]; do esac done +# ─── State-root safety ─────────────────────────────────────── +_real() { (cd -P -- "$1" 2>/dev/null && pwd -P); } +# _is_at_or_above TARGET PATH — TARGET is PATH or an ancestor of it. +_is_at_or_above() { + [ -n "$2" ] || return 1 + [ "$1" = "$2" ] && return 0 + case "$2/" in "${1%/}/"*) return 0 ;; esac + return 1 +} +_refuse() { + echo "gstack-uninstall: refusing to delete $STATE_DIR: $1" >&2 + echo "fix: $2 (docs: $_STATE_DOC)" >&2 + exit 2 +} +if [ "$KEEP_STATE" -eq 0 ] && [ -d "$STATE_DIR" ]; then + _STATE_REAL="$(_real "$STATE_DIR")" + _HOME_REAL="$(_real "$HOME")" + _CHECKOUT_REAL="$(_real "$GSTACK_DIR")" + _GIT_REAL="" + [ -n "$_GIT_ROOT" ] && _GIT_REAL="$(_real "$_GIT_ROOT")" + if [ -z "$_STATE_REAL" ] || [ "$_STATE_REAL" = "/" ]; then + _refuse "it resolves to the filesystem root /" "remove the link with rm -- '$STATE_DIR', or re-run with --keep-state" + elif _is_at_or_above "$_STATE_REAL" "$_HOME_REAL"; then + _refuse "it resolves to $_STATE_REAL, which is your home directory or an ancestor of it" "remove the link with rm -- '$STATE_DIR', or re-run with --keep-state" + elif _is_at_or_above "$_STATE_REAL" "$_CHECKOUT_REAL"; then + _refuse "it resolves to $_STATE_REAL, which is the gstack checkout $_CHECKOUT_REAL or an ancestor of it" "remove the link with rm -- '$STATE_DIR', or re-run with --keep-state" + elif _is_at_or_above "$_STATE_REAL" "$_GIT_REAL"; then + _refuse "it resolves to $_STATE_REAL, which is the current git repository $_GIT_REAL or an ancestor of it" "run gstack-uninstall from outside $_GIT_REAL, or re-run with --keep-state" + fi +fi +# The resolved root is left in place when it is not the default root. +_LEAVE_ROOT="" +if [ "$KEEP_STATE" -eq 0 ] && [ -e "$RESOLVED_ROOT" ]; then + _RESOLVED_REAL="$(_real "$RESOLVED_ROOT")" + _DEFAULT_REAL="$(_real "$STATE_DIR")" + if [ "$RESOLVED_ROOT" != "$STATE_DIR" ] && { [ -z "$_RESOLVED_REAL" ] || [ "$_RESOLVED_REAL" != "$_DEFAULT_REAL" ]; }; then + _LEAVE_ROOT="$RESOLVED_ROOT" + fi +fi +_report_left_root() { + [ -n "$_LEAVE_ROOT" ] || return 0 + local _val + eval "_val=\${$RESOLVED_VAR:-}" + echo "left in place: $_LEAVE_ROOT (selected by $RESOLVED_VAR=$_val)" >&2 + echo "fix: after checking it, remove it with rm -rf -- '$_LEAVE_ROOT' (docs: $_STATE_DOC)" >&2 +} + # ─── Confirmation ──────────────────────────────────────────── if [ "$FORCE" -eq 0 ]; then echo "This will remove gstack from your system:" @@ -70,6 +131,7 @@ if [ "$FORCE" -eq 0 ]; then [ -d "$HOME/.kiro/skills" ] && echo " ~/.kiro/skills/gstack*" [ -d "$HOME/.cursor/skills" ] && echo " ~/.cursor/skills/gstack*" [ "$KEEP_STATE" -eq 0 ] && [ -d "$STATE_DIR" ] && echo " $STATE_DIR" + [ -n "$_LEAVE_ROOT" ] && echo " (kept) $_LEAVE_ROOT: state root selected by $RESOLVED_VAR; left in place" if [ -n "$_GIT_ROOT" ]; then [ -d "$_GIT_ROOT/.claude/skills/gstack" ] && echo " $_GIT_ROOT/.claude/skills/gstack (project-local)" @@ -125,12 +187,16 @@ if [ -n "$_GIT_ROOT" ] && [ -f "$_GIT_ROOT/.gstack/browse.json" ]; then stop_browse_daemon "$_GIT_ROOT/.gstack/browse.json" fi -# Stop daemons tracked in global projects directory -if [ -d "$STATE_DIR/projects" ]; then +# Stop daemons tracked in global projects directories (the resolved root is +# only read here, never deleted). +_PROJ_ROOTS=("$STATE_DIR") +[ "$RESOLVED_ROOT" != "$STATE_DIR" ] && _PROJ_ROOTS+=("$RESOLVED_ROOT") +for _PROJ_ROOT in "${_PROJ_ROOTS[@]}"; do + [ -d "$_PROJ_ROOT/projects" ] || continue while IFS= read -r _BJ; do stop_browse_daemon "$_BJ" - done < <(find "$STATE_DIR/projects" -name browse.json -path '*/.gstack/*' 2>/dev/null || true) -fi + done < <(find "$_PROJ_ROOT/projects" -name browse.json -path '*/.gstack/*' 2>/dev/null || true) +done # ─── Remove gstack hooks from Claude Code settings ────────── # MUST run BEFORE any install-root deletion: SETTINGS_HOOK resolves inside the @@ -400,6 +466,8 @@ for _TMP in /tmp/gstack-latest-version /tmp/gstack-sketch-*.html /tmp/gstack-ske fi done +_report_left_root + # ─── Skipped-entry report ─────────────────────────────────── # Everything any provenance gate refused to delete (Claude shapes 2/3, # cursor real dirs) — listed once, at the end, so nothing is silent. diff --git a/bin/gstack-update-check b/bin/gstack-update-check index 3573c7878a..0337040be2 100755 --- a/bin/gstack-update-check +++ b/bin/gstack-update-check @@ -10,7 +10,7 @@ # GSTACK_DIR — override auto-detected gstack root # GSTACK_REMOTE_URL — override remote VERSION URL (branch-pinned fallback) # GSTACK_REMOTE_REPO — override remote git URL for ls-remote SHA resolution -# GSTACK_STATE_DIR — override ~/.gstack state directory +# GSTACK_HOME — relocate the state root (chain: bin/gstack-state-root.sh) set -euo pipefail # A crash must not read as "up to date" (#1974). With set -e, any unguarded @@ -22,7 +22,9 @@ set -E trap 'rc=$?; echo "CHECK_FAILED gstack-update-check crashed (line $LINENO, rc=$rc) — update status UNKNOWN, not up-to-date"; exit 0' ERR GSTACK_DIR="${GSTACK_DIR:-$(cd "$(dirname "$0")/.." && pwd)}" -STATE_DIR="${GSTACK_STATE_DIR:-$HOME/.gstack}" +. "$(dirname "$0")/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $(dirname "$0")/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +STATE_DIR="$_gstack_sr_root" # Egress receipt helpers (_receipted_curl / _receipted_git). Update checks # are fail-OPEN: a receipt hiccup warns but never blocks the version check. diff --git a/bin/gstack-verify-gate b/bin/gstack-verify-gate index 41f02cb5a0..240eace6da 100755 --- a/bin/gstack-verify-gate +++ b/bin/gstack-verify-gate @@ -12,7 +12,7 @@ # NEVER runs until the user records it in the per-repo trust store: # gstack-verify-gate --trust (run from inside the repo) # The store maps realpath(repo root) -> sha256(command) at -# ${GSTACK_HOME:-$HOME/.gstack}/verify-gate-trust (flat "pathhash", +# $GSTACK_STATE_ROOT/verify-gate-trust (flat "pathhash", # 0600, atomic rewrite). Any edit to the declared command invalidates trust # until --trust is run again. Untrusted commands never block the turn. # @@ -23,7 +23,15 @@ set -uo pipefail TAB="$(printf '\t')" -STORE="${GSTACK_HOME:-$HOME/.gstack}/verify-gate-trust" +# Hook: source the state-root twin (never spawn gstack-paths). A broken +# install fails open, like every other absence. +_VG_TWIN="$(cd "$(dirname "$0")" && pwd)/gstack-state-root.sh" +if [ ! -f "$_VG_TWIN" ] || ! . "$_VG_TWIN" 2>/dev/null; then + echo "verify-gate: $_VG_TWIN missing; gate skipped (reinstall with ./setup or /gstack-upgrade)" + exit 0 +fi +GSTACK_STATE_ROOT="$(gstack_state_root; printf x)"; GSTACK_STATE_ROOT="${GSTACK_STATE_ROOT%x}" +STORE="$GSTACK_STATE_ROOT/verify-gate-trust" _sha256() { if command -v shasum >/dev/null 2>&1; then @@ -100,7 +108,7 @@ _json_escape() { # Args: $1 = root key, $2 = cmd sha256, $3 = cmd verbatim. _log_trust_grant() { local sec_dir log tty ts - sec_dir="${GSTACK_HOME:-$HOME/.gstack}/security" + sec_dir="$GSTACK_STATE_ROOT/security" log="$sec_dir/verify-gate-trust-grants.jsonl" tty=false [ -t 0 ] && tty=true @@ -175,7 +183,7 @@ _session_key() { [ -n "$sid" ] || sid="ppid-$PPID" _sha256 "$sid|$(_trust_key)" } -ATTEMPTS_DIR="${GSTACK_HOME:-$HOME/.gstack}/verify-gate-attempts" +ATTEMPTS_DIR="$GSTACK_STATE_ROOT/verify-gate-attempts" COUNTER="$ATTEMPTS_DIR/$(_session_key)" # A first entry (stop_hook_active=false) starts a fresh blocking episode. diff --git a/browse/src/browser-skill-write.ts b/browse/src/browser-skill-write.ts index 81599b419b..4d0262a463 100644 --- a/browse/src/browser-skill-write.ts +++ b/browse/src/browser-skill-write.ts @@ -18,11 +18,11 @@ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { mkdirSecure } from './file-permissions'; import { isPathWithin } from './platform'; import type { TierPaths } from './browser-skills'; import { defaultTierPaths } from './browser-skills'; +import { resolveStateRoot } from '../../lib/state-root'; // ─── Naming validation ────────────────────────────────────────── @@ -71,7 +71,7 @@ export function stageSkill(opts: StageSkillOptions): string { } const spawnId = opts.spawnId ?? generateSpawnId(); - const tmpRoot = opts.tmpRoot ?? path.join(os.homedir(), '.gstack', '.tmp'); + const tmpRoot = opts.tmpRoot ?? path.join(resolveStateRoot(), '.tmp'); const wrapperDir = path.join(tmpRoot, `skillify-${spawnId}`); const stagedDir = path.join(wrapperDir, opts.name); diff --git a/browse/src/browser-skills.ts b/browse/src/browser-skills.ts index 277f38096b..009d3ea98a 100644 --- a/browse/src/browser-skills.ts +++ b/browse/src/browser-skills.ts @@ -22,8 +22,8 @@ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import * as cp from 'child_process'; +import { resolveStateRoot } from '../../lib/state-root'; // ─── Types ────────────────────────────────────────────────────── @@ -85,13 +85,13 @@ export interface TierPaths { * Project tier requires git or a project hint; returns null when neither resolves. */ export function defaultTierPaths(opts: { projectRoot?: string; home?: string; bundledRoot?: string } = {}): TierPaths { - const home = opts.home ?? os.homedir(); + const stateRoot = opts.home !== undefined ? path.join(opts.home, '.gstack') : resolveStateRoot(); const projectRoot = opts.projectRoot ?? detectProjectRoot(); const bundledRoot = opts.bundledRoot ?? detectBundledRoot(); return { project: projectRoot ? path.join(projectRoot, '.gstack', 'browser-skills') : null, - global: path.join(home, '.gstack', 'browser-skills'), + global: path.join(stateRoot, 'browser-skills'), bundled: path.join(bundledRoot, 'browser-skills'), }; } diff --git a/browse/src/config.ts b/browse/src/config.ts index f7d7eeefae..2274dad7b7 100644 --- a/browse/src/config.ts +++ b/browse/src/config.ts @@ -11,10 +11,10 @@ */ import * as fs from 'fs'; -import * as os from 'os'; import * as path from 'path'; import { mkdirSecure } from './file-permissions'; import { safeUnlinkQuiet } from './error-handling'; +import { readConfigKey, resolveStateRoot } from '../../lib/state-root'; export interface BrowseConfig { projectDir: string; @@ -193,39 +193,26 @@ export function readVersionHash(execPath: string = process.execPath): string | n } } -/** - * Resolve the gstack home directory. - * - * Honors the existing convention used by telemetry.ts and domain-skills.ts: - * 1. GSTACK_HOME env (explicit override) - * 2. $HOME/.gstack (default) - */ +/** The gstack state root: delegates to the shared chain in lib/state-root.ts. */ export function resolveGstackHome(): string { - return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack'); + return resolveStateRoot(); } /** - * Read one key from the flat-YAML config store at /config.yaml - * (the shape bin/gstack-config writes: `key: value` lines). Tolerates - * optional single/double quotes around the value and a trailing `# comment`. - * Returns the unquoted value string, or null when the file is missing or - * unreadable or the key is absent. + * Read one key from the flat-YAML config store via readConfigKey (the same + * reader bin/gstack-config uses, including the most-restrictive merge for + * privacy keys such as telemetry). Tolerates optional single/double quotes + * around the value and a trailing `# comment`. Returns the unquoted value + * string, or null when the file is missing or unreadable or the key is absent. * * Single source of truth for flat-YAML key reads — isPairAgentEnabled * (pair_agent) and telemetry.ts (telemetry tier) both route through it so * the two consent gates can never drift on parsing semantics. */ export function readGstackConfigYamlKey(key: string): string | null { - const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - try { - const yaml = fs.readFileSync(path.join(resolveGstackHome(), 'config.yaml'), 'utf-8'); - // Last match wins: bin/gstack-config's `get` reads duplicates with - // `tail -1`, and both surfaces must agree on the same line. - const all = [...yaml.matchAll(new RegExp(`^\\s*${escaped}\\s*:\\s*['"]?([^'"#\\n]*?)['"]?\\s*(?:#.*)?$`, 'gm'))]; - return all.length > 0 ? all[all.length - 1][1] : null; - } catch { - return null; - } + const raw = readConfigKey(key); + if (raw === null) return null; + return raw.replace(/\s*#.*$/, '').trim().replace(/^(['"])(.*)\1$/, '$2'); } /** diff --git a/browse/src/domain-skills.ts b/browse/src/domain-skills.ts index 92258fee3d..ae8112b8b2 100644 --- a/browse/src/domain-skills.ts +++ b/browse/src/domain-skills.ts @@ -35,9 +35,9 @@ import { promises as fs } from 'fs'; import { open as fsOpen, constants as fsConstants } from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { createHash } from 'crypto'; import type { Page } from 'playwright'; +import { resolveStateRoot } from '../../lib/state-root'; export type SkillState = 'quarantined' | 'active' | 'global'; export type SkillScope = 'project' | 'global'; @@ -63,7 +63,7 @@ export interface DomainSkillRow { const PROMOTE_THRESHOLD = 3; function gstackHome(): string { - return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack'); + return resolveStateRoot(); } function globalFile(): string { diff --git a/browse/src/security-classifier.ts b/browse/src/security-classifier.ts index a89ddf694b..595dea73fb 100644 --- a/browse/src/security-classifier.ts +++ b/browse/src/security-classifier.ts @@ -24,9 +24,9 @@ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { mkdirSecure } from './file-permissions'; import { type LayerSignal } from './security'; +import { resolveStateRoot } from '../../lib/state-root'; // ─── Model location + packaging ────────────────────────────── @@ -45,7 +45,7 @@ import { type LayerSignal } from './security'; * vocab.txt * onnx/model.onnx (~112MB) */ -const MODELS_DIR = path.join(os.homedir(), '.gstack', 'models'); +const MODELS_DIR = path.join(resolveStateRoot(), 'models'); const TESTSAVANT_DIR = path.join(MODELS_DIR, 'testsavant-small'); const TESTSAVANT_HF_URL = 'https://huggingface.co/testsavantai/prompt-injection-defender-small-v0-onnx/resolve/main'; const TESTSAVANT_FILES = [ diff --git a/browse/src/telemetry.ts b/browse/src/telemetry.ts index c71ca8ae2a..ad90925792 100644 --- a/browse/src/telemetry.ts +++ b/browse/src/telemetry.ts @@ -20,11 +20,11 @@ import { promises as fs } from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { readGstackConfigYamlKey } from './config'; +import { resolveStateRoot } from '../../lib/state-root'; function gstackHome(): string { - return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack'); + return resolveStateRoot(); } function analyticsDir(): string { diff --git a/browse/src/tunnel-denial-log.ts b/browse/src/tunnel-denial-log.ts index 82b9c34a5e..15bec5bd17 100644 --- a/browse/src/tunnel-denial-log.ts +++ b/browse/src/tunnel-denial-log.ts @@ -17,10 +17,10 @@ */ import { promises as fsp } from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { mkdirSecure } from './file-permissions'; +import { resolveStateRoot } from '../../lib/state-root'; -const LOG_DIR = path.join(os.homedir(), '.gstack', 'security'); +const LOG_DIR = path.join(resolveStateRoot(), 'security'); const LOG_PATH = path.join(LOG_DIR, 'attempts.jsonl'); const RATE_CAP = 60; // writes per minute const WINDOW_MS = 60_000; diff --git a/browse/test/gstack-update-check.test.ts b/browse/test/gstack-update-check.test.ts index 6b78263f72..a04886aa08 100644 --- a/browse/test/gstack-update-check.test.ts +++ b/browse/test/gstack-update-check.test.ts @@ -58,6 +58,11 @@ beforeEach(() => { join(import.meta.dir, '..', '..', 'bin', 'gstack-egress-lib.sh'), join(binDir, 'gstack-egress-lib.sh'), ); + // Same for the state-root twin every migrated bin sources (docs/state-root.md). + symlinkSync( + join(import.meta.dir, '..', '..', 'bin', 'gstack-state-root.sh'), + join(binDir, 'gstack-state-root.sh'), + ); }); afterEach(() => { diff --git a/canary/SKILL.md b/canary/SKILL.md index 01b2e65519..8a9f1215be 100644 --- a/canary/SKILL.md +++ b/canary/SKILL.md @@ -236,7 +236,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -694,8 +695,9 @@ Per-page and overall status: BROKEN if any confirmed CRITICAL alert occurred; ot Log the result for the review dashboard: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG ``` Write a JSONL entry: `{"skill":"canary","timestamp":"","status":"","url":"","duration_min":,"alerts":}` diff --git a/canary/SKILL.md.tmpl b/canary/SKILL.md.tmpl index daa894dd7d..2aaf7d7094 100644 --- a/canary/SKILL.md.tmpl +++ b/canary/SKILL.md.tmpl @@ -224,8 +224,9 @@ Per-page and overall status: BROKEN if any confirmed CRITICAL alert occurred; ot Log the result for the review dashboard: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" {{SLUG_EVAL}} -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG ``` Write a JSONL entry: `{"skill":"canary","timestamp":"","status":"","url":"","duration_min":,"alerts":}` diff --git a/careful/SKILL.md b/careful/SKILL.md index 5dae5e9728..80220827a6 100644 --- a/careful/SKILL.md +++ b/careful/SKILL.md @@ -36,8 +36,9 @@ patterns before running. If a destructive command is detected, you'll be warned and can choose to proceed or cancel. ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"careful","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"careful","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## What's protected diff --git a/careful/SKILL.md.tmpl b/careful/SKILL.md.tmpl index 8fba18fb0b..f3101d290c 100644 --- a/careful/SKILL.md.tmpl +++ b/careful/SKILL.md.tmpl @@ -31,8 +31,9 @@ patterns before running. If a destructive command is detected, you'll be warned and can choose to proceed or cancel. ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"careful","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"careful","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## What's protected diff --git a/careful/bin/hook-extract.sh b/careful/bin/hook-extract.sh index 594b4d6c00..2934beb2e2 100644 --- a/careful/bin/hook-extract.sh +++ b/careful/bin/hook-extract.sh @@ -64,40 +64,36 @@ gstack_hook_decision() { } # gstack_hook_state_root -# Print the gstack state root, resolved with EXACTLY the chain bin/gstack-paths -# uses (GSTACK_STATE_ROOT): GSTACK_HOME, then CLAUDE_PLUGIN_DATA only when -# CLAUDE_PLUGIN_ROOT names gstack (a CLAUDE_PLUGIN_DATA leaked from another -# plugin via CLAUDE_ENV_FILE must not redirect our state), then $HOME/.gstack, -# then a project-local .gstack. Hooks run on every Edit/Bash call, so this is -# pure bash — never spawn gstack-paths from a hook. The writers (/freeze, -# /guard, /unfreeze, /investigate) resolve through gstack-paths; a reader that -# used a different chain failed OPEN whenever GSTACK_HOME was set (#1459). -# test/hook-scripts.test.ts pins parity against gstack-paths. +# Print the gstack state root: a thin wrapper over gstack_state_root from +# bin/gstack-state-root.sh, the one bash implementation of the chain +# bin/gstack-paths uses (docs/state-root.md). Hooks run on every Edit/Bash +# call, so the twin is pure bash — never spawn gstack-paths from a hook. The +# writers (/freeze, /guard, /unfreeze, /investigate) resolve through +# gstack-paths; a reader that used a different chain failed OPEN whenever +# GSTACK_HOME was set (#1459). test/hook-scripts.test.ts pins parity. # Printed WITHOUT a trailing newline: callers capture with a sentinel # (`r="$(gstack_hook_state_root; printf x)"; r="${r%x}"`) so a root that -# itself ends in a newline round-trips exactly as gstack-paths' %q does — -# otherwise writer and reader would again disagree on the directory. +# itself ends in a newline round-trips exactly as gstack-paths' %q does. +# When the twin is missing (partial upgrade) the wrapper is removed, so +# callers take their own fallback: careful asks, freeze fails closed. gstack_hook_state_root() { - if [ -n "${GSTACK_HOME:-}" ]; then - printf '%s' "$GSTACK_HOME" - elif [ -n "${CLAUDE_PLUGIN_DATA:-}" ] && printf '%s' "${CLAUDE_PLUGIN_ROOT:-}" | grep -qi "gstack"; then - printf '%s' "$CLAUDE_PLUGIN_DATA" - elif [ -n "${HOME:-}" ]; then - printf '%s' "$HOME/.gstack" - else - printf '%s' ".gstack" - fi + gstack_state_root } +_ghsr_twin="${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" +if ! { [ -f "$_ghsr_twin" ] && . "$_ghsr_twin" 2>/dev/null; } || ! command -v gstack_state_root >/dev/null 2>&1; then + unset -f gstack_hook_state_root +fi # gstack_hook_log_fire SKILL PATTERN # Append a hook_fire analytics record (pattern name only, never command -# content). Respects GSTACK_HOME so tests never pollute the operator's real -# analytics file. Deliberately NOT gstack_hook_state_root: every other +# content) under the resolved state root, the same root every other # analytics writer and reader (gstack-skill-start, gstack-retro-metrics, -# gstack-analytics) uses this two-step chain, and the usage log must stay one -# file. Best-effort: failures never affect the hook decision. +# gstack-analytics) uses, so the usage log stays one file and tests never +# pollute the operator's real analytics file. Best-effort: failures (or a +# missing twin) never affect the hook decision. gstack_hook_log_fire() { - _ghlf_dir="${GSTACK_HOME:-$HOME/.gstack}/analytics" + command -v gstack_state_root >/dev/null 2>&1 || return 0 + _ghlf_dir="$(gstack_state_root; printf x)"; _ghlf_dir="${_ghlf_dir%x}/analytics" mkdir -p "$_ghlf_dir" 2>/dev/null || true # Fields are JSON-encoded (a repo basename can carry quotes/backslashes) — # same rule this file states for decisions: never raw-interpolate into JSON. diff --git a/codex/SKILL.md b/codex/SKILL.md index b6dc9b47d0..75d6079085 100644 --- a/codex/SKILL.md +++ b/codex/SKILL.md @@ -239,7 +239,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -349,7 +350,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -554,7 +556,7 @@ This keeps the skill working whether installed as a Claude Code plugin container where `HOME` may be unset and `/tmp` may be read-only. ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" ``` After this, every subsequent bash block in this skill uses `"$PLAN_ROOT"` and diff --git a/codex/SKILL.md.tmpl b/codex/SKILL.md.tmpl index 16babf5a9e..9d45b5a393 100644 --- a/codex/SKILL.md.tmpl +++ b/codex/SKILL.md.tmpl @@ -123,7 +123,7 @@ This keeps the skill working whether installed as a Claude Code plugin container where `HOME` may be unset and `/tmp` may be read-only. ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" ``` After this, every subsequent bash block in this skill uses `"$PLAN_ROOT"` and diff --git a/context-restore/SKILL.md b/context-restore/SKILL.md index 55dcabce7c..3fb251c130 100644 --- a/context-restore/SKILL.md +++ b/context-restore/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -417,8 +418,9 @@ Parse the user's input: ### Step 1: Find saved contexts ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" if [ ! -d "$CHECKPOINT_DIR" ]; then echo "NO_CHECKPOINTS" diff --git a/context-restore/SKILL.md.tmpl b/context-restore/SKILL.md.tmpl index d2e78ca897..8deb6a8404 100644 --- a/context-restore/SKILL.md.tmpl +++ b/context-restore/SKILL.md.tmpl @@ -68,7 +68,7 @@ Parse the user's input: ```bash {{SLUG_SETUP}} -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" if [ ! -d "$CHECKPOINT_DIR" ]; then echo "NO_CHECKPOINTS" diff --git a/context-save/SKILL.md b/context-save/SKILL.md index 458589f807..24f6d4e8b6 100644 --- a/context-save/SKILL.md +++ b/context-save/SKILL.md @@ -239,7 +239,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -406,7 +407,8 @@ If the user types `/context-save resume` or `/context-save restore`, tell them: ### Step 1: Gather state ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" ``` Collect the current working state: @@ -466,8 +468,9 @@ inject shell metacharacters into any subsequent command. The sanitizer is an allowlist: only `a-z 0-9 - .` survive. ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" mkdir -p "$CHECKPOINT_DIR" TIMESTAMP=$(date +%Y%m%d-%H%M%S) @@ -553,8 +556,9 @@ Restore later with /context-restore. ### Step 1: Gather saved contexts ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" if [ -d "$CHECKPOINT_DIR" ]; then echo "CHECKPOINT_DIR=$CHECKPOINT_DIR" diff --git a/context-save/SKILL.md.tmpl b/context-save/SKILL.md.tmpl index 6eaa19666e..40cae5fcd8 100644 --- a/context-save/SKILL.md.tmpl +++ b/context-save/SKILL.md.tmpl @@ -118,7 +118,7 @@ allowlist: only `a-z 0-9 - .` survive. ```bash {{SLUG_SETUP}} -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" mkdir -p "$CHECKPOINT_DIR" TIMESTAMP=$(date +%Y%m%d-%H%M%S) @@ -205,7 +205,7 @@ Restore later with /context-restore. ```bash {{SLUG_SETUP}} -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CHECKPOINT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/checkpoints" if [ -d "$CHECKPOINT_DIR" ]; then echo "CHECKPOINT_DIR=$CHECKPOINT_DIR" diff --git a/design-consultation/SKILL.md b/design-consultation/SKILL.md index 2088b776c3..09667b1aa7 100644 --- a/design-consultation/SKILL.md +++ b/design-consultation/SKILL.md @@ -262,7 +262,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -372,7 +373,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -477,9 +479,10 @@ A `PRODUCT.md` (impeccable's product-context file) already answers the product q Look for office-hours output: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -ls ~/.gstack/projects/$SLUG/*office-hours* 2>/dev/null | head -5 +ls "$GSTACK_STATE_ROOT"/projects/$SLUG/*office-hours* 2>/dev/null | head -5 ls .context/*office-hours* .context/attachments/*office-hours* 2>/dev/null | head -5 ``` diff --git a/design-consultation/SKILL.md.tmpl b/design-consultation/SKILL.md.tmpl index 5d704aa5fd..100025a3b8 100644 --- a/design-consultation/SKILL.md.tmpl +++ b/design-consultation/SKILL.md.tmpl @@ -89,9 +89,10 @@ A `PRODUCT.md` (impeccable's product-context file) already answers the product q Look for office-hours output: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat {{SLUG_EVAL}} -ls ~/.gstack/projects/$SLUG/*office-hours* 2>/dev/null | head -5 +ls "$GSTACK_STATE_ROOT"/projects/$SLUG/*office-hours* 2>/dev/null | head -5 ls .context/*office-hours* .context/attachments/*office-hours* 2>/dev/null | head -5 ``` diff --git a/design-consultation/sections/proposal-and-preview.md b/design-consultation/sections/proposal-and-preview.md index bf0d3aacd3..9642359171 100644 --- a/design-consultation/sections/proposal-and-preview.md +++ b/design-consultation/sections/proposal-and-preview.md @@ -294,7 +294,7 @@ Apply the proposed system to realistic product screens: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/design-system-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" diff --git a/design-consultation/sections/proposal-and-preview.md.tmpl b/design-consultation/sections/proposal-and-preview.md.tmpl index b4948c81d5..61c22429e9 100644 --- a/design-consultation/sections/proposal-and-preview.md.tmpl +++ b/design-consultation/sections/proposal-and-preview.md.tmpl @@ -102,7 +102,7 @@ Apply the proposed system to realistic product screens: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/design-system-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" diff --git a/design-html/SKILL.md b/design-html/SKILL.md index 0e7e5a45f2..aaa45be9ba 100644 --- a/design-html/SKILL.md +++ b/design-html/SKILL.md @@ -243,7 +243,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -457,7 +458,7 @@ Detect context with the CEO-plan check and the design-artifact checks below: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _CEO=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans/"*.md 2>/dev/null | head -1) [ -n "$_CEO" ] && echo "CEO_PLAN: $_CEO" || echo "NO_CEO_PLAN" @@ -465,7 +466,7 @@ _CEO=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans/"*.md 2>/dev/null | he ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _APPROVED=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/designs/"*/approved.json 2>/dev/null | head -1) [ -n "$_APPROVED" ] && echo "APPROVED: $_APPROVED" || echo "NO_APPROVED" diff --git a/design-html/SKILL.md.tmpl b/design-html/SKILL.md.tmpl index d62c7f963a..11eeb0d3ae 100644 --- a/design-html/SKILL.md.tmpl +++ b/design-html/SKILL.md.tmpl @@ -59,7 +59,7 @@ Detect context with the CEO-plan check and the design-artifact checks below: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _CEO=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans/"*.md 2>/dev/null | head -1) [ -n "$_CEO" ] && echo "CEO_PLAN: $_CEO" || echo "NO_CEO_PLAN" @@ -67,7 +67,7 @@ _CEO=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans/"*.md 2>/dev/null | he ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _APPROVED=$(ls -t "$GSTACK_STATE_ROOT/projects/$SLUG/designs/"*/approved.json 2>/dev/null | head -1) [ -n "$_APPROVED" ] && echo "APPROVED: $_APPROVED" || echo "NO_APPROVED" diff --git a/design-review/SKILL.md b/design-review/SKILL.md index 3f58096bf5..b03a1dd45f 100644 --- a/design-review/SKILL.md +++ b/design-review/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -350,7 +351,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -821,7 +823,7 @@ On **B**, continue without scans. On **C**, run `~/.claude/skills/gstack/bin/gst ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" REPORT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/design-audit-$(date +%Y%m%d)" RUN_ID="$(date +%H%M%S)-$$" mkdir -p "$REPORT_DIR/screenshots" "$REPORT_DIR/dom/$RUN_ID" @@ -1866,9 +1868,10 @@ Write the report to `$REPORT_DIR` (already set up in the setup phase): **Also write a summary to the project index:** ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" ``` -Write a one-line summary to `~/.gstack/projects/{slug}/{user}-{branch}-design-audit-{datetime}.md` with a pointer to the full report in `$REPORT_DIR`. +Write a one-line summary to `/{user}-{branch}-design-audit-{datetime}.md` (`PROJECT_DIR` printed above) with a pointer to the full report in `$REPORT_DIR`. **Per-finding additions** (beyond standard design audit report): - Fix Status: verified / best-effort / reverted / deferred diff --git a/design-review/SKILL.md.tmpl b/design-review/SKILL.md.tmpl index d73394c886..49f26241d7 100644 --- a/design-review/SKILL.md.tmpl +++ b/design-review/SKILL.md.tmpl @@ -96,7 +96,7 @@ If `DESIGN_NOT_AVAILABLE`: skip mockup generation — the fix loop works without ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" REPORT_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/design-audit-$(date +%Y%m%d)" RUN_ID="$(date +%H%M%S)-$$" mkdir -p "$REPORT_DIR/screenshots" "$REPORT_DIR/dom/$RUN_ID" @@ -288,7 +288,7 @@ Write the report to `$REPORT_DIR` (already set up in the setup phase): ```bash {{SLUG_SETUP}} ``` -Write a one-line summary to `~/.gstack/projects/{slug}/{user}-{branch}-design-audit-{datetime}.md` with a pointer to the full report in `$REPORT_DIR`. +Write a one-line summary to `/{user}-{branch}-design-audit-{datetime}.md` (`PROJECT_DIR` printed above) with a pointer to the full report in `$REPORT_DIR`. **Per-finding additions** (beyond standard design audit report): - Fix Status: verified / best-effort / reverted / deferred diff --git a/design-shotgun/SKILL.md b/design-shotgun/SKILL.md index c8c7205e58..4241cc7f31 100644 --- a/design-shotgun/SKILL.md +++ b/design-shotgun/SKILL.md @@ -257,7 +257,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -456,7 +457,7 @@ Check for prior design exploration sessions for this project: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _PREV=$(find "$GSTACK_STATE_ROOT/projects/$SLUG/designs/" -name "approved.json" -maxdepth 2 2>/dev/null | sort -r | head -5) [ -n "$_PREV" ] && echo "PREVIOUS_SESSIONS_FOUND" || echo "NO_PREVIOUS_SESSIONS" @@ -512,8 +513,9 @@ ls src/ app/ pages/ components/ 2>/dev/null | head -30 ``` ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true -ls ~/.gstack/projects/$SLUG/*office-hours* 2>/dev/null | head -5 +ls "$GSTACK_STATE_ROOT"/projects/$SLUG/*office-hours* 2>/dev/null | head -5 ``` If DESIGN.md exists, tell the user: "I'll follow your design system in DESIGN.md by @@ -592,7 +594,7 @@ will migrate it to schema v1 on the next write. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _TASTE=$(find "$GSTACK_STATE_ROOT/projects/$SLUG/designs/" -name "approved.json" -maxdepth 2 2>/dev/null | sort -r | head -10) ``` @@ -615,7 +617,7 @@ Set up the output directory: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" diff --git a/design-shotgun/SKILL.md.tmpl b/design-shotgun/SKILL.md.tmpl index e5e60b3b3f..07cee2764e 100644 --- a/design-shotgun/SKILL.md.tmpl +++ b/design-shotgun/SKILL.md.tmpl @@ -66,7 +66,7 @@ Check for prior design exploration sessions for this project: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _PREV=$(find "$GSTACK_STATE_ROOT/projects/$SLUG/designs/" -name "approved.json" -maxdepth 2 2>/dev/null | sort -r | head -5) [ -n "$_PREV" ] && echo "PREVIOUS_SESSIONS_FOUND" || echo "NO_PREVIOUS_SESSIONS" @@ -122,8 +122,9 @@ ls src/ app/ pages/ components/ 2>/dev/null | head -30 ``` ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true -ls ~/.gstack/projects/$SLUG/*office-hours* 2>/dev/null | head -5 +ls "$GSTACK_STATE_ROOT"/projects/$SLUG/*office-hours* 2>/dev/null | head -5 ``` If DESIGN.md exists, tell the user: "I'll follow your design system in DESIGN.md by @@ -165,7 +166,7 @@ designs to bias generation toward the user's demonstrated taste. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true _TASTE=$(find "$GSTACK_STATE_ROOT/projects/$SLUG/designs/" -name "approved.json" -maxdepth 2 2>/dev/null | sort -r | head -10) ``` @@ -188,7 +189,7 @@ Set up the output directory: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" diff --git a/design/src/daemon-state.ts b/design/src/daemon-state.ts index dd20e660fc..7f6dc951a2 100644 --- a/design/src/daemon-state.ts +++ b/design/src/daemon-state.ts @@ -10,8 +10,8 @@ import { execFileSync } from "child_process"; import fs from "fs"; -import os from "os"; import path from "path"; +import { resolveStateRoot } from "../../lib/state-root"; export interface DaemonState { pid: number; @@ -48,11 +48,11 @@ export function resolveLockFilePath(stateFile: string = resolveStateFilePath()): } export function resolveDaemonLogPath(): string { - return path.join(os.homedir(), ".gstack", "design-daemon.log"); + return path.join(resolveStateRoot(), "design-daemon.log"); } export function resolveStartupLogPath(): string { - return path.join(os.homedir(), ".gstack", "design-daemon-startup.log"); + return path.join(resolveStateRoot(), "design-daemon-startup.log"); } /** diff --git a/devex-review/SKILL.md b/devex-review/SKILL.md index 3251bca55d..8305db0b27 100644 --- a/devex-review/SKILL.md +++ b/devex-review/SKILL.md @@ -242,7 +242,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -352,7 +353,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol diff --git a/docs/state-root.md b/docs/state-root.md new file mode 100644 index 0000000000..e67f28cb6d --- /dev/null +++ b/docs/state-root.md @@ -0,0 +1,143 @@ +# Where gstack keeps its state + +gstack keeps everything it remembers — config, analytics, sessions, projects, +learnings, review logs, the egress ledger, the trust-policy store, hook error +logs — under one directory, the **state root**. By default that is +`~/.gstack`. Set `GSTACK_HOME` to put it somewhere else. + +One rule picks the root, and every gstack script, hook and skill uses it. The +rule lives in two owner files that a parity test keeps identical: +`bin/gstack-state-root.sh` (bash) and `lib/state-root.ts` (TypeScript). + +## How the root is chosen + +The first variable in this list with a non-empty value wins. Empty values count +as unset. + +| Order | Source | When to use it | +|------:|--------|----------------| +| 1 | `GSTACK_STATE_ROOT` | `gstack-paths`' own output. It is also honored as input, so re-reading it in the same environment returns the same root. Do not set it by hand. | +| 2 | `GSTACK_HOME` | **The one variable to set** when you want your state somewhere other than `~/.gstack`. | +| 3 | `GSTACK_STATE_DIR` | Legacy alias, honored for compatibility. | +| 4 | `CLAUDE_PLUGIN_DATA` | Only when `CLAUDE_PLUGIN_ROOT` contains `gstack` (any case), so another plugin's data directory never captures gstack state. | +| 5 | `$HOME/.gstack` | The default. On Windows shells, `USERPROFILE` stands in when `HOME` is unset. | +| 6 | `.gstack` | Last resort when there is no home directory at all (some containers). | + +## See which root is in use + +```bash +~/.claude/skills/gstack/bin/gstack-paths --explain +``` + +Real output with `GSTACK_HOME` set while `~/.gstack` still holds older state: + +``` +state root: /home/you/work-state (selected by GSTACK_HOME) +chain (first non-empty wins): + GSTACK_STATE_ROOT unset + GSTACK_HOME /home/you/work-state selected + GSTACK_STATE_DIR unset + CLAUDE_PLUGIN_DATA unset + default /home/you/.gstack ignored +default root /home/you/.gstack also holds gstack state: yes +merged privacy keys (most restrictive value across roots wins): + telemetry: off (from /home/you/.gstack/config.yaml) + memorable_recall: not set (default applies) + codex_reviews: not set (default applies) + update_check: not set (default applies) +docs: https://github.com/garrytan/gstack/blob/main/docs/state-root.md +``` + +`--explain` only reads; it writes nothing and exits 0. `gstack-config list` +also prints a one-line note when `GSTACK_STATE_ROOT`, `GSTACK_HOME` and +`GSTACK_STATE_DIR` name different directories. + +## Move your state + +gstack never moves state for you. To relocate it: + +```bash +cp -a ~/.gstack /new/place/gstack-state +export GSTACK_HOME=/new/place/gstack-state # add this to your shell profile +~/.claude/skills/gstack/bin/gstack-paths --explain # confirm: selected by GSTACK_HOME +``` + +Keep or delete the old `~/.gstack` once you have checked the new root works. +Until you delete it, its privacy settings still count (next section). + +## Privacy settings never get looser when the root moves + +Four config keys are opt-outs: `telemetry` (off < anonymous < community), +`memorable_recall` (off < on), `codex_reviews` (disabled < enabled) and +`update_check` (false < true). gstack reads each of them from the resolved root +**and** from `~/.gstack`, and uses the most restrictive value. So turning +telemetry off once in `~/.gstack` keeps it off after you set `GSTACK_HOME`. +Every other key, including `proactive` and `founder_resources`, reads the +resolved root only. + +When `gstack-config set` writes a merged key but the other root still holds a +more restrictive value, it tells you which root overrides it and prints the +command that changes that root, for example: + +```bash +GSTACK_STATE_ROOT='/home/you/.gstack' ~/.claude/skills/gstack/bin/gstack-config set codex_reviews enabled +``` + +`gstack-config list` shows the winning root for merged keys, for example +`telemetry: off (set, /home/you/.gstack)`. + +Trust-policy deny tiers merge the same way: a `deny` or `read-only` entry in +`~/.gstack/gbrain-repo-policy.json` still applies when your resolved root is +elsewhere. Nothing is ever written to the other root. + +## Uninstall + +`gstack-uninstall` deletes state only at `~/.gstack`. + +- It first refuses (exit 2) when `~/.gstack` resolves — following symlinks — + to `/`, your home directory or one of its parents, the gstack checkout, the + current git repository, or a parent of either. The message names the reason + and a `fix:` line. +- When the resolved root is somewhere else (you set `GSTACK_HOME`, for + example), uninstall leaves it in place and prints + `left in place: (selected by =)` plus the exact + `rm -rf -- ''` command to run after you have checked it. +- `--keep-state` never deletes any state. `--force` only skips the prompt. + +## If gstack-paths is missing + +Skill blocks resolve the root with + +```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +``` + +The second half stops the block instead of writing under `/` if the resolver +is broken. If you see `gstack-paths failed` or +`cannot resolve the gstack state root`, reinstall: run `./setup` in the gstack +checkout, or `/gstack-upgrade`. + +## Claude Code plugin installs + +gstack does not ship an official Claude Code plugin distribution today (no +`.claude-plugin` manifest has ever been on `main`; some forks publish one), and +telemetry does not report plugin-mode installs. When gstack does run as a +plugin, `CLAUDE_PLUGIN_ROOT` names gstack and state lives in +`CLAUDE_PLUGIN_DATA`, while a terminal run outside the plugin session uses +`~/.gstack`. Those are two different roots; run `gstack-paths --explain` in +each environment to see which one is active. Cross-environment support (a +pointer from `~/.gstack` to the plugin root) is deferred until a plugin +distribution exists. + +## For contributors + +- Bash: executables source `bin/gstack-state-root.sh` beside them and call + `gstack_state_root_select` (sets `$_gstack_sr_root`), or `eval` gstack-paths + with the guard above. Hooks must source the twin; never spawn gstack-paths + from a hook. +- TypeScript: `resolveStateRoot()` and `readConfigKey()` from + `lib/state-root.ts`. +- `test/state-root-ratchet.test.ts` fails on a hand-rolled chain, an + executable `~/.gstack` in a template bash block, an unguarded gstack-paths + eval or `export GSTACK_STATE_ROOT` in prose. Its allowlist + (`test/state-root-ratchet.allowlist.json`) needs a reason per entry. diff --git a/document-generate/SKILL.md b/document-generate/SKILL.md index 40d3a5af69..e2cb4324fd 100644 --- a/document-generate/SKILL.md +++ b/document-generate/SKILL.md @@ -242,7 +242,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/document-release/SKILL.md b/document-release/SKILL.md index c832c6ead6..43f702aff4 100644 --- a/document-release/SKILL.md +++ b/document-release/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/freeze/SKILL.md b/freeze/SKILL.md index 6ed7115fee..d77c65f45a 100644 --- a/freeze/SKILL.md +++ b/freeze/SKILL.md @@ -41,8 +41,9 @@ Lock file edits to a specific directory. Any Edit or Write operation targeting a file outside the allowed path will be **blocked** (not just warned). ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"freeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"freeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Setup diff --git a/freeze/SKILL.md.tmpl b/freeze/SKILL.md.tmpl index df8eaf4334..bd58c167a4 100644 --- a/freeze/SKILL.md.tmpl +++ b/freeze/SKILL.md.tmpl @@ -36,8 +36,9 @@ Lock file edits to a specific directory. Any Edit or Write operation targeting a file outside the allowed path will be **blocked** (not just warned). ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"freeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"freeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Setup diff --git a/freeze/bin/freeze-state.sh b/freeze/bin/freeze-state.sh index 6e64c045e4..ad61b80cd2 100755 --- a/freeze/bin/freeze-state.sh +++ b/freeze/bin/freeze-state.sh @@ -3,6 +3,10 @@ set -euo pipefail _here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" . "$_here/../../careful/bin/hook-extract.sh" +if ! command -v gstack_hook_state_root >/dev/null 2>&1; then + echo "FREEZE_ERROR: cannot resolve the gstack state root: $_here/../../bin/gstack-state-root.sh is missing. No boundary changed. Fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)." >&2 + exit 1 +fi STATE_DIR="$(gstack_hook_state_root; printf x)"; STATE_DIR="${STATE_DIR%x}" mkdir -p "$STATE_DIR" STATE_DIR="$(cd "$STATE_DIR" && pwd -P && printf x)"; STATE_DIR="${STATE_DIR%$'\nx'}" diff --git a/gstack-upgrade/SKILL.md b/gstack-upgrade/SKILL.md index 88579d50c6..42d767189a 100644 --- a/gstack-upgrade/SKILL.md +++ b/gstack-upgrade/SKILL.md @@ -58,7 +58,8 @@ Tell user: "Auto-upgrade enabled. Future updates will install automatically." Th **If "Not now":** Write snooze state with escalating backoff (first snooze = 24h, second = 48h, third+ = 1 week), then continue with the current skill. Do not mention the upgrade again. ```bash -_SNOOZE_FILE="$HOME/.gstack/update-snoozed" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_SNOOZE_FILE="$GSTACK_STATE_ROOT/update-snoozed" _REMOTE_VER="{new}" _CUR_LEVEL=0 if [ -f "$_SNOOZE_FILE" ]; then @@ -328,10 +329,11 @@ running. Interpret the `DAEMON_CHECK` result: ### Step 5: Write marker + clear cache ```bash -mkdir -p ~/.gstack -echo "$OLD_VERSION" > ~/.gstack/just-upgraded-from -rm -f ~/.gstack/last-update-check -rm -f ~/.gstack/update-snoozed +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT" +echo "$OLD_VERSION" > "$GSTACK_STATE_ROOT"/just-upgraded-from +rm -f "$GSTACK_STATE_ROOT"/last-update-check +rm -f "$GSTACK_STATE_ROOT"/update-snoozed ``` ### Step 6: Show What's New diff --git a/gstack-upgrade/SKILL.md.tmpl b/gstack-upgrade/SKILL.md.tmpl index 3032c48f3e..70a030f6e8 100644 --- a/gstack-upgrade/SKILL.md.tmpl +++ b/gstack-upgrade/SKILL.md.tmpl @@ -55,7 +55,8 @@ Tell user: "Auto-upgrade enabled. Future updates will install automatically." Th **If "Not now":** Write snooze state with escalating backoff (first snooze = 24h, second = 48h, third+ = 1 week), then continue with the current skill. Do not mention the upgrade again. ```bash -_SNOOZE_FILE="$HOME/.gstack/update-snoozed" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_SNOOZE_FILE="$GSTACK_STATE_ROOT/update-snoozed" _REMOTE_VER="{new}" _CUR_LEVEL=0 if [ -f "$_SNOOZE_FILE" ]; then @@ -325,10 +326,11 @@ running. Interpret the `DAEMON_CHECK` result: ### Step 5: Write marker + clear cache ```bash -mkdir -p ~/.gstack -echo "$OLD_VERSION" > ~/.gstack/just-upgraded-from -rm -f ~/.gstack/last-update-check -rm -f ~/.gstack/update-snoozed +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT" +echo "$OLD_VERSION" > "$GSTACK_STATE_ROOT"/just-upgraded-from +rm -f "$GSTACK_STATE_ROOT"/last-update-check +rm -f "$GSTACK_STATE_ROOT"/update-snoozed ``` ### Step 6: Show What's New diff --git a/gstack-upgrade/migrations/v0.16.2.0.sh b/gstack-upgrade/migrations/v0.16.2.0.sh index afdc09d953..534db737b8 100755 --- a/gstack-upgrade/migrations/v0.16.2.0.sh +++ b/gstack-upgrade/migrations/v0.16.2.0.sh @@ -11,7 +11,8 @@ # Affected: users who ran /office-hours before this version set -euo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" PROFILE_FILE="$GSTACK_HOME/builder-profile.jsonl" # Find all per-project resource logs diff --git a/gstack-upgrade/migrations/v1.0.0.0.sh b/gstack-upgrade/migrations/v1.0.0.0.sh index 2e62fe06ae..f43ea3f6b9 100755 --- a/gstack-upgrade/migrations/v1.0.0.0.sh +++ b/gstack-upgrade/migrations/v1.0.0.0.sh @@ -13,7 +13,8 @@ # Affected: every user on v0.19.x and below who upgrades to v1.x set -euo pipefail -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" PROMPTED_FLAG="$GSTACK_HOME/.writing-style-prompted" PENDING_FLAG="$GSTACK_HOME/.writing-style-prompt-pending" diff --git a/gstack-upgrade/migrations/v1.17.0.0.sh b/gstack-upgrade/migrations/v1.17.0.0.sh index 5b8f1dd95d..7048c73637 100755 --- a/gstack-upgrade/migrations/v1.17.0.0.sh +++ b/gstack-upgrade/migrations/v1.17.0.0.sh @@ -38,7 +38,9 @@ if [ "$SYNC_MODE" = "off" ] || [ -z "$SYNC_MODE" ]; then fi # Skip if no brain-sync git repo exists. -if [ ! -d "${HOME}/.gstack/.git" ]; then +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select +if [ ! -d "$_gstack_sr_root/.git" ]; then exit 0 fi diff --git a/gstack-upgrade/migrations/v1.27.0.0.sh b/gstack-upgrade/migrations/v1.27.0.0.sh index 65ac82890b..e43466e38c 100755 --- a/gstack-upgrade/migrations/v1.27.0.0.sh +++ b/gstack-upgrade/migrations/v1.27.0.0.sh @@ -44,7 +44,8 @@ fi # --------------------------------------------------------------------------- # Configuration # --------------------------------------------------------------------------- -GSTACK_HOME="${HOME}/.gstack" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" SKILLS_DIR="${HOME}/.claude/skills" BIN_DIR="${SKILLS_DIR}/gstack/bin" CONFIG_BIN="${BIN_DIR}/gstack-config" diff --git a/gstack-upgrade/migrations/v1.37.0.0.sh b/gstack-upgrade/migrations/v1.37.0.0.sh index b60b8530c2..c975e6bd54 100755 --- a/gstack-upgrade/migrations/v1.37.0.0.sh +++ b/gstack-upgrade/migrations/v1.37.0.0.sh @@ -38,7 +38,8 @@ if [ -z "${HOME:-}" ]; then exit 0 fi -GSTACK_HOME="${GSTACK_HOME:-$HOME/.gstack}" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" MIGRATIONS_DIR="$GSTACK_HOME/.migrations" DONE_TOUCH="$MIGRATIONS_DIR/v1.37.0.0.done" CONFIG_BIN="$HOME/.claude/skills/gstack/bin/gstack-config" diff --git a/gstack-upgrade/migrations/v1.38.1.0.sh b/gstack-upgrade/migrations/v1.38.1.0.sh index 2a56634d7d..1b23e9edde 100755 --- a/gstack-upgrade/migrations/v1.38.1.0.sh +++ b/gstack-upgrade/migrations/v1.38.1.0.sh @@ -15,7 +15,8 @@ # still run. `set -u` is fine. set -u -GSTACK_HOME="${HOME}/.gstack" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" ALLOWLIST="${GSTACK_HOME}/.brain-allowlist" PRIVACY="${GSTACK_HOME}/.brain-privacy-map.json" GITATTRS="${GSTACK_HOME}/.gitattributes" diff --git a/gstack-upgrade/migrations/v1.40.0.0.sh b/gstack-upgrade/migrations/v1.40.0.0.sh index e482d57a6e..177705d7f9 100755 --- a/gstack-upgrade/migrations/v1.40.0.0.sh +++ b/gstack-upgrade/migrations/v1.40.0.0.sh @@ -22,7 +22,8 @@ set -u -GSTACK_HOME="${HOME}/.gstack" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" ALLOWLIST="${GSTACK_HOME}/.brain-allowlist" PRIVACY="${GSTACK_HOME}/.brain-privacy-map.json" GITATTRS="${GSTACK_HOME}/.gitattributes" diff --git a/gstack-upgrade/migrations/v1.58.0.0.sh b/gstack-upgrade/migrations/v1.58.0.0.sh index da2252286c..bd5adc24fc 100755 --- a/gstack-upgrade/migrations/v1.58.0.0.sh +++ b/gstack-upgrade/migrations/v1.58.0.0.sh @@ -20,7 +20,8 @@ set -u -GSTACK_HOME="${HOME}/.gstack" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" MIGRATION_DIR="${GSTACK_HOME}/.migrations" DONE="${MIGRATION_DIR}/v1.58.0.0.done" mkdir -p "${MIGRATION_DIR}" 2>/dev/null || true diff --git a/gstack-upgrade/migrations/v1.65.0.0.sh b/gstack-upgrade/migrations/v1.65.0.0.sh index 56181d6485..44e698a589 100755 --- a/gstack-upgrade/migrations/v1.65.0.0.sh +++ b/gstack-upgrade/migrations/v1.65.0.0.sh @@ -34,7 +34,8 @@ set -u -GSTACK_HOME="${GSTACK_HOME:-${HOME}/.gstack}" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_HOME="$_gstack_sr_root" MIGRATION_DIR="${GSTACK_HOME}/.migrations" DONE="${MIGRATION_DIR}/v1.65.0.0.done" # Written when a removal happened but the verified end state (a Chromium diff --git a/gstack-upgrade/migrations/v1.78.0.0.sh b/gstack-upgrade/migrations/v1.78.0.0.sh index ee2ed3db39..28c230aaa4 100755 --- a/gstack-upgrade/migrations/v1.78.0.0.sh +++ b/gstack-upgrade/migrations/v1.78.0.0.sh @@ -15,7 +15,8 @@ set -u INSTALL_DIR="${GSTACK_INSTALL_DIR:-$HOME/.claude/skills/gstack}" -GH="${GSTACK_HOME:-$HOME/.gstack}" +. "${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: ${BASH_SOURCE[0]%/*}/../../bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GH="$_gstack_sr_root" mkdir -p "$GH" 2>/dev/null || exit 0 diff --git a/guard/SKILL.md b/guard/SKILL.md index ab16b395bb..b322d7245d 100644 --- a/guard/SKILL.md +++ b/guard/SKILL.md @@ -49,8 +49,9 @@ and `/freeze` skill directories. Both must be installed (they are installed toge by the gstack setup script). ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"guard","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"guard","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Setup diff --git a/guard/SKILL.md.tmpl b/guard/SKILL.md.tmpl index 2f3ee990e8..c9955828fc 100644 --- a/guard/SKILL.md.tmpl +++ b/guard/SKILL.md.tmpl @@ -45,8 +45,9 @@ and `/freeze` skill directories. Both must be installed (they are installed toge by the gstack setup script). ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"guard","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"guard","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Setup diff --git a/health/SKILL.md b/health/SKILL.md index edfd466e03..3bd0466ab8 100644 --- a/health/SKILL.md +++ b/health/SKILL.md @@ -238,7 +238,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -630,7 +631,8 @@ DETAILS: Lint (3 warnings) ## Step 5: Persist to Health History ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" ``` Only when a numeric composite exists, append one JSONL line to @@ -660,8 +662,10 @@ Read the last 10 entries from `~/.gstack/projects/$SLUG/health-history.jsonl` (i file exists and has prior entries). ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG -tail -10 ~/.gstack/projects/$SLUG/health-history.jsonl 2>/dev/null || echo "NO_HISTORY" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" +tail -10 "$GSTACK_STATE_ROOT"/projects/$SLUG/health-history.jsonl 2>/dev/null || echo "NO_HISTORY" ``` **Compare like-for-like coverage.** For each history row, form the set of categories diff --git a/health/SKILL.md.tmpl b/health/SKILL.md.tmpl index 0bca084781..1f490169e7 100644 --- a/health/SKILL.md.tmpl +++ b/health/SKILL.md.tmpl @@ -310,8 +310,9 @@ Read the last 10 entries from `~/.gstack/projects/$SLUG/health-history.jsonl` (i file exists and has prior entries). ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" {{SLUG_SETUP}} -tail -10 ~/.gstack/projects/$SLUG/health-history.jsonl 2>/dev/null || echo "NO_HISTORY" +tail -10 "$GSTACK_STATE_ROOT"/projects/$SLUG/health-history.jsonl 2>/dev/null || echo "NO_HISTORY" ``` **Compare like-for-like coverage.** For each history row, form the set of categories diff --git a/hosts/claude/hooks/auq-error-fallback-hook.ts b/hosts/claude/hooks/auq-error-fallback-hook.ts index 1f4eee8203..d46ab87dd8 100755 --- a/hosts/claude/hooks/auq-error-fallback-hook.ts +++ b/hosts/claude/hooks/auq-error-fallback-hook.ts @@ -30,9 +30,9 @@ */ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { runBin } from './spawn-bin'; import { SPAWNED_ESCAPE_SENTENCE } from './spawned-directive'; +import { logHookError as sharedLogHookError } from './hook-log'; interface HookStdin { tool_name?: string; @@ -40,25 +40,8 @@ interface HookStdin { cwd?: string; } -function stateRoot(): string { - return ( - process.env.GSTACK_STATE_ROOT || - process.env.GSTACK_HOME || - path.join(os.homedir(), '.gstack') - ); -} - function logHookError(msg: string): void { - try { - const sr = stateRoot(); - fs.mkdirSync(sr, { recursive: true }); - fs.appendFileSync( - path.join(sr, 'hook-errors.log'), - `${new Date().toISOString()} auq-error-fallback-hook: ${msg}\n`, - ); - } catch { - // last-resort swallow - } + sharedLogHookError('auq-error-fallback-hook', msg); } function readStdin(): Promise { diff --git a/hosts/claude/hooks/hook-log.ts b/hosts/claude/hooks/hook-log.ts new file mode 100644 index 0000000000..5baa818132 --- /dev/null +++ b/hosts/claude/hooks/hook-log.ts @@ -0,0 +1,59 @@ +/** + * hook-log — the one hook-errors.log writer for the Claude Code hooks in this + * directory. Root from resolveStateRoot() (lib/state-root.ts), mode 0600 on + * every append (an existing 0644 log is tightened), best-effort: logging never + * blocks a hook. Add a hook: `logHookError('my-hook', msg)`; pass + * `{ rateLimit: { nowMs, key } }` to drop repeats within LOG_RATE_LIMIT_MS + * (only memorable-user-prompt uses it). Moved from the five hooks' private + * copies; test/hook-log.test.ts pins the shared root and the mode. + */ +import * as fs from 'fs'; +import * as path from 'path'; +import { createHash } from 'crypto'; +import { resolveStateRoot } from '../../../lib/state-root'; + +export const LOG_RATE_LIMIT_MS = 10 * 60 * 1000; +/** Distinct rate-limit keys remembered at once (the marker file is rewritten on every log line). */ +const RATE_LIMIT_KEYS = 32; + +export interface HookLogOptions { + /** Drop a repeat of `key` logged by this hook within LOG_RATE_LIMIT_MS of `nowMs`. */ + rateLimit?: { nowMs: number; key: string }; +} + +export function hookErrorLogPath(env: NodeJS.ProcessEnv = process.env): string { + return path.join(resolveStateRoot(env), 'hook-errors.log'); +} + +/** + * Append one line to /hook-errors.log. With `rateLimit`, a + * per-hook marker (`hook-errors..last`, up to RATE_LIMIT_KEYS live + * `digest:ts` lines) suppresses repeats, so hooks never contend on it. + */ +export function logHookError(hook: string, msg: string, opts: HookLogOptions = {}): void { + try { + const root = resolveStateRoot(); + fs.mkdirSync(root, { recursive: true }); + const nowMs = opts.rateLimit?.nowMs ?? Date.now(); + if (opts.rateLimit) { + const marker = path.join(root, `hook-errors.${hook}.last`); + const digest = createHash('sha256').update(opts.rateLimit.key).digest('hex').slice(0, 16); + const live: string[] = []; + try { + for (const line of fs.readFileSync(marker, 'utf8').split('\n')) { + const [d, ts] = line.trim().split(':'); + if (!d || !ts || nowMs - Number(ts) >= LOG_RATE_LIMIT_MS) continue; + if (d === digest) return; + live.push(line.trim()); + } + } catch { /* no marker yet */ } + live.push(`${digest}:${nowMs}`); + fs.writeFileSync(marker, `${live.slice(-RATE_LIMIT_KEYS).join('\n')}\n`, { mode: 0o600 }); + } + const log = path.join(root, 'hook-errors.log'); + fs.appendFileSync(log, `${new Date(nowMs).toISOString()} ${hook}: ${msg}\n`, { mode: 0o600 }); + if (process.platform !== 'win32') { try { fs.chmodSync(log, 0o600); } catch { /* not ours to tighten */ } } + } catch { + // best-effort; never block the session because logging failed + } +} diff --git a/hosts/claude/hooks/memorable-user-prompt-hook.ts b/hosts/claude/hooks/memorable-user-prompt-hook.ts index 6520067638..c5fb34b4c4 100644 --- a/hosts/claude/hooks/memorable-user-prompt-hook.ts +++ b/hosts/claude/hooks/memorable-user-prompt-hook.ts @@ -58,6 +58,9 @@ import { import { wrapUntrustedTrackerContent } from '../../../lib/tracker-guard'; import { scan } from '../../../lib/redact-engine'; import { hasRepoPolicyStore, repoPolicyTier } from '../../../lib/gbrain-repo-policy-client'; +import { LOG_RATE_LIMIT_MS, logHookError as sharedLogHookError } from './hook-log'; + +export { LOG_RATE_LIMIT_MS }; export const BUDGET_MS = 4500; export const STDIN_CAP_BYTES = 1024 * 1024; @@ -74,7 +77,6 @@ export const RECHECK_CAP_MS = 500; export const OUTCOME_MIN_MS = 80; /** Kept back from the clock when an outcome append is given the rest of it. */ export const OUTCOME_RESERVE_MS = 50; -export const LOG_RATE_LIMIT_MS = 10 * 60 * 1000; export const ENVELOPE_SOURCE = 'memorable recall (third-party)'; export const SINK = 'memorable-recall'; export const CONSENT = 'memorable_recall=on'; @@ -84,8 +86,6 @@ export const PAYLOAD_CLASS = 'claude-user-prompt-json->local-vendor-cli'; const HOOK_NAME = 'memorable-user-prompt-hook'; /** Per-KiB allowance added to the scan admission check: ~1.5x the measured worst case of scan(). */ const SCAN_MS_PER_KIB = 1; -/** Distinct rate-limit keys remembered at once (the marker file is rewritten on every log line). */ -const RATE_LIMIT_KEYS = 32; /** Candidate objects tried by the tolerant stdout parser before giving up (bounds a hostile brace soup). */ const JSON_CANDIDATES = 64; const GIT_MAX_BUFFER = 64 * 1024; @@ -299,44 +299,16 @@ export function resolveVendor(env: Record, homeDir: return onPath && executable(onPath) ? onPath : null; } -function stateRoot(): string { - return process.env.GSTACK_STATE_ROOT || process.env.GSTACK_HOME || process.env.GSTACK_STATE_DIR - || path.join(os.homedir(), '.gstack'); -} - /** - * Best-effort, rate-limited: a message with the same `key` (default: the - * message itself) within LOG_RATE_LIMIT_MS is not re-logged, so a vendor that - * fails on every prompt with a different timestamp in its stderr still costs - * one line per ten minutes, and two alternating failures cost two. The marker - * (up to RATE_LIMIT_KEYS live `digest:ts` lines) is per hook so hooks never - * contend. The log is chmod 0600 on every append: sibling hooks create the - * same file without a mode, and it can name the session's cwd and vendor + * Best-effort, rate-limited (hook-log.ts): a message with the same `key` + * (default: the message itself) within LOG_RATE_LIMIT_MS is not re-logged, so + * a vendor that fails on every prompt with a different timestamp in its stderr + * still costs one line per ten minutes, and two alternating failures cost two. + * The log is 0600 on every append; it can name the session's cwd and vendor * diagnostics. */ export function logHookError(msg: string, nowMs: number = Date.now(), key: string = msg): void { - try { - const root = stateRoot(); - fs.mkdirSync(root, { recursive: true }); - const marker = path.join(root, `hook-errors.${HOOK_NAME}.last`); - const digest = sha256Hex(key).slice(0, 16); - const live: string[] = []; - try { - for (const line of fs.readFileSync(marker, 'utf8').split('\n')) { - const [d, ts] = line.trim().split(':'); - if (!d || !ts || nowMs - Number(ts) >= LOG_RATE_LIMIT_MS) continue; - if (d === digest) return; - live.push(line.trim()); - } - } catch { /* no marker yet */ } - live.push(`${digest}:${nowMs}`); - fs.writeFileSync(marker, `${live.slice(-RATE_LIMIT_KEYS).join('\n')}\n`, { mode: 0o600 }); - const log = path.join(root, 'hook-errors.log'); - fs.appendFileSync(log, `${new Date(nowMs).toISOString()} ${HOOK_NAME}: ${msg}\n`, { mode: 0o600 }); - if (process.platform !== 'win32') { try { fs.chmodSync(log, 0o600); } catch { /* not ours to tighten */ } } - } catch { - // best-effort; never block the session because logging failed - } + sharedLogHookError(HOOK_NAME, msg, { rateLimit: { nowMs, key } }); } function readStdin(maxBytes: number, timeoutMs: number): Promise<{ buf: Buffer; oversize: boolean; timedOut: boolean }> { diff --git a/hosts/claude/hooks/question-log-hook.ts b/hosts/claude/hooks/question-log-hook.ts index 62952a7783..3d99c3d92c 100644 --- a/hosts/claude/hooks/question-log-hook.ts +++ b/hosts/claude/hooks/question-log-hook.ts @@ -35,8 +35,8 @@ import * as crypto from 'crypto'; import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { runBin } from './spawn-bin'; +import { logHookError as sharedLogHookError } from './hook-log'; interface HookStdin { session_id?: string; @@ -69,19 +69,7 @@ const MARKER_RE = //i; const RECOMMENDED_LABEL_RE = /\(recommended\)\s*$/i; function logHookError(msg: string): void { - try { - const stateRoot = - process.env.GSTACK_STATE_ROOT || - process.env.GSTACK_HOME || - path.join(os.homedir(), '.gstack'); - fs.mkdirSync(stateRoot, { recursive: true }); - fs.appendFileSync( - path.join(stateRoot, 'hook-errors.log'), - `${new Date().toISOString()} question-log-hook: ${msg}\n`, - ); - } catch { - // Last-resort: swallow. Hook must not block. - } + sharedLogHookError('question-log-hook', msg); } function readStdin(): Promise { diff --git a/hosts/claude/hooks/question-preference-hook.ts b/hosts/claude/hooks/question-preference-hook.ts index 3e488363f0..dd7e860a4f 100644 --- a/hosts/claude/hooks/question-preference-hook.ts +++ b/hosts/claude/hooks/question-preference-hook.ts @@ -42,11 +42,12 @@ */ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { runBin, repoRoot } from './spawn-bin'; import { isConductor } from '../../../lib/is-conductor'; import { classifyQuestion } from '../../../scripts/one-way-doors'; import { SPAWNED_ESCAPE_SENTENCE, CONDUCTOR_SPAWNED_DENY_REASON, spawnedByEnv } from './spawned-directive'; +import { resolveStateRoot } from '../../../lib/state-root'; +import { logHookError as sharedLogHookError } from './hook-log'; interface HookStdin { session_id?: string; @@ -66,25 +67,10 @@ interface HookStdin { const MARKER_RE = //i; const RECOMMENDED_LABEL_RE = /\(recommended\)\s*$/i; -function stateRoot(): string { - return ( - process.env.GSTACK_STATE_ROOT || - process.env.GSTACK_HOME || - path.join(os.homedir(), '.gstack') - ); -} +const stateRoot = (): string => resolveStateRoot(); function logHookError(msg: string): void { - try { - const sr = stateRoot(); - fs.mkdirSync(sr, { recursive: true }); - fs.appendFileSync( - path.join(sr, 'hook-errors.log'), - `${new Date().toISOString()} question-preference-hook: ${msg}\n`, - ); - } catch { - // last-resort swallow - } + sharedLogHookError('question-preference-hook', msg); } function readStdin(): Promise { diff --git a/hosts/claude/hooks/timeline-stop-hook.ts b/hosts/claude/hooks/timeline-stop-hook.ts index 30fca9f8b0..f0e658e57e 100755 --- a/hosts/claude/hooks/timeline-stop-hook.ts +++ b/hosts/claude/hooks/timeline-stop-hook.ts @@ -38,6 +38,8 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { runBin } from './spawn-bin'; +import { resolveStateRoot } from '../../../lib/state-root'; +import { logHookError as sharedLogHookError } from './hook-log'; const DEADLINE_MS = 2000; const MAX_TIMELINE_BYTES = 10 * 1024 * 1024; @@ -68,21 +70,8 @@ function readTimelineTail(timelinePath: string, size: number): string { } } -function stateRoot(): string { - return process.env.GSTACK_HOME || path.join(os.homedir(), '.gstack'); -} - function logHookError(msg: string): void { - try { - const root = stateRoot(); - fs.mkdirSync(root, { recursive: true }); - fs.appendFileSync( - path.join(root, 'hook-errors.log'), - `${new Date().toISOString()} timeline-stop-hook: ${msg}\n`, - ); - } catch { - // best-effort; never block the session because logging failed - } + sharedLogHookError('timeline-stop-hook', msg); } interface TimelineEntry { @@ -120,7 +109,7 @@ function main(): void { return; } - const timelinePath = path.join(stateRoot(), 'projects', slug, 'timeline.jsonl'); + const timelinePath = path.join(resolveStateRoot(), 'projects', slug, 'timeline.jsonl'); let stat: fs.Stats; try { stat = fs.statSync(timelinePath); diff --git a/investigate/SKILL.md b/investigate/SKILL.md index 92203c6f96..ed6e3c65bf 100644 --- a/investigate/SKILL.md +++ b/investigate/SKILL.md @@ -277,7 +277,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/ios-clean/SKILL.md b/ios-clean/SKILL.md index 1ad8eebc49..59ae68d417 100644 --- a/ios-clean/SKILL.md +++ b/ios-clean/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/ios-design-review/SKILL.md b/ios-design-review/SKILL.md index 89fe687177..e069b839f2 100644 --- a/ios-design-review/SKILL.md +++ b/ios-design-review/SKILL.md @@ -242,7 +242,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/ios-fix/SKILL.md b/ios-fix/SKILL.md index c45b7e228f..3631e8f0d1 100644 --- a/ios-fix/SKILL.md +++ b/ios-fix/SKILL.md @@ -243,7 +243,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/ios-qa/SKILL.md b/ios-qa/SKILL.md index 1e2596c4fb..155b00d29c 100644 --- a/ios-qa/SKILL.md +++ b/ios-qa/SKILL.md @@ -246,7 +246,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -356,7 +357,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -460,7 +462,8 @@ UDID, tunnel address, and accessor hash. Invalidate the cache when: - The daemon reports the cached UDID is no longer connected. ```bash -SESSION="$HOME/.gstack/ios-qa-session.json" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +SESSION="$GSTACK_STATE_ROOT/ios-qa-session.json" if [ -f "$SESSION" ] && [ "$COLD" != "1" ]; then CACHED_UDID=$(python3 -c "import json,os; d=json.load(open(os.path.expanduser('$SESSION'))); print(d['udid'])") CACHED_PORT=$(python3 -c "import json,os; d=json.load(open(os.path.expanduser('$SESSION'))); print(d['daemon_port'])") diff --git a/ios-qa/SKILL.md.tmpl b/ios-qa/SKILL.md.tmpl index 2e147c5ae8..cafb47f4bd 100644 --- a/ios-qa/SKILL.md.tmpl +++ b/ios-qa/SKILL.md.tmpl @@ -84,7 +84,8 @@ UDID, tunnel address, and accessor hash. Invalidate the cache when: - The daemon reports the cached UDID is no longer connected. ```bash -SESSION="$HOME/.gstack/ios-qa-session.json" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +SESSION="$GSTACK_STATE_ROOT/ios-qa-session.json" if [ -f "$SESSION" ] && [ "$COLD" != "1" ]; then CACHED_UDID=$(python3 -c "import json,os; d=json.load(open(os.path.expanduser('$SESSION'))); print(d['udid'])") CACHED_PORT=$(python3 -c "import json,os; d=json.load(open(os.path.expanduser('$SESSION'))); print(d['daemon_port'])") diff --git a/ios-qa/daemon/src/allowlist.ts b/ios-qa/daemon/src/allowlist.ts index 6496b041e4..a440615a7c 100644 --- a/ios-qa/daemon/src/allowlist.ts +++ b/ios-qa/daemon/src/allowlist.ts @@ -7,13 +7,13 @@ import { readFile, writeFile, mkdir } from 'fs/promises'; import { join, dirname } from 'path'; -import { homedir } from 'os'; import type { Allowlist, AllowlistEntry, Capability } from './types'; import { capabilityCovers } from './types'; +import { resolveStateRoot } from '../../../lib/state-root'; export function defaultAllowlistPath(): string { return process.env.GSTACK_IOS_ALLOWLIST_PATH - ?? join(homedir(), '.gstack', 'ios-qa-allowlist.json'); + ?? join(resolveStateRoot(), 'ios-qa-allowlist.json'); } export async function loadAllowlist(path: string = defaultAllowlistPath()): Promise { diff --git a/ios-qa/daemon/src/audit.ts b/ios-qa/daemon/src/audit.ts index 7b328ca393..c2743c3dc1 100644 --- a/ios-qa/daemon/src/audit.ts +++ b/ios-qa/daemon/src/audit.ts @@ -3,28 +3,28 @@ import { mkdir, appendFile, stat, rename, readFile } from 'fs/promises'; import { join, dirname } from 'path'; -import { homedir } from 'os'; import { createHash } from 'crypto'; import type { AuditRow, AttemptRow } from './types'; +import { resolveStateRoot } from '../../../lib/state-root'; const MAX_BYTES = 10 * 1024 * 1024; const MAX_GENS = 5; export function defaultAuditPath(): string { return process.env.GSTACK_IOS_AUDIT_PATH - ?? join(homedir(), '.gstack', 'security', 'ios-qa-audit.jsonl'); + ?? join(resolveStateRoot(), 'security', 'ios-qa-audit.jsonl'); } export function defaultAttemptsPath(): string { return process.env.GSTACK_IOS_ATTEMPTS_PATH - ?? join(homedir(), '.gstack', 'security', 'attempts.jsonl'); + ?? join(resolveStateRoot(), 'security', 'attempts.jsonl'); } let _saltCache: string | null = null; async function loadDeviceSalt(): Promise { if (_saltCache) return _saltCache; - const path = join(homedir(), '.gstack', 'security', 'device-salt'); + const path = join(resolveStateRoot(), 'security', 'device-salt'); try { _saltCache = (await readFile(path, 'utf-8')).trim(); } catch { diff --git a/ios-qa/daemon/src/single-instance.ts b/ios-qa/daemon/src/single-instance.ts index 0196b0032e..432563e8be 100644 --- a/ios-qa/daemon/src/single-instance.ts +++ b/ios-qa/daemon/src/single-instance.ts @@ -8,8 +8,8 @@ import { readFile, mkdir, unlink } from 'fs/promises'; import { existsSync, openSync, writeSync, closeSync, unlinkSync } from 'fs'; import { join, dirname } from 'path'; -import { homedir } from 'os'; import { spawn } from 'child_process'; +import { resolveStateRoot } from '../../../lib/state-root'; export interface PidfileContents { pid: number; @@ -19,7 +19,7 @@ export interface PidfileContents { export function defaultPidfilePath(): string { return process.env.GSTACK_IOS_DAEMON_PIDFILE - ?? join(homedir(), '.gstack', 'ios-qa-daemon.pid'); + ?? join(resolveStateRoot(), 'ios-qa-daemon.pid'); } /** diff --git a/ios-qa/scripts/gen-accessors.ts b/ios-qa/scripts/gen-accessors.ts index 315f2bde61..d97b02db4a 100644 --- a/ios-qa/scripts/gen-accessors.ts +++ b/ios-qa/scripts/gen-accessors.ts @@ -22,9 +22,9 @@ import { readFileSync, readdirSync, statSync, writeFileSync, mkdirSync, existsSync, copyFileSync, rmSync } from 'fs'; import { join, resolve, dirname } from 'path'; -import { homedir } from 'os'; import { createHash } from 'crypto'; import { execSync } from 'child_process'; +import { resolveStateRoot } from '../../lib/state-root'; export interface AccessorField { name: string; @@ -771,7 +771,7 @@ function detectBuildId(): string { } export function defaultCacheRoot(): string { - return process.env.GSTACK_IOS_CACHE_ROOT ?? join(homedir(), '.gstack', 'cache', 'gen-accessors'); + return process.env.GSTACK_IOS_CACHE_ROOT ?? join(resolveStateRoot(), 'cache', 'gen-accessors'); } export function generate(inputs: GenInputs): GenResult { diff --git a/ios-sync/SKILL.md b/ios-sync/SKILL.md index 1eb47a5aa0..cdf5011fab 100644 --- a/ios-sync/SKILL.md +++ b/ios-sync/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/land-and-deploy/SKILL.md b/land-and-deploy/SKILL.md index 905b2afee4..888e329fa4 100644 --- a/land-and-deploy/SKILL.md +++ b/land-and-deploy/SKILL.md @@ -235,7 +235,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -345,7 +346,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -658,12 +660,13 @@ Unknown scope is not docs-only. `DOCS_ONLY=true` requires SCOPE_DOCS and no othe Check for prior setup confirmation and changed configuration (not proof of a successful deploy): ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -if [ ! -f ~/.gstack/projects/$SLUG/land-deploy-confirmed ]; then +if [ ! -f "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed ]; then echo "FIRST_RUN" else # Check if deploy config has changed since confirmation - SAVED_HASH=$(cat ~/.gstack/projects/$SLUG/land-deploy-confirmed 2>/dev/null) + SAVED_HASH=$(cat "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed 2>/dev/null) CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1) # Also hash workflow files that affect deploy behavior WORKFLOW_HASH=$(find .github/workflows -maxdepth 1 \( -name '*deploy*' -o -name '*cd*' \) 2>/dev/null | xargs cat 2>/dev/null | shasum -a 256 | cut -d' ' -f1) @@ -995,9 +998,10 @@ is passed/skipped/not-needed; inline fixes stopped before merge and cannot appea For rollback include revert SHA or PR URL and unresolved work. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" mkdir -p .gstack/deploy-reports eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG ``` Pass one JSON entry to `~/.claude/skills/gstack/bin/gstack-review-log ''` for diff --git a/land-and-deploy/SKILL.md.tmpl b/land-and-deploy/SKILL.md.tmpl index 22205a256f..7246454972 100644 --- a/land-and-deploy/SKILL.md.tmpl +++ b/land-and-deploy/SKILL.md.tmpl @@ -120,12 +120,13 @@ Unknown scope is not docs-only. `DOCS_ONLY=true` requires SCOPE_DOCS and no othe Check for prior setup confirmation and changed configuration (not proof of a successful deploy): ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" {{SLUG_EVAL}} -if [ ! -f ~/.gstack/projects/$SLUG/land-deploy-confirmed ]; then +if [ ! -f "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed ]; then echo "FIRST_RUN" else # Check if deploy config has changed since confirmation - SAVED_HASH=$(cat ~/.gstack/projects/$SLUG/land-deploy-confirmed 2>/dev/null) + SAVED_HASH=$(cat "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed 2>/dev/null) CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1) # Also hash workflow files that affect deploy behavior WORKFLOW_HASH=$(find .github/workflows -maxdepth 1 \( -name '*deploy*' -o -name '*cd*' \) 2>/dev/null | xargs cat 2>/dev/null | shasum -a 256 | cut -d' ' -f1) @@ -454,9 +455,10 @@ is passed/skipped/not-needed; inline fixes stopped before merge and cannot appea For rollback include revert SHA or PR URL and unresolved work. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" mkdir -p .gstack/deploy-reports {{SLUG_EVAL}} -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG ``` Pass one JSON entry to `~/.claude/skills/gstack/bin/gstack-review-log ''` for diff --git a/land-and-deploy/sections/first-run-validation.md b/land-and-deploy/sections/first-run-validation.md index fa94145441..392a52bf9b 100644 --- a/land-and-deploy/sections/first-run-validation.md +++ b/land-and-deploy/sections/first-run-validation.md @@ -172,11 +172,12 @@ and still refresh deployment facts before each merge approval." Save the deploy config fingerprint so we can detect future changes: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1) WORKFLOW_HASH=$(find .github/workflows -maxdepth 1 \( -name '*deploy*' -o -name '*cd*' \) 2>/dev/null | xargs cat 2>/dev/null | shasum -a 256 | cut -d' ' -f1) -echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > ~/.gstack/projects/$SLUG/land-deploy-confirmed +echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed ``` Continue to Step 2. diff --git a/land-and-deploy/sections/first-run-validation.md.tmpl b/land-and-deploy/sections/first-run-validation.md.tmpl index bf7b878691..cb0d9cd3c8 100644 --- a/land-and-deploy/sections/first-run-validation.md.tmpl +++ b/land-and-deploy/sections/first-run-validation.md.tmpl @@ -134,11 +134,12 @@ and still refresh deployment facts before each merge approval." Save the deploy config fingerprint so we can detect future changes: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" {{SLUG_EVAL}} -mkdir -p ~/.gstack/projects/$SLUG +mkdir -p "$GSTACK_STATE_ROOT"/projects/$SLUG CURRENT_HASH=$(sed -n '/## Deploy Configuration/,/^## /p' CLAUDE.md 2>/dev/null | shasum -a 256 | cut -d' ' -f1) WORKFLOW_HASH=$(find .github/workflows -maxdepth 1 \( -name '*deploy*' -o -name '*cd*' \) 2>/dev/null | xargs cat 2>/dev/null | shasum -a 256 | cut -d' ' -f1) -echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > ~/.gstack/projects/$SLUG/land-deploy-confirmed +echo "${CURRENT_HASH}-${WORKFLOW_HASH}" > "$GSTACK_STATE_ROOT"/projects/$SLUG/land-deploy-confirmed ``` Continue to Step 2. diff --git a/landing-report/SKILL.md b/landing-report/SKILL.md index baf5d02b5e..7a847cff63 100644 --- a/landing-report/SKILL.md +++ b/landing-report/SKILL.md @@ -237,7 +237,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/learn/SKILL.md b/learn/SKILL.md index 65f1bc32ff..a0862e7a6a 100644 --- a/learn/SKILL.md +++ b/learn/SKILL.md @@ -238,7 +238,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -491,7 +492,7 @@ Show summary statistics about the project's learnings. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" LEARN_FILE="$GSTACK_STATE_ROOT/projects/$SLUG/learnings.jsonl" if [ -f "$LEARN_FILE" ]; then TOTAL=$(wc -l < "$LEARN_FILE" | tr -d ' ') diff --git a/learn/SKILL.md.tmpl b/learn/SKILL.md.tmpl index 90d08d2298..bb66d2a88b 100644 --- a/learn/SKILL.md.tmpl +++ b/learn/SKILL.md.tmpl @@ -141,7 +141,7 @@ Show summary statistics about the project's learnings. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" LEARN_FILE="$GSTACK_STATE_ROOT/projects/$SLUG/learnings.jsonl" if [ -f "$LEARN_FILE" ]; then TOTAL=$(wc -l < "$LEARN_FILE" | tr -d ' ') diff --git a/lib/bin-context.ts b/lib/bin-context.ts index d3be44009b..ccc3ef7f3a 100644 --- a/lib/bin-context.ts +++ b/lib/bin-context.ts @@ -7,8 +7,8 @@ import { spawnSync } from "child_process"; import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs"; -import { homedir } from "os"; import { basename, dirname, join } from "path"; +import { resolveStateRoot } from "./state-root"; /** Keep the slug inside the [a-zA-Z0-9._-] alphabet gstack-slug promises (`tr -cd`). */ function sanitizeSlug(s: string): string { @@ -148,7 +148,7 @@ export function outermostRemoteRepo(startDir: string): { root: string; url: stri * 4. Project root's basename; else basename(cwd) for plain non-project folders. */ export function slugFromEnvironment(gstackHome?: string, cwd: string = process.cwd()): string { - const home = gstackHome || process.env.GSTACK_HOME || join(homedir(), ".gstack"); + const home = gstackHome || resolveStateRoot(); const cacheDir = join(home, "slug-cache"); const cacheFile = join(cacheDir, toMsysPath(cwd).replace(/\//g, "_")); diff --git a/lib/code-intelligence/selection.ts b/lib/code-intelligence/selection.ts index b4fe58baf5..c3534afb9b 100644 --- a/lib/code-intelligence/selection.ts +++ b/lib/code-intelligence/selection.ts @@ -12,11 +12,11 @@ */ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs"; -import { homedir } from "os"; import { dirname, join, resolve } from "path"; import { execFileSync } from "child_process"; import { hasRepoPolicyStore, repoPolicyTier } from "../gbrain-repo-policy-client"; import type { CodeProviderId, OpClass } from "./contract"; +import { resolveStateRoot } from "../state-root"; export interface Selection { provider: CodeProviderId | null; @@ -31,7 +31,7 @@ export interface Selection { const EMPTY: Selection = { provider: null, consents: {}, roots: {}, declined: false }; function storePath(env: NodeJS.ProcessEnv = process.env): string { - const home = env.GSTACK_HOME || join(env.HOME || homedir(), ".gstack"); + const home = resolveStateRoot(env); return join(home, "code-intelligence.json"); } diff --git a/lib/cso/state.ts b/lib/cso/state.ts index 39e889a22d..680ca51ef2 100644 --- a/lib/cso/state.ts +++ b/lib/cso/state.ts @@ -4,6 +4,7 @@ import { randomBytes } from 'node:crypto'; import { atomicWriteSync } from '../fs-atomic'; import { CsoError, RunReportV3, canonical, completeness, fingerprint, renderReport, sha256 } from './contracts'; import { redact, sanitizeForJson, sanitizeHelperForJson } from './process'; +import { resolveStateRoot } from '../state-root'; const MAX_STATE_FILE=1024*1024; type ExactStats=Pick & Pick; @@ -179,9 +180,8 @@ export function discardAtomicNoReplaceTemp(path:string,publisherPid:number,optio } export function stateRoot(env: Record = process.env): string { - // Mirrors bin/gstack-paths. Security artifacts are intentionally outside every sync allowlist. - const userHome=env.HOME||(process.platform==='win32'?env.USERPROFILE:''); - return resolve(env.GSTACK_HOME || (env.CLAUDE_PLUGIN_ROOT?.toLowerCase().includes('gstack') ? env.CLAUDE_PLUGIN_DATA : '') || join(userHome || '.', '.gstack')); + // The shared chain (lib/state-root.ts), made absolute. Security artifacts are intentionally outside every sync allowlist. + return resolve(resolveStateRoot(env)); } function ensureDirectory(path:string,hardenExistingLeaf:boolean):string{ const p=resolve(path),root=parse(p).root; diff --git a/lib/egress-receipt.ts b/lib/egress-receipt.ts index 01882ebcf3..fd501eb600 100644 --- a/lib/egress-receipt.ts +++ b/lib/egress-receipt.ts @@ -26,7 +26,7 @@ import { createHash } from 'node:crypto'; import fs from 'node:fs'; -import os from 'node:os'; +import { resolveStateRoot } from './state-root'; import path from 'node:path'; export const EGRESS_RECEIPT_FAILED = 'EGRESS_RECEIPT_FAILED'; @@ -109,14 +109,9 @@ export interface VerifyResult { sizeWarning: string | null; } -/** - * Same resolution order as the rest of gstack (shell sinks, selection code): - * GSTACK_HOME, legacy GSTACK_STATE_DIR, then $HOME/.gstack. - */ +/** The shared state root (lib/state-root.ts), made absolute. */ export function resolveEgressHome(env: Env = process.env): string { - const configured = env.GSTACK_HOME || env.GSTACK_STATE_DIR; - if (configured) return path.resolve(configured); - return path.join(env.HOME || os.homedir(), '.gstack'); + return path.resolve(resolveStateRoot(env)); } export function egressLedgerPath(home: string): string { diff --git a/lib/gbrain-local-status.ts b/lib/gbrain-local-status.ts index 033dc034f7..ae6ebcd8c0 100644 --- a/lib/gbrain-local-status.ts +++ b/lib/gbrain-local-status.ts @@ -49,6 +49,7 @@ import { atomicWriteSync } from "./fs-atomic"; import { homedir } from "os"; import { dirname, join } from "path"; import { buildGbrainEnv, gbrainConfigDir, isExecTimeout, NEEDS_SHELL_ON_WINDOWS } from "./gbrain-exec"; +import { resolveStateRoot } from "./state-root"; export type LocalEngineStatus = | "ok" @@ -116,10 +117,7 @@ function userHome(env?: NodeJS.ProcessEnv): string { /** Cache path computed fresh on each call so tests can mutate GSTACK_HOME per case. */ export function cacheFilePath(): string { - return join( - process.env.GSTACK_HOME || join(userHome(), ".gstack"), - ".gbrain-local-status-cache.json", - ); + return join(resolveStateRoot(), ".gbrain-local-status-cache.json"); } /** diff --git a/lib/gbrain-repo-policy-client.ts b/lib/gbrain-repo-policy-client.ts index 27ef1af659..f62d0a1630 100644 --- a/lib/gbrain-repo-policy-client.ts +++ b/lib/gbrain-repo-policy-client.ts @@ -18,8 +18,8 @@ import { spawnSync } from "child_process"; import { existsSync } from "fs"; -import { homedir } from "os"; import { join } from "path"; +import { mergedStateRoots, resolveStateRoot } from "./state-root"; export type RepoPolicyTierValue = "deny" | "read-only" | "read-write" | "none"; @@ -39,13 +39,16 @@ export interface RepoPolicyResult { /** Absolute path of the policy store for this env (GSTACK_HOME-aware). */ export function repoPolicyStorePath(env: NodeJS.ProcessEnv = process.env): string { - const home = env.GSTACK_HOME || join(env.HOME || homedir(), ".gstack"); + const home = resolveStateRoot(env); return join(home, "gbrain-repo-policy.json"); } -/** No store on disk = no policy was ever set (the fast path — no subprocess). */ +/** + * No store on disk = no policy was ever set (the fast path — no subprocess). + * The ~/.gstack store counts too: its deny tiers merge into every state root. + */ export function hasRepoPolicyStore(env: NodeJS.ProcessEnv = process.env): boolean { - return existsSync(repoPolicyStorePath(env)); + return mergedStateRoots(env).some((root) => existsSync(join(root, "gbrain-repo-policy.json"))); } /** The bash script that owns the store — resolved relative to this file (lib/ → bin/), never cwd. */ diff --git a/lib/gstack-decision.ts b/lib/gstack-decision.ts index 87a0f35cb6..db1774a785 100644 --- a/lib/gstack-decision.ts +++ b/lib/gstack-decision.ts @@ -14,12 +14,12 @@ */ import { join } from "path"; -import { homedir } from "os"; import { randomUUID } from "crypto"; import { existsSync, readFileSync, appendFileSync, statSync, openSync, closeSync, unlinkSync } from "fs"; import { atomicWriteSync } from "./fs-atomic"; import { appendJsonl, readJsonl, hasInjection } from "./jsonl-store"; import { scan } from "./redact-engine"; +import { resolveStateRoot } from "./state-root"; export type DecisionKind = "decide" | "supersede" | "redact"; export type DecisionScope = "repo" | "branch" | "issue"; @@ -57,7 +57,7 @@ export interface DecisionPaths { /** Resolve the per-project decision store paths. Bins pass slug + GSTACK_HOME. */ export function decisionPaths(slug: string, gstackHome?: string): DecisionPaths { - const home = gstackHome || process.env.GSTACK_HOME || join(homedir(), ".gstack"); + const home = gstackHome || resolveStateRoot(); const dir = join(home, "projects", slug || "unknown"); return { log: join(dir, "decisions.jsonl"), diff --git a/lib/gstack-memory-helpers.ts b/lib/gstack-memory-helpers.ts index f511abac89..2ea3a33346 100644 --- a/lib/gstack-memory-helpers.ts +++ b/lib/gstack-memory-helpers.ts @@ -24,7 +24,8 @@ import { appendJsonl } from "./jsonl-store"; import { gbrainConfigDir, isExecTimeout } from "./gbrain-exec"; import { dirname, join } from "path"; import { execFileSync } from "child_process"; -import { homedir, tmpdir } from "os"; +import { tmpdir } from "os"; +import { resolveStateRoot } from "./state-root"; // ── Types ────────────────────────────────────────────────────────────────── @@ -326,7 +327,7 @@ function redactMatch(s: string): string { const ENGINE_CACHE_TTL_MS = 60 * 1000; function gstackHome(): string { - return process.env.GSTACK_HOME || join(homedir(), ".gstack"); + return resolveStateRoot(); } function engineCachePath(): string { diff --git a/lib/redact-audit-log.ts b/lib/redact-audit-log.ts index 8ea03c5bf9..510aba760a 100644 --- a/lib/redact-audit-log.ts +++ b/lib/redact-audit-log.ts @@ -19,6 +19,7 @@ import * as os from "os"; import * as path from "path"; import { createHash } from "crypto"; import { appendJsonl } from "./jsonl-store"; +import { resolveStateRoot } from "./state-root"; export interface SemanticReviewEntry { ts: string; @@ -30,7 +31,7 @@ export interface SemanticReviewEntry { } function securityDir(): string { - const home = process.env.GSTACK_HOME || path.join(os.homedir(), ".gstack"); + const home = resolveStateRoot(); return path.join(home, "security"); } diff --git a/lib/state-root.ts b/lib/state-root.ts new file mode 100644 index 0000000000..a0b1780607 --- /dev/null +++ b/lib/state-root.ts @@ -0,0 +1,103 @@ +/** + * state-root — the one owner of where gstack keeps its state (TS twin of + * bin/gstack-state-root.sh; test/state-root-parity.test.ts keeps them equal). + * Add a caller: `join(resolveStateRoot(), 'analytics')` instead of joining + * homedir() with '.gstack'; read a config key with `readConfigKey('telemetry')`. + * Chain: GSTACK_STATE_ROOT → GSTACK_HOME → GSTACK_STATE_DIR → CLAUDE_PLUGIN_DATA + * (only when CLAUDE_PLUGIN_ROOT contains "gstack") → $HOME/.gstack → .gstack. + * Enforced by test/state-root-ratchet.test.ts. Replaces the hand-rolled chains + * formerly in browse/src/config.ts and lib/cso/state.ts. Docs: docs/state-root.md. + */ +import * as fs from 'node:fs'; + +export type StateRootEnv = Record; + +export const STATE_ROOT_VARS = ['GSTACK_STATE_ROOT', 'GSTACK_HOME', 'GSTACK_STATE_DIR'] as const; + +function userHome(env: StateRootEnv, platform: NodeJS.Platform): string { + return env.HOME || (platform === 'win32' ? env.USERPROFILE || '' : ''); +} + +/** The raw chain value. Pure: never prints, never touches the filesystem. */ +export function resolveStateRoot(env: StateRootEnv = process.env, platform: NodeJS.Platform = process.platform): string { + for (const name of STATE_ROOT_VARS) { + if (env[name]) return env[name] as string; + } + if (env.CLAUDE_PLUGIN_DATA && (env.CLAUDE_PLUGIN_ROOT || '').toLowerCase().includes('gstack')) return env.CLAUDE_PLUGIN_DATA; + const home = userHome(env, platform); + return home ? `${home}/.gstack` : '.gstack'; +} + +/** + * The default root a merged privacy key is also read from. Tests point + * GSTACK_TEST_LEGACY_ROOT at an empty dir (test-setup.ts) so a developer's + * real ~/.gstack never leaks into a run. + */ +function legacyStateRoot(env: StateRootEnv, platform: NodeJS.Platform): string | null { + if (env.GSTACK_TEST_LEGACY_ROOT) return env.GSTACK_TEST_LEGACY_ROOT; + const home = userHome(env, platform); + return home ? `${home}/.gstack` : null; +} + +/** Roots merged privacy settings are read from: the resolved root, then $HOME/.gstack when different. */ +export function mergedStateRoots(env: StateRootEnv = process.env, platform: NodeJS.Platform = process.platform): string[] { + const resolved = resolveStateRoot(env, platform); + const legacy = legacyStateRoot(env, platform); + return legacy && legacy !== resolved ? [resolved, legacy] : [resolved]; +} + +/** Privacy and egress opt-outs: most restrictive first. Read from every candidate root. */ +export const MERGED_CONFIG_KEYS: Record = { + telemetry: ['off', 'anonymous', 'community'], + memorable_recall: ['off', 'on'], + codex_reviews: ['disabled', 'enabled'], + update_check: ['false', 'true'], +}; + +/** Same parse as `gstack-config get`: last `^key:` line wins, value trimmed, empty = unset. */ +function readKeyFromRoot(root: string, key: string): string | null { + let yaml: string; + try { + yaml = fs.readFileSync(`${root}/config.yaml`, 'utf-8'); + } catch { + return null; + } + let value: string | null = null; + for (const line of yaml.split('\n')) { + if (line.startsWith(`${key}:`)) value = line.slice(key.length + 1).trim(); + } + return value ? value : null; +} + +export interface ConfigKeyReading { + value: string | null; + /** Root whose config.yaml supplied the value (null when no root sets it). */ + root: string | null; +} + +/** + * Read one config key. Merged keys (MERGED_CONFIG_KEYS) take the most + * restrictive value across the resolved root and $HOME/.gstack; an + * unrecognized value ranks as most restrictive. Every other key reads the + * resolved root only. + */ +export function readConfigKeyWithRoot(key: string, env: StateRootEnv = process.env, platform: NodeJS.Platform = process.platform): ConfigKeyReading { + const order = MERGED_CONFIG_KEYS[key]; + const candidates = order ? mergedStateRoots(env, platform) : [resolveStateRoot(env, platform)]; + let best: ConfigKeyReading = { value: null, root: null }; + let bestRank = Infinity; + for (const root of candidates) { + const value = readKeyFromRoot(root, key); + if (value === null) continue; + const rank = order ? order.indexOf(value) : 0; + if (rank < bestRank) { + best = { value, root }; + bestRank = rank; + } + } + return best; +} + +export function readConfigKey(key: string, env: StateRootEnv = process.env, platform: NodeJS.Platform = process.platform): string | null { + return readConfigKeyWithRoot(key, env, platform).value; +} diff --git a/office-hours/SKILL.md b/office-hours/SKILL.md index b94af19006..fd3da9cac5 100644 --- a/office-hours/SKILL.md +++ b/office-hours/SKILL.md @@ -273,7 +273,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -383,7 +384,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -533,8 +535,9 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" 3. Use Grep/Glob to map the codebase areas most relevant to the user's request. 4. **List existing design docs for this project:** ```bash + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat - ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null + ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-design-*.md 2>/dev/null ``` If design docs exist, list them: "Prior designs for this project: [titles + dates]" @@ -642,8 +645,9 @@ After the user states the problem (first question in Phase 2A or 2B), search exi Extract 3-5 significant keywords from the user's problem statement and grep across design docs: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -grep -li "\|\|" ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null +grep -li "\|\|" "$GSTACK_STATE_ROOT"/projects/$SLUG/*-design-*.md 2>/dev/null ``` If matches found, read the matching design docs and surface them: diff --git a/office-hours/SKILL.md.tmpl b/office-hours/SKILL.md.tmpl index 898a77b779..cd674c9ebf 100644 --- a/office-hours/SKILL.md.tmpl +++ b/office-hours/SKILL.md.tmpl @@ -86,8 +86,9 @@ Understand the project and the area the user wants to change. 3. Use Grep/Glob to map the codebase areas most relevant to the user's request. 4. **List existing design docs for this project:** ```bash + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat - ls -t ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null + ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-design-*.md 2>/dev/null ``` If design docs exist, list them: "Prior designs for this project: [titles + dates]" @@ -148,8 +149,9 @@ After the user states the problem (first question in Phase 2A or 2B), search exi Extract 3-5 significant keywords from the user's problem statement and grep across design docs: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -grep -li "\|\|" ~/.gstack/projects/$SLUG/*-design-*.md 2>/dev/null +grep -li "\|\|" "$GSTACK_STATE_ROOT"/projects/$SLUG/*-design-*.md 2>/dev/null ``` If matches found, read the matching design docs and surface them: diff --git a/office-hours/sections/design-and-handoff.md b/office-hours/sections/design-and-handoff.md index de78c5761f..71a0576fe4 100644 --- a/office-hours/sections/design-and-handoff.md +++ b/office-hours/sections/design-and-handoff.md @@ -5,19 +5,21 @@ Write the design document to the project directory. ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) ``` **Design lineage:** Before writing, check for existing design docs on this branch: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -PRIOR=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1) +PRIOR=$(ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1) ``` If `$PRIOR` exists, the new doc gets a `Supersedes:` field referencing it. This creates a revision chain — you can trace how a design evolved across office hours sessions. -Write to `~/.gstack/projects/{slug}/{user}-{branch}-design-{datetime}.md`. +Write to `/{user}-{branch}-design-{datetime}.md` (`PROJECT_DIR` printed by the setup block above). **Repo copy (dual-write, #703 + #2000).** When the session runs inside a git repository, ALSO write the doc to `docs/designs/{topic-slug}.md` in the repo — @@ -450,7 +452,7 @@ This must feel earned, not broadcast. If the evidence doesn't support it, skip e with a narrative arc (not a data table). The arc tells the STORY of their journey in second person, referencing specific things they said across sessions. Then open it: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" open "$GSTACK_STATE_ROOT/builder-journey.md" ``` @@ -582,8 +584,9 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null || true)" 2. Log the selection to analytics: ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"office-hours","event":"resources_shown","count":NUM_RESOURCES,"categories":"CAT1,CAT2","ts":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"office-hours","event":"resources_shown","count":NUM_RESOURCES,"categories":"CAT1,CAT2","ts":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` 3. Use AskUserQuestion to offer opening the resources: diff --git a/office-hours/sections/design-and-handoff.md.tmpl b/office-hours/sections/design-and-handoff.md.tmpl index 5924dd706a..0f74cafe8f 100644 --- a/office-hours/sections/design-and-handoff.md.tmpl +++ b/office-hours/sections/design-and-handoff.md.tmpl @@ -10,12 +10,13 @@ DATETIME=$(date +%Y%m%d-%H%M%S) **Design lineage:** Before writing, check for existing design docs on this branch: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -PRIOR=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1) +PRIOR=$(ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-design-*.md 2>/dev/null | head -1) ``` If `$PRIOR` exists, the new doc gets a `Supersedes:` field referencing it. This creates a revision chain — you can trace how a design evolved across office hours sessions. -Write to `~/.gstack/projects/{slug}/{user}-{branch}-design-{datetime}.md`. +Write to `/{user}-{branch}-design-{datetime}.md` (`PROJECT_DIR` printed by the setup block above). **Repo copy (dual-write, #703 + #2000).** When the session runs inside a git repository, ALSO write the doc to `docs/designs/{topic-slug}.md` in the repo — @@ -316,7 +317,7 @@ This must feel earned, not broadcast. If the evidence doesn't support it, skip e with a narrative arc (not a data table). The arc tells the STORY of their journey in second person, referencing specific things they said across sessions. Then open it: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" open "$GSTACK_STATE_ROOT/builder-journey.md" ``` @@ -448,8 +449,9 @@ eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null || true)" 2. Log the selection to analytics: ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"office-hours","event":"resources_shown","count":NUM_RESOURCES,"categories":"CAT1,CAT2","ts":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"office-hours","event":"resources_shown","count":NUM_RESOURCES,"categories":"CAT1,CAT2","ts":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` 3. Use AskUserQuestion to offer opening the resources: diff --git a/open-gstack-browser/SKILL.md b/open-gstack-browser/SKILL.md index 0b6d71d8a9..22efff5826 100644 --- a/open-gstack-browser/SKILL.md +++ b/open-gstack-browser/SKILL.md @@ -208,6 +208,7 @@ may have persisted from a crash. This prevents "already connected" false positives and Chromium profile lock conflicts. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" # Kill any existing browse server if [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/.gstack/browse.json" ]; then _OLD_PID=$(cat "$(git rev-parse --show-toplevel)/.gstack/browse.json" 2>/dev/null | grep -o '"pid":[[:space:]]*[0-9]*' | grep -o '[0-9]*') @@ -217,7 +218,7 @@ if [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/.gstack/browse.json" ]; th rm -f "$(git rev-parse --show-toplevel)/.gstack/browse.json" fi # Clean Chromium profile locks (can persist after crashes) -_PROFILE_DIR="$HOME/.gstack/chromium-profile" +_PROFILE_DIR="$GSTACK_STATE_ROOT/chromium-profile" for _LF in SingletonLock SingletonSocket SingletonCookie; do rm -f "$_PROFILE_DIR/$_LF" 2>/dev/null || true done diff --git a/open-gstack-browser/SKILL.md.tmpl b/open-gstack-browser/SKILL.md.tmpl index bb6b8893d4..5ea932ea70 100644 --- a/open-gstack-browser/SKILL.md.tmpl +++ b/open-gstack-browser/SKILL.md.tmpl @@ -37,6 +37,7 @@ may have persisted from a crash. This prevents "already connected" false positives and Chromium profile lock conflicts. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" # Kill any existing browse server if [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/.gstack/browse.json" ]; then _OLD_PID=$(cat "$(git rev-parse --show-toplevel)/.gstack/browse.json" 2>/dev/null | grep -o '"pid":[[:space:]]*[0-9]*' | grep -o '[0-9]*') @@ -46,7 +47,7 @@ if [ -f "$(git rev-parse --show-toplevel 2>/dev/null)/.gstack/browse.json" ]; th rm -f "$(git rev-parse --show-toplevel)/.gstack/browse.json" fi # Clean Chromium profile locks (can persist after crashes) -_PROFILE_DIR="$HOME/.gstack/chromium-profile" +_PROFILE_DIR="$GSTACK_STATE_ROOT/chromium-profile" for _LF in SingletonLock SingletonSocket SingletonCookie; do rm -f "$_PROFILE_DIR/$_LF" 2>/dev/null || true done diff --git a/pair-agent/SKILL.md b/pair-agent/SKILL.md index 154975b2f1..04f805b64f 100644 --- a/pair-agent/SKILL.md +++ b/pair-agent/SKILL.md @@ -239,7 +239,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/plan-ceo-review/SKILL.md b/plan-ceo-review/SKILL.md index 28e9c767db..27eec7f80b 100644 --- a/plan-ceo-review/SKILL.md +++ b/plan-ceo-review/SKILL.md @@ -258,7 +258,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -368,7 +369,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -572,8 +574,9 @@ Read any `/office-hours` design doc as the problem, constraints and approach sou **Handoff note check** (reuses $SLUG and $BRANCH from the design doc check above): ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -HANDOFF=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null | head -1) +HANDOFF=$(ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null | head -1) [ -n "$HANDOFF" ] && echo "HANDOFF_FOUND: $HANDOFF" || echo "NO_HANDOFF" ``` In a separate shell, first recompute $SLUG and $BRANCH with the design-doc commands. @@ -1119,7 +1122,7 @@ summary; the summary cannot serve as the plan. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CEO_PLANS="$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans" mkdir -p "$CEO_PLANS" echo "CEO_PLANS=$CEO_PLANS" diff --git a/plan-ceo-review/SKILL.md.tmpl b/plan-ceo-review/SKILL.md.tmpl index a4f877f392..ad2bf3bc7d 100644 --- a/plan-ceo-review/SKILL.md.tmpl +++ b/plan-ceo-review/SKILL.md.tmpl @@ -118,8 +118,9 @@ Read any `/office-hours` design doc as the problem, constraints and approach sou **Handoff note check** (reuses $SLUG and $BRANCH from the design doc check above): ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -HANDOFF=$(ls -t ~/.gstack/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null | head -1) +HANDOFF=$(ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null | head -1) [ -n "$HANDOFF" ] && echo "HANDOFF_FOUND: $HANDOFF" || echo "NO_HANDOFF" ``` In a separate shell, first recompute $SLUG and $BRANCH with the design-doc commands. @@ -502,7 +503,7 @@ summary; the summary cannot serve as the plan. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" CEO_PLANS="$GSTACK_STATE_ROOT/projects/$SLUG/ceo-plans" mkdir -p "$CEO_PLANS" echo "CEO_PLANS=$CEO_PLANS" diff --git a/plan-ceo-review/sections/review-sections.md b/plan-ceo-review/sections/review-sections.md index dd22c7ac70..91cf656a05 100644 --- a/plan-ceo-review/sections/review-sections.md +++ b/plan-ceo-review/sections/review-sections.md @@ -787,8 +787,9 @@ Rules: backslashes serialize cleanly — never use hand-rolled `echo` / `printf`. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="${HOME}/.gstack/projects/${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" mkdir -p "$TASKS_DIR" TASKS_FILE="$TASKS_DIR/tasks-ceo-review-$(date +%Y%m%d-%H%M%S).jsonl" COMMIT=$(git rev-parse HEAD 2>/dev/null || echo unknown) @@ -1006,10 +1007,11 @@ skip Review Log, success telemetry and the next-skill handoff. After producing the Completion Summary, remove this branch's handoff notes only if the storage policy permits cleanup. Otherwise retain them and report that cleanup was not performed. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat # gstack-slug prints both SLUG and BRANCH; eval sets them in this shell. eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -rm -f ~/.gstack/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null || true +rm -f "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null || true ``` ## Review Log diff --git a/plan-ceo-review/sections/review-sections.md.tmpl b/plan-ceo-review/sections/review-sections.md.tmpl index c613b02b4a..4e62799f31 100644 --- a/plan-ceo-review/sections/review-sections.md.tmpl +++ b/plan-ceo-review/sections/review-sections.md.tmpl @@ -525,10 +525,11 @@ skip Review Log, success telemetry and the next-skill handoff. After producing the Completion Summary, remove this branch's handoff notes only if the storage policy permits cleanup. Otherwise retain them and report that cleanup was not performed. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat # gstack-slug prints both SLUG and BRANCH; eval sets them in this shell. {{SLUG_EVAL}} -rm -f ~/.gstack/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null || true +rm -f "$GSTACK_STATE_ROOT"/projects/$SLUG/*-$BRANCH-ceo-handoff-*.md 2>/dev/null || true ``` ## Review Log diff --git a/plan-design-review/SKILL.md b/plan-design-review/SKILL.md index 48574b18c1..bc1edba879 100644 --- a/plan-design-review/SKILL.md +++ b/plan-design-review/SKILL.md @@ -264,7 +264,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -374,7 +375,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -786,7 +788,7 @@ First, set up the output directory. Name it after the screen/feature being desig ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" @@ -1124,7 +1126,7 @@ offer to generate a visual mockup showing what the improved version would look l ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/ideal-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" _ROOT=$(git rev-parse --show-toplevel 2>/dev/null) diff --git a/plan-design-review/SKILL.md.tmpl b/plan-design-review/SKILL.md.tmpl index db88a19fbf..5667fddd9c 100644 --- a/plan-design-review/SKILL.md.tmpl +++ b/plan-design-review/SKILL.md.tmpl @@ -224,7 +224,7 @@ First, set up the output directory. Name it after the screen/feature being desig ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" echo "DESIGN_DIR: $_DESIGN_DIR" @@ -298,7 +298,7 @@ offer to generate a visual mockup showing what the improved version would look l ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _DESIGN_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/designs/ideal-$(date +%Y%m%d)" mkdir -p "$_DESIGN_DIR" _ROOT=$(git rev-parse --show-toplevel 2>/dev/null) diff --git a/plan-design-review/sections/review-sections.md b/plan-design-review/sections/review-sections.md index a68fe61389..afde48a361 100644 --- a/plan-design-review/sections/review-sections.md +++ b/plan-design-review/sections/review-sections.md @@ -333,8 +333,9 @@ Rules: backslashes serialize cleanly — never use hand-rolled `echo` / `printf`. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="${HOME}/.gstack/projects/${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" mkdir -p "$TASKS_DIR" TASKS_FILE="$TASKS_DIR/tasks-design-review-$(date +%Y%m%d-%H%M%S).jsonl" COMMIT=$(git rev-parse HEAD 2>/dev/null || echo unknown) diff --git a/plan-devex-review/SKILL.md b/plan-devex-review/SKILL.md index 007d9d1f4d..91e5200404 100644 --- a/plan-devex-review/SKILL.md +++ b/plan-devex-review/SKILL.md @@ -236,7 +236,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -346,7 +347,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol diff --git a/plan-devex-review/sections/review-sections.md b/plan-devex-review/sections/review-sections.md index 22f227e2c4..efcf30c774 100644 --- a/plan-devex-review/sections/review-sections.md +++ b/plan-devex-review/sections/review-sections.md @@ -700,8 +700,9 @@ Rules: backslashes serialize cleanly — never use hand-rolled `echo` / `printf`. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="${HOME}/.gstack/projects/${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" mkdir -p "$TASKS_DIR" TASKS_FILE="$TASKS_DIR/tasks-devex-review-$(date +%Y%m%d-%H%M%S).jsonl" COMMIT=$(git rev-parse HEAD 2>/dev/null || echo unknown) diff --git a/plan-eng-review/SKILL.md b/plan-eng-review/SKILL.md index 2057da9239..1461ab99d8 100644 --- a/plan-eng-review/SKILL.md +++ b/plan-eng-review/SKILL.md @@ -284,7 +284,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -394,7 +395,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol diff --git a/plan-eng-review/sections/review-sections.md b/plan-eng-review/sections/review-sections.md index 57c85f4eb2..cf8facb512 100644 --- a/plan-eng-review/sections/review-sections.md +++ b/plan-eng-review/sections/review-sections.md @@ -735,14 +735,15 @@ When these test and eval choices are resolved, write the Test Plan Artifact belo After resolving the Test review decisions, record the approved test requirements in an artifact for `/qa` and `/qa-only`. List any unresolved choices separately as pending, not required implementation. Update this artifact if later approved decisions change the tests. Use the Review record and write policy above. ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG # sets SLUG and BRANCH +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" # sets SLUG and BRANCH TEST_PLAN_USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) ``` Use `SLUG` and the sanitized `BRANCH` from gstack-slug, `TEST_PLAN_USER` for {user}, and `DATETIME` for {datetime}. Set {date} to today. Read the local origin URL with `git remote get-url origin` and use its owner/repo; without an origin, write `local-only`. No network request is needed. -Write to `~/.gstack/projects/{slug}/{user}-{branch}-eng-review-test-plan-{datetime}.md`: +Write to `/{user}-{branch}-eng-review-test-plan-{datetime}.md` (`PROJECT_DIR` printed above): ```markdown # Test Plan @@ -1170,8 +1171,9 @@ Rules: backslashes serialize cleanly — never use hand-rolled `echo` / `printf`. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="${HOME}/.gstack/projects/${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" mkdir -p "$TASKS_DIR" TASKS_FILE="$TASKS_DIR/tasks-eng-review-$(date +%Y%m%d-%H%M%S).jsonl" COMMIT=$(git rev-parse HEAD 2>/dev/null || echo unknown) diff --git a/plan-tune/SKILL.md b/plan-tune/SKILL.md index 7606358ec0..7067ef4e47 100644 --- a/plan-tune/SKILL.md +++ b/plan-tune/SKILL.md @@ -248,7 +248,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -505,7 +506,8 @@ explicit. 3. ALWAYS touch the marker, regardless of choice: ```bash - touch ~/.gstack/.question-tuning-prompted + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT"/.question-tuning-prompted ``` 4. If A or B: enable: @@ -564,7 +566,7 @@ explicit. # Ensure profile exists ~/.claude/skills/gstack/bin/gstack-developer-profile --read >/dev/null # Update declared dimensions atomically - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _PROFILE="$GSTACK_STATE_ROOT/developer-profile.json" bun -e " const fs = require('fs'); @@ -584,7 +586,8 @@ explicit. 2. Touch the marker so the Setup gate doesn't re-fire: ```bash - touch ~/.gstack/.declared-setup-prompted + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT"/.declared-setup-prompted ``` Touch it even if the user bails out partway — they were asked; they chose not to complete. The Setup gate respects that. They can rerun the 5-Q @@ -640,7 +643,7 @@ Parse the JSON. Present in **plain English**, not raw floats: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" if [ ! -f "$_LOG" ]; then echo "NO_LOG" @@ -734,7 +737,7 @@ is a trust boundary (Codex #15 in the design doc). 3. After Y, write: ```bash - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _PROFILE="$GSTACK_STATE_ROOT/developer-profile.json" bun -e " const fs = require('fs'); @@ -780,7 +783,7 @@ cycle cost-to-date. ```bash ~/.claude/skills/gstack/bin/gstack-question-preference --stats eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" if [ -f "$_LOG" ]; then bun -e " @@ -832,7 +835,7 @@ any that misfired via `always-ask`. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" [ ! -f "$_LOG" ] && echo 'NO_LOG' || bun -e " const lines = require('fs').readFileSync('$_LOG','utf-8').trim().split('\n').filter(Boolean); @@ -864,7 +867,7 @@ adoption: high-traffic unmarked questions are the next candidates to retrofit. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" [ ! -f "$_LOG" ] && echo 'NO_LOG' || bun -e " const lines = require('fs').readFileSync('$_LOG','utf-8').trim().split('\n').filter(Boolean); diff --git a/plan-tune/SKILL.md.tmpl b/plan-tune/SKILL.md.tmpl index dc1214d4c0..9b0f82077f 100644 --- a/plan-tune/SKILL.md.tmpl +++ b/plan-tune/SKILL.md.tmpl @@ -156,7 +156,8 @@ explicit. 3. ALWAYS touch the marker, regardless of choice: ```bash - touch ~/.gstack/.question-tuning-prompted + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT"/.question-tuning-prompted ``` 4. If A or B: enable: @@ -215,7 +216,7 @@ explicit. # Ensure profile exists ~/.claude/skills/gstack/bin/gstack-developer-profile --read >/dev/null # Update declared dimensions atomically - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _PROFILE="$GSTACK_STATE_ROOT/developer-profile.json" bun -e " const fs = require('fs'); @@ -235,7 +236,8 @@ explicit. 2. Touch the marker so the Setup gate doesn't re-fire: ```bash - touch ~/.gstack/.declared-setup-prompted + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT"/.declared-setup-prompted ``` Touch it even if the user bails out partway — they were asked; they chose not to complete. The Setup gate respects that. They can rerun the 5-Q @@ -291,7 +293,7 @@ Parse the JSON. Present in **plain English**, not raw floats: ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" if [ ! -f "$_LOG" ]; then echo "NO_LOG" @@ -385,7 +387,7 @@ is a trust boundary (Codex #15 in the design doc). 3. After Y, write: ```bash - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _PROFILE="$GSTACK_STATE_ROOT/developer-profile.json" bun -e " const fs = require('fs'); @@ -431,7 +433,7 @@ cycle cost-to-date. ```bash ~/.claude/skills/gstack/bin/gstack-question-preference --stats eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" if [ -f "$_LOG" ]; then bun -e " @@ -483,7 +485,7 @@ any that misfired via `always-ask`. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" [ ! -f "$_LOG" ] && echo 'NO_LOG' || bun -e " const lines = require('fs').readFileSync('$_LOG','utf-8').trim().split('\n').filter(Boolean); @@ -515,7 +517,7 @@ adoption: high-traffic unmarked questions are the next candidates to retrofit. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _LOG="$GSTACK_STATE_ROOT/projects/$SLUG/question-log.jsonl" [ ! -f "$_LOG" ] && echo 'NO_LOG' || bun -e " const lines = require('fs').readFileSync('$_LOG','utf-8').trim().split('\n').filter(Boolean); diff --git a/qa-only/SKILL.md b/qa-only/SKILL.md index ff95a79105..5334eec526 100644 --- a/qa-only/SKILL.md +++ b/qa-only/SKILL.md @@ -238,7 +238,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -348,7 +349,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -582,7 +584,7 @@ permissions or fixed paths override them. Do not create a forbidden second copy. Use this session's existing project slug and state directory for the project copy. If unknown or not writable within the supplied permissions, report that copy as blocked; still write the permitted local report. Do not run state-setup helpers. -Write identical content to `~/.gstack/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md`. +Write identical content to `$GSTACK_STATE_ROOT/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md` (the state root this session resolved). Get `{user}`/`{branch}` from `git config user.name`/`git branch --show-current` (fallbacks: `unknown-user`/`detached`); sanitize like `{target}`. Use UTC `YYYYMMDDTHHMMSSZ`. If that destination exists, choose a fresh suffixed filename; never replace a prior report. diff --git a/qa-only/SKILL.md.tmpl b/qa-only/SKILL.md.tmpl index 55169e631e..60f7efd9f7 100644 --- a/qa-only/SKILL.md.tmpl +++ b/qa-only/SKILL.md.tmpl @@ -177,7 +177,7 @@ permissions or fixed paths override them. Do not create a forbidden second copy. Use this session's existing project slug and state directory for the project copy. If unknown or not writable within the supplied permissions, report that copy as blocked; still write the permitted local report. Do not run state-setup helpers. -Write identical content to `~/.gstack/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md`. +Write identical content to `$GSTACK_STATE_ROOT/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md` (the state root this session resolved). Get `{user}`/`{branch}` from `git config user.name`/`git branch --show-current` (fallbacks: `unknown-user`/`detached`); sanitize like `{target}`. Use UTC `YYYYMMDDTHHMMSSZ`. If that destination exists, choose a fresh suffixed filename; never replace a prior report. diff --git a/qa/SKILL.md b/qa/SKILL.md index ef409b1464..fb51c768c6 100644 --- a/qa/SKILL.md +++ b/qa/SKILL.md @@ -242,7 +242,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -352,7 +353,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -579,9 +581,10 @@ Prefer the richer of recent project test plans and plans in conversation over gi 1. **Project-scoped test plans:** Find the latest for this repo: ```bash + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" - ls -t ~/.gstack/projects/$SLUG/*-test-plan-*.md 2>/dev/null | head -1 + ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-test-plan-*.md 2>/dev/null | head -1 ``` 2. **Conversation context:** Prior `/plan-eng-review` or `/plan-ceo-review` test plans. 3. Fall back to git diff only if neither exists. @@ -748,9 +751,10 @@ Write the Output Structure report locally and copy the same content to project c **Project-scoped:** Write test outcome artifact for cross-session context: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" ``` -Write to `~/.gstack/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md` +Write to `/{user}-{branch}-test-outcome-{datetime}.md` (`PROJECT_DIR` printed above) **Per-issue additions:** - Fix Status: verified / best-effort / reverted / deferred diff --git a/qa/SKILL.md.tmpl b/qa/SKILL.md.tmpl index ea46ebad7a..3911028006 100644 --- a/qa/SKILL.md.tmpl +++ b/qa/SKILL.md.tmpl @@ -113,9 +113,10 @@ Prefer the richer of recent project test plans and plans in conversation over gi 1. **Project-scoped test plans:** Find the latest for this repo: ```bash + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat {{SLUG_EVAL}} - ls -t ~/.gstack/projects/$SLUG/*-test-plan-*.md 2>/dev/null | head -1 + ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-test-plan-*.md 2>/dev/null | head -1 ``` 2. **Conversation context:** Prior `/plan-eng-review` or `/plan-ceo-review` test plans. 3. Fall back to git diff only if neither exists. @@ -272,7 +273,7 @@ Write the Output Structure report locally and copy the same content to project c ```bash {{SLUG_SETUP}} ``` -Write to `~/.gstack/projects/{slug}/{user}-{branch}-test-outcome-{datetime}.md` +Write to `/{user}-{branch}-test-outcome-{datetime}.md` (`PROJECT_DIR` printed above) **Per-issue additions:** - Fix Status: verified / best-effort / reverted / deferred diff --git a/retro/SKILL.md b/retro/SKILL.md index d538002de6..72fa3b8970 100644 --- a/retro/SKILL.md +++ b/retro/SKILL.md @@ -258,7 +258,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -1121,8 +1122,9 @@ Considering the full cross-project picture. ### Global Step 8: Load history & compare ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -ls -t ~/.gstack/retros/global-*.json 2>/dev/null | head -5 +ls -t "$GSTACK_STATE_ROOT"/retros/global-*.json 2>/dev/null | head -5 ``` **Only compare against a prior retro with the same `window` value** (e.g., 7d vs 7d). If the most recent prior retro has a different window, skip comparison and note: "Prior global retro used a different window — skipping comparison." @@ -1134,18 +1136,21 @@ If no prior global retros exist, append: "First global retro recorded — run ag ### Global Step 9: Save snapshot ```bash -mkdir -p ~/.gstack/retros +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/retros ``` Determine the next unused sequence number for today, using the same session-reminder date as Global Step 1: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat today="" next=1 -while [ -e "$HOME/.gstack/retros/global-${today}-${next}.json" ]; do next=$((next + 1)); done +while [ -e "$GSTACK_STATE_ROOT/retros/global-${today}-${next}.json" ]; do next=$((next + 1)); done +echo "RETRO_FILE: $GSTACK_STATE_ROOT/retros/global-${today}-${next}.json" ``` -Use the Write tool to save JSON to `~/.gstack/retros/global-${today}-${next}.json`: +Use the Write tool to save JSON to the printed `RETRO_FILE`: ```json { diff --git a/retro/SKILL.md.tmpl b/retro/SKILL.md.tmpl index 44a63fea1e..8ff30d38a9 100644 --- a/retro/SKILL.md.tmpl +++ b/retro/SKILL.md.tmpl @@ -667,8 +667,9 @@ Considering the full cross-project picture. ### Global Step 8: Load history & compare ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -ls -t ~/.gstack/retros/global-*.json 2>/dev/null | head -5 +ls -t "$GSTACK_STATE_ROOT"/retros/global-*.json 2>/dev/null | head -5 ``` **Only compare against a prior retro with the same `window` value** (e.g., 7d vs 7d). If the most recent prior retro has a different window, skip comparison and note: "Prior global retro used a different window — skipping comparison." @@ -680,18 +681,21 @@ If no prior global retros exist, append: "First global retro recorded — run ag ### Global Step 9: Save snapshot ```bash -mkdir -p ~/.gstack/retros +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/retros ``` Determine the next unused sequence number for today, using the same session-reminder date as Global Step 1: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat today="" next=1 -while [ -e "$HOME/.gstack/retros/global-${today}-${next}.json" ]; do next=$((next + 1)); done +while [ -e "$GSTACK_STATE_ROOT/retros/global-${today}-${next}.json" ]; do next=$((next + 1)); done +echo "RETRO_FILE: $GSTACK_STATE_ROOT/retros/global-${today}-${next}.json" ``` -Use the Write tool to save JSON to `~/.gstack/retros/global-${today}-${next}.json`: +Use the Write tool to save JSON to the printed `RETRO_FILE`: ```json { diff --git a/retro/sections/report-format.md b/retro/sections/report-format.md index 7b506c0b82..4c160c8689 100644 --- a/retro/sections/report-format.md +++ b/retro/sections/report-format.md @@ -51,9 +51,10 @@ Narrative covering: Check review JSONL logs for plan completion data from /ship runs this period: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -cat ~/.gstack/projects/$SLUG/*-reviews.jsonl 2>/dev/null | grep '"skill":"ship"' | grep '"plan_items_total"' || echo "NO_PLAN_DATA" +cat "$GSTACK_STATE_ROOT"/projects/$SLUG/*-reviews.jsonl 2>/dev/null | grep '"skill":"ship"' | grep '"plan_items_total"' || echo "NO_PLAN_DATA" ``` If plan completion data exists within the retro time window: diff --git a/retro/sections/report-format.md.tmpl b/retro/sections/report-format.md.tmpl index 2f327db88c..e41284b8df 100644 --- a/retro/sections/report-format.md.tmpl +++ b/retro/sections/report-format.md.tmpl @@ -49,9 +49,10 @@ Narrative covering: Check review JSONL logs for plan completion data from /ship runs this period: ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -cat ~/.gstack/projects/$SLUG/*-reviews.jsonl 2>/dev/null | grep '"skill":"ship"' | grep '"plan_items_total"' || echo "NO_PLAN_DATA" +cat "$GSTACK_STATE_ROOT"/projects/$SLUG/*-reviews.jsonl 2>/dev/null | grep '"skill":"ship"' | grep '"plan_items_total"' || echo "NO_PLAN_DATA" ``` If plan completion data exists within the retro time window: diff --git a/review/SKILL.md b/review/SKILL.md index c77b485371..5cf8d0edf0 100644 --- a/review/SKILL.md +++ b/review/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -350,7 +351,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol diff --git a/scripts/analytics.ts b/scripts/analytics.ts index 6aa93cb37a..1e4697c3a2 100644 --- a/scripts/analytics.ts +++ b/scripts/analytics.ts @@ -13,7 +13,7 @@ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; +import { resolveStateRoot } from '../lib/state-root'; export interface AnalyticsEvent { skill: string; @@ -23,7 +23,7 @@ export interface AnalyticsEvent { pattern?: string; } -const ANALYTICS_FILE = path.join(os.homedir(), '.gstack', 'analytics', 'skill-usage.jsonl'); +const ANALYTICS_FILE = path.join(resolveStateRoot(), 'analytics', 'skill-usage.jsonl'); /** * Parse JSONL content into AnalyticsEvent[], skipping malformed lines. diff --git a/scripts/declared-annotation.ts b/scripts/declared-annotation.ts index fa45c585ba..e856b080b7 100644 --- a/scripts/declared-annotation.ts +++ b/scripts/declared-annotation.ts @@ -22,9 +22,9 @@ */ import * as fs from 'fs'; import * as path from 'path'; -import * as os from 'os'; import { SIGNAL_MAP, type Dimension, ALL_DIMENSIONS } from './psychographic-signals'; +import { resolveStateRoot } from '../lib/state-root'; const STRONG_HIGH = 0.7; const STRONG_LOW = 0.3; @@ -61,11 +61,7 @@ interface DeveloperProfile { } function stateRoot(): string { - return ( - process.env.GSTACK_STATE_ROOT || - process.env.GSTACK_HOME || - path.join(os.homedir(), '.gstack') - ); + return resolveStateRoot(); } function readProfile(): DeveloperProfile | null { diff --git a/scripts/gen-skill-docs.ts b/scripts/gen-skill-docs.ts index d19281ada6..186b860622 100644 --- a/scripts/gen-skill-docs.ts +++ b/scripts/gen-skill-docs.ts @@ -27,6 +27,7 @@ import type { HostConfig } from './host-config'; const ROOT = path.resolve(import.meta.dir, '..'); import { ALL_MODEL_NAMES, resolveModel, type Model } from './models'; +import { resolveStateRoot } from '../lib/state-root'; type HostArg = Host | 'all'; @@ -75,7 +76,7 @@ export interface GenerationResult { /** Canonical generation never reads local detection state unless opted in. */ function loadGbrainOverride(respectDetection: boolean): boolean { if (!respectDetection) return false; - const stateDir = process.env.GSTACK_HOME || path.join(process.env.HOME || '', '.gstack'); + const stateDir = resolveStateRoot(); try { const json = JSON.parse(fs.readFileSync(path.join(stateDir, 'gbrain-detection.json'), 'utf-8')); // Slow, remote, and locked engines are still usable (#1964/#2051/#2456). @@ -1087,7 +1088,7 @@ export async function main(args = process.argv.slice(2)): Promise { } if (!settings.dryRun) { try { - const config = fs.readFileSync(path.join(process.env.HOME || '', '.gstack', 'config.yaml'), 'utf-8'); + const config = fs.readFileSync(path.join(resolveStateRoot(), 'config.yaml'), 'utf-8'); if (/^skill_prefix:\s*true/m.test(config)) { console.log('\nNote: skill_prefix is true. Run gstack-relink to re-apply name: patches (it patches both the install and any active gbrain render).'); } diff --git a/scripts/resolvers/preamble/generate-context-recovery.ts b/scripts/resolvers/preamble/generate-context-recovery.ts index 31ade38a99..e2bf727f2c 100644 --- a/scripts/resolvers/preamble/generate-context-recovery.ts +++ b/scripts/resolvers/preamble/generate-context-recovery.ts @@ -17,7 +17,8 @@ At session start or after compaction, recover recent project context. \`\`\`bash eval "$(${binDir}/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=\${_BRANCH:-unknown} -_PROJ="\${GSTACK_HOME:-$HOME/.gstack}/projects/\${SLUG:-unknown}" +eval "$(${binDir}/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/\${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/scripts/resolvers/preamble/generate-search-before-building.ts b/scripts/resolvers/preamble/generate-search-before-building.ts index dc41a9b9a0..84ccba5ae6 100644 --- a/scripts/resolvers/preamble/generate-search-before-building.ts +++ b/scripts/resolvers/preamble/generate-search-before-building.ts @@ -18,7 +18,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: \`\`\`bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(${ctx.paths.binDir}/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true \`\`\``; } diff --git a/scripts/resolvers/tasks-section.ts b/scripts/resolvers/tasks-section.ts index 0941c3942c..202e8cce37 100644 --- a/scripts/resolvers/tasks-section.ts +++ b/scripts/resolvers/tasks-section.ts @@ -59,8 +59,9 @@ Rules: backslashes serialize cleanly — never use hand-rolled \`echo\` / \`printf\`. \`\`\`bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="\${HOME}/.gstack/projects/\${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/\${SLUG:-unknown}" mkdir -p "$TASKS_DIR" TASKS_FILE="$TASKS_DIR/tasks-${phase}-$(date +%Y%m%d-%H%M%S).jsonl" COMMIT=$(git rev-parse HEAD 2>/dev/null || echo unknown) @@ -105,8 +106,9 @@ Before rendering the Final Approval Gate output block below, aggregate the per-phase task lists each review skill wrote. \`\`\`bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" -TASKS_DIR="\${HOME}/.gstack/projects/\${SLUG:-unknown}" +TASKS_DIR="$GSTACK_STATE_ROOT/projects/\${SLUG:-unknown}" BRANCH=$(git branch --show-current 2>/dev/null || echo unknown) # Commit window: last 5 commits on this branch. Drops stale standalone reviews. COMMITS_RECENT=$(git log --format=%H -n 5 2>/dev/null | tr '\\n' '|' | sed 's/|$//') diff --git a/scripts/resolvers/testing.ts b/scripts/resolvers/testing.ts index 71c72d984e..6b8367cb94 100644 --- a/scripts/resolvers/testing.ts +++ b/scripts/resolvers/testing.ts @@ -489,14 +489,15 @@ ${subheading} Test Plan Artifact After resolving the Test review decisions, record the approved test requirements in an artifact for \`/qa\` and \`/qa-only\`. List any unresolved choices separately as pending, not required implementation. Update this artifact if later approved decisions change the tests. Use the Review record and write policy above. \`\`\`bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG # sets SLUG and BRANCH +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" # sets SLUG and BRANCH TEST_PLAN_USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) \`\`\` Use \`SLUG\` and the sanitized \`BRANCH\` from gstack-slug, \`TEST_PLAN_USER\` for {user}, and \`DATETIME\` for {datetime}. Set {date} to today. Read the local origin URL with \`git remote get-url origin\` and use its owner/repo; without an origin, write \`local-only\`. No network request is needed. -Write to \`~/.gstack/projects/{slug}/{user}-{branch}-eng-review-test-plan-{datetime}.md\`: +Write to \`/{user}-{branch}-eng-review-test-plan-{datetime}.md\` (\`PROJECT_DIR\` printed above): \`\`\`markdown # Test Plan @@ -614,12 +615,13 @@ ${subheading} Test Plan Artifact After producing the coverage diagram, write a test plan artifact so \`/qa\` and \`/qa-only\` can consume it: \`\`\`bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) \`\`\` -Write to \`~/.gstack/projects/{slug}/{user}-{branch}-ship-test-plan-{datetime}.md\`: +Write to \`/{user}-{branch}-ship-test-plan-{datetime}.md\` (\`PROJECT_DIR\` printed above): \`\`\`markdown # Test Plan diff --git a/scripts/resolvers/utility.ts b/scripts/resolvers/utility.ts index 4b614a2ea1..f4e4b5e2ee 100644 --- a/scripts/resolvers/utility.ts +++ b/scripts/resolvers/utility.ts @@ -33,7 +33,8 @@ export function generateSlugEval(ctx: TemplateContext): string { } export function generateSlugSetup(ctx: TemplateContext): string { - return `eval "$(${ctx.paths.binDir}/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG`; + return `eval "$(${ctx.paths.binDir}/gstack-paths)"; : "\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(${ctx.paths.binDir}/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG"`; } export function generateBaseBranchDetect(_ctx: TemplateContext): string { diff --git a/setup b/setup index 86ddc52422..53d2b17362 100755 --- a/setup +++ b/setup @@ -167,6 +167,9 @@ fi INSTALL_GSTACK_DIR="$(cd "$(dirname "$0")" && pwd)" SOURCE_GSTACK_DIR="$(cd "$(dirname "$0")" && pwd -P)" +# One state root for everything setup writes (bin/gstack-state-root.sh, docs/state-root.md). +. "$SOURCE_GSTACK_DIR/bin/gstack-state-root.sh" 2>/dev/null || { echo "$0: cannot resolve the gstack state root: $SOURCE_GSTACK_DIR/bin/gstack-state-root.sh is missing. fix: reinstall with ./setup or /gstack-upgrade (docs/state-root.md)" >&2; exit 1; } +gstack_state_root_select; GSTACK_STATE_ROOT="$_gstack_sr_root" INSTALL_SKILLS_DIR="$(dirname "$INSTALL_GSTACK_DIR")" BROWSE_BIN="$SOURCE_GSTACK_DIR/browse/dist/browse" CODEX_SKILLS="${CODEX_HOME:-$HOME/.codex}/skills" @@ -308,7 +311,7 @@ _link_or_copy() { # marker) means we created the entry and may delete or refresh it whole; WEAK # (byte-identity with our source, or the two-line generated banner on a real # file) covers only that SKILL.md — never the directory — and a differing -# weakly-proven file is moved to ${GSTACK_HOME:-~/.gstack}/backups/skills// +# weakly-proven file is moved to $GSTACK_STATE_ROOT/backups/skills// # before we install over it. An entry is OURS # when: it is a symlink resolving into the gstack payload / render dir (or any # path with a `gstack` segment, the convention cleanup and gstack-uninstall @@ -332,7 +335,7 @@ _gstack_target_is_ours() { # $1 = absolute target path, $2 = gstack payload dir local t="$1" g="$2" g_real render render_real g_real="$(cd "$g" 2>/dev/null && pwd -P || printf '%s' "$g")" - render="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}" + render="${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}" render_real="$(cd "$render" 2>/dev/null && pwd -P || printf '%s' "$render")" case "$t" in "$g"/*|"$g_real"/*|"$render"/*|"$render_real"/*|gstack/*|*/gstack/*|*/.gstack/render/claude/*) return 0 ;; @@ -363,7 +366,7 @@ _claude_entry_is_ours() { # A gbrain install serves the RENDERED file (link_claude_skill_dirs prefers # it), so an exact copy of that render is ours too. if [ -n "$src_md" ]; then - render_md="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}/$(basename "$(dirname "$src_md")")/SKILL.md" + render_md="${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}/$(basename "$(dirname "$src_md")")/SKILL.md" [ -f "$render_md" ] && cmp -s "$entry/SKILL.md" "$render_md" && return 0 fi _gstack_generated_header "$entry/SKILL.md" && return 0 @@ -389,7 +392,7 @@ _claude_entry_owned_strongly() { } # Weakly-proven real files we would otherwise overwrite are moved here (mv, so # the path is free for the link); the final summary prints one line. -_SKILL_BACKUP_ROOT="${GSTACK_HOME:-$HOME/.gstack}/backups/skills/$(date +%Y%m%dT%H%M%S)" +_SKILL_BACKUP_ROOT="$GSTACK_STATE_ROOT/backups/skills/$(date +%Y%m%dT%H%M%S)" _BACKED_UP_SKILL_MDS=() _backup_skill_md() { # Returns non-zero when the file could NOT be moved: the caller must then @@ -1620,7 +1623,7 @@ link_claude_skill_dirs() { # file's section-base paths point into the render dir, so section reads # resolve there too. _skill_md_src="$gstack_dir/$dir_name/SKILL.md" - _render_dir="${GSTACK_USER_RENDER_DIR:-${GSTACK_HOME:-$HOME/.gstack}/render/claude}" + _render_dir="${GSTACK_USER_RENDER_DIR:-$GSTACK_STATE_ROOT/render/claude}" if [ -f "$_render_dir/$dir_name/SKILL.md" ]; then _skill_md_src="$_render_dir/$dir_name/SKILL.md" fi @@ -2868,7 +2871,7 @@ fi # Users who install gbrain after running ./setup should re-run setup OR # call `gstack-config gbrain-refresh`. DETECT_BIN="$SOURCE_GSTACK_DIR/bin/gstack-gbrain-detect" -GBRAIN_STATE_DIR="${GSTACK_HOME:-$HOME/.gstack}" +GBRAIN_STATE_DIR="$GSTACK_STATE_ROOT" DETECTION_FILE="$GBRAIN_STATE_DIR/gbrain-detection.json" _GSTACK_RENDER_DIR="${GSTACK_USER_RENDER_DIR:-$GBRAIN_STATE_DIR/render/claude}" # PID-unique tmp so concurrent setups (parallel Conductor workspaces) can't @@ -3290,8 +3293,10 @@ fi # posture). An explicit answer is persisted and never re-asked; an explicit # "false" is a recorded decline (adversarial review finding 11). # `gstack-config get` defaults absent keys to "false", which is -# indistinguishable from a decline — test key presence in the config file. -_GSTACK_CFG_FILE="${GSTACK_HOME:-$HOME/.gstack}/config.yaml" +# indistinguishable from a decline — test key presence in the config file +# of the resolved state root (the twin beside gstack-config). +. "$(dirname "$GSTACK_CONFIG")/gstack-state-root.sh" 2>/dev/null && gstack_state_root_select +_GSTACK_CFG_FILE="${_gstack_sr_root:-$GSTACK_STATE_ROOT}/config.yaml" if ! grep -q '^redact_prepush_hook:' "$_GSTACK_CFG_FILE" 2>/dev/null; then if [ "$QUIET" -ne 1 ] && [ -t 0 ] && [ -t 1 ]; then _REDACT_PROMPT_TIMEOUT=10 diff --git a/setup-deploy/SKILL.md b/setup-deploy/SKILL.md index 20e90c26fb..e104d19bae 100644 --- a/setup-deploy/SKILL.md +++ b/setup-deploy/SKILL.md @@ -239,7 +239,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.md index 37029db047..342b74bd9b 100644 --- a/setup-gbrain/SKILL.md +++ b/setup-gbrain/SKILL.md @@ -238,7 +238,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -905,10 +906,11 @@ configured Mac is a first-class doctor path: every step detects existing state, repairs only what's missing, and reports here. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" ~/.claude/skills/gstack/bin/gstack-gbrain-detect 2>/dev/null || true ~/.claude/skills/gstack/bin/gstack-config get transcript_ingest_mode 2>/dev/null || echo "off" ~/.claude/skills/gstack/bin/gstack-config get artifacts_sync_mode 2>/dev/null || echo "off" -[ -f ~/.gstack/.gbrain-sync-state.json ] && cat ~/.gstack/.gbrain-sync-state.json || echo "{}" +[ -f "$GSTACK_STATE_ROOT"/.gbrain-sync-state.json ] && cat "$GSTACK_STATE_ROOT"/.gbrain-sync-state.json || echo "{}" ``` Read `gbrain_mcp_mode` from the detect output and pick the right verdict @@ -1040,13 +1042,14 @@ this at build time. failures are not evidence of a competing run: ```bash - if ! mkdir -p ~/.gstack; then - echo "ERROR: Cannot create setup-gbrain lock parent ~/.gstack." >&2 + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + if ! mkdir -p "$GSTACK_STATE_ROOT"; then + echo "ERROR: Cannot create setup-gbrain lock parent $GSTACK_STATE_ROOT." >&2 exit 1 fi - if ! mkdir ~/.gstack/.setup-gbrain.lock.d; then - if [ -d ~/.gstack/.setup-gbrain.lock.d ]; then - echo "Another /setup-gbrain instance is running. Wait for it, or remove ~/.gstack/.setup-gbrain.lock.d only if you are sure it is stale." >&2 + if ! mkdir "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; then + if [ -d "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d ]; then + echo "Another /setup-gbrain instance is running. Wait for it, or remove $GSTACK_STATE_ROOT/.setup-gbrain.lock.d only if you are sure it is stale." >&2 else echo "ERROR: Cannot acquire setup-gbrain lock." >&2 fi diff --git a/setup-gbrain/SKILL.md.tmpl b/setup-gbrain/SKILL.md.tmpl index 4fb40d7505..0510826210 100644 --- a/setup-gbrain/SKILL.md.tmpl +++ b/setup-gbrain/SKILL.md.tmpl @@ -543,10 +543,11 @@ configured Mac is a first-class doctor path: every step detects existing state, repairs only what's missing, and reports here. ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" ~/.claude/skills/gstack/bin/gstack-gbrain-detect 2>/dev/null || true ~/.claude/skills/gstack/bin/gstack-config get transcript_ingest_mode 2>/dev/null || echo "off" ~/.claude/skills/gstack/bin/gstack-config get artifacts_sync_mode 2>/dev/null || echo "off" -[ -f ~/.gstack/.gbrain-sync-state.json ] && cat ~/.gstack/.gbrain-sync-state.json || echo "{}" +[ -f "$GSTACK_STATE_ROOT"/.gbrain-sync-state.json ] && cat "$GSTACK_STATE_ROOT"/.gbrain-sync-state.json || echo "{}" ``` Read `gbrain_mcp_mode` from the detect output and pick the right verdict @@ -678,13 +679,14 @@ this at build time. failures are not evidence of a competing run: ```bash - if ! mkdir -p ~/.gstack; then - echo "ERROR: Cannot create setup-gbrain lock parent ~/.gstack." >&2 + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + if ! mkdir -p "$GSTACK_STATE_ROOT"; then + echo "ERROR: Cannot create setup-gbrain lock parent $GSTACK_STATE_ROOT." >&2 exit 1 fi - if ! mkdir ~/.gstack/.setup-gbrain.lock.d; then - if [ -d ~/.gstack/.setup-gbrain.lock.d ]; then - echo "Another /setup-gbrain instance is running. Wait for it, or remove ~/.gstack/.setup-gbrain.lock.d only if you are sure it is stale." >&2 + if ! mkdir "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; then + if [ -d "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d ]; then + echo "Another /setup-gbrain instance is running. Wait for it, or remove $GSTACK_STATE_ROOT/.setup-gbrain.lock.d only if you are sure it is stale." >&2 else echo "ERROR: Cannot acquire setup-gbrain lock." >&2 fi diff --git a/ship/SKILL.md b/ship/SKILL.md index 263b7645ce..5121588496 100644 --- a/ship/SKILL.md +++ b/ship/SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -350,7 +351,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -1051,7 +1053,8 @@ git config --get core.hooksPath >/dev/null 2>&1 || _HOOKS_CONFIG_STATUS=$? if [ -n "$_HOOK_PATH" ] && [ -n "$_HOOKS_DIR" ] && [ "$_HOOKS_CONFIG_STATUS" = "1" ] && [ ! -L "$_HOOKS_DIR" ]; then _HOOKS_IN_GIT_DIR="yes" fi -_PREPUSH_PROMPTED=$([ -f "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" ] && echo "yes" || echo "no") +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PREPUSH_PROMPTED=$([ -f "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ] && echo "yes" || echo "no") if [ "$_REDACT_PREPUSH" = "true" ] && [ "$_HOOKS_IN_GIT_DIR" = "yes" ] && [ "$_HOOK_STATE" != "unmanaged" ]; then ~/.claude/skills/gstack/bin/gstack-redact install-prepush-hook || exit $? fi @@ -1088,7 +1091,8 @@ Branch on the echoed values: ALWAYS (after either answer, but NOT if the question itself failed to render — a failed AskUserQuestion must re-offer next time): ```bash - touch "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ``` 3. **Declined earlier** — continue without comment. @@ -1174,8 +1178,7 @@ The shell supplies the branch. Run this automatically, without confirmation. After a successful ship, show the non-blocking /plan-tune nudge once per machine: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" -export GSTACK_STATE_ROOT +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _NUDGE_MARKER="$GSTACK_STATE_ROOT/.plan-tune-nudge-shown" _QT=$(~/.claude/skills/gstack/bin/gstack-config get question_tuning 2>/dev/null || echo "false") if [ ! -f "$_NUDGE_MARKER" ] && [ "$_QT" = "false" ]; then diff --git a/ship/SKILL.md.tmpl b/ship/SKILL.md.tmpl index 89f3837784..1154b6dcf5 100644 --- a/ship/SKILL.md.tmpl +++ b/ship/SKILL.md.tmpl @@ -500,7 +500,8 @@ git config --get core.hooksPath >/dev/null 2>&1 || _HOOKS_CONFIG_STATUS=$? if [ -n "$_HOOK_PATH" ] && [ -n "$_HOOKS_DIR" ] && [ "$_HOOKS_CONFIG_STATUS" = "1" ] && [ ! -L "$_HOOKS_DIR" ]; then _HOOKS_IN_GIT_DIR="yes" fi -_PREPUSH_PROMPTED=$([ -f "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" ] && echo "yes" || echo "no") +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PREPUSH_PROMPTED=$([ -f "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ] && echo "yes" || echo "no") if [ "$_REDACT_PREPUSH" = "true" ] && [ "$_HOOKS_IN_GIT_DIR" = "yes" ] && [ "$_HOOK_STATE" != "unmanaged" ]; then ~/.claude/skills/gstack/bin/gstack-redact install-prepush-hook || exit $? fi @@ -537,7 +538,8 @@ Branch on the echoed values: ALWAYS (after either answer, but NOT if the question itself failed to render — a failed AskUserQuestion must re-offer next time): ```bash - touch "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ``` 3. **Declined earlier** — continue without comment. @@ -622,8 +624,7 @@ The shell supplies the branch. Run this automatically, without confirmation. After a successful ship, show the non-blocking /plan-tune nudge once per machine: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" -export GSTACK_STATE_ROOT +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _NUDGE_MARKER="$GSTACK_STATE_ROOT/.plan-tune-nudge-shown" _QT=$(~/.claude/skills/gstack/bin/gstack-config get question_tuning 2>/dev/null || echo "false") if [ ! -f "$_NUDGE_MARKER" ] && [ "$_QT" = "false" ]; then diff --git a/ship/sections/pr-body.md b/ship/sections/pr-body.md index f784e36f5d..fb2c0f2cbd 100644 --- a/ship/sections/pr-body.md +++ b/ship/sections/pr-body.md @@ -10,7 +10,7 @@ then return here for a new lookup, fresh body and both redaction scans before pu 1. Resolve the archive directory and branch: ```bash - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug)" CURRENT_BRANCH=$(git branch --show-current) SPEC_ARCHIVES="$GSTACK_STATE_ROOT/projects/$SLUG/specs" diff --git a/ship/sections/pr-body.md.tmpl b/ship/sections/pr-body.md.tmpl index aa098242da..3a7b15e926 100644 --- a/ship/sections/pr-body.md.tmpl +++ b/ship/sections/pr-body.md.tmpl @@ -8,7 +8,7 @@ then return here for a new lookup, fresh body and both redaction scans before pu 1. Resolve the archive directory and branch: ```bash - eval "$(~/.claude/skills/gstack/bin/gstack-paths)" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug)" CURRENT_BRANCH=$(git branch --show-current) SPEC_ARCHIVES="$GSTACK_STATE_ROOT/projects/$SLUG/specs" diff --git a/ship/sections/test-coverage.md b/ship/sections/test-coverage.md index a8020e1f83..8759b758f7 100644 --- a/ship/sections/test-coverage.md +++ b/ship/sections/test-coverage.md @@ -288,12 +288,13 @@ Coverage line: `Test Coverage Audit: N new code paths. M covered (Y% any test, X After producing the coverage diagram, write a test plan artifact so `/qa` and `/qa-only` can consume it: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) ``` -Write to `~/.gstack/projects/{slug}/{user}-{branch}-ship-test-plan-{datetime}.md`: +Write to `/{user}-{branch}-ship-test-plan-{datetime}.md` (`PROJECT_DIR` printed above): ```markdown # Test Plan diff --git a/skillify/SKILL.md b/skillify/SKILL.md index 759b9d327a..23e038c963 100644 --- a/skillify/SKILL.md +++ b/skillify/SKILL.md @@ -237,7 +237,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/spec/SKILL.md b/spec/SKILL.md index c07a362d96..b65e2f6b1f 100644 --- a/spec/SKILL.md +++ b/spec/SKILL.md @@ -238,7 +238,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -348,7 +349,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol diff --git a/spec/sections/gate-and-file.md b/spec/sections/gate-and-file.md index 95186ca9d6..fa2941b6b6 100644 --- a/spec/sections/gate-and-file.md +++ b/spec/sections/gate-and-file.md @@ -287,7 +287,7 @@ Resolve the archive path via the existing `gstack-paths` helper (handles `GSTACK_HOME`, `CLAUDE_PLUGIN_DATA`, Windows fallback): ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug)" ARCHIVE_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/specs" mkdir -p "$ARCHIVE_DIR" diff --git a/spec/sections/gate-and-file.md.tmpl b/spec/sections/gate-and-file.md.tmpl index 975db7d18e..9bd0ec7f80 100644 --- a/spec/sections/gate-and-file.md.tmpl +++ b/spec/sections/gate-and-file.md.tmpl @@ -156,7 +156,7 @@ Resolve the archive path via the existing `gstack-paths` helper (handles `GSTACK_HOME`, `CLAUDE_PLUGIN_DATA`, Windows fallback): ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$(~/.claude/skills/gstack/bin/gstack-slug)" ARCHIVE_DIR="$GSTACK_STATE_ROOT/projects/$SLUG/specs" mkdir -p "$ARCHIVE_DIR" diff --git a/sync-gbrain/SKILL.md b/sync-gbrain/SKILL.md index bf60cfae39..610df456cf 100644 --- a/sync-gbrain/SKILL.md +++ b/sync-gbrain/SKILL.md @@ -239,7 +239,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 diff --git a/test-audit/SKILL.md b/test-audit/SKILL.md index 2246b78d97..591346ce3d 100644 --- a/test-audit/SKILL.md +++ b/test-audit/SKILL.md @@ -234,7 +234,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -426,15 +427,17 @@ Retirement card, complete before any edit: `test`, `detects`, `non_test_callers` ## Step 1: Scope and seeds ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat -eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" DATETIME=$(date +%Y%m%d-%H%M%S) -REPORT=~/.gstack/projects/$SLUG/test-audit-$DATETIME.md +REPORT="$GSTACK_STATE_ROOT"/projects/$SLUG/test-audit-$DATETIME.md DEFAULT_BRANCH=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||') echo "REPORT: $REPORT" echo "DEFAULT_BRANCH: ${DEFAULT_BRANCH:-unknown}" git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/' -ls -t ~/.gstack/projects/$SLUG/*-"$BRANCH"-eng-review-test-plan-*.md 2>/dev/null | head -1 | sed 's/^/SEED_PLAN:/' +ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-"$BRANCH"-eng-review-test-plan-*.md 2>/dev/null | head -1 | sed 's/^/SEED_PLAN:/' ``` - Scope is the paths given, else the whole repository. With more than 300 test files diff --git a/test-audit/SKILL.md.tmpl b/test-audit/SKILL.md.tmpl index 1507bab549..6158ed0b27 100644 --- a/test-audit/SKILL.md.tmpl +++ b/test-audit/SKILL.md.tmpl @@ -48,15 +48,16 @@ repo, 10 candidates). ## Step 1: Scope and seeds ```bash +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" setopt +o nomatch 2>/dev/null || true # zsh compat {{SLUG_SETUP}} DATETIME=$(date +%Y%m%d-%H%M%S) -REPORT=~/.gstack/projects/$SLUG/test-audit-$DATETIME.md +REPORT="$GSTACK_STATE_ROOT"/projects/$SLUG/test-audit-$DATETIME.md DEFAULT_BRANCH=$(git symbolic-ref --short refs/remotes/origin/HEAD 2>/dev/null | sed 's|^origin/||') echo "REPORT: $REPORT" echo "DEFAULT_BRANCH: ${DEFAULT_BRANCH:-unknown}" git ls-files | grep -cE '(^|/)(tests?|spec|__tests__)/|(^|/)test_[^/]+\.py$|_test\.(go|py|rb|ts|js|exs)$|\.(test|spec)\.[jt]sx?$|_spec\.rb$|Test\.(java|kt)$' | sed 's/^/TESTFILES:/' -ls -t ~/.gstack/projects/$SLUG/*-"$BRANCH"-eng-review-test-plan-*.md 2>/dev/null | head -1 | sed 's/^/SEED_PLAN:/' +ls -t "$GSTACK_STATE_ROOT"/projects/$SLUG/*-"$BRANCH"-eng-review-test-plan-*.md 2>/dev/null | head -1 | sed 's/^/SEED_PLAN:/' ``` - Scope is the paths given, else the whole repository. With more than 300 test files diff --git a/test-setup.ts b/test-setup.ts index fb742ab2df..703917e85f 100644 --- a/test-setup.ts +++ b/test-setup.ts @@ -16,6 +16,24 @@ * stays dead. */ import { afterEach, beforeAll } from 'bun:test'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +// State-root hermeticity (docs/state-root.md). Tests isolate state with +// GSTACK_HOME, but GSTACK_STATE_ROOT and GSTACK_STATE_DIR outrank or join it +// in the chain, so an ambient value from the parent shell would redirect +// every test's state. Strip them before any test module loads. The merged +// privacy keys also read $HOME/.gstack; point that second root at a +// per-process path that is never created (an empty root that leaves no +// residue in fixtures that audit their temp dirs), so a developer's real +// config never changes a result (only the dedicated merge tests unset +// GSTACK_TEST_LEGACY_ROOT). +for (const name of ['GSTACK_STATE_ROOT', 'GSTACK_STATE_DIR']) { + if (process.env[name] === undefined) continue; + delete process.env[name]; + process.stderr.write(`test-setup: stripped inherited ${name}; tests isolate state via GSTACK_HOME\n`); +} +process.env.GSTACK_TEST_LEGACY_ROOT = path.join(os.tmpdir(), `gstack-test-legacy-root-${process.pid}-${Date.now()}-unused`); // Narrowly restore PATH after every test. Defends against the recurring // pollution class where one test sets `process.env.PATH = '/test/bin:/usr/bin'` diff --git a/test/fixtures/context-budget.json b/test/fixtures/context-budget.json index aea3dabd0e..6069603b62 100644 --- a/test/fixtures/context-budget.json +++ b/test/fixtures/context-budget.json @@ -62,6 +62,6 @@ "spec": 14993, "sync-gbrain": 13975, "test-audit": 10439, - "unfreeze": 393 + "unfreeze": 448 } } diff --git a/test/fixtures/golden/claude-ship-SKILL.md b/test/fixtures/golden/claude-ship-SKILL.md index 263b7645ce..5121588496 100644 --- a/test/fixtures/golden/claude-ship-SKILL.md +++ b/test/fixtures/golden/claude-ship-SKILL.md @@ -240,7 +240,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$(~/.claude/skills/gstack/bin/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -350,7 +351,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -1051,7 +1053,8 @@ git config --get core.hooksPath >/dev/null 2>&1 || _HOOKS_CONFIG_STATUS=$? if [ -n "$_HOOK_PATH" ] && [ -n "$_HOOKS_DIR" ] && [ "$_HOOKS_CONFIG_STATUS" = "1" ] && [ ! -L "$_HOOKS_DIR" ]; then _HOOKS_IN_GIT_DIR="yes" fi -_PREPUSH_PROMPTED=$([ -f "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" ] && echo "yes" || echo "no") +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PREPUSH_PROMPTED=$([ -f "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ] && echo "yes" || echo "no") if [ "$_REDACT_PREPUSH" = "true" ] && [ "$_HOOKS_IN_GIT_DIR" = "yes" ] && [ "$_HOOK_STATE" != "unmanaged" ]; then ~/.claude/skills/gstack/bin/gstack-redact install-prepush-hook || exit $? fi @@ -1088,7 +1091,8 @@ Branch on the echoed values: ALWAYS (after either answer, but NOT if the question itself failed to render — a failed AskUserQuestion must re-offer next time): ```bash - touch "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" + eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ``` 3. **Declined earlier** — continue without comment. @@ -1174,8 +1178,7 @@ The shell supplies the branch. Run this automatically, without confirmation. After a successful ship, show the non-blocking /plan-tune nudge once per machine: ```bash -eval "$(~/.claude/skills/gstack/bin/gstack-paths)" -export GSTACK_STATE_ROOT +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _NUDGE_MARKER="$GSTACK_STATE_ROOT/.plan-tune-nudge-shown" _QT=$(~/.claude/skills/gstack/bin/gstack-config get question_tuning 2>/dev/null || echo "false") if [ ! -f "$_NUDGE_MARKER" ] && [ "$_QT" = "false" ]; then diff --git a/test/fixtures/golden/codex-ship-SKILL.md b/test/fixtures/golden/codex-ship-SKILL.md index 19f116cd9f..28fcd5c0d8 100644 --- a/test/fixtures/golden/codex-ship-SKILL.md +++ b/test/fixtures/golden/codex-ship-SKILL.md @@ -248,7 +248,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$($GSTACK_BIN/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$($GSTACK_BIN/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -358,7 +359,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$($GSTACK_BIN/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -1415,12 +1417,13 @@ Coverage line: `Test Coverage Audit: N new code paths. M covered (Y% any test, X After producing the coverage diagram, write a test plan artifact so `/qa` and `/qa-only` can consume it: ```bash -eval "$($GSTACK_ROOT/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$($GSTACK_ROOT/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) ``` -Write to `~/.gstack/projects/{slug}/{user}-{branch}-ship-test-plan-{datetime}.md`: +Write to `/{user}-{branch}-ship-test-plan-{datetime}.md` (`PROJECT_DIR` printed above): ```markdown # Test Plan @@ -3162,7 +3165,8 @@ git config --get core.hooksPath >/dev/null 2>&1 || _HOOKS_CONFIG_STATUS=$? if [ -n "$_HOOK_PATH" ] && [ -n "$_HOOKS_DIR" ] && [ "$_HOOKS_CONFIG_STATUS" = "1" ] && [ ! -L "$_HOOKS_DIR" ]; then _HOOKS_IN_GIT_DIR="yes" fi -_PREPUSH_PROMPTED=$([ -f "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" ] && echo "yes" || echo "no") +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PREPUSH_PROMPTED=$([ -f "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ] && echo "yes" || echo "no") if [ "$_REDACT_PREPUSH" = "true" ] && [ "$_HOOKS_IN_GIT_DIR" = "yes" ] && [ "$_HOOK_STATE" != "unmanaged" ]; then $GSTACK_ROOT/bin/gstack-redact install-prepush-hook || exit $? fi @@ -3199,7 +3203,8 @@ Branch on the echoed values: ALWAYS (after either answer, but NOT if the question itself failed to render — a failed AskUserQuestion must re-offer next time): ```bash - touch "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" + eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ``` 3. **Declined earlier** — continue without comment. @@ -3264,7 +3269,7 @@ then return here for a new lookup, fresh body and both redaction scans before pu 1. Resolve the archive directory and branch: ```bash - eval "$($GSTACK_ROOT/bin/gstack-paths)" + eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$($GSTACK_ROOT/bin/gstack-slug)" CURRENT_BRANCH=$(git branch --show-current) SPEC_ARCHIVES="$GSTACK_STATE_ROOT/projects/$SLUG/specs" @@ -3453,8 +3458,7 @@ The shell supplies the branch. Run this automatically, without confirmation. After a successful ship, show the non-blocking /plan-tune nudge once per machine: ```bash -eval "$($GSTACK_ROOT/bin/gstack-paths)" -export GSTACK_STATE_ROOT +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _NUDGE_MARKER="$GSTACK_STATE_ROOT/.plan-tune-nudge-shown" _QT=$($GSTACK_ROOT/bin/gstack-config get question_tuning 2>/dev/null || echo "false") if [ ! -f "$_NUDGE_MARKER" ] && [ "$_QT" = "false" ]; then diff --git a/test/fixtures/golden/factory-ship-SKILL.md b/test/fixtures/golden/factory-ship-SKILL.md index 6eae0bc5b9..74c2d27309 100644 --- a/test/fixtures/golden/factory-ship-SKILL.md +++ b/test/fixtures/golden/factory-ship-SKILL.md @@ -228,7 +228,8 @@ At session start or after compaction, recover recent project context. ```bash eval "$($GSTACK_BIN/gstack-slug 2>/dev/null)" _BRANCH=$(git branch --show-current 2>/dev/null | tr -cd 'a-zA-Z0-9._/-') || :; _BRANCH=${_BRANCH:-unknown} -_PROJ="${GSTACK_HOME:-$HOME/.gstack}/projects/${SLUG:-unknown}" +eval "$($GSTACK_BIN/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PROJ="$GSTACK_STATE_ROOT/projects/${SLUG:-unknown}" if [ -d "$_PROJ" ]; then echo "--- RECENT ARTIFACTS ---" find "$_PROJ/ceo-plans" "$_PROJ/checkpoints" -type f -name "*.md" 2>/dev/null | xargs -r ls -t 2>/dev/null | head -3 @@ -338,7 +339,8 @@ Then build the complete version of what remains. **Eureka:** When first-principles reasoning contradicts conventional wisdom, name it and log: ```bash -jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +eval "$($GSTACK_BIN/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> "$GSTACK_STATE_ROOT/analytics/eureka.jsonl" 2>/dev/null || true ``` ## Completion Status Protocol @@ -1395,12 +1397,13 @@ Coverage line: `Test Coverage Audit: N new code paths. M covered (Y% any test, X After producing the coverage diagram, write a test plan artifact so `/qa` and `/qa-only` can consume it: ```bash -eval "$($GSTACK_ROOT/bin/gstack-slug 2>/dev/null)" && mkdir -p ~/.gstack/projects/$SLUG +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +eval "$($GSTACK_ROOT/bin/gstack-slug 2>/dev/null)" && mkdir -p "$GSTACK_STATE_ROOT/projects/$SLUG" && echo "PROJECT_DIR: $GSTACK_STATE_ROOT/projects/$SLUG" USER=$(whoami) DATETIME=$(date +%Y%m%d-%H%M%S) ``` -Write to `~/.gstack/projects/{slug}/{user}-{branch}-ship-test-plan-{datetime}.md`: +Write to `/{user}-{branch}-ship-test-plan-{datetime}.md` (`PROJECT_DIR` printed above): ```markdown # Test Plan @@ -3428,7 +3431,8 @@ git config --get core.hooksPath >/dev/null 2>&1 || _HOOKS_CONFIG_STATUS=$? if [ -n "$_HOOK_PATH" ] && [ -n "$_HOOKS_DIR" ] && [ "$_HOOKS_CONFIG_STATUS" = "1" ] && [ ! -L "$_HOOKS_DIR" ]; then _HOOKS_IN_GIT_DIR="yes" fi -_PREPUSH_PROMPTED=$([ -f "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" ] && echo "yes" || echo "no") +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +_PREPUSH_PROMPTED=$([ -f "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ] && echo "yes" || echo "no") if [ "$_REDACT_PREPUSH" = "true" ] && [ "$_HOOKS_IN_GIT_DIR" = "yes" ] && [ "$_HOOK_STATE" != "unmanaged" ]; then $GSTACK_ROOT/bin/gstack-redact install-prepush-hook || exit $? fi @@ -3465,7 +3469,8 @@ Branch on the echoed values: ALWAYS (after either answer, but NOT if the question itself failed to render — a failed AskUserQuestion must re-offer next time): ```bash - touch "${GSTACK_HOME:-$HOME/.gstack}/.redact-prepush-prompted" + eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" + touch "$GSTACK_STATE_ROOT/.redact-prepush-prompted" ``` 3. **Declined earlier** — continue without comment. @@ -3530,7 +3535,7 @@ then return here for a new lookup, fresh body and both redaction scans before pu 1. Resolve the archive directory and branch: ```bash - eval "$($GSTACK_ROOT/bin/gstack-paths)" + eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" eval "$($GSTACK_ROOT/bin/gstack-slug)" CURRENT_BRANCH=$(git branch --show-current) SPEC_ARCHIVES="$GSTACK_STATE_ROOT/projects/$SLUG/specs" @@ -3719,8 +3724,7 @@ The shell supplies the branch. Run this automatically, without confirmation. After a successful ship, show the non-blocking /plan-tune nudge once per machine: ```bash -eval "$($GSTACK_ROOT/bin/gstack-paths)" -export GSTACK_STATE_ROOT +eval "$($GSTACK_ROOT/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" _NUDGE_MARKER="$GSTACK_STATE_ROOT/.plan-tune-nudge-shown" _QT=$($GSTACK_ROOT/bin/gstack-config get question_tuning 2>/dev/null || echo "false") if [ ! -f "$_NUDGE_MARKER" ] && [ "$_QT" = "false" ]; then diff --git a/test/fixtures/state-root-selection-golden.json b/test/fixtures/state-root-selection-golden.json new file mode 100644 index 0000000000..71d41558f3 --- /dev/null +++ b/test/fixtures/state-root-selection-golden.json @@ -0,0 +1,64 @@ +{ + "recordedAt": "96764e80", + "note": "paid evals selected by touching each W1 source file, recorded on the base commit before the change", + "modules": { + "lib/state-root.ts": { + "sources": [ + "browse/src/config.ts", + "lib/cso/state.ts" + ], + "e2e": [ + "aside-browse-basic", + "aside-browse-flow", + "benchmark-workflow", + "browse-basic", + "browse-snapshot", + "canary-workflow", + "carve-section-loading", + "cso-diff-mode", + "cso-full-audit", + "cso-infra-scope", + "design-review-detector-shim-dom", + "design-review-fix", + "diagram-authoring-quality", + "diagram-triplet", + "qa-b6-static", + "qa-b7-spa", + "qa-b8-checkout", + "qa-fix-loop", + "qa-only-no-fix", + "qa-quick" + ], + "llmJudge": [ + "browse/SKILL.md reference" + ] + }, + "bin/gstack-state-root.sh": { + "sources": [ + "bin/gstack-paths", + "careful/bin/hook-extract.sh" + ], + "e2e": [ + "investigate-owned-abort", + "investigate-owned-completion", + "investigate-owned-ending-error", + "plan-design-with-ui-scope" + ], + "llmJudge": [] + }, + "hosts/claude/hooks/hook-log.ts": { + "sources": [ + "hosts/claude/hooks/question-log-hook.ts", + "hosts/claude/hooks/question-preference-hook.ts", + "hosts/claude/hooks/auq-error-fallback-hook.ts", + "hosts/claude/hooks/timeline-stop-hook.ts", + "hosts/claude/hooks/memorable-user-prompt-hook.ts" + ], + "e2e": [ + "auto-decide-preserved", + "docsync-spawned" + ], + "llmJudge": [] + } + } +} diff --git a/test/freeze-owned-lifecycle.test.ts b/test/freeze-owned-lifecycle.test.ts index 10a7223413..e3a2cf6b30 100644 --- a/test/freeze-owned-lifecycle.test.ts +++ b/test/freeze-owned-lifecycle.test.ts @@ -50,7 +50,7 @@ beforeEach(() => { env = { ...process.env, HOME: join(root, 'home'), GSTACK_HOME: join(root, 'state'), CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '' }; mkdirSync(env.GSTACK_HOME!); state = join(env.GSTACK_HOME!, 'freeze-dir.txt'); - for (const file of ['freeze/bin/check-freeze.sh', 'freeze/bin/freeze-state.sh', 'careful/bin/hook-extract.sh', 'bin/gstack-paths']) { + for (const file of ['freeze/bin/check-freeze.sh', 'freeze/bin/freeze-state.sh', 'careful/bin/hook-extract.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh']) { if (!existsSync(join(ROOT, file))) continue; const dest = join(env.HOME!, '.claude/skills/gstack', file); mkdirSync(dirname(dest), { recursive: true }); diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.ts index ce0918308a..e4999aa6a7 100644 --- a/test/gen-skill-docs.test.ts +++ b/test/gen-skill-docs.test.ts @@ -1936,6 +1936,7 @@ describe('BENEFITS_FROM resolver', () => { fs.mkdirSync(cwd); fs.copyFileSync(path.join(ROOT, 'bin/gstack-slug'), helper); fs.chmodSync(helper, 0o755); + fs.copyFileSync(path.join(ROOT, 'bin/gstack-state-root.sh'), path.join(path.dirname(helper), 'gstack-state-root.sh')); const expected = path.join(home, '.gstack/projects/canonical-override/session-unknown-design-current.md'); const wrong = path.join(home, '.gstack/projects/project/session-unknown-design-wrong.md'); for (const file of [expected, wrong]) { diff --git a/test/gstack-paths.test.ts b/test/gstack-paths.test.ts index a8a71c8f53..eee62b5b4a 100644 --- a/test/gstack-paths.test.ts +++ b/test/gstack-paths.test.ts @@ -271,3 +271,119 @@ describe('CEO plan persistence uses the selected state root', () => { } } }); + +describe('gstack-paths state-root contract (W1)', () => { + const DOC = 'https://github.com/garrytan/gstack/blob/main/docs/state-root.md'; + function runRaw(args: string[], env: Record, bin = BIN) { + return spawnSync('bash', [bin, ...args], { + env: { PATH: process.env.PATH, USERPROFILE: '', TMPDIR: os.tmpdir(), ...env } as Record, + encoding: 'utf-8', + timeout: 30_000, + }); + } + + test('GSTACK_STATE_ROOT and GSTACK_STATE_DIR join the chain in declared precedence', () => { + expect(run({ HOME: '/tmp/home', GSTACK_STATE_ROOT: '/tmp/a', GSTACK_HOME: '/tmp/b' }).GSTACK_STATE_ROOT).toBe('/tmp/a'); + expect(run({ HOME: '/tmp/home', GSTACK_STATE_DIR: '/tmp/c' }).GSTACK_STATE_ROOT).toBe('/tmp/c'); + expect(run({ HOME: '/tmp/home', GSTACK_HOME: '/tmp/b', GSTACK_STATE_DIR: '/tmp/c' }).GSTACK_STATE_ROOT).toBe('/tmp/b'); + expect(run({ HOME: '/tmp/home', GSTACK_STATE_DIR: '/tmp/c', CLAUDE_PLUGIN_DATA: '/tmp/p', CLAUDE_PLUGIN_ROOT: '/x/gstack' }).GSTACK_STATE_ROOT).toBe('/tmp/c'); + }); + + test('reading its own output back as input returns the same root', () => { + const env = { HOME: '/tmp/home', GSTACK_HOME: '/tmp/b', GSTACK_STATE_DIR: '/tmp/c' }; + const first = run(env).GSTACK_STATE_ROOT; + expect(run({ ...env, GSTACK_STATE_ROOT: first }).GSTACK_STATE_ROOT).toBe(first); + }); + + test('stderr is empty on success, even with disagreeing root variables', () => { + const r = runRaw([], { HOME: '/tmp/home', GSTACK_STATE_ROOT: '/tmp/a', GSTACK_HOME: '/tmp/b', GSTACK_STATE_DIR: '/tmp/c' }); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + }); + + test('--explain golden: default environment', () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-explain-')); + try { + const r = runRaw(['--explain'], { HOME: home, GSTACK_TEST_LEGACY_ROOT: '' }); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + expect(r.stdout).toBe([ + `state root: ${home}/.gstack (selected by default)`, + 'chain (first non-empty wins):', + ' GSTACK_STATE_ROOT unset', + ' GSTACK_HOME unset', + ' GSTACK_STATE_DIR unset', + ' CLAUDE_PLUGIN_DATA unset', + ` default ${home}/.gstack selected`, + 'merged privacy keys (most restrictive value across roots wins):', + ' telemetry: not set (default applies)', + ' memorable_recall: not set (default applies)', + ' codex_reviews: not set (default applies)', + ' update_check: not set (default applies)', + `docs: ${DOC}`, + '', + ].join('\n')); + expect(fs.readdirSync(home)).toEqual([]); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + + test('--explain golden: disagreeing environment with state in $HOME/.gstack', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-explain-')); + const home = path.join(tmp, 'home'); + const a = path.join(tmp, 'a'); + try { + fs.mkdirSync(path.join(home, '.gstack'), { recursive: true }); + fs.writeFileSync(path.join(home, '.gstack', 'config.yaml'), 'telemetry: off\ncodex_reviews: disabled\n'); + fs.mkdirSync(a); + fs.writeFileSync(path.join(a, 'config.yaml'), 'telemetry: community\nupdate_check: true\n'); + const r = runRaw(['--explain'], { + HOME: home, GSTACK_TEST_LEGACY_ROOT: '', GSTACK_STATE_ROOT: a, GSTACK_HOME: '/tmp/b', + CLAUDE_PLUGIN_DATA: '/tmp/p', CLAUDE_PLUGIN_ROOT: '/plugins/codex', + }); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + expect(r.stdout).toBe([ + `state root: ${a} (selected by GSTACK_STATE_ROOT)`, + 'chain (first non-empty wins):', + ` GSTACK_STATE_ROOT ${a} selected`, + ' GSTACK_HOME /tmp/b ignored', + ' GSTACK_STATE_DIR unset', + ' CLAUDE_PLUGIN_DATA /tmp/p ignored', + ` default ${home}/.gstack ignored`, + `default root ${home}/.gstack also holds gstack state: yes`, + 'merged privacy keys (most restrictive value across roots wins):', + ` telemetry: off (from ${home}/.gstack/config.yaml)`, + ' memorable_recall: not set (default applies)', + ` codex_reviews: disabled (from ${home}/.gstack/config.yaml)`, + ` update_check: true (from ${a}/config.yaml)`, + `docs: ${DOC}`, + '', + ].join('\n')); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + test('a missing bin/gstack-state-root.sh fails stop: nonzero, empty stdout, message, no writes', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-paths-broken-')); + try { + const bin = path.join(tmp, 'bin'); + fs.mkdirSync(bin); + fs.copyFileSync(BIN, path.join(bin, 'gstack-paths')); + const tmpRoot = path.join(tmp, 'tmproot'); + const r = runRaw([], { HOME: path.join(tmp, 'home'), TMPDIR: tmpRoot }, path.join(bin, 'gstack-paths')); + expect(r.status).not.toBe(0); + expect(r.stdout).toBe(''); + expect(r.stderr).toContain('gstack-paths: cannot resolve the gstack state root'); + expect(r.stderr).toContain(path.join(bin, 'gstack-state-root.sh')); + expect(r.stderr).toContain('./setup'); + expect(r.stderr).toContain('/gstack-upgrade'); + expect(r.stderr).toContain(DOC); + expect(fs.readdirSync(tmp).sort()).toEqual(['bin']); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/gstack-skill-start.test.ts b/test/gstack-skill-start.test.ts index f2b133ab42..e6549c666c 100644 --- a/test/gstack-skill-start.test.ts +++ b/test/gstack-skill-start.test.ts @@ -168,6 +168,7 @@ describe('gstack-skill-start behavior', () => { // Shadow the real bin dir by copying the script next to the poisoned tool. fs.copyFileSync(START, path.join(fakeBin, 'gstack-skill-start')); fs.chmodSync(path.join(fakeBin, 'gstack-skill-start'), 0o755); + fs.copyFileSync(path.join(path.dirname(START), 'gstack-state-root.sh'), path.join(fakeBin, 'gstack-state-root.sh')); const out = execFileSync(path.join(fakeBin, 'gstack-skill-start'), ['--skill', 't'], { timeout: 30_000, encoding: 'utf-8', diff --git a/test/helpers/carve-guards.ts b/test/helpers/carve-guards.ts index 914bb07438..1fd607dc41 100644 --- a/test/helpers/carve-guards.ts +++ b/test/helpers/carve-guards.ts @@ -166,7 +166,7 @@ export const CARVE_GUARDS: Record = { // wave's headline capability) grows the union to 1.195x. Deliberate: // the section is on-demand (loads only for Apple store targets), so // per-invocation cost for non-iOS ships is one manifest line. - maxSizeRatio: 1.397, // Shared advisory identity/dedup + critical-severity validation: 248,065 union bytes / 187,706 baseline = 1.3216 (2026-09-17). + test value bar in the lazy Step 7 section (value cards, weak paths, gate table, base control, machine checks; ~13.6KB): measured 1.396 (2026-09-29). + maxSizeRatio: 1.402, // Shared advisory identity/dedup + critical-severity validation: 248,065 union bytes / 187,706 baseline = 1.3216 (2026-09-17). + test value bar in the lazy Step 7 section (value cards, weak paths, gate table, base control, machine checks; ~13.6KB): measured 1.396 (2026-09-29). + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.401 (2026-09-30). }, 'plan-ceo-review': { skill: 'plan-ceo-review', @@ -184,7 +184,7 @@ export const CARVE_GUARDS: Record = { // v1.65 merge: provisional larger-of-both-waves budget; re-measured below. // Fork port wave 2 (#703): the repo-doc-preference block in the design // check grew every plan-review skeleton ~0.7KB. Measured values noted. - maxSkeletonBytes: 80_150, // + depth-specific output and 0H/0I feasibility boundary clarity + the Aside probe's failure reason; measured 80,111. + maxSkeletonBytes: 80_700, // + depth-specific output and 0H/0I feasibility boundary clarity + the Aside probe's failure reason; measured 80,111. + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 80,649 (2026-09-30). minUnionBytes: 123_600, // token-reduction Phases 1-2 (v1.69.x branch): preamble bash -> bin/gstack-skill-start, onboarding -> gated emission; measured union 137,346 mustContain: ['SCOPE EXPANSION', 'SELECTIVE EXPANSION', 'HOLD SCOPE', 'SCOPE REDUCTION'], // Default-on Codex outside-voice (codexPreflight block + CODEX_MODE branch @@ -221,7 +221,7 @@ export const CARVE_GUARDS: Record = { // 1.08 → 1.10: the scope-gate exceptions block (+ its adversarial-review // hardening: host-anchored mode signal, precedence, passing-mention // guards) and the plan-mode preamble reword land the union at 1.092. - maxSizeRatio: 1.169, // + clarity rules for saved decisions/setup gates + the Aside probe's failure reason; measured 1.1504. + test value bar and Tests to Retire in the lazy Test review section (~2.6KB); measured 1.168 + maxSizeRatio: 1.174, // + clarity rules for saved decisions/setup gates + the Aside probe's failure reason; measured 1.1504. + test value bar and Tests to Retire in the lazy Test review section (~2.6KB); measured 1.168 + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.173 (2026-09-30). }, 'plan-design-review': { skill: 'plan-design-review', @@ -407,7 +407,9 @@ do not launch the downstream skill or open a browser.`, // the cross-session decision-memory nudge) lands this carved skeleton just over // the strict 1.05; headroom for the shared preamble additions. // v1.64+v1.65 merge sums both waves' preamble growth; measured 1.073. - maxSizeRatio: 1.08, + // + W1 guarded state-root resolution in the Context Recovery preamble, the + // eureka log and the office-hours lookup; measured 1.082 (2026-09-30). + maxSizeRatio: 1.083, }, cso: { skill: 'cso', @@ -664,7 +666,7 @@ do not launch the downstream skill or open a browser.`, }, behavioral: 'prompt', maxSkeletonBytes: 63_500, // + v2.0 {{ASIDE_SETUP}}/{{BROWSE_FALLBACK}} (replaces the browse setup block); measured 61_253 - maxSizeRatio: 1.095, // + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + maxSizeRatio: 1.102, // + v1.81 Aside contract + gstack-browser fallback block (1.080 on v1.91.7.0) + the shared test value bar at 8a.5 ({{TEST_VALUE_BAR:qa}}); measured 1.094 + W1 guarded state-root resolution (`eval gstack-paths; : "${GSTACK_STATE_ROOT:?…}"`) in the Context Recovery preamble, the eureka log and each state-writing bash block; measured 1.101 (2026-09-30) minUnionBytes: 69_500, // measured union 70,385 // 'aside repl' pins the Aside contract; '$B goto' pins the fallback block in the always-loaded skeleton. mustContain: ['bug', 'aside repl', '$B goto', 'fix', 'Health Score Rubric', 'regression'], diff --git a/test/helpers/health-eval-fixture.ts b/test/helpers/health-eval-fixture.ts index 5abafefeca..bdadbf6a3f 100644 --- a/test/helpers/health-eval-fixture.ts +++ b/test/helpers/health-eval-fixture.ts @@ -52,6 +52,7 @@ export function createHealthEvalFixture(dir: string, repoRoot: string): HealthEv fs.mkdirSync(path.join(dir, 'bin'), { recursive: true }); fs.copyFileSync(path.join(repoRoot, 'bin', 'gstack-slug'), path.join(dir, 'bin', 'gstack-slug')); fs.chmodSync(path.join(dir, 'bin', 'gstack-slug'), 0o755); + fs.copyFileSync(path.join(repoRoot, 'bin', 'gstack-state-root.sh'), path.join(dir, 'bin', 'gstack-state-root.sh')); // Only redirect installed paths. The workflow and score/history rules come // from the real generated skill, without its unrelated shared preamble. diff --git a/test/helpers/touchfiles-data.ts b/test/helpers/touchfiles-data.ts index ae4fe6a003..4439fd4551 100644 --- a/test/helpers/touchfiles-data.ts +++ b/test/helpers/touchfiles-data.ts @@ -21,7 +21,7 @@ * Each test lists the file patterns that, if changed, require the test to run. */ export const E2E_TOUCHFILES: Record = { - 'ship-skipped-queued-finding': [ + 'ship-skipped-queued-finding': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'package.json', 'bun.lock', '.github/docker/Dockerfile.ci', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/sections.ts', 'scripts/resolvers/index.ts', 'scripts/resolvers/types.ts', 'scripts/gen-skill-docs.ts', 'scripts/host-config.ts', @@ -36,29 +36,29 @@ export const E2E_TOUCHFILES: Record = { 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eval-budgets.ts' ], - 'investigate-owned-completion': ['investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-completion.test.ts', 'test/helpers/e2e-gate.ts'], - 'investigate-owned-abort': ['investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-termination.test.ts', 'test/helpers/e2e-gate.ts'], - 'investigate-owned-ending-error': ['investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-termination.test.ts', 'test/helpers/e2e-gate.ts'], - 'shared-libs-review-path-eligibility': ['review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], - 'shared-libs-review-index-flags': ['review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-paths-max-turns-public.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], - 'shared-libs-review-prior-coverage': ['review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], + 'investigate-owned-completion': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-completion.test.ts', 'test/helpers/e2e-gate.ts'], + 'investigate-owned-abort': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-termination.test.ts', 'test/helpers/e2e-gate.ts'], + 'investigate-owned-ending-error': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'investigate/**', 'freeze/**', 'guard/**', 'unfreeze/**', 'careful/bin/hook-extract.sh', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/workflow-boundaries-fixture.ts', 'test/skill-e2e-investigate-owned-termination.test.ts', 'test/helpers/e2e-gate.ts'], + 'shared-libs-review-path-eligibility': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], + 'shared-libs-review-index-flags': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-paths-max-turns-public.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], + 'shared-libs-review-prior-coverage': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'review/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-paths.test.ts', 'test/helpers/shared-libs-path-fixture.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/fixtures/shared-libs-resolved-reads-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], 'shared-libs-codex-read-only': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'test/helpers/codex-session-runner.ts', 'test/helpers/skill-fixture.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/eval-budgets.ts', 'test/codex-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'hosts/codex.ts', 'hosts/define-host.ts', 'scripts/resolvers/constants.ts', 'test/fixtures/shared-libs-readonly-substitution-ci16358.json', 'test/helpers/agent-sdk-runner.ts'], // Shared-code audit and scoped review lifecycle 'shared-libs-read-only': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-readonly-substitution-ci16358.json', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/shared-libs-review-start-evidence.ts', 'test/helpers/shared-libs-path-fixture.ts'], 'shared-libs-unsupported-git': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-readonly-substitution-ci16358.json', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/shared-libs-review-start-evidence.ts', 'test/helpers/shared-libs-path-fixture.ts'], - 'shared-libs-review-lifecycle': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'review/**', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/helpers/shared-libs-path-fixture.ts', 'test/fixtures/shared-libs-lifecycle-r59-stage-scope-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], - 'shared-libs-review-revalidation': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'review/**', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/helpers/shared-libs-review-start-evidence.ts', 'test/fixtures/shared-libs-review-start-public.json', 'test/fixtures/shared-libs-revalidation-max-turns-public.json', 'test/fixtures/shared-libs-index-flags-*.json', 'test/helpers/shared-libs-path-fixture.ts' ], + 'shared-libs-review-lifecycle': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'review/**', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-index-flags-*.json', 'test/helpers/shared-libs-path-fixture.ts', 'test/fixtures/shared-libs-lifecycle-r59-stage-scope-public.json', 'test/helpers/shared-libs-review-start-evidence.ts'], + 'shared-libs-review-revalidation': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'review/**', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'lib/review-evidence.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'bin/gstack-wtree', 'test/skill-e2e-shared-libs.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/helpers/shared-libs-review-start-evidence.ts', 'test/fixtures/shared-libs-review-start-public.json', 'test/fixtures/shared-libs-revalidation-max-turns-public.json', 'test/fixtures/shared-libs-index-flags-*.json', 'test/helpers/shared-libs-path-fixture.ts' ], 'shared-libs-opportunity-judgment': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-periodic.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/llm-judge.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-readonly-substitution-ci16358.json', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/shared-libs-plan-actor.ts', 'test/helpers/shared-libs-plan-excerpt.ts'], 'shared-libs-pr-coverage': ['deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'test/skill-e2e-shared-libs-periodic.test.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/llm-judge.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts', 'test/fixtures/shared-libs-readonly-substitution-ci16358.json', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/shared-libs-plan-actor.ts', 'test/helpers/shared-libs-plan-excerpt.ts'], 'shared-libs-plan-callers': ['test/helpers/shared-libs-plan-actor.ts', 'scripts/resolvers/confidence.ts', 'test/helpers/shared-libs-plan-excerpt.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'deslop-shared-libs/**', 'scripts/resolvers/shared-libs.ts', 'scripts/resolvers/index.ts', 'test/helpers/shared-libs-eval-fixture.ts', 'plan-eng-review/**', 'test/skill-e2e-shared-libs-periodic.test.ts', 'test/fixtures/plan-scope-recovery-av.json', 'scripts/resolvers/preamble/generate-preamble-bash.ts', 'scripts/resolvers/preamble/generate-completion-status.ts', 'test/helpers/e2e-gate.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/agent-sdk-runner.ts', 'test/helpers/llm-judge.ts', 'lib/claude-bin.ts', 'lib/eval-model.ts'], - 'ship-docsync-missing-marker': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-missing-asset': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-launch-failure': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-timeout-unsettled': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-late-result': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-stale-before': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-stale-after': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], - 'ship-docsync-recovery': ['ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-missing-marker': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-missing-asset': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-launch-failure': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-timeout-unsettled': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-late-result': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-stale-before': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-stale-after': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], + 'ship-docsync-recovery': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/testing.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/docsync-*.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts'], 'review-exploratory-small-cli': ['bin/gstack-qa-evidence', 'lib/qa-evidence.ts', 'lib/fs-atomic.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-evidence.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'review/**', 'ship/**', 'qa/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'scripts/resolvers/sections.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/qa-callers-fixture.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-fixture.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/session-runner.ts', 'test/skill-e2e-qa-callers.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/skill-census.ts'], 'ship-exploratory-small-cli': ['bin/gstack-qa-evidence', 'lib/qa-evidence.ts', 'lib/fs-atomic.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-evidence.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'review/**', 'ship/**', 'qa/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'scripts/resolvers/sections.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/qa-callers-fixture.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-fixture.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/session-runner.ts', 'test/skill-e2e-qa-callers.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/skill-census.ts'], 'ship-exploratory-unavailable': ['bin/gstack-qa-evidence', 'lib/qa-evidence.ts', 'lib/fs-atomic.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-evidence.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'review/**', 'ship/**', 'qa/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/review-army.ts', 'scripts/resolvers/sections.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/qa-callers-fixture.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-fixture.ts', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/session-runner.ts', 'test/skill-e2e-qa-callers.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/skill-census.ts'], @@ -69,13 +69,13 @@ export const E2E_TOUCHFILES: Record = { 'qa-functional-cli-fix': ['bin/gstack-qa-evidence', 'bin/gstack-qa-deadline', 'lib/qa-evidence.ts', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'lib/fs-atomic.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-evidence.ts', 'qa/**', 'qa-only/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/utility.ts', 'scripts/resolvers/sections.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/skill-fixture.ts', 'test/skill-e2e-qa-functional-fix.test.ts', 'test/helpers/office-hours-attempt.ts'], 'qa-functional-webhook-fix': ['bin/gstack-qa-evidence', 'bin/gstack-qa-deadline', 'lib/qa-evidence.ts', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'lib/fs-atomic.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-evidence.ts', 'qa/**', 'qa-only/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/utility.ts', 'scripts/resolvers/sections.ts', 'scripts/gen-skill-docs.ts', 'test/helpers/qa-functional-*.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/skill-fixture.ts', 'test/skill-e2e-qa-functional-fix.test.ts', 'test/helpers/office-hours-attempt.ts'], // Browse core (+ test-server dependency) - 'browse-basic': [ 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-bws.test.ts'], - 'browse-snapshot': [ 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-bws.test.ts'], + 'browse-basic': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-bws.test.ts'], + 'browse-snapshot': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-bws.test.ts'], // Aside-driven browsing skills — live E2E against the Aside AI browser, the // primary browser (test/skill-e2e-aside.test.ts self-skips without a running Aside) - 'aside-browse-basic': [ 'browse/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/basic.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], - 'aside-browse-flow': [ 'browse/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/forms.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], + 'aside-browse-basic': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'browse/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/basic.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], + 'aside-browse-flow': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'browse/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/forms.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], 'aside-qa-quick': [ 'qa/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/basic.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], 'aside-scrape-json': [ 'scrape/**', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/basic.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], 'aside-canary-quick': [ 'canary/**', 'scripts/resolvers/aside.ts', 'browse/test/test-server.ts', 'browse/test/fixtures/basic.html', 'test/helpers/aside-available.ts', 'test/skill-e2e-aside.test.ts', 'test/helpers/e2e-gate.ts'], @@ -89,7 +89,7 @@ export const E2E_TOUCHFILES: Record = { // through the real runner, plus the script wiring that gates + maps it // (token-reduction Phase 2: generate-first-run-guidance.ts was deleted; the // gate + token→tip map live in bin/gstack-skill-start's emission layer). - 'first-task-scaffold': [ 'bin/gstack-skill-start', 'bin/gstack-skill-end', 'bin/gstack-first-task-detect', 'scripts/resolvers/preamble/generate-preamble-bash.ts', 'test/skill-e2e-first-task-scaffold.test.ts', 'test/helpers/session-runner.ts'], + 'first-task-scaffold': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-skill-start', 'bin/gstack-skill-end', 'bin/gstack-first-task-detect', 'scripts/resolvers/preamble/generate-preamble-bash.ts', 'test/skill-e2e-first-task-scaffold.test.ts', 'test/helpers/session-runner.ts'], // SKILL.md setup + preamble (depend on ROOT SKILL.md + gen-skill-docs) 'skillmd-setup-discovery': [ 'SKILL.md', 'SKILL.md.tmpl', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-bws.test.ts'], @@ -97,16 +97,16 @@ export const E2E_TOUCHFILES: Record = { 'skillmd-outside-git': [ 'SKILL.md', 'SKILL.md.tmpl', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-bws.test.ts'], 'session-awareness': [ 'SKILL.md', 'SKILL.md.tmpl', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-bws.test.ts'], - 'operational-learning': [ 'scripts/resolvers/preamble.ts', 'bin/gstack-learnings-log', 'test/skill-e2e-bws.test.ts'], + 'operational-learning': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'scripts/resolvers/preamble.ts', 'bin/gstack-learnings-log', 'test/skill-e2e-bws.test.ts'], // QA (+ test-server dependency). /qa drives Aside first (the resolver) and // the browse binary as fallback (browse/src), so both are deps. - 'qa-quick': ['bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', 'test/helpers/aside-available.ts', 'test/fixtures/qa-only-browser-probe.ts', 'test/helpers/bootstrap-retention.ts', 'test/helpers/qa-browser-deadline-evidence.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-only-cleanup.ts'], - 'qa-b6-static': [ 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval.html', 'test/fixtures/qa-eval-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], - 'qa-b7-spa': [ 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval-spa.html', 'test/fixtures/qa-eval-spa-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], - 'qa-b8-checkout': [ 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval-checkout.html', 'test/fixtures/qa-eval-checkout-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], - 'qa-only-no-fix': ['test/helpers/qa-only-cleanup.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/fixtures/qa-only-observation-public.json', 'test/fixtures/qa-only-charter-public.json', 'test/fixtures/qa-only-browser-probe.ts', 'browse/test/fixtures/qa-only.html', 'test/helpers/qa-browser-deadline-evidence.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa-only/**', 'qa/sections/**', 'qa/templates/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', 'test/helpers/aside-available.ts', 'test/helpers/bootstrap-retention.ts', 'test/helpers/qa-evidence-producer.ts'], - 'qa-fix-loop': ['bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', + 'qa-quick': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa/**', 'scripts/resolvers/browse.ts', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', 'test/helpers/aside-available.ts', 'test/fixtures/qa-only-browser-probe.ts', 'test/helpers/bootstrap-retention.ts', 'test/helpers/qa-browser-deadline-evidence.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-only-cleanup.ts'], + 'qa-b6-static': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval.html', 'test/fixtures/qa-eval-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], + 'qa-b7-spa': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval-spa.html', 'test/fixtures/qa-eval-spa-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], + 'qa-b8-checkout': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/helpers/llm-judge.ts', 'browse/test/fixtures/qa-eval-checkout.html', 'test/fixtures/qa-eval-checkout-ground-truth.json', 'test/skill-e2e-qa-bugs.test.ts', 'test/helpers/aside-available.ts'], + 'qa-only-no-fix': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/qa-only-cleanup.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/fixtures/qa-only-observation-public.json', 'test/fixtures/qa-only-charter-public.json', 'test/fixtures/qa-only-browser-probe.ts', 'browse/test/fixtures/qa-only.html', 'test/helpers/qa-browser-deadline-evidence.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa-only/**', 'qa/sections/**', 'qa/templates/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', 'test/helpers/aside-available.ts', 'test/helpers/bootstrap-retention.ts', 'test/helpers/qa-evidence-producer.ts'], + 'qa-fix-loop': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-qa-deadline', 'lib/qa-deadline.ts', 'lib/claude-code-windows-job.ts', 'qa/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'browse/test/test-server.ts', 'test/skill-e2e-qa-workflow.test.ts', 'test/helpers/aside-available.ts', 'test/fixtures/qa-only-browser-probe.ts', 'test/helpers/bootstrap-retention.ts', 'test/helpers/qa-browser-deadline-evidence.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-only-cleanup.ts'], 'qa-bootstrap': ['test/helpers/bootstrap-retention.ts', 'qa/**', 'ship/**', 'test/skill-e2e-qa-workflow.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/aside-available.ts', 'test/fixtures/qa-only-browser-probe.ts', 'test/helpers/qa-browser-deadline-evidence.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-only-cleanup.ts'], @@ -117,7 +117,7 @@ export const E2E_TOUCHFILES: Record = { 'review-enum-completeness': [ 'review/**', 'test/fixtures/review-eval-enum*.rb', 'test/skill-e2e-review.test.ts', 'test/fixtures/fake-impeccable.ts', 'test/helpers/fake-impeccable.ts'], 'review-base-branch': [ 'review/**', 'test/skill-e2e-review-attribution.test.ts'], - 'review-design-lite': [ 'review/**', 'test/fixtures/review-eval-design-slop.*', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'scripts/resolvers/design-checklist.ts', 'scripts/resolvers/review-army.ts', 'test/skill-e2e-review.test.ts' + 'review-design-lite': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'review/**', 'test/fixtures/review-eval-design-slop.*', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'scripts/resolvers/design-checklist.ts', 'scripts/resolvers/review-army.ts', 'test/skill-e2e-review.test.ts' ], @@ -185,7 +185,7 @@ export const E2E_TOUCHFILES: Record = { // include question-tuning.ts and generate-ask-user-format.ts because the // AUTO_DECIDE preamble injection lives there and changes can flip the // regression test outcome between 'asked' and 'auto_decided'. - 'plan-ceo-review-plan-mode': [ + 'plan-ceo-review-plan-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/plan-count-fixture.ts', @@ -203,7 +203,7 @@ export const E2E_TOUCHFILES: Record = { "test/fixtures/eng-option-b-scope-al.json", 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'scripts/resolvers/tasks-section.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts'], - 'plan-eng-review-plan-mode': [ + 'plan-eng-review-plan-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/auto-decide-recommendation-361c.json', @@ -226,7 +226,7 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", 'test/fixtures/pty-companion-cli.ts', 'test/helpers/plan-seed-submission.ts', 'test/fixtures/plan-seed-cli.ts', 'test/helpers/owned-claude-transcript.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'scripts/resolvers/testing.ts', 'test/helpers/plan-mode-evidence.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts'], - 'plan-design-review-plan-mode': [ + 'plan-design-review-plan-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/auto-decide-recommendation-361c.json', @@ -252,7 +252,7 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", 'test/fixtures/pty-companion-cli.ts', 'test/helpers/plan-seed-submission.ts', 'test/fixtures/plan-seed-cli.ts', 'test/helpers/owned-claude-transcript.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'test/helpers/plan-mode-evidence.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/review-eval-design-slop.html', 'test/helpers/aside-available.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/fake-impeccable.ts', 'test/helpers/llm-judge.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts'], - 'plan-devex-review-plan-mode': [ + 'plan-devex-review-plan-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/fixtures/auto-decide-recommendation-361c.json', @@ -273,7 +273,7 @@ export const E2E_TOUCHFILES: Record = { // (--max-concurrency + --retry 1), so worst-case cost is ~2x a single // pass of each, sharing the API budget with sibling tests — not the // sequential ~+10min a local read suggests. - 'plan-mode-no-op': [ + 'plan-mode-no-op': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/fixtures/auto-decide-recommendation-361c.json', @@ -304,21 +304,21 @@ export const E2E_TOUCHFILES: Record = { // INSIDE the existing 4 plan-X-review-plan-mode test files (covered // transitively by the entries above). Two new standalone files exist for // skills with no prior plan-mode test: - 'office-hours-auto-mode': [ + 'office-hours-auto-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/fixtures/auto-decide-recommendation-361c.json', 'test/fixtures/auto-decide-target-361c.json', 'test/fixtures/native-auto-decide-ag.json', 'test/helpers/native-auto-decide.ts', 'test/fixtures/auto-decide-current-declaration-6aef.json', 'test/fixtures/auto-decide-explanatory-mode-043a.json', 'test/fixtures/auto-decide-explanatory-mode-749df.json', 'bin/gstack-skill-start', 'bin/gstack-skill-end', 'office-hours/**', 'scripts/resolvers/preamble/generate-completion-status.ts', 'scripts/resolvers/question-tuning.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/preamble.ts', 'test/helpers/claude-pty-runner.ts', 'test/helpers/pty/**', 'test/fixtures/design-ui-boxed-question.json', 'test/helpers/hermetic-skill-runtime.ts', 'test/helpers/pty-trust-dialog.ts', 'test/skill-e2e-office-hours-auto-mode.test.ts', 'test/fixtures/eng-d2-truncated-border-0bcd.json', 'test/fixtures/eng-d1-clipped-elision-1579.json', 'test/fixtures/eng-d2-planning-prelude-4d.json', 'test/fixtures/ceo-approach-z-call.json', 'test/fixtures/ceo-approach-z-screen.txt', 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-fixture.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts', 'test/helpers/pty-screen.ts'], - 'office-hours-phase4-fork': [ 'bin/gstack-skill-start', 'bin/gstack-skill-end', 'office-hours/**', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/preamble/generate-completion-status.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/question-tuning.ts', 'test/helpers/llm-judge.ts', 'test/skill-e2e-office-hours-phase4.test.ts' ], + 'office-hours-phase4-fork': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-skill-start', 'bin/gstack-skill-end', 'office-hours/**', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/preamble/generate-completion-status.ts', 'scripts/resolvers/preamble.ts', 'scripts/resolvers/question-tuning.ts', 'test/helpers/llm-judge.ts', 'test/skill-e2e-office-hours-phase4.test.ts' ], 'llm-judge-recommendation': ['codex/**', 'test/helpers/llm-judge.ts', 'test/llm-judge-recommendation.test.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'codex/SKILL.md.tmpl', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts'], // v1.21+ AUTO_DECIDE preserve eval (periodic). Verifies the Tool resolution // fix doesn't trip the legitimate /plan-tune opt-in path: when the user has // written a never-ask preference, AUQ should still auto-decide rather than // surfacing the question. Touches the question-tuning + preference // infrastructure plus the resolvers that own the AUTO_DECIDE preamble. - 'auto-decide-preserved': [ + 'auto-decide-preserved': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'hosts/claude/hooks/hook-log.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/auto-decide-recommendation-361c.json', @@ -362,7 +362,7 @@ export const E2E_TOUCHFILES: Record = { "test/fixtures/ceo-hold-commitment-ar.json", 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/ceo-finding-fixture.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'test/helpers/owned-claude-transcript.ts', 'scripts/resolvers/tasks-section.ts', 'test/fixtures/ceo-expansion-pacing-77.json', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/plan-count-artifacts.ts', 'test/helpers/plan-count-file-permission.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts'], - 'plan-design-with-ui-scope': [ 'test/helpers/pty-screen.ts', + 'plan-design-with-ui-scope': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/pty-screen.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/autoplan-public-narration-ad.json', 'test/helpers/plan-count-fixture.ts', @@ -401,7 +401,7 @@ export const E2E_TOUCHFILES: Record = { // devex, office-hours + future PR2 carves). One file iterating CARVE_GUARDS; // the selector sets GSTACK_CARVE_SKILL= to scope cost to the changed // skill (D-CODEX A). Touching the registry/helper or sections.ts runs all. - 'carve-section-loading': [ + 'carve-section-loading': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-review-log', 'bin/gstack-review-read', 'lib/review-evidence.ts', 'bin/gstack-slug', 'bin/gstack-wtree', 'bin/gstack-config', 'bin/gstack-brain-enqueue', 'test/fixtures/autoplan-amend-input-77.json', @@ -424,7 +424,7 @@ export const E2E_TOUCHFILES: Record = { // review-phase AskUserQuestion). Uses runPlanSkillFloorCheck — minimal // "did agent fire ANY AUQ?" observer that exits early on first non-permission // numbered-option render. ~1-3 min typical wall time per test, ~$2-6 total. - 'plan-eng-finding-floor': [ 'test/helpers/pty-screen.ts', + 'plan-eng-finding-floor': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/pty-screen.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-floor-quote-70b.json', 'test/fixtures/plan-create-permission-361c.json', @@ -440,7 +440,7 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'scripts/resolvers/testing.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts'], - 'plan-ceo-finding-floor': [ 'test/helpers/pty-screen.ts', + 'plan-ceo-finding-floor': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/pty-screen.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-floor-quote-70b.json', 'test/fixtures/plan-create-permission-361c.json', @@ -452,7 +452,7 @@ export const E2E_TOUCHFILES: Record = { 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'scripts/resolvers/tasks-section.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts'], - 'plan-design-finding-floor': [ 'test/helpers/pty-screen.ts', + 'plan-design-finding-floor': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/pty-screen.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-floor-quote-70b.json', @@ -469,7 +469,7 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'test/helpers/ceo-finding-fixture.ts', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/eng-cache-writer-decision.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/owned-claude-transcript.ts', 'test/helpers/plan-count-pending-exit.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-count-transcript.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts'], - 'plan-devex-finding-floor': [ 'test/helpers/pty-screen.ts', + 'plan-devex-finding-floor': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/pty-screen.ts', 'test/fixtures/plan-floor-dx-custom-491.json', 'test/fixtures/plan-floor-dx-editor-hint.json', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-floor-quote-70b.json', 'test/fixtures/plan-floor-product-type-70b.json', @@ -487,7 +487,7 @@ export const E2E_TOUCHFILES: Record = { // a model fires one AUQ then batches the rest into a "## Decisions to // confirm" plan write. runPlanSkillFloorCheck cannot detect that shape // (it exits on first AUQ); runPlanSkillCounting can. - 'plan-eng-multi-finding-batching': [ + 'plan-eng-multi-finding-batching': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-create-permission-361c.json', @@ -526,7 +526,7 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", 'test/fixtures/pty-companion-cli.ts', 'lib/fs-atomic.ts', 'test/helpers/owned-claude-transcript.ts', 'test/fixtures/webfetch-permission.json', 'test/helpers/plan-skill-questions.ts', 'test/fixtures/eng-auq-validation-error.json', 'test/fixtures/bash-directory-permission.json', 'test/fixtures/design-tasks-bash-permission.json', 'test/fixtures/read-permission.json', 'test/fixtures/ceo-split-e5-numbered-description-491.json', 'test/helpers/plan-skill-question-events.ts', 'test/helpers/plan-skill-question-hook-scope.ts', 'test/helpers/skill-census.ts', 'test/helpers/ceo-finding-fixture.ts', 'test/helpers/plan-review-decisions.ts', 'test/helpers/plan-review-cases.ts', 'test/helpers/llm-judge.ts', 'lib/eval-model.ts', 'test/skill-e2e-plan-decision-classification.test.ts', 'test/fixtures/plan-decision-classification.ts', 'scripts/resolvers/testing.ts', 'test/fixtures/eng-file-permission-repaint.json', 'test/helpers/auto-decision-state.ts', 'test/helpers/autoplan-artifact-digest.ts', 'test/helpers/autoplan-artifact-permission.ts', 'test/helpers/autoplan-artifact-recorder.ts', 'test/helpers/dx-selected-navigation.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/native-auto-decide.ts', 'test/helpers/plan-count-pending-question.ts', 'test/helpers/plan-floor-review.ts', 'test/helpers/plan-floor-target.ts', 'test/helpers/plan-scope-selection.ts', 'test/helpers/plan-seed-submission.ts'], - 'plan-ceo-split-overflow': [ + 'plan-ceo-split-overflow': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'lib/claude-public-transcript.ts', 'test/fixtures/plan-create-prepublication-491.json', 'test/fixtures/plan-create-combined-permission-70b.json', 'test/fixtures/plan-create-permission-361c.json', @@ -551,16 +551,16 @@ export const E2E_TOUCHFILES: Record = { // Agent SDK. Gate-tier (deterministic stub server, fixed inputs); fires // when the skill template, the verify helper, the artifacts-init helper, // or the detect script changes. - 'setup-gbrain-remote': [ + 'setup-gbrain-remote': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/setup-gbrain-sandbox.ts', 'test/helpers/office-hours-attempt.ts', 'test/helpers/eval-store.ts', 'test/helpers/e2e-helpers.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'lib/eval-model.ts','setup-gbrain/sections/brain-init.md.tmpl', 'setup-gbrain/sections/claude-md-persist.md.tmpl', 'setup-gbrain/sections/manifest.json', 'test/helpers/setup-gbrain-fixture.ts', 'setup-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-mcp-verify', 'bin/gstack-artifacts-init', 'bin/gstack-gbrain-detect', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-setup-gbrain-remote.test.ts', 'test/helpers/e2e-gate.ts'], - 'setup-gbrain-bad-token': [ 'setup-gbrain/sections/brain-init.md.tmpl', 'setup-gbrain/sections/manifest.json', 'test/helpers/setup-gbrain-fixture.ts', 'setup-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-mcp-verify', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-setup-gbrain-bad-token.test.ts', + 'setup-gbrain-bad-token': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'setup-gbrain/sections/brain-init.md.tmpl', 'setup-gbrain/sections/manifest.json', 'test/helpers/setup-gbrain-fixture.ts', 'setup-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-mcp-verify', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-setup-gbrain-bad-token.test.ts', 'test/helpers/setup-gbrain-sandbox.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/setup-gbrain-fixture-command.ts', 'bin/gstack-gbrain-detect', 'lib/gbrain-local-status.ts', 'lib/gbrain-exec.ts', 'bin/gstack-gbrain-lib.sh', 'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'test/helpers/office-hours-attempt.ts', 'test/helpers/e2e-gate.ts'], // v1.34.0.0 split-engine Path 4 + Step 4.5 Yes (local PGLite for code). // Periodic-tier per codex #12 (AgentSDK harness is non-deterministic). // Fires when the setup-gbrain template, install/verify/init helpers, or // the agent-sdk-runner harness changes. - 'setup-gbrain-path4-local-pglite': [ 'setup-gbrain/sections/brain-init.md.tmpl', 'setup-gbrain/sections/claude-md-persist.md.tmpl', 'setup-gbrain/sections/manifest.json', 'test/helpers/setup-gbrain-fixture.ts', 'setup-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-mcp-verify', 'bin/gstack-gbrain-install', 'bin/gstack-gbrain-detect', 'lib/gbrain-local-status.ts', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-setup-gbrain-path4-local-pglite.test.ts', + 'setup-gbrain-path4-local-pglite': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'setup-gbrain/sections/brain-init.md.tmpl', 'setup-gbrain/sections/claude-md-persist.md.tmpl', 'setup-gbrain/sections/manifest.json', 'test/helpers/setup-gbrain-fixture.ts', 'setup-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-mcp-verify', 'bin/gstack-gbrain-install', 'bin/gstack-gbrain-detect', 'lib/gbrain-local-status.ts', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-setup-gbrain-path4-local-pglite.test.ts', 'test/helpers/setup-gbrain-sandbox.ts', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/helpers/setup-gbrain-fixture-command.ts', 'lib/gbrain-exec.ts', 'bin/gstack-gbrain-lib.sh', 'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'test/helpers/office-hours-attempt.ts', 'test/helpers/e2e-gate.ts'], // AskUserQuestion format regression (RECOMMENDATION + Completeness: N/10) @@ -617,7 +617,7 @@ export const E2E_TOUCHFILES: Record = { // Expanded coverage (CT3) — 6 non-plan-review skills inherit Pros/Cons via preamble // /plan-tune (v1 observational) - 'plan-tune-inspect': [ 'plan-tune/**', 'scripts/question-registry.ts', 'scripts/psychographic-signals.ts', 'scripts/one-way-doors.ts', 'bin/gstack-question-log', 'bin/gstack-question-preference', 'bin/gstack-developer-profile', 'test/skill-e2e-plan-tune.test.ts'], + 'plan-tune-inspect': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'plan-tune/**', 'scripts/question-registry.ts', 'scripts/psychographic-signals.ts', 'scripts/one-way-doors.ts', 'bin/gstack-question-log', 'bin/gstack-question-preference', 'bin/gstack-developer-profile', 'test/skill-e2e-plan-tune.test.ts'], // /plan-tune cathedral (T16 — 5 E2E scenarios, all gate per D12) @@ -649,19 +649,19 @@ export const E2E_TOUCHFILES: Record = { 'scripts/resolvers/testing.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts', 'test/helpers/office-hours-completion.ts'], // Ship - 'ship-managed-hook-refresh': ['ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', + 'ship-managed-hook-refresh': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', 'test/helpers/ship-hook-actor.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-ship-hook-refresh.test.ts', 'test/helpers/e2e-gate.ts'], - 'ship-unmanaged-hook-consent': ['ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', + 'ship-unmanaged-hook-consent': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', 'test/helpers/ship-hook-actor.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-ship-hook-consent.test.ts', 'test/helpers/e2e-gate.ts'], - 'ship-local-hook-preservation': ['ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', + 'ship-local-hook-preservation': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'bin/gstack-redact', 'bin/gstack-config', 'scripts/gen-skill-docs.ts', 'test/helpers/ship-hook-actor.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/agent-sdk-runner.ts', 'test/skill-e2e-ship-hook-consent.test.ts', 'test/helpers/e2e-gate.ts'], - 'ship-base-branch': [ 'ship/**', 'bin/gstack-repo-mode', 'test/skill-e2e-review-attribution.test.ts', + 'ship-base-branch': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'bin/gstack-repo-mode', 'test/skill-e2e-review-attribution.test.ts', 'scripts/resolvers/testing.ts' ], 'ship-local-workflow': [ 'ship/**', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-workflow.test.ts', @@ -671,29 +671,29 @@ export const E2E_TOUCHFILES: Record = { ], // Retro - 'retro': [ 'bin/gstack-retro-metrics', 'retro/**', 'test/skill-e2e-retro.test.ts'], - 'retro-base-branch': [ 'bin/gstack-retro-metrics', 'retro/**', 'test/skill-e2e-retro.test.ts'], + 'retro': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-retro-metrics', 'retro/**', 'test/skill-e2e-retro.test.ts'], + 'retro-base-branch': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-retro-metrics', 'retro/**', 'test/skill-e2e-retro.test.ts'], // CSO - 'cso-full-audit': [ 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], - 'cso-diff-mode': [ 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], - 'cso-infra-scope': [ 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], + 'cso-full-audit': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], + 'cso-diff-mode': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], + 'cso-infra-scope': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'cso/**', 'lib/cso/**', 'lib/redact-engine.ts', 'lib/redact-patterns.ts', 'test/skill-e2e-cso.test.ts'], // Learnings - 'learnings-show': [ 'learn/**', 'bin/gstack-learnings-search', 'bin/gstack-learnings-log', 'scripts/resolvers/learnings.ts', 'test/skill-e2e-learnings.test.ts'], + 'learnings-show': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'learn/**', 'bin/gstack-learnings-search', 'bin/gstack-learnings-log', 'scripts/resolvers/learnings.ts', 'test/skill-e2e-learnings.test.ts'], // Session Intelligence (timeline, context recovery, /context-save + /context-restore) - 'timeline-event-flow': [ 'bin/gstack-timeline-log', 'bin/gstack-timeline-read', 'test/skill-e2e-session-intelligence.test.ts'], - 'context-recovery-artifacts': [ 'scripts/resolvers/preamble.ts', 'bin/gstack-timeline-log', 'bin/gstack-slug', 'learn/**', 'test/skill-e2e-session-intelligence.test.ts'], - 'context-save-writes-file': [ 'context-save/**', 'bin/gstack-slug', 'test/skill-e2e-session-intelligence.test.ts'], - 'context-restore-loads-latest': [ 'context-restore/**', 'bin/gstack-slug', 'test/skill-e2e-session-intelligence.test.ts'], + 'timeline-event-flow': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'bin/gstack-timeline-log', 'bin/gstack-timeline-read', 'test/skill-e2e-session-intelligence.test.ts'], + 'context-recovery-artifacts': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'scripts/resolvers/preamble.ts', 'bin/gstack-timeline-log', 'bin/gstack-slug', 'learn/**', 'test/skill-e2e-session-intelligence.test.ts'], + 'context-save-writes-file': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'context-save/**', 'bin/gstack-slug', 'test/skill-e2e-session-intelligence.test.ts'], + 'context-restore-loads-latest': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'context-restore/**', 'bin/gstack-slug', 'test/skill-e2e-session-intelligence.test.ts'], // Context skills E2E (live-fire, Skill-tool routing path) — see // test/skill-e2e-context-skills.test.ts. These are periodic-tier because // each one spawns claude -p and costs ~$0.20-$0.40. Collectively they // verify the thing the /checkpoint → /context-save rename was for. 'context-save-routing': [ 'context-save/**', 'scripts/resolvers/preamble.ts', 'test/skill-e2e-context-skills.test.ts'], - 'context-save-then-restore-roundtrip': [ 'context-save/**', 'context-restore/**', 'bin/gstack-slug', 'test/skill-e2e-context-skills.test.ts'], + 'context-save-then-restore-roundtrip': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'context-save/**', 'context-restore/**', 'bin/gstack-slug', 'test/skill-e2e-context-skills.test.ts'], 'context-restore-fragment-match': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts'], 'context-restore-empty-state': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts'], 'context-restore-list-delegates': [ 'context-restore/**', 'test/skill-e2e-context-skills.test.ts'], @@ -724,7 +724,7 @@ export const E2E_TOUCHFILES: Record = { 'test/helpers/skill-fixture.ts', 'test/helpers/outside-voice-fixture.ts', 'test/helpers/outside-voice-evidence.ts', 'test/fixtures/outside-async-task-m-events.json', 'test/skill-e2e-outside-voice.test.ts', 'test/helpers/outside-voice-receipt.ts', 'test/helpers/e2e-gate.ts'], - 'outside-voice-claude-code-to-codex': [ + 'outside-voice-claude-code-to-codex': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'review/**', 'codex/**', 'hosts/claude.ts', 'hosts/define-host.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/index.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/constants.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', @@ -733,7 +733,7 @@ export const E2E_TOUCHFILES: Record = { 'test/helpers/skill-fixture.ts', 'test/helpers/outside-voice-fixture.ts', 'test/helpers/outside-voice-evidence.ts', 'test/fixtures/outside-async-task-m-events.json', 'test/skill-e2e-outside-voice.test.ts', 'test/helpers/codex-session-runner.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/outside-voice-receipt.ts'], // Disabled means no extra plan review, including a native Agent fallback. - 'outside-plan-disabled-no-fallback': [ + 'outside-plan-disabled-no-fallback': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/fixtures/disabled-retained-record.json', 'scripts/resolvers/testing.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', @@ -759,7 +759,7 @@ export const E2E_TOUCHFILES: Record = { // Coverage audit (shared fixture) + triage + gates - 'ship-coverage-audit': [ + 'ship-coverage-audit': ['bin/gstack-state-root.sh', 'lib/state-root.ts', "test/fixtures/coverage-audit-aw.json", @@ -804,20 +804,20 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", "scripts/resolvers/preamble/generate-completion-status.ts", 'test/helpers/coverage-audit.ts', 'test/helpers/office-hours-attempt.ts', 'scripts/resolvers/testing.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts' ], - 'ship-triage': [ 'ship/**', 'bin/gstack-repo-mode', 'test/skill-e2e-triage.test.ts', + 'ship-triage': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'bin/gstack-repo-mode', 'test/skill-e2e-triage.test.ts', 'scripts/resolvers/testing.ts' ], - 'ship-docsync': [ 'ship/**', 'document-release/**', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/sections.ts', 'test/skill-e2e-ship-docsync.test.ts', + 'ship-docsync': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/sections.ts', 'test/skill-e2e-ship-docsync.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/docsync-*.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], - 'ship-docsync-completion': ['ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], - 'ship-docsync-current': ['ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], - 'ship-docsync-failure': ['ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], - 'ship-docsync-store': ['ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], + 'ship-docsync-completion': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], + 'ship-docsync-current': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], + 'ship-docsync-failure': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], + 'ship-docsync-store': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'ship/**', 'document-release/**', 'test/skill-e2e-ship-docsync.test.ts', 'test/helpers/docsync-*.ts', 'test/helpers/session-runner.ts', 'test/helpers/hermetic-env.ts', 'bin/gstack-skill-start', 'bin/gstack-session-kind', 'scripts/resolvers/sections.ts', 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'scripts/gen-skill-docs.ts', 'scripts/resolvers/testing.ts', 'test/helpers/qa-checkpoint-evidence.ts', 'test/helpers/qa-functional-observer.ts', 'test/helpers/e2e-gate.ts', 'test/helpers/qa-evidence-producer.ts', 'test/helpers/qa-functional-fixture.ts'], // #2733 behavioral proof: the JSON contract survives a firing gate inside a // spawned-marked subagent. Deps name every behavior under test — the // session-kind override, the skill-start gates, both hooks + the shared // directive, and the AUQ prose rule — so changing any of them selects it. - 'docsync-spawned': [ + 'docsync-spawned': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'hosts/claude/hooks/hook-log.ts', 'ship/sections/pr-body.md', 'document-release/**', 'ship/sections/documentation.md', @@ -844,15 +844,15 @@ export const E2E_TOUCHFILES: Record = { "scripts/resolvers/preamble/generate-preamble-bash.ts", "scripts/resolvers/preamble/generate-completion-status.ts", 'scripts/resolvers/preamble/generate-ask-user-format.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/review-eval-design-slop.html', 'test/helpers/aside-available.ts', 'test/helpers/fake-impeccable.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], - 'design-review-fix': [ 'design-review/**', 'scripts/resolvers/aside.ts', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-catalog.ts', 'browse/src/**', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-design.test.ts', + 'design-review-fix': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'design-review/**', 'scripts/resolvers/aside.ts', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-catalog.ts', 'browse/src/**', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-design.test.ts', 'scripts/resolvers/testing.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/review-eval-design-slop.html', 'test/helpers/aside-available.ts', 'test/helpers/fake-impeccable.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], // Design detector (user-installed impeccable engine) through the fake engine shim: source mode on a diff and DOM mode on a served page. - 'design-review-detector-shim': [ 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'lib/dom-dump-script.ts', 'lib/dom-dump.js', 'bin/gstack-design-detect.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.*', 'test/skill-e2e-design.test.ts', + 'design-review-detector-shim': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'lib/dom-dump-script.ts', 'lib/dom-dump.js', 'bin/gstack-design-detect.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.*', 'test/skill-e2e-design.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], - 'design-review-detector-shim-dom': [ 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-detect-contract.ts', 'lib/dom-dump-script.ts', 'lib/dom-dump.js', 'bin/gstack-design-detect.ts', 'browse/src/**', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.*', 'test/skill-e2e-design.test.ts', + 'design-review-detector-shim-dom': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-detect-contract.ts', 'lib/dom-dump-script.ts', 'lib/dom-dump.js', 'bin/gstack-design-detect.ts', 'browse/src/**', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.*', 'test/skill-e2e-design.test.ts', 'scripts/resolvers/testing.ts', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], - 'design-review-plugin-handoff': [ 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/testing.ts', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.html', 'test/skill-e2e-design.test.ts', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], - 'design-html-slop-gate': [ 'design-html/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/skill-e2e-design.test.ts', 'test/fixtures/review-eval-design-slop.html', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], + 'design-review-plugin-handoff': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'design-review/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/testing.ts', 'lib/design-catalog.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/fixtures/review-eval-design-slop.html', 'test/skill-e2e-design.test.ts', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], + 'design-html-slop-gate': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'design-html/**', 'scripts/resolvers/design.ts', 'scripts/resolvers/outside-voice.ts', 'lib/design-detect-contract.ts', 'bin/gstack-design-detect.ts', 'test/helpers/fake-impeccable.ts', 'test/fixtures/fake-impeccable.ts', 'test/fixtures/impeccable-detect-sample.json', 'test/skill-e2e-design.test.ts', 'test/fixtures/review-eval-design-slop.html', 'test/helpers/aside-available.ts', 'test/helpers/llm-judge.ts', 'test/helpers/office-hours-attempt.ts'], // /diagram (diagram-render bundle consumers). Triplet = deterministic // functional (gate); authoring quality = LLM-judged benchmark (periodic). @@ -860,23 +860,23 @@ export const E2E_TOUCHFILES: Record = { // bin/gstack-render.ts): Aside when it is running, the browse daemon // otherwise — so both engines are deps. Triplet = deterministic functional // (gate); authoring quality = LLM-judged benchmark (periodic). - 'diagram-triplet': [ 'diagram/**', 'lib/diagram-render/**', 'lib/aside-render.ts', 'bin/gstack-render.ts', 'test/helpers/aside-available.ts', 'browse/src/**', 'test/skill-e2e-diagram.test.ts', 'test/helpers/llm-judge.ts'], - 'diagram-authoring-quality': [ 'diagram/**', 'lib/diagram-render/**', 'lib/aside-render.ts', 'bin/gstack-render.ts', 'test/helpers/aside-available.ts', 'browse/src/**', 'test/helpers/llm-judge.ts', 'test/skill-e2e-diagram.test.ts'], + 'diagram-triplet': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'diagram/**', 'lib/diagram-render/**', 'lib/aside-render.ts', 'bin/gstack-render.ts', 'test/helpers/aside-available.ts', 'browse/src/**', 'test/skill-e2e-diagram.test.ts', 'test/helpers/llm-judge.ts'], + 'diagram-authoring-quality': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'diagram/**', 'lib/diagram-render/**', 'lib/aside-render.ts', 'bin/gstack-render.ts', 'test/helpers/aside-available.ts', 'browse/src/**', 'test/helpers/llm-judge.ts', 'test/skill-e2e-diagram.test.ts'], // gstack-upgrade 'gstack-upgrade-happy-path': [ 'gstack-upgrade/**', 'test/skill-e2e-workflow.test.ts', 'test/fixtures/coverage-audit-fixture.ts', 'test/helpers/coverage-audit.ts', 'test/helpers/office-hours-attempt.ts'], // Deploy skills 'land-and-deploy-workflow': [ 'land-and-deploy/**', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-deploy.test.ts'], - 'land-and-deploy-first-run': [ 'land-and-deploy/**', 'scripts/gen-skill-docs.ts', 'bin/gstack-slug', 'test/skill-e2e-deploy.test.ts'], - 'land-and-deploy-review-gate': [ 'land-and-deploy/**', 'bin/gstack-review-read', 'test/skill-e2e-deploy.test.ts'], - 'canary-workflow': [ 'canary/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'test/skill-e2e-deploy.test.ts'], - 'benchmark-workflow': [ 'benchmark/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'test/skill-e2e-deploy.test.ts'], + 'land-and-deploy-first-run': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'land-and-deploy/**', 'scripts/gen-skill-docs.ts', 'bin/gstack-slug', 'test/skill-e2e-deploy.test.ts'], + 'land-and-deploy-review-gate': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'land-and-deploy/**', 'bin/gstack-review-read', 'test/skill-e2e-deploy.test.ts'], + 'canary-workflow': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'canary/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'test/skill-e2e-deploy.test.ts'], + 'benchmark-workflow': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'benchmark/**', 'scripts/resolvers/aside.ts', 'browse/src/**', 'test/skill-e2e-deploy.test.ts'], 'setup-deploy-workflow': [ 'setup-deploy/**', 'scripts/gen-skill-docs.ts', 'test/skill-e2e-deploy.test.ts'], // Autoplan - 'autoplan-dual-voice': [ + 'autoplan-dual-voice': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'test/helpers/hermetic-env.ts', 'test/helpers/autoplan-dual-voice-evidence.ts', 'test/fixtures/autoplan-dual-false-positive-6bd.json', @@ -1043,7 +1043,7 @@ export const E2E_TOUCHFILES: Record = { // frontmatter. Touched by anything that changes resolver output, gen // pipeline, detection helper, refresh subcommand, or the on-demand // docs the resolver points to. - 'office-hours-brain-writeback': [ 'office-hours/sections/**', + 'office-hours-brain-writeback': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'office-hours/sections/**', 'scripts/resolvers/gbrain.ts', 'scripts/gen-skill-docs.ts', 'bin/gstack-gbrain-detect', @@ -1064,8 +1064,8 @@ export const E2E_TOUCHFILES: Record = { 'scripts/resolvers/gbrain.ts', 'test/skill-e2e-gbrain-roundtrip-local.test.ts' ], - 'sync-gbrain-read-ready': ['sync-gbrain/SKILL.md.tmpl', 'sync-gbrain/SKILL.md', 'bin/gstack-gbrain-read-capability.ts', 'lib/gbrain-exec.ts', 'test/helpers/sync-gbrain-readiness-fixture.ts', 'test/helpers/sync-gbrain-readiness-verdict.ts', 'test/skill-e2e-sync-gbrain-readiness.test.ts', 'test/helpers/e2e-gate.ts'], - 'sync-gbrain-read-unknown': ['sync-gbrain/SKILL.md.tmpl', 'sync-gbrain/SKILL.md', 'bin/gstack-gbrain-read-capability.ts', 'lib/gbrain-exec.ts', 'test/helpers/sync-gbrain-readiness-fixture.ts', 'test/helpers/sync-gbrain-readiness-verdict.ts', 'test/skill-e2e-sync-gbrain-readiness.test.ts', 'test/helpers/e2e-gate.ts'], + 'sync-gbrain-read-ready': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'sync-gbrain/SKILL.md.tmpl', 'sync-gbrain/SKILL.md', 'bin/gstack-gbrain-read-capability.ts', 'lib/gbrain-exec.ts', 'test/helpers/sync-gbrain-readiness-fixture.ts', 'test/helpers/sync-gbrain-readiness-verdict.ts', 'test/skill-e2e-sync-gbrain-readiness.test.ts', 'test/helpers/e2e-gate.ts'], + 'sync-gbrain-read-unknown': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'sync-gbrain/SKILL.md.tmpl', 'sync-gbrain/SKILL.md', 'bin/gstack-gbrain-read-capability.ts', 'lib/gbrain-exec.ts', 'test/helpers/sync-gbrain-readiness-fixture.ts', 'test/helpers/sync-gbrain-readiness-verdict.ts', 'test/skill-e2e-sync-gbrain-readiness.test.ts', 'test/helpers/e2e-gate.ts'], // WS2 arm benchmark — with-skill vs without-skill agentic arms scored on // the git diff left behind (research instrument, never a release gate). @@ -1497,7 +1497,7 @@ export const E2E_TIERS: Record = { export const LLM_JUDGE_TOUCHFILES: Record = { 'review/SKILL.md workflow': ['review/**', 'qa/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/review-army.ts', 'scripts/resolvers/review-dashboard.ts', 'scripts/resolvers/plan-gates.ts', 'scripts/resolvers/spec-review.ts', 'scripts/resolvers/outside-voice-steps.ts', 'scripts/resolvers/review-scope.ts', 'scripts/resolvers/outside-voice.ts', 'scripts/resolvers/sections.ts', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts'], 'setup-browser-cookies/SKILL.md workflow': ['setup-browser-cookies/SKILL.md.tmpl', 'setup-browser-cookies/SKILL.md', 'BROWSER.md', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/manual-judge-review-fixture.ts', '.github/cookie-workflow-manual-review.json', 'test/helpers/workflow-judge-input.ts', 'test/skill-llm-eval.test.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts'], - 'browse/SKILL.md reference': ['browse/sections/**', 'browse/SKILL.md', 'browse/SKILL.md.tmpl', 'browse/src/**', 'test/skill-llm-eval.test.ts', 'SKILL.md', 'SKILL.md.tmpl', 'gstack/llms.txt', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts', 'test/helpers/workflow-judge-input.ts'], + 'browse/SKILL.md reference': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'browse/sections/**', 'browse/SKILL.md', 'browse/SKILL.md.tmpl', 'browse/src/**', 'test/skill-llm-eval.test.ts', 'SKILL.md', 'SKILL.md.tmpl', 'gstack/llms.txt', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts', 'test/helpers/workflow-judge-input.ts'], 'setup block': ['browse/SKILL.md', 'browse/SKILL.md.tmpl', 'scripts/resolvers/aside.ts', 'scripts/resolvers/browse.ts', 'test/skill-llm-eval.test.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts', 'test/helpers/workflow-judge-input.ts'], 'qa/SKILL.md workflow': ['qa/**', 'qa/sections/**', 'qa/SKILL.md', 'qa/SKILL.md.tmpl', 'scripts/resolvers/qa.ts', 'scripts/resolvers/utility.ts', 'scripts/resolvers/sections.ts', 'test/helpers/workflow-judge-input.ts', 'test/skill-llm-eval.test.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts'], 'qa/SKILL.md health rubric': ['qa/sections/**', 'qa/SKILL.md', 'qa/SKILL.md.tmpl', 'test/skill-llm-eval.test.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts', 'test/helpers/workflow-judge-input.ts'], @@ -1545,7 +1545,7 @@ export const LLM_JUDGE_TOUCHFILES: Record = { 'retro/SKILL.md instructions': ['retro/sections/**', 'retro/SKILL.md', 'retro/SKILL.md.tmpl', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'scripts/eval-input-cache.ts', 'test/helpers/workflow-excerpt.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts'], 'qa-only/SKILL.md workflow': ['qa-only/**', 'qa-only/SKILL.md', 'qa-only/SKILL.md.tmpl', 'qa/**', 'scripts/resolvers/qa.ts', 'scripts/resolvers/utility.ts', 'scripts/resolvers/sections.ts', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'scripts/eval-input-cache.ts', 'test/helpers/workflow-excerpt.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts'], 'gstack-upgrade/SKILL.md upgrade flow': ['gstack-upgrade/SKILL.md', 'gstack-upgrade/SKILL.md.tmpl', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'scripts/eval-input-cache.ts', 'test/helpers/workflow-excerpt.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts'], - 'sync-gbrain/SKILL.md read-only readiness': ['sync-gbrain/SKILL.md', 'sync-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-read-capability.ts', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'scripts/eval-input-cache.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts'], + 'sync-gbrain/SKILL.md read-only readiness': ['bin/gstack-state-root.sh', 'lib/state-root.ts', 'sync-gbrain/SKILL.md', 'sync-gbrain/SKILL.md.tmpl', 'bin/gstack-gbrain-read-capability.ts', 'test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-input.ts', 'test/helpers/workflow-judge-cache.ts', 'scripts/eval-input-cache.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts'], // Voice directive 'voice directive tone': ['scripts/resolvers/preamble.ts', 'review/SKILL.md', 'review/SKILL.md.tmpl', 'scripts/gen-skill-docs.ts', 'test/skill-llm-eval.test.ts', 'test/fixtures/eval-baselines.json', 'test/helpers/cookie-workflow-judge-input.ts', 'test/helpers/cookie-workflow-manual-review.ts', 'test/helpers/llm-judge.ts', 'test/helpers/workflow-excerpt.ts', 'test/helpers/workflow-judge-cache.ts', 'test/helpers/workflow-judge-input.ts'], diff --git a/test/hook-log.test.ts b/test/hook-log.test.ts new file mode 100644 index 0000000000..57c78ace8f --- /dev/null +++ b/test/hook-log.test.ts @@ -0,0 +1,81 @@ +/** + * hosts/claude/hooks/hook-log.ts is the one hook-errors.log writer. All five + * Claude Code hooks must log under the same resolved state root for the same + * env, and the log must end up 0600 even when it already existed as 0644. + */ +import { describe, test, expect } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const HOOKS = path.join(ROOT, 'hosts', 'claude', 'hooks'); + +function runHook(name: string, stdin: string, env: Record, cwd: string) { + return spawnSync('bash', [path.join(HOOKS, name)], { + input: stdin, + cwd, + env: { ...process.env, GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', ...env }, + encoding: 'utf-8', + timeout: 30_000, + }); +} + +describe('hook-log: one root, one mode', () => { + test('all five hooks append to /hook-errors.log, and a 0644 log becomes 0600', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-hook-log-')); + try { + const state = path.join(tmp, 'state'); + const home = path.join(tmp, 'home'); + const proj = path.join(tmp, 'hooklog-proj'); + fs.mkdirSync(state, { recursive: true }); + fs.mkdirSync(home, { recursive: true }); + fs.mkdirSync(proj, { recursive: true }); + const log = path.join(state, 'hook-errors.log'); + fs.writeFileSync(log, ''); + fs.chmodSync(log, 0o644); + const env = { GSTACK_HOME: state, HOME: home }; + + for (const hook of ['question-log-hook', 'question-preference-hook', 'auq-error-fallback-hook', 'memorable-user-prompt-hook']) { + const r = runHook(hook, '{not json', env, proj); + expect(r.status).toBe(0); + } + const slug = spawnSync('bash', [path.join(ROOT, 'bin', 'gstack-slug')], { cwd: proj, env: { ...process.env, ...env }, encoding: 'utf-8', timeout: 30_000 }) + .stdout.match(/^SLUG=(.+)$/m)?.[1]; + expect(slug).toBeTruthy(); + const timeline = path.join(state, 'projects', slug!, 'timeline.jsonl'); + fs.mkdirSync(path.dirname(timeline), { recursive: true }); + fs.writeFileSync(timeline, ''); + fs.truncateSync(timeline, 10 * 1024 * 1024 + 1); + expect(runHook('timeline-stop-hook', JSON.stringify({ cwd: proj }), env, proj).status).toBe(0); + + const text = fs.readFileSync(log, 'utf-8'); + for (const hook of ['question-log-hook', 'question-preference-hook', 'auq-error-fallback-hook', 'memorable-user-prompt-hook', 'timeline-stop-hook']) { + expect(text).toContain(` ${hook}: `); + } + expect(fs.existsSync(path.join(home, '.gstack', 'hook-errors.log'))).toBe(false); + if (process.platform !== 'win32') expect(fs.statSync(log).mode & 0o777).toBe(0o600); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + + test('rate limit drops a repeat key within the window and logs it again after', async () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-hook-log-rl-')); + const saved = process.env.GSTACK_HOME; + process.env.GSTACK_HOME = tmp; + try { + const { logHookError, LOG_RATE_LIMIT_MS } = await import('../hosts/claude/hooks/hook-log'); + logHookError('rl-hook', 'first', { rateLimit: { nowMs: 1_000, key: 'k' } }); + logHookError('rl-hook', 'second', { rateLimit: { nowMs: 2_000, key: 'k' } }); + logHookError('rl-hook', 'third', { rateLimit: { nowMs: 1_000 + LOG_RATE_LIMIT_MS, key: 'k' } }); + logHookError('rl-hook', 'plain'); + const lines = fs.readFileSync(path.join(tmp, 'hook-errors.log'), 'utf-8').trim().split('\n'); + expect(lines.map((l) => l.split(': ')[1])).toEqual(['first', 'third', 'plain']); + } finally { + if (saved === undefined) delete process.env.GSTACK_HOME; else process.env.GSTACK_HOME = saved; + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/hook-scripts.test.ts b/test/hook-scripts.test.ts index 95cfcd2135..df3b9575c6 100644 --- a/test/hook-scripts.test.ts +++ b/test/hook-scripts.test.ts @@ -1082,11 +1082,11 @@ describe('check-freeze.sh state-root resolution (#1459 / #1509)', () => { // ============================================================ // gstack_hook_log_fire analytics sink follows the same state root (#1459) // ============================================================ -// The hook_fire record lands under ${GSTACK_HOME:-$HOME/.gstack}/analytics — -// the SAME two-step chain every other analytics writer and reader uses -// (gstack-skill-start, gstack-retro-metrics, gstack-analytics) — deliberately -// NOT the plugin-aware state root the freeze FILE uses, so the usage log stays -// one file. Logging is best-effort: an unwritable sink never changes the decision. +// The hook_fire record lands under the resolved state root (bin/gstack-state-root.sh) +// — the SAME root the freeze FILE and every other analytics writer and reader +// (gstack-skill-start, gstack-retro-metrics, gstack-analytics) use, so the usage +// log stays one file. Logging is best-effort: an unwritable sink never changes +// the decision. describe('gstack_hook_log_fire writes under the resolved state root', () => { const BOUNDARY = '/Users/dev/project/src/'; const OUTSIDE = '/Users/dev/other-project/index.ts'; @@ -1114,16 +1114,16 @@ describe('gstack_hook_log_fire writes under the resolved state root', () => { }); }); - test('plugin install: the freeze FILE is read from CLAUDE_PLUGIN_DATA but hook_fire still lands under $HOME/.gstack/analytics (one usage log)', () => { + test('plugin install: the freeze FILE and hook_fire both use CLAUDE_PLUGIN_DATA (one state root, one usage log)', () => { withFreezeDir(BOUNDARY, (pluginData) => { withEmptyDir((fakeHome) => { const { output } = runHook(FREEZE_SCRIPT, freezeInput(OUTSIDE), freezeEnv(pluginData, { HOME: fakeHome, CLAUDE_PLUGIN_ROOT: '/Plugins/GSTACK' })); expect(output.hookSpecificOutput?.permissionDecision).toBe('deny'); - const rec = lastRecord(path.join(fakeHome, '.gstack', 'analytics', 'skill-usage.jsonl')); + const rec = lastRecord(path.join(pluginData, 'analytics', 'skill-usage.jsonl')); expect(rec.event).toBe('hook_fire'); expect(rec.skill).toBe('freeze'); - expect(fs.existsSync(path.join(pluginData, 'analytics'))).toBe(false); + expect(fs.existsSync(path.join(fakeHome, '.gstack', 'analytics'))).toBe(false); }); }); }); diff --git a/test/ios-qa-regen.test.ts b/test/ios-qa-regen.test.ts index 2aa39884c8..08bd4a822b 100644 --- a/test/ios-qa-regen.test.ts +++ b/test/ios-qa-regen.test.ts @@ -48,6 +48,8 @@ function copyIntoFakeInstall(workDir: string): { root: string; launcher: string copyFileSync(join(ROOT, 'bin', 'gstack-ios-qa-regen'), launcher); chmodSync(launcher, 0o755); copyFileSync(join(ROOT, 'ios-qa', 'scripts', 'gen-accessors.ts'), join(scriptsDir, 'gen-accessors.ts')); + mkdirSync(join(root, 'lib'), { recursive: true }); + copyFileSync(join(ROOT, 'lib', 'state-root.ts'), join(root, 'lib', 'state-root.ts')); for (const [template] of SAFE_TEMPLATE_MAP) { copyFileSync(join(ROOT, 'ios-qa', 'templates', template), join(templatesDir, template)); } diff --git a/test/plan-tune-cathedral.test.ts b/test/plan-tune-cathedral.test.ts index 4ac4fd8fbd..def4fcac49 100644 --- a/test/plan-tune-cathedral.test.ts +++ b/test/plan-tune-cathedral.test.ts @@ -43,6 +43,7 @@ function scaffoldFixture(workDir: string): { workDir: string; stateRoot: string; 'gstack-codex-session-import', 'gstack-distill-free-text', 'gstack-distill-apply', + 'gstack-state-root.sh', ]) { const src = path.join(ROOT, 'bin', script); if (fs.existsSync(src)) { @@ -65,10 +66,10 @@ function scaffoldFixture(workDir: string): { workDir: string; stateRoot: string; if (fs.existsSync(src)) fs.copyFileSync(src, path.join(scriptsDir, f)); } - // Both imports are resolved relative to the copied install, not the source checkout. + // These imports are resolved relative to the copied install, not the source checkout. const libDir = path.join(workDir, 'lib'); fs.mkdirSync(libDir, { recursive: true }); - for (const file of ['jsonl-store.ts', 'is-conductor.ts']) { + for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts']) { fs.copyFileSync(path.join(ROOT, 'lib', file), path.join(libDir, file)); } diff --git a/test/pty-upgrade-isolation.test.ts b/test/pty-upgrade-isolation.test.ts index 71cf24817a..423489d31a 100644 --- a/test/pty-upgrade-isolation.test.ts +++ b/test/pty-upgrade-isolation.test.ts @@ -100,11 +100,15 @@ describe('seeded PTY update-check isolation', () => { const state = path.join(home, 'explicit-state'); fs.mkdirSync(state); fs.writeFileSync(path.join(state, 'config.yaml'), 'update_check: true\nartifacts_sync_mode_prompted: true\n'); + // gstack-update-check reads its cache from the same state root GSTACK_HOME selects (docs/state-root.md). + const stateCache = path.join(state, 'last-update-check'); + fs.writeFileSync(stateCache, UPGRADE); const output = runPreamble(home, { ...env, GSTACK_HOME: state }); expect(output).toContain(UPGRADE.trim()); expect(output).toContain('GSTACK_INSTRUCTION_BEGIN: upgrade-flow'); expect(output).toContain('UPDATE_CHECK: true'); expect(fs.readFileSync(cache, 'utf8')).toBe(UPGRADE); + expect(fs.readFileSync(stateCache, 'utf8')).toBe(UPGRADE); expect(fs.existsSync(networkLog)).toBe(false); }); }); diff --git a/test/relink.test.ts b/test/relink.test.ts index 65424f9f16..45b9e62331 100644 --- a/test/relink.test.ts +++ b/test/relink.test.ts @@ -56,6 +56,8 @@ function setupMockInstall(skills: string[]): void { fs.mkdirSync(mockBin, { recursive: true }); fs.copyFileSync(path.join(BIN, 'gstack-config'), path.join(mockBin, 'gstack-config')); fs.chmodSync(path.join(mockBin, 'gstack-config'), 0o755); + // A real install always ships the state-root twin beside the bins that source it. + fs.copyFileSync(path.join(BIN, 'gstack-state-root.sh'), path.join(mockBin, 'gstack-state-root.sh')); if (fs.existsSync(path.join(BIN, 'gstack-relink'))) { fs.copyFileSync(path.join(BIN, 'gstack-relink'), path.join(mockBin, 'gstack-relink')); fs.chmodSync(path.join(mockBin, 'gstack-relink'), 0o755); diff --git a/test/setup-claude-code-migration.test.ts b/test/setup-claude-code-migration.test.ts index 91b084e826..dcc14d6dfe 100644 --- a/test/setup-claude-code-migration.test.ts +++ b/test/setup-claude-code-migration.test.ts @@ -30,7 +30,7 @@ function fixture(copy: boolean) { put(path.join(root, 'VERSION'), '2.0.0.0\n'); put(path.join(root, 'ETHOS.md'), 'Fixture ethos\n'); put(path.join(root, 'package.json'), JSON.stringify({ type: 'module', scripts: { 'gen:skill-docs': 'bun run scripts/gen-skill-docs.ts' } })); - for (const bin of ['gstack-config', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code']) { + for (const bin of ['gstack-config', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code', 'gstack-state-root.sh']) { const target = path.join(root, 'bin', bin); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(path.join(ROOT, 'bin', bin), target); diff --git a/test/setup-gbrain-fixture.test.ts b/test/setup-gbrain-fixture.test.ts index 7053e095b7..9b0ea860b6 100644 --- a/test/setup-gbrain-fixture.test.ts +++ b/test/setup-gbrain-fixture.test.ts @@ -33,6 +33,11 @@ describe('setup-gbrain documented lock acquisition', () => { fs.mkdirSync(parent); fs.writeFileSync(lock, 'preserve lock file'); } + // The block resolves the state root through the installed gstack-paths. + const installBin = path.join(home, '.claude', 'skills', 'gstack', 'bin'); + fs.mkdirSync(installBin, { recursive: true }); + for (const b of ['gstack-paths', 'gstack-state-root.sh']) fs.copyFileSync(path.join(import.meta.dir, '..', 'bin', b), path.join(installBin, b)); + fs.chmodSync(path.join(installBin, 'gstack-paths'), 0o755); const source = fs.readFileSync(path.join(import.meta.dir, '..', 'setup-gbrain', 'SKILL.md.tmpl'), 'utf8'); const script = source.match(/\*\*Concurrent-run lock\.\*\*[\s\S]*?```bash\n([\s\S]*?)\n ```/)?.[1]; expect(script).toBeDefined(); diff --git a/test/skill-e2e-bws.test.ts b/test/skill-e2e-bws.test.ts index f1fc5d782f..bf90158456 100644 --- a/test/skill-e2e-bws.test.ts +++ b/test/skill-e2e-bws.test.ts @@ -219,7 +219,7 @@ Report the exact output — either "READY: " or "NEEDS_SETUP".`, // identically on main). const binDir = path.join(opDir, 'bin'); fs.mkdirSync(binDir, { recursive: true }); - for (const script of ['gstack-learnings-log', 'gstack-slug']) { + for (const script of ['gstack-learnings-log', 'gstack-slug', 'gstack-state-root.sh']) { fs.copyFileSync(path.join(ROOT, 'bin', script), path.join(binDir, script)); fs.chmodSync(path.join(binDir, script), 0o755); } diff --git a/test/skill-e2e-context-skills.test.ts b/test/skill-e2e-context-skills.test.ts index 32335ffe13..69a6803935 100644 --- a/test/skill-e2e-context-skills.test.ts +++ b/test/skill-e2e-context-skills.test.ts @@ -59,7 +59,7 @@ function setupWorkdir(suffix: string): { workDir: string; gstackHome: string; sl const binDir = path.join(workDir, 'bin'); fs.mkdirSync(binDir, { recursive: true }); for (const script of [ - 'gstack-timeline-log', 'gstack-timeline-read', 'gstack-slug', + 'gstack-timeline-log', 'gstack-timeline-read', 'gstack-slug', 'gstack-state-root.sh', 'gstack-learnings-log', 'gstack-learnings-search', 'gstack-update-check', 'gstack-config', 'gstack-repo-mode', ]) { diff --git a/test/skill-e2e-learnings.test.ts b/test/skill-e2e-learnings.test.ts index 8672ef3c2a..78a933fd85 100644 --- a/test/skill-e2e-learnings.test.ts +++ b/test/skill-e2e-learnings.test.ts @@ -40,7 +40,7 @@ describeIfSelected('Learnings E2E', ['learnings-show'], () => { // Copy bin scripts needed by /learn const binDir = path.join(workDir, 'bin'); fs.mkdirSync(binDir, { recursive: true }); - for (const script of ['gstack-learnings-search', 'gstack-learnings-log', 'gstack-slug']) { + for (const script of ['gstack-learnings-search', 'gstack-learnings-log', 'gstack-slug', 'gstack-state-root.sh']) { fs.copyFileSync(path.join(ROOT, 'bin', script), path.join(binDir, script)); fs.chmodSync(path.join(binDir, script), 0o755); } diff --git a/test/skill-e2e-plan-tune.test.ts b/test/skill-e2e-plan-tune.test.ts index 17a7a2a0f5..7bb7530be8 100644 --- a/test/skill-e2e-plan-tune.test.ts +++ b/test/skill-e2e-plan-tune.test.ts @@ -50,6 +50,7 @@ describeIfSelected('PlanTune E2E', ['plan-tune-inspect'], () => { for (const script of [ 'gstack-slug', 'gstack-config', + 'gstack-state-root.sh', 'gstack-question-log', 'gstack-question-preference', 'gstack-developer-profile', diff --git a/test/skill-e2e-session-intelligence.test.ts b/test/skill-e2e-session-intelligence.test.ts index 90fdbe149f..de28e2d12d 100644 --- a/test/skill-e2e-session-intelligence.test.ts +++ b/test/skill-e2e-session-intelligence.test.ts @@ -44,7 +44,7 @@ describeIfSelected('Session Intelligence E2E', [ const binDir = path.join(workDir, 'bin'); fs.mkdirSync(binDir, { recursive: true }); for (const script of [ - 'gstack-timeline-log', 'gstack-timeline-read', 'gstack-slug', + 'gstack-timeline-log', 'gstack-timeline-read', 'gstack-slug', 'gstack-state-root.sh', 'gstack-learnings-log', 'gstack-learnings-search', ]) { const src = path.join(ROOT, 'bin', script); diff --git a/test/skill-e2e-skillify.test.ts b/test/skill-e2e-skillify.test.ts index 175bb03fa3..1fd2bec515 100644 --- a/test/skill-e2e-skillify.test.ts +++ b/test/skill-e2e-skillify.test.ts @@ -96,7 +96,7 @@ function setupSkillifyWorkdir(suffix: string, installSkills: string[] = ['scrape const binDir = path.join(workDir, 'bin'); fs.mkdirSync(binDir, { recursive: true }); for (const script of [ - 'gstack-timeline-log', 'gstack-slug', 'gstack-config', + 'gstack-timeline-log', 'gstack-slug', 'gstack-config', 'gstack-state-root.sh', 'gstack-update-check', 'gstack-repo-mode', 'gstack-learnings-log', 'gstack-learnings-search', ]) { diff --git a/test/skill-positional-literals.test.ts b/test/skill-positional-literals.test.ts index 84ef43d033..6a48dd89bf 100644 --- a/test/skill-positional-literals.test.ts +++ b/test/skill-positional-literals.test.ts @@ -93,8 +93,9 @@ for (const host of ['claude', 'codex'] as const) for (const args of [[], tenArgu test(`${label}: upgrade snooze advances the same-version level`, () => { mkdirSync(join(root, '.gstack'), { recursive: true }); writeFileSync(join(root, '.gstack/update-snoozed'), '{new} 1 0\n'); - const block = skill(host, 'gstack-upgrade').match(/```bash\n(_SNOOZE_FILE=[\s\S]*?)```/)![1]; - expect(run(apply(block)).status).toBe(0); + const block = skill(host, 'gstack-upgrade').match(/```bash\n((?:eval [^\n]*gstack-paths[^\n]*\n)?_SNOOZE_FILE=[\s\S]*?)```/)![1]; + // The block resolves the state root first; this fixture has no install, so it supplies the root directly. + expect(run(apply(block), { GSTACK_STATE_ROOT: join(root, '.gstack') }).status).toBe(0); expect(readFileSync(join(root, '.gstack/update-snoozed'), 'utf8')).toMatch(/^\{new\} 2 \d+\n$/); }); test(`${label}: health error preserves its diagnostic argument`, () => { diff --git a/test/state-root-config-merge.test.ts b/test/state-root-config-merge.test.ts new file mode 100644 index 0000000000..efc614727c --- /dev/null +++ b/test/state-root-config-merge.test.ts @@ -0,0 +1,149 @@ +/** + * Privacy and egress opt-outs never become more permissive when the state + * root moves (W1): merged keys and trust-policy deny tiers take the most + * restrictive value across the resolved root and $HOME/.gstack. These are the + * dedicated merge tests, so they unset GSTACK_TEST_LEGACY_ROOT (test-setup.ts) + * and use a fake HOME instead. + */ +import { describe, test, expect, beforeEach, afterEach } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { readConfigKey } from '../lib/state-root'; +import { repoPolicyTier, repoPolicyTierBatch } from '../lib/gbrain-repo-policy-client'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const CONFIG = path.join(ROOT, 'bin', 'gstack-config'); +const POLICY = path.join(ROOT, 'bin', 'gstack-gbrain-repo-policy'); + +let tmp: string, home: string, legacy: string, resolved: string, env: Record; + +beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-merge-')); + home = path.join(tmp, 'home'); + legacy = path.join(home, '.gstack'); + resolved = path.join(tmp, 'custom'); + fs.mkdirSync(legacy, { recursive: true }); + fs.mkdirSync(resolved, { recursive: true }); + env = { + ...(process.env as Record), + HOME: home, GSTACK_HOME: resolved, GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', + }; + delete env.GSTACK_TEST_LEGACY_ROOT; +}); +afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + +function config(args: string[], extra: Record = {}) { + return spawnSync('bash', [CONFIG, ...args], { env: { ...env, ...extra }, encoding: 'utf-8', timeout: 20_000 }); +} + +describe('merged config keys', () => { + test('a restrictive $HOME/.gstack only applies when GSTACK_TEST_LEGACY_ROOT does not redirect the second root', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'telemetry: off\n'); + fs.writeFileSync(path.join(resolved, 'config.yaml'), 'telemetry: community\n'); + expect(config(['get', 'telemetry']).stdout).toBe('off'); + const emptyLegacy = path.join(tmp, 'empty-legacy'); + fs.mkdirSync(emptyLegacy); + expect(config(['get', 'telemetry'], { GSTACK_TEST_LEGACY_ROOT: emptyLegacy }).stdout).toBe('community'); + expect(readConfigKey('telemetry', { ...env, GSTACK_TEST_LEGACY_ROOT: emptyLegacy })).toBe('community'); + expect(readConfigKey('telemetry', env)).toBe('off'); + }); + + test('codex_reviews: disabled in $HOME/.gstack survives a later unrelated set in a different resolved root', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'codex_reviews: disabled\n'); + expect(config(['set', 'explain_level', 'terse']).status).toBe(0); + expect(config(['set', 'codex_reviews', 'enabled']).status).toBe(0); + expect(config(['get', 'codex_reviews']).stdout).toBe('disabled'); + }); + + test('proactive: true in the resolved root wins even when $HOME/.gstack says false (not a merged key)', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'proactive: false\n'); + expect(config(['set', 'proactive', 'true']).status).toBe(0); + expect(config(['get', 'proactive']).stdout).toBe('true'); + }); + + test('set names the receiving root and the overriding root, and the printed command changes the merged value', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'codex_reviews: disabled\n'); + const r = config(['set', 'codex_reviews', 'enabled']); + expect(r.status).toBe(0); + expect(r.stderr).toContain(`gstack-config: set codex_reviews in ${resolved}/config.yaml, but codex_reviews is still 'disabled': ${legacy}/config.yaml sets that more restrictive value`); + expect(r.stderr).toContain('docs/state-root.md'); + const fix = r.stderr.split('\n').find((l) => l.startsWith('fix: '))!; + expect(fix).toContain(`GSTACK_STATE_ROOT='${legacy}'`); + const command = fix.slice('fix: '.length).replace(/ \(https:.*\)$/, ''); + expect(spawnSync('bash', ['-c', command], { env, encoding: 'utf-8', timeout: 20_000 }).status).toBe(0); + expect(config(['get', 'codex_reviews']).stdout).toBe('enabled'); + }); + + test('a set with no overriding root stays silent', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'telemetry: anonymous\n'); + const r = config(['set', 'telemetry', 'off']); + expect(r.status).toBe(0); + expect(r.stderr).toBe(''); + }); + + test('list shows the winning root for merged keys and a disagreement line when root variables differ', () => { + fs.writeFileSync(path.join(legacy, 'config.yaml'), 'telemetry: off\n'); + fs.writeFileSync(path.join(resolved, 'config.yaml'), 'telemetry: community\nproactive: false\n'); + const plain = config(['list']).stdout; + expect(plain).toContain(`telemetry: off (set, ${legacy})`); + expect(plain).toContain('proactive: false (set)'); + expect(plain).not.toContain('root-selecting variables disagree'); + const other = path.join(tmp, 'other'); + const disagree = config(['list'], { GSTACK_STATE_DIR: other }).stdout; + expect(disagree).toContain(`# note: root-selecting variables disagree: GSTACK_HOME=${resolved} GSTACK_STATE_DIR=${other}; using ${resolved} (GSTACK_HOME wins).`); + expect(disagree).toContain('gstack-paths --explain'); + }); +}); + +describe('trust-policy deny tiers merge through bin/gstack-gbrain-repo-policy', () => { + const url = 'https://github.com/acme/secret'; + function policy(args: string[], input?: string) { + return spawnSync('bash', [POLICY, ...args], { env, input, encoding: 'utf-8', timeout: 20_000 }); + } + + test('a deny in $HOME/.gstack wins over read-write in the resolved root, for get, get --batch and the client', () => { + expect(policy(['set', url, 'read-write']).status).toBe(0); + fs.writeFileSync(path.join(legacy, 'gbrain-repo-policy.json'), JSON.stringify({ _schema_version: 2, 'github.com/acme/secret': 'deny' })); + expect(policy(['get', url]).stdout.trim()).toBe('deny'); + expect(policy(['get', '--batch'], `${url}\nhttps://github.com/acme/other\n`).stdout).toBe('deny\nnone\n'); + expect(repoPolicyTier(url, env).tier).toBe('deny'); + expect(repoPolicyTierBatch([url], env).get(url)?.tier).toBe('deny'); + }); + + test('a legacy store alone still denies, and a legacy read-write never loosens the resolved tier', () => { + fs.writeFileSync(path.join(legacy, 'gbrain-repo-policy.json'), JSON.stringify({ _schema_version: 2, 'github.com/acme/secret': 'deny', 'github.com/acme/open': 'read-write' })); + expect(repoPolicyTier(url, env).tier).toBe('deny'); + expect(policy(['get', '--batch'], `${url}\n`).stdout).toBe('deny\n'); + expect(policy(['set', 'https://github.com/acme/open', 'read-only']).status).toBe(0); + expect(policy(['get', 'https://github.com/acme/open']).stdout.trim()).toBe('read-only'); + expect(fs.readFileSync(path.join(legacy, 'gbrain-repo-policy.json'), 'utf-8')).toContain('"read-write"'); + }); +}); + +describe('test preload hermeticity', () => { + test('bun test strips an inherited GSTACK_STATE_ROOT / GSTACK_STATE_DIR with one line each, and redirects the legacy root', () => { + const probe = path.join(tmp, 'probe.test.ts'); + fs.writeFileSync(probe, [ + "import { test, expect } from 'bun:test';", + "import { resolveStateRoot } from '" + path.join(ROOT, 'lib', 'state-root.ts').replace(/\\/g, '/') + "';", + "test('probe', () => {", + " expect(process.env.GSTACK_STATE_ROOT).toBeUndefined();", + " expect(process.env.GSTACK_STATE_DIR).toBeUndefined();", + " expect(process.env.GSTACK_TEST_LEGACY_ROOT).toBeTruthy();", + " expect(resolveStateRoot()).toBe(process.env.GSTACK_HOME);", + "});", + ].join('\n')); + const r = spawnSync('bun', ['test', '--preload', path.join(ROOT, 'test-setup.ts'), probe], { + cwd: tmp, + env: { ...env, GSTACK_HOME: resolved, GSTACK_STATE_ROOT: path.join(tmp, 'ambient'), GSTACK_STATE_DIR: path.join(tmp, 'ambient2') }, + encoding: 'utf-8', + timeout: 60_000, + }); + expect(r.status).toBe(0); + expect(r.stderr).toContain('test-setup: stripped inherited GSTACK_STATE_ROOT; tests isolate state via GSTACK_HOME'); + expect(r.stderr).toContain('test-setup: stripped inherited GSTACK_STATE_DIR; tests isolate state via GSTACK_HOME'); + expect(r.stderr.match(/test-setup: stripped/g)?.length).toBe(2); + }); +}); diff --git a/test/state-root-one-variable.test.ts b/test/state-root-one-variable.test.ts new file mode 100644 index 0000000000..4de1b48158 --- /dev/null +++ b/test/state-root-one-variable.test.ts @@ -0,0 +1,68 @@ +/** + * One variable moves every store (W1). With only GSTACK_HOME, only + * GSTACK_STATE_ROOT or only GSTACK_STATE_DIR pointing at a temp dir, the + * config, egress ledger, trust-policy store, telemetry and analytics log, hook + * error log, and the root uninstall reports all resolve under that directory, + * and nothing lands in $HOME/.gstack. + */ +import { describe, test, expect } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { resolveStateRoot } from '../lib/state-root'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const BIN = path.join(ROOT, 'bin'); + +for (const variable of ['GSTACK_HOME', 'GSTACK_STATE_ROOT', 'GSTACK_STATE_DIR'] as const) { + describe(`only ${variable} set`, () => { + test('every store resolves under it', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-one-var-')); + try { + const root = path.join(tmp, 'root'); + const home = path.join(tmp, 'home'); + const cwd = path.join(tmp, 'cwd'); + for (const d of [root, home, cwd]) fs.mkdirSync(d, { recursive: true }); + const env: Record = { + ...(process.env as Record), + HOME: home, GSTACK_HOME: '', GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', + GSTACK_TEST_LEGACY_ROOT: '', [variable]: root, + }; + expect(resolveStateRoot(env)).toBe(root); + const run = (cmd: string, args: string[], input?: string) => + spawnSync(cmd, args, { cwd, env, input, encoding: 'utf-8', timeout: 30_000 }); + + // config + expect(run('bash', [path.join(BIN, 'gstack-config'), 'set', 'telemetry', 'anonymous']).status).toBe(0); + expect(fs.readFileSync(path.join(root, 'config.yaml'), 'utf-8')).toContain('telemetry: anonymous'); + // telemetry + analytics log + expect(run('bash', [path.join(BIN, 'gstack-telemetry-log'), '--skill', 'qa', '--duration', '1', '--outcome', 'success', '--session-id', 'one-var-1', '--no-sweep']).status).toBe(0); + expect(fs.readFileSync(path.join(root, 'analytics', 'skill-usage.jsonl'), 'utf-8')).toContain('"skill":"qa"'); + // egress ledger + const receipt = run('bun', [path.join(BIN, 'gstack-egress-receipt'), 'write', '--sink', 'test', '--host', 'example.invalid', '--class', 'test', '--no-payload', '--consent', 'test']); + expect(receipt.status).toBe(0); + expect(fs.existsSync(path.join(root, 'security', 'egress.jsonl'))).toBe(true); + // trust-policy store + expect(run('bash', [path.join(BIN, 'gstack-gbrain-repo-policy'), 'set', 'https://github.com/a/b', 'deny']).status).toBe(0); + expect(fs.existsSync(path.join(root, 'gbrain-repo-policy.json'))).toBe(true); + // hook error log + const hook = run('bash', [path.join(ROOT, 'hosts', 'claude', 'hooks', 'question-log-hook')], '{not json'); + expect(hook.status).toBe(0); + expect(fs.readFileSync(path.join(root, 'hook-errors.log'), 'utf-8')).toContain('question-log-hook'); + // uninstall target: a non-default root is reported, never deleted + const skillsGstack = path.join(home, '.claude', 'skills', 'gstack'); + fs.mkdirSync(path.dirname(skillsGstack), { recursive: true }); + const un = run('bash', [path.join(BIN, 'gstack-uninstall'), '--force']); + expect(un.status).toBe(0); + expect(un.stderr).toContain(`left in place: ${root} (selected by ${variable}=${root})`); + expect(un.stderr).toContain(`fix: after checking it, remove it with rm -rf -- '${root}'`); + expect(fs.existsSync(path.join(root, 'config.yaml'))).toBe(true); + + expect(fs.existsSync(path.join(home, '.gstack'))).toBe(false); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); + }); +} diff --git a/test/state-root-parity.test.ts b/test/state-root-parity.test.ts new file mode 100644 index 0000000000..295411129e --- /dev/null +++ b/test/state-root-parity.test.ts @@ -0,0 +1,150 @@ +/** + * Parity: lib/state-root.ts (TS) and bin/gstack-state-root.sh (bash) are the + * two owners of the one state-root chain. Every row runs through both with an + * empty PATH (the bash twin must use builtins only — hooks call it on every + * tool use) and must produce byte-identical roots and config readings. + */ +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { resolveStateRoot, readConfigKey } from '../lib/state-root'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const TWIN = path.join(ROOT, 'bin', 'gstack-state-root.sh').replace(/\\/g, '/'); +const BASH = Bun.which('bash') ?? '/bin/bash'; + +type Row = { name: string; env: Record; win?: boolean }; + +function bashEval(row: Row, body: string): string { + const ostype = row.win ? 'msys' : 'linux-gnu'; + const r = spawnSync(BASH, ['-c', `OSTYPE=${ostype}; . "${TWIN}" && ${body}`], { + env: { USERPROFILE: '', ...row.env, PATH: '' }, + encoding: 'utf-8', + timeout: 10_000, + }); + if (r.status !== 0) throw new Error(`bash twin failed for ${row.name}: ${r.stderr}`); + return r.stdout; +} + +function tsEnv(row: Row): Record { + return { USERPROFILE: '', ...row.env }; +} + +const A = '/state/a', B = '/state/b', C = '/state/c'; +const rootRows: Row[] = [ + { name: 'nothing set, HOME set', env: { HOME: '/home/u' } }, + { name: 'GSTACK_STATE_ROOT alone', env: { HOME: '/home/u', GSTACK_STATE_ROOT: A } }, + { name: 'GSTACK_HOME alone', env: { HOME: '/home/u', GSTACK_HOME: B } }, + { name: 'GSTACK_STATE_DIR alone', env: { HOME: '/home/u', GSTACK_STATE_DIR: C } }, + { name: 'STATE_ROOT + HOME differ', env: { HOME: '/home/u', GSTACK_STATE_ROOT: A, GSTACK_HOME: B } }, + { name: 'STATE_ROOT + STATE_DIR differ', env: { HOME: '/home/u', GSTACK_STATE_ROOT: A, GSTACK_STATE_DIR: C } }, + { name: 'GSTACK_HOME + STATE_DIR differ', env: { HOME: '/home/u', GSTACK_HOME: B, GSTACK_STATE_DIR: C } }, + { name: 'all three differ', env: { HOME: '/home/u', GSTACK_STATE_ROOT: A, GSTACK_HOME: B, GSTACK_STATE_DIR: C } }, + { name: 'plugin data with gstack plugin root', env: { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '/plug', CLAUDE_PLUGIN_ROOT: '/plugins/gstack' } }, + { name: 'plugin data with mixed-case gstack root', env: { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '/plug', CLAUDE_PLUGIN_ROOT: '/plugins/GStack-1.2' } }, + { name: 'plugin data with foreign plugin root', env: { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '/plug', CLAUDE_PLUGIN_ROOT: '/plugins/codex' } }, + { name: 'plugin data without plugin root', env: { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '/plug' } }, + { name: 'GSTACK_STATE_DIR beats plugin data', env: { HOME: '/home/u', GSTACK_STATE_DIR: C, CLAUDE_PLUGIN_DATA: '/plug', CLAUDE_PLUGIN_ROOT: '/plugins/gstack' } }, + { name: 'empty strings count as unset', env: { HOME: '/home/u', GSTACK_STATE_ROOT: '', GSTACK_HOME: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '' } }, + { name: 'empty STATE_ROOT falls to GSTACK_HOME', env: { HOME: '/home/u', GSTACK_STATE_ROOT: '', GSTACK_HOME: B } }, + { name: 'empty plugin data with gstack root', env: { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '/plugins/gstack' } }, + { name: 'unset HOME', env: {} }, + { name: 'empty HOME', env: { HOME: '' } }, + { name: 'unset HOME ignores USERPROFILE off Windows', env: { USERPROFILE: 'C:/Users/u' } }, + { name: 'path with spaces and newline', env: { HOME: '/home/u', GSTACK_HOME: '/state/with space\n' } }, + { name: 'Windows: HOME unset uses USERPROFILE', env: { USERPROFILE: 'C:/Users/u' }, win: true }, + { name: 'Windows: HOME wins over USERPROFILE', env: { HOME: '/c/Users/h', USERPROFILE: 'C:/Users/u' }, win: true }, + { name: 'Windows: nothing set', env: {}, win: true }, + { name: 'Windows: GSTACK_HOME backslash path', env: { GSTACK_HOME: 'C:\\gstack\\state', USERPROFILE: 'C:/Users/u' }, win: true }, +]; + +describe('state root parity (bash twin vs lib/state-root.ts)', () => { + for (const row of rootRows) { + test(row.name, () => { + const bash = bashEval(row, 'gstack_state_root; printf x').replace(/x$/, ''); + expect(bash).toBe(resolveStateRoot(tsEnv(row), row.win ? 'win32' : 'linux')); + }); + } + + test('precedence is GSTACK_STATE_ROOT, GSTACK_HOME, GSTACK_STATE_DIR, gstack plugin data, $HOME/.gstack, .gstack', () => { + const base = { HOME: '/home/u', CLAUDE_PLUGIN_DATA: '/plug', CLAUDE_PLUGIN_ROOT: '/x/gstack' }; + expect(resolveStateRoot({ ...base, GSTACK_STATE_ROOT: A, GSTACK_HOME: B, GSTACK_STATE_DIR: C }, 'linux')).toBe(A); + expect(resolveStateRoot({ ...base, GSTACK_HOME: B, GSTACK_STATE_DIR: C }, 'linux')).toBe(B); + expect(resolveStateRoot({ ...base, GSTACK_STATE_DIR: C }, 'linux')).toBe(C); + expect(resolveStateRoot(base, 'linux')).toBe('/plug'); + expect(resolveStateRoot({ HOME: '/home/u' }, 'linux')).toBe('/home/u/.gstack'); + expect(resolveStateRoot({}, 'linux')).toBe('.gstack'); + }); +}); + +describe('config key parity (gstack_read_config_key vs readConfigKey)', () => { + let tmp: string; + let resolved: string, home: string, legacyOverride: string; + + beforeAll(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cfg-parity-')); + resolved = path.join(tmp, 'resolved'); + home = path.join(tmp, 'home'); + legacyOverride = path.join(tmp, 'legacy'); + fs.mkdirSync(resolved, { recursive: true }); + fs.mkdirSync(path.join(home, '.gstack'), { recursive: true }); + fs.mkdirSync(legacyOverride, { recursive: true }); + fs.writeFileSync(path.join(resolved, 'config.yaml'), [ + '# telemetry: off (comment lines never match)', + 'telemetry: community', + 'codex_reviews: enabled', + 'update_check: true ', + 'memorable_recall: on\r', + 'proactive: true', + 'proactive: false', + 'founder_resources: true', + 'empty_key:', + ].join('\n')); + fs.writeFileSync(path.join(home, '.gstack', 'config.yaml'), [ + 'telemetry: anonymous', + 'codex_reviews: disabled', + 'memorable_recall: bogus', + 'proactive: true', + 'founder_resources: false', + 'only_legacy: yes', + ].join('\n')); + fs.writeFileSync(path.join(legacyOverride, 'config.yaml'), 'telemetry: off\nupdate_check: false'); + }); + afterAll(() => fs.rmSync(tmp, { recursive: true, force: true })); + + const keys = ['telemetry', 'codex_reviews', 'update_check', 'memorable_recall', 'proactive', 'founder_resources', 'empty_key', 'only_legacy', 'missing']; + + test('every key reads identically through both twins, with and without the test legacy override', () => { + const envs: Row[] = [ + { name: 'resolved + real home', env: { HOME: home, GSTACK_HOME: resolved } }, + { name: 'legacy override', env: { HOME: home, GSTACK_HOME: resolved, GSTACK_TEST_LEGACY_ROOT: legacyOverride } }, + { name: 'resolved is the default root', env: { HOME: home } }, + { name: 'no HOME', env: { GSTACK_HOME: resolved } }, + { name: 'Windows USERPROFILE home', env: { USERPROFILE: home, GSTACK_HOME: resolved }, win: true }, + ]; + for (const row of envs) { + for (const key of keys) { + const bash = bashEval(row, `gstack_read_config_key ${key}; printf x`).replace(/x$/, ''); + const ts = readConfigKey(key, tsEnv(row), row.win ? 'win32' : 'linux') ?? ''; + expect(`${row.name}/${key}=${bash}`).toBe(`${row.name}/${key}=${ts}`); + } + } + }); + + test('merged keys take the most restrictive value; other keys read the resolved root only', () => { + const env = { HOME: home, GSTACK_HOME: resolved }; + expect(readConfigKey('telemetry', env, 'linux')).toBe('anonymous'); + expect(readConfigKey('codex_reviews', env, 'linux')).toBe('disabled'); + expect(readConfigKey('update_check', env, 'linux')).toBe('true'); + expect(readConfigKey('memorable_recall', env, 'linux')).toBe('bogus'); + expect(readConfigKey('proactive', env, 'linux')).toBe('false'); + expect(readConfigKey('founder_resources', env, 'linux')).toBe('true'); + expect(readConfigKey('only_legacy', env, 'linux')).toBeNull(); + expect(readConfigKey('empty_key', env, 'linux')).toBeNull(); + const overridden = { ...env, GSTACK_TEST_LEGACY_ROOT: legacyOverride }; + expect(readConfigKey('telemetry', overridden, 'linux')).toBe('off'); + expect(readConfigKey('codex_reviews', overridden, 'linux')).toBe('enabled'); + }); +}); diff --git a/test/state-root-ratchet.allowlist.json b/test/state-root-ratchet.allowlist.json new file mode 100644 index 0000000000..f828584c5d --- /dev/null +++ b/test/state-root-ratchet.allowlist.json @@ -0,0 +1,15 @@ +[ + { "path": "test/", "match": "*", "reason": "tests build fixtures with explicit state roots on purpose" }, + { "path": "browse/test/", "match": "*", "reason": "tests build fixtures with explicit state roots on purpose" }, + { "path": "docs/", "match": "*", "reason": "docs and design records quote paths as illustrative prose" }, + { "path": "CHANGELOG.md", "match": "*", "reason": "release history quotes old and new chains as prose" }, + { "path": "TODOS.md", "match": "*", "reason": "backlog prose, never executed" }, + { "path": "lib/state-root.ts", "match": "*", "reason": "the TS owner of the chain" }, + { "path": "bin/gstack-state-root.sh", "match": "*", "reason": "the bash owner of the chain" }, + { "path": "careful/bin/check-careful.sh", "match": "_GSTACK_HOME_DIR=\"${GSTACK_HOME:-$HOME/.gstack}\"", "reason": "partial-upgrade fallback, reached only when an older hook-extract.sh lacks gstack_hook_state_root (legacy order kept on purpose)" }, + { "path": "gstack-upgrade/SKILL.md.tmpl", "match": "elif [ -d \"$HOME/.gstack/repos/gstack/.git\" ]; then", "reason": "the relocated gstack checkout is an install location, not state" }, + { "path": "gstack-upgrade/SKILL.md.tmpl", "match": "INSTALL_DIR=\"$HOME/.gstack/repos/gstack\"", "reason": "the relocated gstack checkout is an install location, not state" }, + { "path": "scripts/resolvers/review.ts", "match": "*", "reason": "PENDING CROSS-OWNER (W5): delete this entry once the W1 handoff's review.ts / new-module edits are applied" }, + { "path": "scripts/resolvers/design.ts", "match": "*", "reason": "PENDING CROSS-OWNER (W5): delete this entry once the W1 handoff's design.ts edits are applied" }, + { "path": "scripts/test-free-shards.ts", "match": "*", "reason": "PENDING CROSS-OWNER (W2): delete this entry once the W1 handoff's test-free-shards.ts edit is applied" } +] diff --git a/test/state-root-ratchet.test.ts b/test/state-root-ratchet.test.ts new file mode 100644 index 0000000000..e0f27815a1 --- /dev/null +++ b/test/state-root-ratchet.test.ts @@ -0,0 +1,155 @@ +/** + * Ratchet (a): one state-root rule. Outside the two owners (lib/state-root.ts, + * bin/gstack-state-root.sh) and the committed allowlist, no tracked file may + * hand-roll the chain, and every gstack-paths eval must fail stop. + */ +import { describe, test, expect } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; +import { resolveStateRoot } from '../lib/state-root'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const ALLOWLIST_PATH = 'test/state-root-ratchet.allowlist.json'; + +type AllowEntry = { path: string; match: string; reason?: string }; +type Violation = { file: string; line: number; text: string; rule: string }; + +const CHAIN = /\\?\$\{GSTACK_(?:HOME|STATE_ROOT|STATE_DIR):-/; +const HOMEDIR_GSTACK = /homedir\(\)\s*,\s*['"`]\.gstack['"`]/g; +const PROSE_ROOT = /(~|\\?\$HOME|\\?\$\{HOME\})\/\.gstack(?![\w-])/; +const PATHS_EVAL = /eval "\$\(.*gstack-paths"?\)"/; +const GUARD = ': "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"'; +const GUARD_TS = ': "\\${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"'; + +const isProseSource = (f: string) => f.endsWith('.tmpl') || f.startsWith('scripts/resolvers/'); +const isExecutable = (f: string, text: string) => + /^#!.*\b(bash|sh)\b/.test(text) || f.endsWith('.sh') || f === 'setup'; + +/** Lines inside ```bash / ```sh fences (template-literal fences \`\`\` included), comments skipped. */ +function bashBlockLines(text: string): Array<[number, string]> { + const out: Array<[number, string]> = []; + let inBash = false; + text.split('\n').forEach((line, i) => { + const fence = line.trim().match(/^(?:\\`|`){3}(\w*)/); + if (fence) { inBash = inBash ? false : /^(bash|sh)$/.test(fence[1]); return; } + if (inBash && !line.trim().startsWith('#')) out.push([i + 1, line]); + }); + return out; +} + +export function scan(files: Map): Violation[] { + const v: Violation[] = []; + for (const [file, text] of files) { + const lines = text.split('\n'); + const code = (line: string) => !/^\s*(#|\/\/|\*)/.test(line) || isProseSource(file); + lines.forEach((line, i) => { + if (code(line) && CHAIN.test(line)) v.push({ file, line: i + 1, text: line.trim(), rule: 'inline state-root chain' }); + }); + if (/\.(ts|js|mjs)$/.test(file) || !file.includes('.')) { + for (const m of text.matchAll(HOMEDIR_GSTACK)) { + const line = text.slice(0, m.index).split('\n').length; + v.push({ file, line, text: lines[line - 1].trim(), rule: 'homedir() joined with .gstack' }); + } + } + if (isProseSource(file)) { + for (const [n, line] of bashBlockLines(text)) { + if (PROSE_ROOT.test(line)) v.push({ file, line: n, text: line.trim(), rule: 'executable ~/.gstack in a bash block' }); + } + lines.forEach((line, i) => { + if (/export GSTACK_STATE_ROOT\b/.test(line)) v.push({ file, line: i + 1, text: line.trim(), rule: 'export GSTACK_STATE_ROOT in prose' }); + }); + } + if (isProseSource(file) || isExecutable(file, text)) { + lines.forEach((line, i) => { + if (code(line) && PATHS_EVAL.test(line) && !line.includes(GUARD) && !line.includes(GUARD_TS)) { + v.push({ file, line: i + 1, text: line.trim(), rule: 'unguarded gstack-paths eval' }); + } + }); + } + } + return v; +} + +function allowed(v: Violation, allow: AllowEntry[]): boolean { + return allow.some((a) => (a.path.endsWith('/') ? v.file.startsWith(a.path) : v.file === a.path) + && (a.match === '*' || v.text === a.match)); +} + +function report(violations: Violation[]): string { + if (violations.length === 0) return ''; + return [ + ...violations.map((x) => `${x.file}:${x.line} ${x.text} (${x.rule})`), + 'Rule: gstack state lives under one root resolved by one chain; a hand-rolled chain drifts (plugin installs and GSTACK_HOME users silently split their state), and an unguarded eval writes under / when the resolver is missing.', + 'Fix: in prose and executables use eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; ' + GUARD + + ' (hooks and bins may source bin/gstack-state-root.sh instead); in TS use resolveStateRoot() from lib/state-root.ts.', + `Allowlist: ${ALLOWLIST_PATH}, keyed on file path plus matched line text, each entry with a reason. Legitimate only for illustrative prose, an install location that is not state, or a named partial-upgrade fallback.`, + ].join('\n'); +} + +function trackedFiles(): Map { + const r = spawnSync('git', ['ls-files', '-z'], { cwd: ROOT, encoding: 'utf-8', timeout: 30_000 }); + const files = new Map(); + for (const f of r.stdout.split('\0').filter(Boolean)) { + if (/\.(png|jpg|jpeg|gif|webp|pdf|ico|woff2?|ttf|lock|onnx|bin|zip)$/i.test(f)) continue; + const full = path.join(ROOT, f); + try { + const stat = fs.lstatSync(full); + if (!stat.isFile() || stat.size > 2_000_000) continue; + files.set(f, fs.readFileSync(full, 'utf-8')); + } catch { /* deleted in the working tree */ } + } + return files; +} + +const allow: AllowEntry[] = JSON.parse(fs.readFileSync(path.join(ROOT, ALLOWLIST_PATH), 'utf-8')); + +describe('ratchet (a): one state-root rule', () => { + test('every allowlist entry carries a reason', () => { + const missing = allow.filter((a) => !a.reason || !a.reason.trim()); + expect(missing.map((a) => `${a.path} :: ${a.match}`)).toEqual([]); + }); + + test('no tracked file outside the owners and the allowlist hand-rolls the state root', () => { + expect(report(scan(trackedFiles()).filter((x) => !allowed(x, allow)))).toBe(''); + }); + + test('planted violations fail with file:line, the Fix: text and the allowlist path', () => { + const planted = new Map([ + ['bin/gstack-planted', '#!/usr/bin/env bash\n# a comment "${GSTACK_HOME:-$HOME/.gstack}" is prose\nX="${GSTACK_HOME:-$HOME/.gstack}"\neval "$("$(dirname "$0")/gstack-paths")"\n'], + ['lib/planted.ts', "import { homedir } from 'os';\nconst r = join(\n homedir(), '.gstack');\n"], + ['planted/SKILL.md.tmpl', 'Prose ~/.gstack is fine.\n```bash\n# comment ~/.gstack is fine\nmkdir -p ~/.gstack/analytics\nexport GSTACK_STATE_ROOT\neval "$(~/.claude/skills/gstack/bin/gstack-paths)"\n```\n'], + ]); + const found = scan(planted); + expect(found.map((x) => `${x.file}:${x.line}:${x.rule}`)).toEqual([ + 'bin/gstack-planted:3:inline state-root chain', + 'bin/gstack-planted:4:unguarded gstack-paths eval', + 'lib/planted.ts:3:homedir() joined with .gstack', + 'planted/SKILL.md.tmpl:4:executable ~/.gstack in a bash block', + 'planted/SKILL.md.tmpl:5:export GSTACK_STATE_ROOT in prose', + 'planted/SKILL.md.tmpl:6:unguarded gstack-paths eval', + ]); + const message = report(found); + expect(message).toContain('planted/SKILL.md.tmpl:4 mkdir -p ~/.gstack/analytics'); + expect(message).toContain('Fix: '); + expect(message).toContain('resolveStateRoot()'); + expect(message).toContain(ALLOWLIST_PATH); + }); + + test('allowlist entries are keyed on text, not line numbers: inserting a line above still passes', () => { + const file = 'careful/bin/check-careful.sh'; + const text = fs.readFileSync(path.join(ROOT, file), 'utf-8'); + const shifted = new Map([[file, `# inserted line\n${text}`]]); + const found = scan(shifted); + expect(found.length).toBeGreaterThan(0); + expect(found.filter((x) => !allowed(x, allow))).toEqual([]); + }); + + test('guarded evals and the owners pass, and the TS owner resolves the documented default', () => { + const ok = new Map([ + ['x/SKILL.md.tmpl', '```bash\neval "$(~/.claude/skills/gstack/bin/gstack-paths)"; ' + GUARD + '\nls "$GSTACK_STATE_ROOT"/projects\n```\n'], + ]); + expect(scan(ok)).toEqual([]); + expect(resolveStateRoot({ HOME: '/h' }, 'linux')).toBe('/h/.gstack'); + }); +}); diff --git a/test/state-root-resolver-failure.test.ts b/test/state-root-resolver-failure.test.ts new file mode 100644 index 0000000000..f7ea042dd6 --- /dev/null +++ b/test/state-root-resolver-failure.test.ts @@ -0,0 +1,73 @@ +/** + * Resolver failure is fail-stop (W1). With bin/gstack-state-root.sh removed + * from an install, a real bash block copied from a generated SKILL.md and a + * migrated executable both stop with the reinstall message, and nothing is + * written outside the test's temp root. + */ +import { describe, test, expect } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { resolveStateRoot } from '../lib/state-root'; + +const ROOT = path.resolve(import.meta.dir, '..'); + +/** The first ```bash block of a generated SKILL.md that evals gstack-paths. */ +function contextRecoveryBlock(): string { + const md = fs.readFileSync(path.join(ROOT, 'qa', 'SKILL.md'), 'utf-8'); + const start = md.indexOf('## Context Recovery'); + const open = md.indexOf('```bash\n', start) + '```bash\n'.length; + return md.slice(open, md.indexOf('\n```', open)); +} + +/** Every path under dir, except a host git wrapper's own log dir (not gstack's). */ +function listTree(dir: string): string[] { + const out: string[] = []; + for (const e of fs.readdirSync(dir, { withFileTypes: true })) { + if (e.name === '.capy') continue; + const p = path.join(dir, e.name); + out.push(p); + if (e.isDirectory() && !e.isSymbolicLink()) out.push(...listTree(p)); + } + return out; +} + +describe('state-root resolver failure', () => { + test('a generated SKILL.md block and a migrated bin stop with the reinstall message when the twin is missing', () => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-resolver-fail-')); + try { + const home = path.join(tmp, 'home'); + const bin = path.join(home, '.claude', 'skills', 'gstack', 'bin'); + const cwd = path.join(tmp, 'cwd'); + fs.mkdirSync(bin, { recursive: true }); + fs.mkdirSync(cwd); + for (const b of ['gstack-paths', 'gstack-slug', 'gstack-config']) { + fs.copyFileSync(path.join(ROOT, 'bin', b), path.join(bin, b)); + fs.chmodSync(path.join(bin, b), 0o755); + } + const env = { + PATH: process.env.PATH ?? '', HOME: home, TMPDIR: path.join(tmp, 'tmp'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', + }; + expect(resolveStateRoot(env)).toBe(`${home}/.gstack`); + const before = listTree(tmp).sort(); + + const block = contextRecoveryBlock(); + expect(block).toContain('gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"'); + const skill = spawnSync('bash', ['-c', block + '\necho REACHED_END'], { cwd, env, encoding: 'utf-8', timeout: 30_000 }); + expect(skill.status).not.toBe(0); + expect(skill.stderr).toContain('gstack-paths failed; reinstall with ./setup or /gstack-upgrade'); + expect(skill.stdout).not.toContain('REACHED_END'); + + const config = spawnSync('bash', [path.join(bin, 'gstack-config'), 'set', 'telemetry', 'off'], { cwd, env, encoding: 'utf-8', timeout: 30_000 }); + expect(config.status).toBe(1); + expect(config.stderr).toContain('cannot resolve the gstack state root'); + expect(config.stderr).toContain('reinstall with ./setup or /gstack-upgrade'); + + expect(listTree(tmp).sort()).toEqual(before); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/test/state-root-touchfile-superset.test.ts b/test/state-root-touchfile-superset.test.ts new file mode 100644 index 0000000000..8906577965 --- /dev/null +++ b/test/state-root-touchfile-superset.test.ts @@ -0,0 +1,35 @@ +/** + * Touchfile coverage for W1's new modules: touching lib/state-root.ts, + * bin/gstack-state-root.sh or hosts/claude/hooks/hook-log.ts must select at + * least the paid evals their source files selected on the base commit + * (test/fixtures/state-root-selection-golden.json, recorded before the move). + */ +import { describe, test, expect } from 'bun:test'; +import * as fs from 'fs'; +import * as path from 'path'; +import { E2E_TOUCHFILES, LLM_JUDGE_TOUCHFILES, GLOBAL_TOUCHFILES, selectTests } from './helpers/touchfiles'; +import { resolveStateRoot } from '../lib/state-root'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const GOLDEN = 'test/fixtures/state-root-selection-golden.json'; +const golden: { modules: Record } = + JSON.parse(fs.readFileSync(path.join(ROOT, GOLDEN), 'utf-8')); + +describe('W1 touchfile superset', () => { + test('the golden covers every new state-root module', () => { + expect(Object.keys(golden.modules).sort()).toEqual(['bin/gstack-state-root.sh', 'hosts/claude/hooks/hook-log.ts', 'lib/state-root.ts']); + expect(typeof resolveStateRoot).toBe('function'); + }); + + for (const [mod, rec] of Object.entries(golden.modules)) { + test(`touching ${mod} selects a superset of ${rec.sources.join(', ')}`, () => { + const e2e = new Set(selectTests([mod], E2E_TOUCHFILES, GLOBAL_TOUCHFILES).selected); + const llm = new Set(selectTests([mod], LLM_JUDGE_TOUCHFILES, GLOBAL_TOUCHFILES).selected); + const missing = [...rec.e2e.filter((t) => !e2e.has(t)), ...rec.llmJudge.filter((t) => !llm.has(t))]; + expect(missing, [ + `${mod} selects fewer paid evals than its source files did: ${missing.join(', ')}`, + `Fix: add ${mod} to those entries in test/helpers/touchfiles-data.ts (golden: ${GOLDEN}).`, + ].join('\n')).toEqual([]); + }); + } +}); diff --git a/test/team-mode.test.ts b/test/team-mode.test.ts index 2419c60e04..982cd0b11a 100644 --- a/test/team-mode.test.ts +++ b/test/team-mode.test.ts @@ -351,7 +351,7 @@ describe('setup --team / --no-team / -q', () => { fs.writeFileSync(file, content, { mode: 0o755 }); }; try { - for (const rel of ['setup', 'VERSION', 'SKILL.md', 'qa/SKILL.md', 'bin/gstack-config', 'bin/gstack-patch-names', 'scripts/resolve-codex-generation-model.ts', 'scripts/models.ts', 'scripts/preflight-codex-overlap.ts', 'scripts/discover-skills.ts', 'scripts/external-skill-names.ts', 'scripts/host-config.ts']) { + for (const rel of ['setup', 'VERSION', 'SKILL.md', 'qa/SKILL.md', 'bin/gstack-config', 'bin/gstack-patch-names', 'bin/gstack-state-root.sh', 'scripts/resolve-codex-generation-model.ts', 'scripts/models.ts', 'scripts/preflight-codex-overlap.ts', 'scripts/discover-skills.ts', 'scripts/external-skill-names.ts', 'scripts/host-config.ts']) { const dest = path.join(cwd, rel); fs.mkdirSync(path.dirname(dest), { recursive: true }); fs.copyFileSync(path.join(ROOT, rel), dest); diff --git a/test/uninstall.test.ts b/test/uninstall.test.ts index 82316d5eb2..83d5e39267 100644 --- a/test/uninstall.test.ts +++ b/test/uninstall.test.ts @@ -258,7 +258,7 @@ describe('hook cleanup runs before the install root is deleted', () => { fs.mkdirSync(installBin, { recursive: true }); // The installed copies — the uninstaller under test IS the one inside // the root it deletes. - for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config']) { + for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) { const src = path.join(ROOT, 'bin', b); const dst = path.join(installBin, b); fs.copyFileSync(src, dst); @@ -317,7 +317,7 @@ describe('the Memorable bridge hook is removed by name and the kept config is le const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack'); const installBin = path.join(installRoot, 'bin'); fs.mkdirSync(installBin, { recursive: true }); - for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config']) { + for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) { const dst = path.join(installBin, b); fs.copyFileSync(path.join(ROOT, 'bin', b), dst); fs.chmodSync(dst, 0o755); @@ -360,7 +360,7 @@ describe('the Memorable arm stays quiet when nothing of its is registered', () = const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack'); const installBin = path.join(installRoot, 'bin'); fs.mkdirSync(installBin, { recursive: true }); - for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config']) { + for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) { const dst = path.join(installBin, b); fs.copyFileSync(path.join(ROOT, 'bin', b), dst); fs.chmodSync(dst, 0o755); @@ -392,7 +392,7 @@ describe('hook cleanup under lock contention is loud, never silent (review-army) const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack'); const installBin = path.join(installRoot, 'bin'); fs.mkdirSync(installBin, { recursive: true }); - for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config']) { + for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) { const dst = path.join(installBin, b); fs.copyFileSync(path.join(ROOT, 'bin', b), dst); fs.chmodSync(dst, 0o755); @@ -449,7 +449,7 @@ describe('the consent key never outlives the hook, even when the config lives ou const installBin = path.join(installRoot, 'bin'); fs.mkdirSync(installBin, { recursive: true }); fs.mkdirSync(otherRoot, { recursive: true }); - for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config']) { + for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) { const dst = path.join(installBin, b); fs.copyFileSync(path.join(ROOT, 'bin', b), dst); fs.chmodSync(dst, 0o755); @@ -480,7 +480,7 @@ describe('the consent flip does not depend on the hook manager being present', ( const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack'); const installBin = path.join(installRoot, 'bin'); fs.mkdirSync(installBin, { recursive: true }); - for (const b of ['gstack-uninstall', 'gstack-config']) { // no settings hook, no session-update + for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh']) { // no settings hook, no session-update const dst = path.join(installBin, b); fs.copyFileSync(path.join(ROOT, 'bin', b), dst); fs.chmodSync(dst, 0o755); @@ -499,3 +499,65 @@ describe('the consent flip does not depend on the hook manager being present', ( } }); }); + +describe('state-root safety: only the default root is deleted (docs/state-root.md)', () => { + let tmp: string, mockHome: string, installBin: string, installRoot: string; + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-uninstall-root-')); + mockHome = path.join(tmp, 'home'); + installRoot = path.join(mockHome, '.claude', 'skills', 'gstack'); + installBin = path.join(installRoot, 'bin'); + fs.mkdirSync(installBin, { recursive: true }); + for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh']) { + fs.copyFileSync(path.join(ROOT, 'bin', b), path.join(installBin, b)); + fs.chmodSync(path.join(installBin, b), 0o755); + } + }); + afterEach(() => fs.rmSync(tmp, { recursive: true, force: true })); + function uninstall(args: string[], env: Record, input?: string) { + return spawnSync('bash', [path.join(installBin, 'gstack-uninstall'), ...args], { + cwd: tmp, input, encoding: 'utf-8', timeout: 30_000, + env: { ...process.env, HOME: mockHome, GSTACK_SETTINGS_FILE: path.join(mockHome, 'settings.json'), + GSTACK_HOME: '', GSTACK_STATE_ROOT: '', GSTACK_STATE_DIR: '', CLAUDE_PLUGIN_DATA: '', ...env } as Record, + }); + } + + for (const mode of ['--force', 'interactive'] as const) { + test(`a custom GSTACK_HOME root is left in place with the removal command (${mode}); $HOME/.gstack goes`, () => { + const custom = path.join(tmp, 'custom-state'); + fs.mkdirSync(path.join(custom, 'projects'), { recursive: true }); + fs.mkdirSync(path.join(mockHome, '.gstack'), { recursive: true }); + const r = mode === '--force' ? uninstall(['--force'], { GSTACK_HOME: custom }) : uninstall([], { GSTACK_HOME: custom }, 'y\n'); + expect(r.status).toBe(0); + expect(r.stderr).toContain(`left in place: ${custom} (selected by GSTACK_HOME=${custom})`); + expect(r.stderr).toContain(`fix: after checking it, remove it with rm -rf -- '${custom}'`); + expect(r.stderr).toContain('docs/state-root.md'); + expect(fs.existsSync(path.join(custom, 'projects'))).toBe(true); + expect(fs.existsSync(path.join(mockHome, '.gstack'))).toBe(false); + if (mode === 'interactive') expect(r.stdout).toContain(`(kept) ${custom}`); + }); + } + + for (const [label, target] of [['$HOME', () => mockHome], ['/', () => '/'], ['the gstack checkout', () => installRoot]] as const) { + test(`$HOME/.gstack symlinked to ${label} is refused with exit 2 and a fix line`, () => { + fs.symlinkSync(target(), path.join(mockHome, '.gstack')); + const r = uninstall(['--force'], {}); + expect(r.status).toBe(2); + expect(r.stderr).toContain(`gstack-uninstall: refusing to delete ${path.join(mockHome, '.gstack')}: `); + expect(r.stderr).toMatch(/^fix: .*docs\/state-root\.md/m); + expect(fs.existsSync(path.join(installBin, 'gstack-uninstall'))).toBe(true); + expect(fs.lstatSync(path.join(mockHome, '.gstack')).isSymbolicLink()).toBe(true); + }); + } + + test('--keep-state deletes nothing and never refuses', () => { + const custom = path.join(tmp, 'custom-state'); + fs.mkdirSync(custom, { recursive: true }); + fs.symlinkSync(mockHome, path.join(mockHome, '.gstack')); + const r = uninstall(['--force', '--keep-state'], { GSTACK_HOME: custom }); + expect(r.status).toBe(0); + expect(r.stderr).not.toContain('left in place:'); + expect(fs.existsSync(custom)).toBe(true); + expect(fs.lstatSync(path.join(mockHome, '.gstack')).isSymbolicLink()).toBe(true); + }); +}); diff --git a/test/user-render-out-dir-install.test.ts b/test/user-render-out-dir-install.test.ts index e982f9cd6b..07dd014e7c 100644 --- a/test/user-render-out-dir-install.test.ts +++ b/test/user-render-out-dir-install.test.ts @@ -173,6 +173,7 @@ describe('link_claude_skill_dirs prefers rendered SKILL.md (behavior)', () => { 'SKILL_PREFIX=0', '_WINDOWS_COPY_NOTE_PRINTED=1', `GSTACK_HOME="${home}"`, + `GSTACK_STATE_ROOT="${home}"`, extractFn(SETUP_SRC, '_link_or_copy'), extractFn(SETUP_SRC, '_print_windows_copy_note_once'), extractFn(SETUP_SRC, '_link_skill_runtime_assets'), diff --git a/unfreeze/SKILL.md b/unfreeze/SKILL.md index e7e59380f3..7fa6e8e956 100644 --- a/unfreeze/SKILL.md +++ b/unfreeze/SKILL.md @@ -25,8 +25,9 @@ Use when asked to "unfreeze", "unlock edits", "remove freeze", or Remove the edit restriction set by `/freeze`, allowing edits to all directories. ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"unfreeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"unfreeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Clear the boundary diff --git a/unfreeze/SKILL.md.tmpl b/unfreeze/SKILL.md.tmpl index 58f4c3a4b1..04a4022dad 100644 --- a/unfreeze/SKILL.md.tmpl +++ b/unfreeze/SKILL.md.tmpl @@ -21,8 +21,9 @@ sensitive: true Remove the edit restriction set by `/freeze`, allowing edits to all directories. ```bash -mkdir -p ~/.gstack/analytics -echo '{"skill":"unfreeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +eval "$(~/.claude/skills/gstack/bin/gstack-paths)"; : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}" +mkdir -p "$GSTACK_STATE_ROOT"/analytics +echo '{"skill":"unfreeze","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> "$GSTACK_STATE_ROOT"/analytics/skill-usage.jsonl 2>/dev/null || true ``` ## Clear the boundary