Files
gstack/lib/bin-context.ts
T
f30b7b788a v1.91.13.0 fix: severe bug wave (autoplan guard, land-and-deploy CI gate, project identity, gbrain, review gates) (#3013)
* fix(land-and-deploy): never merge over red, pending or missing CI (#2995)

/land-and-deploy gated only on required checks, so a repo with none
(every GitHub Free private repo, any repo without branch protection)
skipped the CI wait and could merge over red CI. The verdict now comes
from bin/gstack-ci-gate, a tested helper bound to the head SHA: all
checks by default, cancel/unknown buckets fail, NO_CHECKS needs explicit
per-head approval, and both merge commands (including --auto) run only
after a PASS for the same SHA they pin with --match-head-commit.

Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>

* fix(slug): give nested-group projects their own state bucket and verify checkpoint identity (#3003, #2901)

gstack-slug kept only the last two remote path segments, so
customer-a/product/repo and customer-b/product/repo shared one bucket
and /context-restore could present another project's checkpoint.

- One canonical-remote rule (bash + TS, golden vectors) used by all six
  resolvers: lowercased host, no userinfo/port/.git, Azure DevOps and
  Bitbucket Server normalized. 3+ segment remotes get
  <last-two>-<16 hex>; two-segment remotes (all of GitHub) are unchanged.
- Versioned sticky cache (v2:) keeps cache hits git-free.
- context-save stamps the credential-free remote and root;
  context-restore only treats this project's checkpoints as latest,
  reports foreign/unverified ones first, and treats a different root
  with the same remote (Conductor handoff) as information.
- gstack-slug --adopt-legacy copies only files the user confirms.
- question-preference-hook reads the same versioned cache, so never-ask
  preferences fire; unknown identity asks instead of auto-deciding.

* fix(gbrain): brain context loads, managed sync works, memory sync stops duplicating (#2883, #2985, #2922)

- brain-context-load called 'gbrain list_pages' (an MCP tool name), so
  every skill's brain context was 0 bytes. It now uses 'gbrain list'
  with gbrain's real filter flags, and prints one line when queries fail.
- The code-stage sync always passes --no-pull (managed gbrain >= 0.51
  refuses without it); a gbrain that rejects the flag fails with an
  upgrade message and is never retried without it. stderr is streamed
  with a bounded tail and quoted in failure summaries.
- /sync-gbrain gains --sources (and GSTACK_MEMORY_INGEST_SOURCES); by
  default it skips types already synced through a federated curated
  source, so curated pages stop being re-duplicated.

Co-authored-by: Vitor Cepeda Lopes <vitor@vitorcepedalopes.com>
Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>

* fix(codex,cso): clean Codex reviews stop failing; semgrep and trivy SARIF results import (#2769, #3011)

- Codex review gate is PASS / FAIL / UNVERIFIED. Untagged output (what
  a clean 'codex review --base' prints) is UNVERIFIED, not FAIL, and
  never a false PASS; P2/P3-only output passes.
- import-sarif resolves semgrep's undeclared %SRCROOT% and trivy's
  ROOTPATH (including git-URL targets) through explicit, captured
  mappings; declared bases must sit inside the source root or the
  run's checkout, URIs are percent-decoded, and rejected results are
  counted with rule, base and path instead of silently dropped.

* fix: version strings are not IPs, failed update checks are not 'up to date', private security reporting (#2856, #2786, #2984)

- The pre-push redact hook exempts a root VERSION file that is only a
  version string and the version token in CHANGELOG release headings;
  the engine allowlist is untouched.
- gstack-update-check caches an unreadable remote as CHECK_FAILED with
  a short TTL instead of UP_TO_DATE; /gstack-upgrade never reports
  'latest' after a failed check.
- SECURITY.md points reporters at GitHub private vulnerability
  reporting.
- pr-title-sync (pull_request_target, write token) pins actions/checkout
  to a reviewed SHA.

* fix(autoplan): publication guard accepts real Claude Code journals (#3007, #3009, #2968, #2977, #2986, #3006)

The guard required a session journal to start with a user message, but
Claude Code starts it with SessionStart hook attachments (and a forked
compacted session starts with a compact_boundary), so every phase was
denied for anyone with a SessionStart hook. Windows path spellings
(C:/, /c/, drive case) were rejected too.

- Reader accepts the captured startup, compact, clear and fork shapes
  (claude 2.1.284 fixture), computes root uniqueness over every
  candidate, and returns typed reason codes instead of one string.
- Hard denials (competing root, foreign cwd, sidechain, agent, cycle,
  malformed, identity) say what happened and how to run the reviews by
  hand; unflushed journals still retry.
- A well-formed, stable journal whose root shape is unrecognized now
  warns ('phase publication was NOT verified') and continues, without
  overriding Claude Code's own permission check; no bypass switch.
- Windows paths fold before validation, so '..' is still rejected.
- Periodic drift canary runs the reader on fresh journals from the
  pinned claude.

Co-authored-by: Charles M Berg <77517285+CharlesBerg85@users.noreply.github.com>
Co-authored-by: laurenbdaniels-coder <264343335+laurenbdaniels-coder@users.noreply.github.com>
Co-authored-by: Jordan Mayer <176445995+maydaycyber@users.noreply.github.com>
Co-authored-by: elmesery-dev <elmesery.dev@gmail.com>

* v1.91.13.0: severe bug fix wave release notes, stale gbrain verbs in docs

* test: seed the versioned slug cache in the memory-injection deny case (#2901)

The preference hook now resolves the project bucket from gstack-slug's
v2 slug-cache entry instead of basename(cwd); this fixture still wrote
preferences under the basename bucket without the entry the skill
preamble always writes first.

* fix: full-suite follow-ups for the fix wave

- gstack-slug's --help heredoc is over 512B, so it gets the BASH_COMPAT=50
  pipe-deadlock guard like the other bins.
- Refresh the codex/factory ship goldens for the plan-gates slug change.
- The periodic lane gains the autoplan journal drift canary (107 paid
  files); raise the eval-slices cap to 25 so every slice still starts
  at once until its recorded duration lets the planner pack it.

* fix(plan-eng-review): clearer Step 0 sequencing, write routes and section outputs

The workflow judge scored plan-eng-review's instructions at
actionability 3.67 (bar 4) on text unchanged from main. Resolve the
ambiguities it named together, without changing any gate or output:
Step 0 names the Read's order and keeps one STOP; the pending-call,
read-only, forbidden-write and failed-save rules become one Write
routes block; header/label limits and grid checks are concrete;
Performance gets a checklist; each section has a stated output shape;
Lake Score is defined. Same total length (parity cap).

---------

Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>
Co-authored-by: Vitor Cepeda Lopes <vitor@vitorcepedalopes.com>
Co-authored-by: Charles M Berg <77517285+CharlesBerg85@users.noreply.github.com>
Co-authored-by: laurenbdaniels-coder <264343335+laurenbdaniels-coder@users.noreply.github.com>
Co-authored-by: Jordan Mayer <176445995+maydaycyber@users.noreply.github.com>
Co-authored-by: elmesery-dev <elmesery.dev@gmail.com>
2026-10-02 11:11:00 -07:00

339 lines
16 KiB
TypeScript

/**
* bin-context — tiny shared helpers for non-interactive gstack bins that need the
* project slug, current branch, and argv flags. Extracted from the decision bins
* (gstack-decision-log / gstack-decision-search) so the slug/branch/flag plumbing
* lives in one audited place instead of being copy-pasted per bin.
*/
import { spawnSync } from "child_process";
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "fs";
import { basename, dirname, join } from "path";
import { resolveStateRoot } from "./state-root";
import { legacyRemoteSlug, remoteSlug } from "./remote-identity";
/** Keep the slug inside the [a-zA-Z0-9._-] alphabet gstack-slug promises (`tr -cd`). */
function sanitizeSlug(s: string): string {
return s.replace(/[^a-zA-Z0-9._-]/g, "");
}
/**
* A Windows path in the MSYS form git-bash's `pwd` reports:
* `C:\Users\j\foo` → `/c/Users/j/foo`. gstack-slug keys its cache on THAT form
* (`tr '/' '_'`), so a native lookup must reproduce it exactly or it misses the very
* entry gstack-slug wrote and silently re-derives instead of staying consistent.
* Exported for the cache-key test; non-Windows paths pass through unchanged.
*/
export function toMsysPath(p: string): string {
const drive = p.match(/^([A-Za-z]):[\\/]/);
const body = (drive ? p.slice(2) : p).replace(/\\/g, "/");
return drive ? `/${drive[1].toLowerCase()}${body}` : body;
}
/** `-f` in bash terms: a regular file (following symlinks), never a directory. */
function isFile(p: string): boolean {
try {
return statSync(p).isFile();
} catch {
return false;
}
}
// Marker tiers mirror bin/gstack-slug's `_outermost_project_root` exactly.
// STRONG = canonical version-control / language project files ("this directory
// is a real project of its own"); .git is checked separately because it can be
// a directory (normal repo) or a file (worktree / submodule pointer).
// WEAK = content-only project signals (markdown bundles, asset collections).
const STRONG_FILE_MARKERS = [".project.yaml", "package.json", "pyproject.toml", "Cargo.toml", "Gemfile", "go.mod"];
const WEAK_FILE_MARKERS = ["README.md", "README", "README.rst", "LICENSE", "LICENSE.md"];
/**
* Native port of bin/gstack-slug's `_outermost_project_root`: walk UP
* from `startDir` tracking the OUTERMOST ancestor holding a strong marker and
* the outermost holding a weak marker. Outermost STRONG wins; else outermost
* WEAK; else "". Build/deploy artifacts (.vercel, node_modules, dist, ...) are
* deliberately NOT markers, so they can't establish a phantom project root.
*
* Termination mirrors the bash fix for windows-free-tests: break on dirname's
* FIXED POINT (drive roots `C:\`, relative `.`, UNC `//srv` never reach the
* literal "/"), with a 64-depth belt-and-braces cap. Exported for the
* hostile-path termination tests.
*/
export function outermostProjectRoot(startDir: string): string {
let dir = startDir;
let outermostStrong = "";
let outermostWeak = "";
let depth = 0;
while (dir && dir !== "/" && depth < 64) {
if (existsSync(join(dir, ".git")) || STRONG_FILE_MARKERS.some((m) => isFile(join(dir, m)))) {
outermostStrong = dir;
} else if (WEAK_FILE_MARKERS.some((m) => isFile(join(dir, m)))) {
outermostWeak = dir;
}
const parent = dirname(dir);
if (parent === dir) break; // dirname fixed point (C:\, ., //srv)
dir = parent;
depth += 1;
}
// Strong markers win over weak; either wins over nothing.
return outermostStrong || outermostWeak;
}
/**
* Native port of bin/gstack-slug's `_outermost_remote_repo` (step 1a): walk UP
* from `startDir` tracking the OUTERMOST ancestor that has a `.git` entry
* (directory for normal clones, FILE for git-worktrees/submodules — `git -C`
* resolves a worktree's remote through its main clone) AND whose `origin`
* remote resolves. This is the canonical-identity walk: a marker-only
* ancestor with no resolvable origin (stray empty ~/.git, stray package.json)
* cannot win here, so it cannot hijack remote-derived identity the way it can
* hijack the marker walk above. Nested-repo semantics preserved: an inner
* repo under an outer canonical-remote repo still resolves to the OUTER
* repo's remote (outermost wins). git spawns only at `.git`-bearing ancestors
* — typically one. Exported for the parity tests.
*/
export function outermostRemoteRepo(startDir: string): { root: string; url: string } {
let dir = startDir;
let root = "";
let url = "";
let depth = 0;
while (dir && dir !== "/" && depth < 64) {
if (existsSync(join(dir, ".git"))) {
const r = spawnSync("git", ["-C", dir, "remote", "get-url", "origin"], { encoding: "utf-8" });
const u = r.status === 0 ? (r.stdout || "").trim() : "";
if (u) {
root = dir;
url = u;
}
}
const parent = dirname(dir);
if (parent === dir) break; // dirname fixed point (C:\, ., //srv)
dir = parent;
depth += 1;
}
return { root, url };
}
/**
* Native port of bin/gstack-slug's resolution order, used when that script cannot be
* spawned (see resolveSlug). Same steps, same alphabet, same cache file — so this and
* the shell path always agree. They must: the bins WRITE using this, while the
* Context Recovery preamble READS using the script.
*
* Resolution order (parity with the bash script, pinned by
* test/bin-context-windows-slug.test.ts against test/gstack-slug-cwd-walk-up.test.ts
* and test/gstack-slug-parity.test.ts):
* 0. $GSTACK_PROJECT_SLUG env override — wins over everything, never cached.
* 1. Walk UP to the OUTERMOST project root (see outermostProjectRoot). Without
* the walk, a nested/vendored repo derived its slug from the INNERMOST
* `git remote get-url origin`, splitting the store the bash side keeps whole.
* 2. Cached slug is sticky (#2212) — EXCEPT two provable bug shapes. Entries
* are versioned ("v2:<slug>"); an unversioned entry is recomputed once and
* moves only when it equals the pre-#3003 last-two slug of a 3+-segment
* remote:
* - old-bug shape (#1125): cached value equals basename(cwd) while the
* walk-up says cwd is NOT the project root; that cache came from the
* pre-walk-up resolver, so recompute and heal.
* - degraded-ancestor shape (2026-08-17), STRAY-REPO shape ONLY: cached
* equals the marker root's basename, the marker root is anchored by a
* .git entry whose origin does NOT resolve (the stray empty ~/.git
* live bug), and a remote-bearing repo BELOW it exists — the
* pre-remote-first resolver degraded to that stray ancestor's basename
* (SLUG=<username>). A marker root anchored by package.json /
* pyproject etc. with NO .git is legit #2212 sticky identity and must
* NOT be healed. Legit remote-adopting stickiness is safe too: there
* the repo that adopted the remote IS the marker root (remote root ==
* project root), so the heal never fires.
* 3. Canonical remote-derived slug from the OUTERMOST remote-bearing repo
* (see outermostRemoteRepo — never PROJECT_ROOT, which may be a
* marker-only ancestor with no remote): remoteSlug() from
* lib/remote-identity.ts — owner-repo for 2-segment and local remotes,
* "<last-two>-<16 hex>" for 3+-segment hosted remotes (#3003) —
* byte-parity with browse/bin/remote-slug. Degenerate slugs
* ("", ".", "..", anything with "/") are rejected — a hostile origin
* like `url = ..` must never escape ~/.gstack/projects/<slug>.
* 4. Project root's basename; else basename(cwd) for plain non-project folders.
*/
/** gstack-slug's per-path cache file: the cwd in MSYS form with "/" → "_". */
export function slugCacheFile(stateRoot: string, cwd: string): string {
return join(stateRoot, "slug-cache", toMsysPath(cwd).replace(/\//g, "_"));
}
/** Cache entries written since #3003 carry this version prefix ("v2:<slug>"). */
export const SLUG_CACHE_VERSION_PREFIX = "v2:";
/**
* The slug a versioned cache entry records for `cwd`, or undefined when there is
* no entry, the entry predates the versioned format, or its value is unusable
* (empty, "." or ".." after sanitizing). Never spawns git: hot-path readers
* (the AskUserQuestion preference hook) rely on gstack-slug, which every skill
* preamble runs, having already written the entry.
*/
export function readVersionedSlugCache(stateRoot: string, cwd: string): string | undefined {
let raw: string;
try {
raw = readFileSync(slugCacheFile(stateRoot, cwd), "utf-8");
} catch {
return undefined;
}
if (!raw.startsWith(SLUG_CACHE_VERSION_PREFIX)) return undefined;
const slug = sanitizeSlug(raw.slice(SLUG_CACHE_VERSION_PREFIX.length).trim());
return slug && slug !== "." && slug !== ".." ? slug : undefined;
}
export function slugFromEnvironment(gstackHome?: string, cwd: string = process.cwd()): string {
const home = gstackHome || resolveStateRoot();
const cacheDir = join(home, "slug-cache");
const cacheFile = slugCacheFile(home, cwd);
// 0. explicit env override — per-invocation escape hatch, never persisted
// (caching it would rebind THIS cwd's slug for every later env-less run).
const envSlug = sanitizeSlug((process.env.GSTACK_PROJECT_SLUG || "").trim());
if (envSlug && envSlug !== "." && envSlug !== "..") return envSlug;
// 1. outermost project root along the cwd ancestor chain (may be "").
const projectRoot = outermostProjectRoot(cwd);
// Lazy, memoized remote discovery (mirrors gstack-slug's _resolve_remote):
// needed on exactly two paths — fresh resolution and the degraded-ancestor
// heal check — so ordinary cache hits stay git-spawn-free.
let remote: { root: string; url: string } | null = null;
const resolveRemote = () => (remote ??= outermostRemoteRepo(cwd));
let slug = "";
// 2. cached slug is sticky (#2212), except the two provable bug shapes
// (old-bug #1125 and degraded-ancestor 2026-08-17 — see the doc above).
if (existsSync(cacheFile)) {
try {
const raw = readFileSync(cacheFile, "utf-8");
const versioned = raw.startsWith(SLUG_CACHE_VERSION_PREFIX);
const cached = sanitizeSlug((versioned ? raw.slice(SLUG_CACHE_VERSION_PREFIX.length) : raw).trim());
if (cached) {
const pwdBase = sanitizeSlug(basename(cwd));
const rootBase = projectRoot ? sanitizeSlug(basename(projectRoot)) : "";
const oldBugShape = cached === pwdBase && projectRoot !== "" && projectRoot !== cwd;
const degradedAncestorShape =
!oldBugShape &&
projectRoot !== "" &&
cached === rootBase &&
// STRAY-REPO shape only: the marker root must be anchored by a .git
// entry whose origin does NOT resolve. A root anchored by
// package.json etc. (no .git) is legit #2212 sticky identity.
existsSync(join(projectRoot, ".git")) &&
(() => {
const rootOrigin = spawnSync("git", ["-C", projectRoot, "remote", "get-url", "origin"], {
encoding: "utf-8",
});
const rootUrl = rootOrigin.status === 0 ? (rootOrigin.stdout || "").trim() : "";
if (rootUrl) return false; // marker root's own origin resolves — not the stray shape
const r = resolveRemote();
return r.url !== "" && r.root !== projectRoot;
})();
if (!oldBugShape && !degradedAncestorShape) {
slug = cached;
// Unversioned (pre-#3003) entry: recompute once. Keep the sticky
// value unless it is exactly the old last-two slug of a 3+-segment
// remote (mirrors bin/gstack-slug).
if (!versioned) {
const { url } = resolveRemote();
if (url) {
const upgraded = remoteSlug(url);
const legacy = legacyRemoteSlug(url);
if (upgraded && upgraded !== legacy && cached === legacy) slug = upgraded;
}
}
}
}
} catch {
slug = "";
}
}
// 3. canonical remote-derived slug from the outermost remote-bearing repo,
// via the shared rule in lib/remote-identity.ts (twin of
// bin/gstack-remote-identity.sh): legacy last-two parse for 2-segment and
// local remotes, "<last-two>-<16 hex>" for 3+-segment hosted remotes.
if (!slug) {
const { url } = resolveRemote();
if (url) {
const candidate = remoteSlug(url);
// Dot-only / degenerate guard (mirrors bin/gstack-slug): a hostile
// origin like `url = ..` yields "." or ".." here, which would file
// state OUTSIDE ~/.gstack/projects/. Reject and let the basename
// fallback below anchor identity instead.
if (candidate && candidate !== "." && candidate !== ".." && !candidate.includes("/")) {
slug = candidate;
}
}
}
// 4. project root's basename, else pwd basename for plain folders.
if (!slug && projectRoot) slug = sanitizeSlug(basename(projectRoot));
if (!slug) slug = sanitizeSlug(basename(cwd));
if (!slug) return "unknown";
// 5. cache it, as gstack-slug does — atomic, self-healing (only rewrites when
// the value changed — single-shot, key-local), and failures stay silent.
try {
let current = "";
try {
current = readFileSync(cacheFile, "utf-8");
} catch {
// no cache yet — write below
}
if (current !== `${SLUG_CACHE_VERSION_PREFIX}${slug}`) {
mkdirSync(cacheDir, { recursive: true });
const tmp = `${cacheFile}.tmp.${process.pid}`;
writeFileSync(tmp, `${SLUG_CACHE_VERSION_PREFIX}${slug}`, "utf-8");
renameSync(tmp, cacheFile);
}
} catch {
// best-effort cache; a miss only costs a re-derive on the next call
}
return slug;
}
/** Windows cannot exec an extensionless `#!/usr/bin/env bash` script (no shebang, no
* PATHEXT match for an explicit path), so gstack-slug spawns ENOENT there. */
export const NEEDS_NATIVE_SLUG_ON_WINDOWS = process.platform === "win32";
/**
* Resolve the project slug via the `gstack-slug` helper (parses `SLUG=...`).
*
* On Windows that spawn fails ENOENT (see NEEDS_NATIVE_SLUG_ON_WINDOWS) and `r.stdout`
* is undefined — the same class of hazard as the gbrain shim spawns in lib/gbrain-exec.ts
* (#1731). Returning the literal "unknown" filed every decision under
* ~/.gstack/projects/unknown/ — one bucket shared by every project on the machine —
* while the bash-side Context Recovery preamble resolved the real slug, found no
* decisions.active.json there, and skipped through a bare `if [ -f … ]` with no else.
*
* Nothing failed, for ten days: BOTH decision bins (log and search) missed identically,
* so writes and searches stayed consistent with each other, and the only component that
* resolved correctly was silent by design.
*
* `shell: true` is NOT the fix here, unlike #1731: cmd.exe cannot run a bash script
* either. Nor is re-spawning through `bash` — on Windows that frequently resolves to
* WSL, whose $HOME and /mnt/c paths yield a different slug AND a different cache
* directory, trading one split store for another.
*
* POSIX behaviour is unchanged: the fallback is win32-only, where the previous result
* was unconditionally wrong and so has nothing to regress.
*/
export function resolveSlug(slugBinPath: string): string {
const r = spawnSync(slugBinPath, { encoding: "utf-8" });
const m = (r.stdout || "").match(/^SLUG=(.+)$/m);
if (m) return m[1].trim();
if (NEEDS_NATIVE_SLUG_ON_WINDOWS) return slugFromEnvironment();
return "unknown";
}
/** Current git branch, or undefined on detached HEAD / outside a repo. */
export function gitBranch(): string | undefined {
const r = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf-8" });
const b = (r.stdout || "").trim();
return b && b !== "HEAD" ? b : undefined;
}
/** The value following `--flag` in argv, or undefined if absent. */
export function flagValue(args: string[], name: string): string | undefined {
const i = args.indexOf(name);
return i >= 0 ? args[i + 1] : undefined;
}