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.
This commit is contained in:
garrytan committed 2026-09-30 06:38:50 +00:00
1 parent ab3b6f02e8
commit cd7485b0b4
98 files changed
+546 -268

No files matched your search

+2 -2
View File
@@ -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, "_"));
+2 -2
View File
@@ -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");
}
+3 -3
View File
@@ -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<fs.BigIntStats,'dev'|'ino'|'mtimeNs'|'ctimeNs'|'isFile'|'isSymbolicLink'|'isDirectory'> & Pick<fs.Stats,'nlink'|'size'|'mode'|'uid'>;
@@ -179,9 +180,8 @@ export function discardAtomicNoReplaceTemp(path:string,publisherPid:number,optio
}
export function stateRoot(env: Record<string,string|undefined> = 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;
+3 -8
View File
@@ -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 {
+2 -4
View File
@@ -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");
}
/**
+2 -2
View File
@@ -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"),
+3 -2
View File
@@ -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 {
+2 -1
View File
@@ -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");
}
+8 -4
View File
@@ -39,6 +39,13 @@ function legacyStateRoot(env: StateRootEnv, platform: NodeJS.Platform): string |
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<string, readonly string[]> = {
telemetry: ['off', 'anonymous', 'community'],
@@ -75,11 +82,8 @@ export interface ConfigKeyReading {
* resolved root only.
*/
export function readConfigKeyWithRoot(key: string, env: StateRootEnv = process.env, platform: NodeJS.Platform = process.platform): ConfigKeyReading {
const resolved = resolveStateRoot(env, platform);
const order = MERGED_CONFIG_KEYS[key];
const candidates = [resolved];
const legacy = order ? legacyStateRoot(env, platform) : null;
if (legacy && legacy !== resolved) candidates.push(legacy);
const candidates = order ? mergedStateRoots(env, platform) : [resolveStateRoot(env, platform)];
let best: ConfigKeyReading = { value: null, root: null };
let bestRank = Infinity;
for (const root of candidates) {