Files
gstack/lib/script-invocation.ts
T
82530ac143 v1.91.117.0 fix: pregate bats lanes, WTREE_UNAVAILABLE, doctor rows, SKILL.md size guard, planMode hosts (fix wave PR 5) (#3236)
* fix(pregate): recognise bats test files so lanes does not fail in bats repos (#3161)

gstack-pregate never treated a .bats file as a test, so in a repository whose
tests are bats files the lanes check failed every run with PREGATE_NO_LANE: a
.gstack/pregate.json dependency pointing at tests/foo.bats selected nothing, a
selection manifest printing .bats paths yielded 0 files, and a bats run that
executed no tests could not trip the zero-run rule.

Recognise .bats in the test-file pattern and in the manifest-output parser, and
read the bats TAP plan and pretty summary (as a last resort, after every
existing runner's summary) so a run that reports zero tests is a failure.

Fixes #3161.

Cherry-picked from #3177 (d355c116b). Conflicts resolved as in the author's own
merges (b09476beb, 444f4e768): lane-selection.ts keeps main's isTestFile-based
manifest parser, and lanes.ts carries the bats summary on main's supervised runner.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(pregate): a nested .bats file is selected and run end to end (#3161)

Reviewer test for #3177: touched itself with no declaration, and through a
declared dependency; a failing nested bats run reports the bats counts.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): a wtree failure is WTREE_UNAVAILABLE, not an unresolvable base (#3197)

The pregate consumers of the working-tree fingerprint (buildContext,
withFingerprint, verifyPregate) move to lib/script-invocation.ts's
{tree}|{error} form, and lib/regen.ts drops its string-returning wrapper.

- A fingerprint failure was reported as "policy source unavailable:
  origin/<base> is not a resolvable commit" with git fetch as the fix. It is
  now WTREE_UNAVAILABLE: a launch failure lists each Windows bash candidate
  with its rejection reason and names GSTACK_GIT_BASH; a gstack-wtree exit
  keeps the repair it printed (set TMPDIR to a writable directory).
- A fingerprint failing after a check is incomplete with that cause, not
  "working tree changed"; verify says the tree cannot be fingerprinted.
- #3190's gstack-config read (test_backend) goes through runScriptSync, so
  Windows reaches it through Git Bash. The tripwire learns the bin-constant
  shape that let it through.
- Under --json every context refusal is one envelope on stdout
  ({ok:false,status:'refused',code,detail,fix,docs}, exit 3); the run object
  carries ok and status too, and GSTACK_RESULT goes to stderr.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* ci(pregate): gstack-pregate joins the Windows pregate job; pregate tests return to the Windows lane (#3197)

- windows-pregate-e2e runs gstack-pregate run (preflight: regen, secrets
  through the gstack-redact bun bin, literals, guards) in both journeys, and
  asserts a missing GSTACK_GIT_BASH refuses with one WTREE_UNAVAILABLE --json
  envelope.
- test/helpers/pregate-fixture.ts and restamp-fixture.ts runBin launch bins
  through lib/script-invocation.ts (bun bins as Bun argv, bash bins through
  Git Bash on Windows), which removes the "shebang via CreateProcess" reason
  for the pregate tests; they move from KNOWN_WINDOWS_INCOMPATIBLE to
  KNOWN_WINDOWS_SAFE.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* doctor: list rescue refs and warn about CLAUDE.md skill lists

gstack-doctor's plain report gains two rows. 'rescue refs' lists each
refs/gstack/rescue/* commit in the install checkout, newest first, with its
date, a needs-manual-resolution label when the rescue held unmerged files, and
the shell-quoted inspect and delete commands bin/gstack-ff-update's banner
prints. 'CLAUDE.md' warns when a gstack section in ~/.claude/CLAUDE.md or the
project's CLAUDE.md enumerates skills (#3169) and prints the short block to
paste instead; docs/troubleshooting.md#claude-md-skill-list explains it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* doctor: name the Windows bash gstack resolves and what chose it

On Windows (OSTYPE msys/cygwin) gstack-doctor adds a 'windows bash' row from
lib/script-invocation.ts resolveWindowsBash, run through the new thin
bin/gstack-windows-bash.ts with the bun on PATH: the resolved bash and the
override or discovery step that chose it, a warn when GSTACK_GIT_BASH and
GSTACK_BASH differ, and a fail carrying the BASH_UNAVAILABLE line (every
candidate with its rejection reason) when none qualifies. Tests inject the
platform (GSTACK_DOCTOR_PLATFORM) and the discovery inputs
(GSTACK_DOCTOR_BASH_PROBE) so the row runs on every OS.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* doctor --check: name the held-install recovery on Windows, not bin/gstack-upgrade

bin/gstack-upgrade compares a pwd -P path (/c/...) with git's toplevel
(C:/...) and refuses on every Git Bash install, so on Windows the revision
row's upgrade fix (REVISION_BELOW_MINIMUM, the Capy-wrapper variant and
REVISION_UNMET) names the held-install recovery forms from
docs/troubleshooting.md#auto-update-held-install-recovery instead: the Git
Bash form and the Windows PowerShell 5.1 form, each labelled by shell with the
install path quoted for that shell. Other platforms keep bin/gstack-upgrade.
A test pins both printed forms to the documented ones.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(skills): omit the plan-mode section on hosts without plan mode (#3168)

generatePlanModeInfo now honours capabilities.planMode. Hosts that declare
planMode:false (codex, agy, hermes, openclaw, and define-host's default:
factory, kiro, slate, cursor, gbrain) no longer render the
'## Plan Mode Safe Operations' and '## Skill Invocation During Plan Mode'
preamble sections. Claude, copilot and opencode are unchanged.

The codex, factory and agy ship goldens are regenerated. The clarity test that
pinned the plan-mode entry-order prose on every host now pins it on planMode
hosts and asserts its absence elsewhere (intentional contract change).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(skills): guard generated SKILL.md size at 100,000 chars on every host (#3199)

A free test renders every host and fails when a generated SKILL.md exceeds
100,000 characters, naming host, skill, actual size, limit and the fix. The 89
current offenders are pinned at their exact size in
test/fixtures/skill-md-size-allowlist.json: growth past a pin fails, and a
shrink fails until the pin is lowered. The shared-preamble hoist is deferred
(owner Garry, revisit 2026-11-15).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(pregate): keep #3177's bats tests beside the nested-directory test

Moves #3177's bats describe block verbatim from test/pregate-selection.test.ts
into test/pregate-bats-nested.test.ts, so pregate-selection.test.ts is
unchanged on this branch and the in-flight field-list-2 pregate lane
(capy/fl2-L6-pregate, which edits that file's imports and adds cases) merges
without a conflict. No assertion changes.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* doctor --check: keep bin/gstack-upgrade as the Windows fix (path spelling fixed on main)

Reverts 37bac07f8. Plan item D named the held-install recovery forms on
Windows only until bin/gstack-upgrade stopped refusing Git Bash installs.
bin/gstack-upgrade:63-67 now compares with gstack_path_same from
bin/gstack-path-spelling.sh, pinned by test/gstack-upgrade-path-spelling.test.ts,
so bin/gstack-upgrade is the right fix on every platform again.

* test(skills): measure the size-guard pins on v1.91.109.0

#3225 (merged into this branch) grew 53 pinned skills: 3 characters each from
the Aside driver resolver, and about 340 more in plan-design-review and
plan-devex-review from the #3219 summary sections. The pins are this PR's
starting measurement, so they are taken on the merged base; no skill this PR
renders grew.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* ci(windows): only the pregate tests that pass on windows-latest join the lane

windows-free-tests run 38984824731 (this branch at 8ed6da402) ran the moved
files. gstack-regen and the new pregate-wtree-refusal passed. pregate-guards,
-remote, -regate, -invalidation, -selection and -bats-nested launched
gstack-pregate fine but fail on Linux-host expectations: their fixture lanes are
Linux workflow jobs, which a Windows host records as requires-remote
obligations. They go back to KNOWN_WINDOWS_INCOMPATIBLE with that reason
instead of "shebang via CreateProcess".

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* windows curation: keep CI run ids out of reason prose (pii.phone false positive)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* skill-md size pins: follow #3231's review-army line (+21 chars on five inlining hosts)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* doctor test: drop the reverted Windows upgrade-fix wording from item D's describe

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* skill-md size pins: follow #3226 (plan-devex-review +3324) and #3234 (autoplan +59)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* WTREE_UNAVAILABLE moves to lib/result-codes-release.ts (#3235 split; result-codes.ts stays at 796 of 800 lines); doctor fixture copies the release table; size pins follow #3235's review +1

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(changelog): fix wave PR 5 release notes

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* v1.91.117.0 fix: fix wave PR 5 (pregate bats + WTREE_UNAVAILABLE, doctor rows, SKILL.md size guard, planMode hosts)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(qa): an invalid-input probe breaks only the rule it tests

The paid gate's qa-functional-cli-report failed again on #3236 (run
39001107574): the agent probed the digits-only amount rule with -5, which
the positivity check rejected first, so the planted parseInt defect stayed
hidden and it reported no defect. The contract map's invalid-input row now
asks for each input to break only the rule it tests, so another check
cannot reject it first.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: harjothkhara <48686985+harjothkhara@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
2026-10-17 04:36:00 +00:00

261 lines
14 KiB
TypeScript

/**
* script-invocation — the one way gstack's TypeScript runs its own shebang
* bins and `bash -c` strings (#3197).
*
* Windows has no shebangs: Bun's spawnSync cannot execute an extensionless
* `#!/usr/bin/env bash` script (`bin/gstack-wtree`, `gstack-slug`) or a
* `#!/usr/bin/env bun` one (`gstack-redact`), and `shell: true` does not help
* (cmd.exe has no idea what a shebang is). So:
* - bun-shebang bins run as `<bun> <script>` on every platform, `<bun>`
* being the running Bun (process.execPath) or, inside a compiled binary,
* the `bun` on PATH;
* - bash-shebang bins and `bash -c` strings exec directly on POSIX and go
* through the resolved Git Bash on Windows.
*
* Windows bash resolution, in order (one fixture table,
* test/fixtures/windows-bash-resolution.json, pins it):
* 1. GSTACK_GIT_BASH (canonical; the name setup.ps1 reads), GSTACK_BASH as
* a deprecated alias at the same precedence. GSTACK_GIT_BASH wins when
* both are set; a warning prints once when they differ. An override that
* does not exist is refused, never silently skipped.
* 2. bash next to `git --exec-path` (resolves through scoop-style shims,
* per-user and portable Git).
* 3. The known install paths.
* 4. A PATH `bash` only when `uname -s` reports MSYS or MINGW. System32 and
* WindowsApps `bash.exe` are WSL launchers and are rejected unprobed.
* 5. Otherwise a refusal listing each candidate with its rejection reason
* and naming GSTACK_GIT_BASH (BASH_UNAVAILABLE).
* Paths are forward-slashed: Bun's spawnSync on Windows returns ENOENT for a
* backslash exe path containing spaces, and bash reads backslashes as escapes.
*/
import { spawnSync, type SpawnSyncOptions, type SpawnSyncOptionsWithStringEncoding, type SpawnSyncReturns } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
import { resultLine } from './result-codes';
export const BIN_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin');
export interface BashProbe {
platform?: string;
env?: NodeJS.ProcessEnv;
exists?: (p: string) => boolean;
/** `git --exec-path`; the default asks git only on a real Windows host. */
gitExecPath?: () => string | null;
which?: (cmd: string) => string | null;
/** `uname -s` as the candidate bash reports it. */
uname?: (bash: string) => string | null;
}
export interface BashCandidate { path: string; source: string; rejected: string | null }
export type BashResolution =
| { ok: true; bash: string; source: string; tried: BashCandidate[]; warning?: string }
| { ok: false; tried: BashCandidate[]; message: string; warning?: string };
const slash = (p: string) => p.replace(/\\/g, '/');
const WSL_LAUNCHER = /\/(?:windows\/(?:system32|sysnative)|microsoft\/windowsapps)\//i;
const GIT_ROOT_FROM_EXEC_PATH = /^(.*)\/(?:mingw64|mingw32|clangarm64|clang64|ucrt64|usr\/lib)\/(?:libexec\/)?git-core$/i;
function knownInstalls(env: NodeJS.ProcessEnv): string[] {
return [
'C:/Program Files/Git/bin/bash.exe',
'C:/Program Files/Git/usr/bin/bash.exe',
'C:/Program Files (x86)/Git/bin/bash.exe',
...(env.LOCALAPPDATA ? [`${slash(env.LOCALAPPDATA)}/Programs/Git/bin/bash.exe`] : []),
...(env.USERPROFILE ? [`${slash(env.USERPROFILE)}/scoop/apps/git/current/bin/bash.exe`] : []),
];
}
function defaultGitExecPath(): string | null {
const r = spawnSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 10_000, windowsHide: true });
return r.status === 0 ? r.stdout.trim() || null : null;
}
function defaultUname(bash: string): string | null {
const r = spawnSync(bash, ['-c', 'uname -s'], { encoding: 'utf8', timeout: 10_000, windowsHide: true });
return r.status === 0 ? r.stdout.trim() || null : null;
}
/** The refusal text shared by every consumer (scripts, gbrain sync, the doctor). */
export function noBashMessage(tried: readonly BashCandidate[]): string {
const list = tried.map(c => `${c.source} ${c.path}: ${c.rejected}`).join('; ');
return resultLine('gstack', 'BASH_UNAVAILABLE', `tried ${list}`);
}
export function resolveWindowsBash(o: BashProbe = {}): BashResolution {
const env = o.env ?? process.env;
const exists = o.exists ?? fs.existsSync;
const live = process.platform === 'win32';
const tried: BashCandidate[] = [];
const canonical = env.GSTACK_GIT_BASH?.trim();
const alias = env.GSTACK_BASH?.trim();
const warning = canonical && alias && slash(canonical) !== slash(alias)
? `gstack: GSTACK_GIT_BASH (${canonical}) and the deprecated GSTACK_BASH (${alias}) differ; using GSTACK_GIT_BASH`
: undefined;
const found = (bash: string, source: string): BashResolution => {
tried.push({ path: bash, source, rejected: null });
return { ok: true, bash, source, tried, warning };
};
const refuse = (): BashResolution => ({ ok: false, tried, message: noBashMessage(tried), warning });
const override = canonical || alias;
if (override) {
const source = canonical ? 'GSTACK_GIT_BASH' : 'GSTACK_BASH';
if (exists(slash(override))) return found(slash(override), source);
tried.push({ path: slash(override), source, rejected: 'does not exist' });
return refuse();
}
tried.push({ path: '(unset)', source: 'GSTACK_GIT_BASH', rejected: 'not set' });
const seen = new Set<string>();
const execPath = (o.gitExecPath ?? (live ? defaultGitExecPath : () => null))();
const root = execPath ? GIT_ROOT_FROM_EXEC_PATH.exec(slash(execPath).replace(/\/+$/, ''))?.[1] : undefined;
if (!execPath) tried.push({ path: '(git)', source: 'git --exec-path', rejected: 'git not found or failed' });
else if (!root) tried.push({ path: slash(execPath), source: 'git --exec-path', rejected: 'not a Git for Windows or MSYS2 layout' });
else for (const bash of [`${root}/bin/bash.exe`, `${root}/usr/bin/bash.exe`]) {
seen.add(bash.toLowerCase());
if (exists(bash)) return found(bash, 'git --exec-path');
tried.push({ path: bash, source: 'git --exec-path', rejected: 'not found' });
}
for (const bash of knownInstalls(env)) {
if (seen.has(bash.toLowerCase())) continue;
if (exists(bash)) return found(bash, 'install path');
tried.push({ path: bash, source: 'install path', rejected: 'not found' });
}
const onPath = (o.which ?? (live ? (c: string) => Bun.which(c) : () => null))('bash');
if (!onPath) { tried.push({ path: 'bash', source: 'PATH', rejected: 'not on PATH' }); return refuse(); }
const bash = slash(onPath);
if (WSL_LAUNCHER.test(bash)) { tried.push({ path: bash, source: 'PATH', rejected: 'WSL launcher, not Git Bash' }); return refuse(); }
const kind = (o.uname ?? defaultUname)(bash);
if (kind && /^(?:MSYS|MINGW)/i.test(kind)) return found(bash, 'PATH');
tried.push({ path: bash, source: 'PATH', rejected: `uname -s reports ${kind ?? 'nothing'}, not MSYS/MINGW` });
return refuse();
}
export interface CachedProbe extends BashProbe {
stat?: (p: string) => { mtimeMs: number } | null;
}
/**
* The hooks' resolver: spawn-free on the hot path. The override is never
* cached; otherwise the last resolution is reused while `git` on PATH keeps
* its path and mtime and the cached bash still exists. Written by temp file
* plus rename; only successes are cached.
*/
export function resolveWindowsBashCached(cacheFile: string, o: CachedProbe = {}): BashResolution {
const env = o.env ?? process.env;
if (env.GSTACK_GIT_BASH?.trim() || env.GSTACK_BASH?.trim()) return resolveWindowsBash(o);
const exists = o.exists ?? fs.existsSync;
const stat = o.stat ?? ((p: string) => { try { return fs.statSync(p); } catch { return null; } });
const git = (o.which ?? (process.platform === 'win32' ? (c: string) => Bun.which(c) : () => null))('git');
const key = git ? `${slash(git)}|${stat(git)?.mtimeMs ?? 'missing'}` : 'no-git';
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
if (cached?.key === key && typeof cached.bash === 'string' && exists(cached.bash)) {
return { ok: true, bash: cached.bash, source: `${cached.source} (cached)`, tried: [{ path: cached.bash, source: `${cached.source} (cached)`, rejected: null }] };
}
} catch { /* no usable cache: resolve below */ }
const res = resolveWindowsBash(o);
if (res.ok) {
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
const tmp = `${cacheFile}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ key, bash: res.bash, source: res.source }) + '\n');
fs.renameSync(tmp, cacheFile);
} catch { /* an unwritable cache only costs the next resolution */ }
}
return res;
}
export interface InvocationOptions extends BashProbe {
/** Supplies the Windows bash resolution (the hooks pass their cached resolver). */
resolve?: () => BashResolution;
/** The Bun that runs bun-shebang bins. */
bunExe?: string;
}
export type Invocation = { ok: true; cmd: string; argv: string[] } | { ok: false; error: string; tried?: BashCandidate[] };
/** The running Bun, or the `bun` on PATH when this process is a compiled binary. */
export function bunExecutable(): string {
const exe = process.execPath;
return /^bun(?:-debug)?(?:\.exe)?$/i.test(path.basename(exe)) ? exe : (Bun.which('bun') ?? 'bun');
}
function readShebang(script: string): string {
try {
const fd = fs.openSync(script, 'r');
try {
const buf = Buffer.alloc(128);
const n = fs.readSync(fd, buf, 0, 128, 0);
return buf.subarray(0, n).toString('utf8').split('\n')[0] ?? '';
} finally { fs.closeSync(fd); }
} catch { return ''; }
}
const warned = new Set<string>();
function windowsBash(o: InvocationOptions): { ok: true; bash: string } | { ok: false; error: string; tried: BashCandidate[] } {
const res = o.resolve ? o.resolve() : resolveWindowsBash(o);
if (res.warning && !warned.has(res.warning)) { warned.add(res.warning); process.stderr.write(res.warning + '\n'); }
return res.ok ? { ok: true, bash: res.bash } : { ok: false, error: res.message, tried: res.tried };
}
/** How to run a gstack shebang bin on this platform. */
export function scriptInvocation(script: string, args: readonly string[], o: InvocationOptions = {}): Invocation {
if (/^#!.*\bbun\b/.test(readShebang(script))) return { ok: true, cmd: o.bunExe ?? bunExecutable(), argv: [script, ...args] };
if ((o.platform ?? process.platform) !== 'win32') return { ok: true, cmd: script, argv: [...args] };
const bash = windowsBash(o);
return bash.ok ? { ok: true, cmd: bash.bash, argv: [slash(script), ...args] } : bash;
}
/** How to run `bash -c <command>` on this platform. */
export function bashCommandInvocation(command: string, o: InvocationOptions = {}): Invocation {
if ((o.platform ?? process.platform) !== 'win32') return { ok: true, cmd: 'bash', argv: ['-c', command] };
const bash = windowsBash(o);
return bash.ok ? { ok: true, cmd: bash.bash, argv: ['-c', command] } : bash;
}
/** A spawnSync-shaped failure for an invocation that could not be built, so callers keep one error path. */
function unlaunched(error: string, encoding: unknown, tried?: BashCandidate[]): SpawnSyncReturns<string | Buffer> {
const empty = encoding && encoding !== 'buffer' ? '' : Buffer.alloc(0);
return { pid: 0, output: [null, empty, empty], stdout: empty, stderr: empty, status: null, signal: null, error: Object.assign(new Error(error), { code: 'BASH_UNAVAILABLE', tried }) };
}
export function runScriptSync(script: string, args: readonly string[], opts: SpawnSyncOptionsWithStringEncoding, o?: InvocationOptions): SpawnSyncReturns<string>;
export function runScriptSync(script: string, args: readonly string[], opts: SpawnSyncOptions, o?: InvocationOptions): SpawnSyncReturns<string | Buffer>;
export function runScriptSync(script: string, args: readonly string[], opts: SpawnSyncOptions, o: InvocationOptions = {}): SpawnSyncReturns<string | Buffer> {
const inv = scriptInvocation(script, args, o);
return inv.ok ? spawnSync(inv.cmd, inv.argv, opts) : unlaunched(inv.error, opts.encoding, inv.tried);
}
export function runBashSync(command: string, opts: SpawnSyncOptionsWithStringEncoding, o?: InvocationOptions): SpawnSyncReturns<string>;
export function runBashSync(command: string, opts: SpawnSyncOptions, o?: InvocationOptions): SpawnSyncReturns<string | Buffer>;
export function runBashSync(command: string, opts: SpawnSyncOptions, o: InvocationOptions = {}): SpawnSyncReturns<string | Buffer> {
const inv = bashCommandInvocation(command, o);
return inv.ok ? spawnSync(inv.cmd, inv.argv, opts) : unlaunched(inv.error, opts.encoding, inv.tried);
}
export type WtreeResult = { tree: string } | { error: string; kind: 'launch' | 'exit'; tried?: BashCandidate[] };
/**
* The working-tree content fingerprint (bin/gstack-wtree): tracked and
* untracked non-ignored files, as a 40- or 64-hex git tree id (SHA-1 or
* SHA-256 repositories). `launch` means gstack-wtree never ran (no bash, a
* spawn error; `tried` lists each Windows bash candidate when none was
* found); `exit` means it ran and failed (its stderr says why).
*/
export function wtreeFingerprint(o: { cwd: string; timeoutMs?: number; env?: NodeJS.ProcessEnv; invocation?: InvocationOptions }): WtreeResult {
const r = runScriptSync(path.join(BIN_DIR, 'gstack-wtree'), [], {
cwd: o.cwd, encoding: 'utf8', timeout: o.timeoutMs ?? 60_000, windowsHide: true,
env: { ...(o.env ?? process.env), GIT_OPTIONAL_LOCKS: '0' },
}, o.invocation);
const out = (r.stdout ?? '').trim();
if (r.status === 0 && /^[0-9a-f]{40,64}$/.test(out)) return { tree: out };
if (r.error && r.status === null && r.signal === null) return { kind: 'launch', error: `gstack-wtree could not start: ${r.error.message}`, tried: (r.error as { tried?: BashCandidate[] }).tried };
const why = (r.stderr ?? '').trim().split('\n').pop() || (r.signal ? `killed by ${r.signal}` : r.status === 0 ? `unexpected output ${JSON.stringify(out.slice(0, 80))}` : 'no stderr');
return { kind: 'exit', error: `gstack-wtree exited ${r.status ?? r.signal}: ${why}` };
}