v1.91.11.0 refactor: one state-root rule, browse route table, shared shard engine, PTY harness split, MECE review resolvers (#3002)

* refactor(resolvers): split review.ts into MECE resolver modules (pure move)

Move every function from scripts/resolvers/review.ts, unchanged, into:
- review-dashboard.ts: review dashboard, plan-file review report
- plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery,
  plan-completion audit/gate (ship + review), plan verification exec
- spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause
- outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan
  review, Codex doc review, disabled-outside record
- review-scope.ts: scope drift, cross-review dedup, shared-code reuse

review.ts is deleted; index.ts imports the new modules. gen-skill-docs
output is byte-identical for every host (--host all). Test imports and
source-path references are re-pointed; the two source-text report/gate
tests in gen-skill-docs.test.ts become behavioral renders across every
consuming skill and host. All 46 touchfile entries that named review.ts
now name all five modules, guarded by a recorded selection golden.

* test(browse): black-box auth matrix for every server route and both surfaces

Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token,
root token, scoped token and the SSE cookie for all 33 routes, plus unmatched
paths and wrong methods. Denials assert today's exact status, body and content
type; allowed credentials assert the handler was reached. Written against the
unchanged if-chain server so the W3 route-table refactor must keep it green.

* refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts

The shared shard engine grows from the existing strict-output module
(runShardChild, killProcessGroup, signal forwarding, strict classifier).
scripts/test-strict-output.ts stays as a re-export so existing importers,
mock.module paths and the strict-output/run-shard-child tests are unchanged.
The engine inherits the global touchfile entry; the free runner's CLI-routing
fixture copies the new module.

* refactor(resolvers): decompose the three >150-line review resolvers (output-neutral)

Split generateAdversarialStep, generateCodexPlanReview and
generatePlanCompletionAuditInner into per-section helpers whose template
literals are copied verbatim, so every function in the new modules is at
or under 150 lines. gen-skill-docs output is byte-identical for every host
(--host all, compared against 96764e80 with a fixed --link-root).

* refactor(resolvers): one outside-voice failure policy (deliberate prose unification)

outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the
auth / timeout / empty-response bullets for all four call sites that
hand-typed them (Codex second opinion, adversarial step, Codex plan
review, design outside voices). Options are explicit per site
(timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no
defaults.

Deliberate generated-prose changes (every host):
- office-hours: 'Fall back to <native> subagent.' becomes
  'Fall back to the <native> subagent below.'
- plan-devex-review: the plain 'Auth failure (stderr contains ...)'
  bullets become the canonical bold bullets; auth also triggers on
  'API key'; 'auth failed' becomes 'authentication failed'.
- review/ship adversarial: 'exceeded 9 minutes and was terminated'
  becomes 'timed out after 9 minutes and was terminated'; the timeout
  is still MISSING COVERAGE.
- design outside voices: unchanged.

Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a
reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE
retention test, refreshed codex/factory ship goldens, and outside-voice.ts
in every touchfile entry of review.ts and design.ts (selection golden
extended).

* test(pty): fake PTY session driver with an injectable clock through the runner launch seam

The three plan-skill runners take an optional PtyDriver (launch, now,
monotonic, sleep); omitted, they use the real launcher and clocks exactly as
before. test/helpers/pty/fake-session.ts feeds scripted frames through that
seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting
and floor for success, deadline timeout, permission prompt and plan-ready
outcomes with no CLI or real timers. These cases must stay green unchanged
through the W4 split and the runPtySession extraction.

Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now
also lists test/helpers/pty/**.

* refactor(shard-engine): run both lanes on the shared engine; lane policy injected

Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard
tmp/Chromium sandbox + async cleanup backstop, log-path allocation and
full-stream log capture, one duration-seed reader/writer with a lane
predicate, LanePolicy (seed predicate + zero-execution verdict),
strictShardStatus, and the shared CLI flag loop. runShardChild takes an
optional companion (signal/settle) and waits a bounded 250ms to reap a
wall-killed child.

Free lane stops spawning shards itself: runFreeShard uses runShardChild
with trackShardBrowser as the companion (win32 path unchanged: no process
group, no negative-pid kill). Its sync state-dir removal stays lane policy.
Paid lane uses the sandbox, log, seed, verdict and flag primitives; the
hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged
(free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds,
warning under selection and passed-empty under EVALS_ALL).

paid-free-boundary's closure assertion now names the engine module, where
the strict classifier lives.

* test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity

- test/shard-engine.test.ts: failing/unhandled/module-load output fails both
  lanes, per-lane zero-execution and seed rules, whole-group kill on a wall
  timeout (both lanes), mocked-win32 path with no negative-pid kill,
  companion settle order, log capture, sandbox isolation, flag loop.
- test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence:
  seven outcome fixtures plus one real shard, run through both lanes and
  compared with classifications recorded from the base runners (96764e80).
- test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set,
  defaults, validation errors and the Unknown argument error per lane match
  the base runners.

* refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines

Output-neutral extraction under the fixture-corpus equivalence and runner
tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free);
paidShardCommand, settleShardSpool, settleBootstrapRetention and
printLogTail (paid). The bootstrap scope-creation block that
bootstrap-retention.test.ts evaluates stays verbatim.

* refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel

Pure move: every line of the former 5,047-line runner lands verbatim in one
module (four private helpers gain `export` for cross-module use):
binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it),
launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries,
runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the
original public surface by name; pty/ modules import siblings directly.

Tests that read the runner's source text:
- rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv:
  fallback chain, --model before extraArgs, hermetic --strict-mcp-config),
  pty-skill-seeding-wiring (runners through the fake driver; launcher through
  a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model"
  grep is replaced by the runners' fake-driver launch assertions.
- pty-screen-session / pty-screen-supervision: stop copying runner source;
  they mock.module the real pty/screen.ts (and the fixture cleanup) instead.
- re-pointed to the owning module (they execute a sliced runner body with
  injected boundaries; no seam exists for those boundaries yet):
  eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication,
  plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts
  and scans every pty/ module for raw process.env spreads.
- plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts.

* test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage

Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and
top-level function lengths by brace matching over masked source (strings,
comments, regex literals and template text masked; ${} expressions kept),
covering function declarations, arrow functions assigned to consts and
route-table handler properties, with no parser dependency. Its self-test
uses template literals and code-fence braces copied from
scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json
binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and
records the residual runner sizes (free 2352, paid 1921) as non-growth caps;
allowlist entries are keyed on file plus matched text and need a reason.
Failure output lists file:line, the rule, Fix: and the allowlist path.

touchfiles.test.ts gains the moved-code superset check over
test/fixtures/touchfile-move-goldens/ (W2 golden recorded at 96764e80:
test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none).

* refactor(browse): declared route table replaces the buildFetchHandler if-chain

The ~1,300-line if-chain in buildFetchHandler becomes a route table:
each entry declares method, path, auth kind and surfaces, and one auth
gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer,
scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token
required; extension-origin: 403 Forbidden). Unmatched requests take the
declared fallthrough (root-bearer check, then plain-text 404). Handlers move
to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files,
inspector}.ts and receive a RouteContext with auth checks as functions
instead of closing over factory locals. Dispatch order is unchanged:
tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a
literal in server.ts.

Behavior-preserving: the black-box auth matrix from the previous commit
passes unchanged. /memory and /inspector/events are declared root-bearer
because the blanket check always ran before their SSE-cookie branch.

Source-text route tests are rewritten as behavioral tests through
buildFetchHandler or a route's real handler with a stub RouteContext
(browse/test/route-test-harness.ts). Checks with no runtime seam are
re-pointed to the route modules: Surface type, /inspector/events SSE
helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import,
and the ngrok config lookup and startTunnel wiring that stay in server.ts.

* test(browse): stubbed-handler auth matrix and route inventory for the route table

Every ROUTES entry runs through the real dispatcher and gate with stub
handlers on each declared surface and six credentials; denials assert the
exact status and body each auth kind returned at 96764e8, admitted
credentials assert the handler ran (with the gate's TokenInfo for scoped
routes). Also pins the reviewed route inventory (method, path, auth kind,
surfaces), that every entry declares auth and surfaces, that the table's
tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the
unmatched fallthrough, and that the root token is rejected on every tunnel
route through buildFetchHandler.

* test(browse): ratchet (b) keeps route dispatch inside the route table

Scans browse/src/server.ts and browse/src/routes/*.ts for pathname
comparisons; only the table matcher and the tunnel-surface filter are
allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json
(keyed on file plus line text). Also checks every entry declares auth and
surfaces and that gstack registers no beforeRoute overlay itself. Self-tests
plant a violation and assert the file:line, Fix: and allowlist path in the
message, that a shifted line stays allowlisted, and that a reasonless entry
is rejected.

* test: touchfile superset check for modules moved out of browse/src/server.ts

Records the paid evals selected by touching browse/src/server.ts at 96764e80
(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects
a superset. The test reads every golden in test/fixtures/moved-module-selection/
so other moved-code goldens can sit beside it.

* test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane

Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded
host cannot turn a pass into a timeout. Base and branch runners still agree
on every classification under the new walls. The Windows exclusion entry
moves the free runner's ratchet (c) residual cap to 2356 lines.

* refactor(pty): one runPtySession loop drives observation, counting and floor

test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* ->
timeout and the failure contract the three runners each hand-rolled: the
run's own error wins over capture and close errors, close always runs, owned
fixture cleanup runs last (also when launch fails). Each runner now supplies a
PtySessionPlan: its boot/command step, poll cadence (2s observation/floor
sleep; counting's output wake + 250ms coalesce), tick policy (permission
handling, native identity, terminal rules stay per runner because they differ)
and capture hooks. The runner bodies are decomposed into top-level steps so no
function exceeds 150 lines; behavior is unchanged and the fake-driver cases
from the first W4 commit pass unmodified.

The counting capture step and the native completion-summary predicate are now
named functions (countingCapture, isNativeCompletionSummary), so
plan-create-prepublication and plan-count-completion call them directly
instead of executing sliced source. The two harnesses that still execute a
sliced runner body with injected boundaries (eng-seeded-completion-ai,
plan-floor-permission) pass the PtyDriver seam instead of overriding
Date/Bun.sleep.

* test(ratchet-c): register route modules, review resolver modules and server.ts residual cap

* refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines

launchClaudePty (349 lines) becomes launch preparation (args, hermetic
child env, owned state roots), recorder creation, spawn, the trust-dialog
watcher, close, and the session handle over one PtyProcess state object. The
failure order is unchanged: abort the viewport, dispose any recorders created
so far, dispose the viewport, rethrow. The --model / --strict-mcp-config
ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests.

engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each
self-contained issue family (declared cache, library retry hooks, cache
owner, injected singleton, shared writers, injected export) moves verbatim
into its own function. Every pty/ module is now <= 800 lines and every
top-level function <= 150 lines.

* test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams

The 188 unit tests move verbatim into claude-pty-runner.{screen,classify,
auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each
file imports only what it uses from the barrel). The five files that no longer
read a SKILL.md template join the test-of-test ratchet baseline with a reason.

* test(touchfiles): moved PTY modules keep their paid-eval selection

test/fixtures/touchfile-selection/w4-pty.json records, at 96764e8, the paid
evals selected by touching test/helpers/claude-pty-runner.ts (20) and
test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file
under test/helpers/pty/ (and pty/screen.ts for both sources) selects a
superset, reading every golden in that directory so later moves can add one;
a planted-violation case pins the report and its Fix line.

* fix(browse): unexchanged pair setup keys no longer authenticate bearer requests

validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and
/file (found while building the W3 auth matrix). A setup key now only
authenticates the /connect exchange.

* W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests

* W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack

Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design,
ios-qa daemon, lib and scripts resolve the state root through
bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the
twin and stop with a reinstall message when it is missing; hooks source it
and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts
delegate to resolveStateRoot. Analytics writers and readers move together
so the usage log stays one file. gstack-uninstall deletes state only at
~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor,
the checkout or the git root, and leaves any other resolved root in place
with the removal command. Fixtures that copy single bins now copy the twin.

* W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity

readConfigKey / gstack_read_config_key return the most restrictive
telemetry, memorable_recall, codex_reviews and update_check across the
resolved root and ~/.gstack; other keys read the resolved root only.
gstack-config set reports an overriding root with the exact override
command, list shows the winning root and a root-variable disagreement line.
gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress
reads through readConfigKey. test-setup.ts strips inherited
GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root.

* W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts)

One hook-errors.log writer: root from resolveStateRoot, 0600 on every
append, opt-in rate limit used only by memorable-user-prompt. The five
hooks route through it.

* W1: docs/state-root.md and README troubleshooting pointer

Precedence table, a real --explain example, the move-your-state recipe,
merged privacy keys, the uninstall rule, the resolver-failure fix, and the
plugin-mode note (evidence gate: no official plugin distribution).

* W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a)

Every gstack-paths eval in templates and resolvers carries the fail-stop
guard; executable ~/.gstack paths in bash blocks (context recovery preamble,
eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock,
retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer
prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE.
ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex),
ship goldens re-pinned, parity and context-budget caps raised to the measured
sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a
reasoned allowlist; W1 touchfile entries plus a superset golden.

* refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams

* test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps

* v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave

* test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture

* fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees

* fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity)

* test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck

* test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case

* fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped

* fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks)

* test(qa-callers): disable git auto maintenance in the caller fixture

Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git
2.55 it rewrote .git/objects fan-out directories while the write observer was
running, which surfaced as unauthorized mutations. Same gc.auto=0 /
maintenance.auto=false guard the shared-libs fixture already uses.

* test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked

* test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files)

The doc-sync fault cases replayed attempt 1 before reaching their gate and ran
out of their 285s budget. The fixture now seeds attempt 1 and the parent starts
at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave
(fb526898, e6ac813d, 6ce10ff7, d0c53577, 77cce3be). Local: stale-before,
recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
This commit is contained in:
Garry Tan authored and GitHub committed 2026-10-01 11:57:48 -07:00
1 parent 96764e80a6
commit df89475b17
383 files changed
+19348 -12625

No files matched your search

+4 -2
View File
@@ -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 ───────────────────────────────────────
+3 -1
View File
@@ -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"
+2 -1
View File
@@ -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. */
+2 -1
View File
@@ -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);
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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, <epoch>-<pid>-<uniq>.json.
# Writers (gstack-brain-enqueue, --discover-new) create records via tmp-file
# + atomic rename; the drain deletes exactly the files it snapshotted. No
+3 -1
View File
@@ -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.
+13 -9
View File
@@ -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" </dev/null 2>&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 --------------------------------------------------
+3 -1
View File
@@ -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"
+45 -16
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
# gstack-config — read/write ~/.gstack/config.yaml
# gstack-config — read/write <state root>/config.yaml (default ~/.gstack/config.yaml)
#
# Usage:
# gstack-config get <key> — 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
+9 -31
View File
@@ -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/<slug>/designs/ (where design-
* cwd) or under <state root>/projects/<slug>/designs/ (where design-
* review keeps rendered-DOM dumps: `designs/<audit>/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).
* <state root>/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';
+3 -1
View File
@@ -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 —
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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"
+3 -11
View File
@@ -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 {
+5 -5
View File
@@ -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' "<gstack state root: $_gstack_egress_lib_dir/gstack-state-root.sh is missing; reinstall with ./setup or /gstack-upgrade>"
fi
}
+5 -4
View File
@@ -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" });
+2 -1
View File
@@ -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:
+2 -2
View File
@@ -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();
+50 -5
View File
@@ -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() {
+3 -1
View File
@@ -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
+3 -2
View File
@@ -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
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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=""
+5 -3
View File
@@ -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
+2 -1
View File
@@ -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;
+71 -13
View File
@@ -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.
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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"
+2 -2
View File
@@ -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<typeof scan>[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
+6 -4
View File
@@ -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/<ts>/
# differing file is moved to $GSTACK_STATE_ROOT/backups/skills/<ts>/
# 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.
+3 -1
View File
@@ -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
+4 -2
View File
@@ -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"
+3 -1
View File
@@ -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:-}"
+3 -1
View File
@@ -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 '
+4 -1
View File
@@ -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.
+3 -1
View File
@@ -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)
+3 -1
View File
@@ -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
+4 -2
View File
@@ -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=<temp> 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 '/' '_')
+3 -1
View File
@@ -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
+135
View File
@@ -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 "$(<their dir>/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"
}
+2 -1
View File
@@ -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;
+5 -3
View File
@@ -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
+4 -2
View File
@@ -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"
+3 -1
View File
@@ -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"
+3 -1
View File
@@ -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
+75 -7
View File
@@ -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.
+4 -2
View File
@@ -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.
+12 -4
View File
@@ -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 "path<TAB>hash",
# $GSTACK_STATE_ROOT/verify-gate-trust (flat "path<TAB>hash",
# 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.