mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-27 23:21:53 +02:00
* fix(memory-ingest): --scan-secrets scans the rendered page and fails closed --scan-secrets ran gitleaks on the raw transcript .jsonl, then imported a page rendered from it. gitleaks' assignment rules don't match across a JSON-escaped quote (KEY=\"v\" on disk), so a secret the rendered page shows as KEY="v" was imported unflagged. And the gate skipped a file only on scanner "gitleaks" with findings, so a scan that errored (non-zero exit, 16MB maxBuffer overflow on a file with many findings, unparseable report) or could not run (gitleaks missing, slow-probe cooldown) imported the file unscanned. Scan the rendered page body, the exact bytes writeStaged() writes, via a new secretScanText() helper, and skip the file whenever the scan did not complete. Skipped files stay out of the state file, so the next run retries them. Reword the helper warnings and setup-gbrain/memory.md, which described the fail-open as intended. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(test): reconcile Bun failure markers and footer counts * fix(sync-gbrain): verify source-scoped reads without mutation * fix(test): recognize grounded TTHW target choices structurally * fix(aside): make the readiness probe work under zsh and report why it failed The probe built its deadline into `_T` and expanded it unquoted, so `$_T aside repl …` only worked in a shell that word-splits. zsh does not: it looked for a command literally named "gtimeout 30", the probe answered ASIDE_NOT_RUNNING with Aside installed and ready, and every browsing skill fell back to the bundled Chromium in silence. zsh is the macOS default and Aside is macOS-only, so on a stock Mac the probe could never report READY. The deadline becomes a function, `_gs_d`. It receives the command as "$@", already split, so sh, bash and zsh all behave the same, and the gtimeout → timeout → perl alarm chain is unchanged. A 4th arm runs the call unbounded when none of the three is present, which is what the empty `_T` did before. Not `eval`: it re-parses the string, so the parens and `;` of the perl arm become syntax and that arm dies in bash *and* zsh — on a stock Mac, the arm that actually runs. On failure the probe now prints the CLI's reason after ASIDE_NOT_RUNNING:, the shape gstack-render already uses: the first line that starts with a capital letter, i.e. the CLI's own sentence or Node's `Error:` line below its loader frame. "Not running" covers states with different fixes — no window open for the profile, a NODE_OPTIONS preload that kills the CLI — and a bare verdict sent all of them to "open the Aside app". The BROWSER SETUP prose quotes that reason before asking the user to open the app. The text pin asserted the broken invocation verbatim, so it now pins the function and asserts neither `$_T aside repl` nor an eval form comes back. A second test executes the rendered probe in sh, bash and zsh on each of the four deadline arms with stubbed binaries on a narrowed PATH, plus two failing CLIs: one that prints its own sentence, one that crashes like Node with the useful line below the frame. The deadline function costs zero bytes against the lines it replaces; the reason costs 53 per copy of the probe (44 where the reworded BROWSER SETUP line gives 9 back). That moves four guards by the measured amount: plan-devex-review's skeleton cap to 68,550 (measured 68,544), plan-ceo-review's skeleton cap to 80,150 (measured 80,111) and union ratio to 1.081 (measured 1.0803), and plan-eng-review's union ratio to 1.151 (measured 1.1504). Fixes #2842, #2941. * Clarify engineering review startup and decision flow * Fix Windows readiness fixture PATH and command shim * fix(test): recognize grounded TTHW target choices structurally * Clarify engineering review startup and decision flow * fix(test): restrict QA-only fixture tools to its no-Edit contract * v1.90.0.0 fix(sync-gbrain): guard readiness verdicts and refresh metadata * fix(browse): validate canonical upload targets * fix(gbrain): classify structured PGLite busy response * fix(browse): preserve native extension runtime APIs * Fix displayless browser handoff ownership * Accept unique installed autoplan methodology aliases * fix(skills): preserve positional literals during installation * fix(browse): checksum installer contents through stdin * fix(test): normalize Windows checksum fixture paths * test: emulate unavailable shasum in Windows checksum fixture * fix(investigate): preserve owned freeze lifecycle * fix(review): preserve N+1 retry and Red Team completion * fix: bound Aside readiness and preserve safe fallback * test: exercise setup and Chromium on native ARM * fix: preserve install ownership and ARM browser selection * Fix gbrain ingest scan boundaries and seed observation * Refresh managed ship hooks and supervise expanded paid census * Reject resumed gbrain pages excluded by current policy * Recover zombie agent locks safely and enable CI Python venv * Repair paid actor declarations and Aside pitch assertions * Bump consolidated wave to next free minor release * Clarify CEO review admin choices and option tradeoffs * Preserve CEO mode handoff anchors in clarified workflow * Make Windows portability fixtures use shell-native paths * Restore ARM Bun alias and clarify ship review gates * Refresh ship workflow golden snapshots * Fix Windows DX documentation controls without piped stdin * Decode Codex child pipes without Bun's encoded-stream stall * Bound DX pre-review audit before product questions * Clarify trusted review-start read in paid revalidation * Bump consolidated wave to next free minor release * Clarify CEO review admin choices and option tradeoffs * Preserve CEO mode handoff anchors in clarified workflow * Make Windows portability fixtures use shell-native paths * Restore ARM Bun alias and clarify ship review gates * Refresh ship workflow golden snapshots * Fix Windows DX documentation controls without piped stdin * Decode Codex child pipes without Bun's encoded-stream stall * Bound DX pre-review audit before product questions * Clarify trusted review-start read in paid revalidation * Reconcile new main planning flow and paid judge census * fix: reconcile rebased planning and source-bound validation * test: pin cookie workflow judge to scored Sonnet model * fix: keep terminal agent boot out of module imports * fix: preserve pending-question uncertainty in engineering review * fix: stabilize Windows reliability-wave fixtures * fix: clarify design consultation research workflow * fix: preserve independent design consultation inputs * fix: resolve design taste scope and browser research guidance * fix: make consultation opt-in preflight unambiguous * test: await native Edge owner readiness or terminal result --------- Co-authored-by: Bruce Krysiak <brucek@alum.mit.edu> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Antonio Vitalic <antoninte99@gmail.com>
265 lines
14 KiB
TypeScript
265 lines
14 KiB
TypeScript
/** One rename, shared by setup and the v1.82 upgrade migration. No model calls. */
|
|
import * as fs from 'node:fs';
|
|
import * as os from 'node:os';
|
|
import * as path from 'node:path';
|
|
import { spawnSync } from 'node:child_process';
|
|
|
|
const OLD = 'gstack-claude';
|
|
const NEXT = 'gstack-claude-code';
|
|
const BANNER = '<!-- AUTO-GENERATED from';
|
|
const RUNTIME_FILES = ['bin/gstack-claude-code', 'lib/claude-code.ts', 'lib/claude-code-windows-job.ts', 'lib/claude-bin.ts', 'lib/outside-review-result.ts'];
|
|
|
|
export interface RenameOptions {
|
|
installDir: string;
|
|
home?: string;
|
|
env?: NodeJS.ProcessEnv;
|
|
copy?: boolean;
|
|
/** The source checkout can itself live inside a repo-local skills directory. */
|
|
skillsDir?: string;
|
|
log?: (line: string) => void;
|
|
/** Tests render fixtures here; production invokes only gen-skill-docs. */
|
|
render?: (host: string, output: string) => void;
|
|
}
|
|
|
|
function exists(file: string): boolean { return fs.lstatSync(file, { throwIfNoEntry: false }) !== undefined; }
|
|
function generated(file: string): boolean {
|
|
try {
|
|
const header = fs.readFileSync(file, 'utf8').slice(0, 8192);
|
|
return header.includes(BANNER) && header.includes('<!-- Regenerate: bun run gen:skill-docs -->');
|
|
} catch { return false; }
|
|
}
|
|
function inside(file: string, root: string): boolean {
|
|
const rel = path.relative(root, file);
|
|
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
}
|
|
function linkIsOurs(file: string, root: string): boolean {
|
|
try {
|
|
const target = path.resolve(path.dirname(file), fs.readlinkSync(file));
|
|
// Resolve every existing component before accepting ownership: a path
|
|
// lexically inside the checkout can still escape through a directory link.
|
|
// Missing suffixes cover dangling links after standalone generation prunes.
|
|
let existing = target;
|
|
const missing: string[] = [];
|
|
while (!exists(existing)) {
|
|
missing.unshift(path.basename(existing));
|
|
const parent = path.dirname(existing);
|
|
if (parent === existing) return false;
|
|
existing = parent;
|
|
}
|
|
return inside(path.join(fs.realpathSync(existing), ...missing), root);
|
|
} catch { return false; }
|
|
}
|
|
function owned(entry: string, root: string): boolean {
|
|
const stat = fs.lstatSync(entry, { throwIfNoEntry: false });
|
|
if (!stat) return false;
|
|
if (stat.isSymbolicLink()) return linkIsOurs(entry, root);
|
|
if (!stat.isDirectory()) return false;
|
|
if (fs.lstatSync(path.join(entry, 'SKILL.md'), { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
return linkIsOurs(path.join(entry, 'SKILL.md'), root);
|
|
}
|
|
return generated(path.join(entry, 'SKILL.md')) || fs.existsSync(path.join(entry, '.gstack-owned'));
|
|
}
|
|
function atomicCopy(source: string, target: string): void {
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
const tmp = `${target}.rename-${process.pid}-${Math.random().toString(36).slice(2)}`;
|
|
try {
|
|
fs.copyFileSync(source, tmp);
|
|
fs.chmodSync(tmp, fs.statSync(source).mode);
|
|
fs.renameSync(tmp, target);
|
|
} finally { fs.rmSync(tmp, { force: true }); }
|
|
}
|
|
function preserveCopy(file: string): void {
|
|
let backup = `${file}.before-claude-code`;
|
|
for (let n = 1; exists(backup); n++) backup = `${file}.before-claude-code.${n}`;
|
|
fs.renameSync(file, backup);
|
|
}
|
|
function copySkill(source: string, target: string, root: string, preserve = false): void {
|
|
fs.mkdirSync(target, { recursive: true });
|
|
const files = ['SKILL.md', 'agents/openai.yaml'];
|
|
if (fs.existsSync(path.join(source, 'sections'))) {
|
|
for (const name of fs.readdirSync(path.join(source, 'sections'))) {
|
|
if (fs.statSync(path.join(source, 'sections', name)).isFile()) files.push(`sections/${name}`);
|
|
}
|
|
}
|
|
for (const rel of files) {
|
|
const src = path.join(source, rel);
|
|
if (!fs.existsSync(src)) continue;
|
|
const dest = path.join(target, rel);
|
|
// Never traverse a user-owned metadata directory link.
|
|
const parent = path.dirname(dest);
|
|
if (fs.lstatSync(parent, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
if (!linkIsOurs(parent, root)) throw new Error(`foreign metadata directory: ${parent}`);
|
|
if (preserve) {
|
|
// A copied host can carry legacy section links into another host's
|
|
// render. Replace our link before writing, never mutate that source.
|
|
fs.unlinkSync(parent);
|
|
fs.mkdirSync(parent, { recursive: true });
|
|
}
|
|
}
|
|
if (preserve && fs.lstatSync(dest, { throwIfNoEntry: false })?.isFile() && !fs.readFileSync(src).equals(fs.readFileSync(dest))) {
|
|
preserveCopy(dest);
|
|
}
|
|
atomicCopy(src, dest);
|
|
}
|
|
}
|
|
function retire(entry: string, root: string, oldSources: string[]): void {
|
|
if (!owned(entry, root)) return;
|
|
if (fs.lstatSync(entry).isSymbolicLink()) { fs.unlinkSync(entry); return; }
|
|
// Weak ownership proves the skill file, never the user's adjacent notes/assets.
|
|
// A customized copy (or one whose old render is already gone) is saved beside
|
|
// the old skill, without a SKILL.md that could keep the retired command alive.
|
|
const file = path.join(entry, 'SKILL.md');
|
|
if (fs.lstatSync(file, { throwIfNoEntry: false })?.isFile() && !oldSources.some(source => {
|
|
try { return fs.readFileSync(source).equals(fs.readFileSync(file)); } catch { return false; }
|
|
})) {
|
|
preserveCopy(file);
|
|
} else {
|
|
fs.rmSync(file, { force: true });
|
|
}
|
|
fs.rmSync(path.join(entry, '.gstack-owned'), { force: true });
|
|
for (const name of fs.readdirSync(entry)) {
|
|
const file = path.join(entry, name);
|
|
if (fs.lstatSync(file).isSymbolicLink() && linkIsOurs(file, root)) fs.unlinkSync(file);
|
|
}
|
|
try { fs.rmdirSync(entry); } catch { /* user files and metadata stay */ }
|
|
}
|
|
|
|
export function migrateClaudeCodeSkills(opts: RenameOptions): { migrated: number; pending: string[] } {
|
|
const root = fs.realpathSync(opts.installDir);
|
|
const env = { ...process.env, ...opts.env };
|
|
const home = opts.home ?? env.HOME ?? os.homedir();
|
|
const log = opts.log ?? ((line) => process.stderr.write(`${line}\n`));
|
|
const targets = [
|
|
{ host: 'codex', subdir: '.agents', dir: path.join(env.CODEX_HOME ?? path.join(home, '.codex'), 'skills') },
|
|
{ host: 'kiro', subdir: '.kiro', dir: path.join(home, '.kiro', 'skills') },
|
|
{ host: 'factory', subdir: '.factory', dir: path.join(home, '.factory', 'skills') },
|
|
{ host: 'opencode', subdir: '.opencode', dir: path.join(home, '.config', 'opencode', 'skills') },
|
|
{ host: 'cursor', subdir: '.cursor', dir: path.join(home, '.cursor', 'skills') },
|
|
];
|
|
if (opts.skillsDir) {
|
|
const local = targets.find(t => t.subdir === path.basename(path.dirname(opts.skillsDir!)));
|
|
if (local && !targets.some(t => path.resolve(t.dir) === path.resolve(opts.skillsDir!))) {
|
|
targets.push({ ...local, dir: path.resolve(opts.skillsDir) });
|
|
}
|
|
}
|
|
// Capture before generation: a build can otherwise erase a symlink's source.
|
|
const candidates = targets.filter(t => owned(path.join(t.dir, OLD), root));
|
|
const oldSources = targets.map(t => path.join(root, t.subdir, 'skills', OLD, 'SKILL.md'));
|
|
const result = { migrated: 0, pending: [] as string[] };
|
|
const render = opts.render ?? ((host: string, output: string) => {
|
|
const args = ['run', 'scripts/gen-skill-docs.ts', '--host', host, '--out-dir', output];
|
|
if (host === 'codex') {
|
|
let model = env.GSTACK_CODEX_GENERATION_MODEL;
|
|
if (!model) {
|
|
const probe = spawnSync(process.execPath, ['run', 'scripts/resolve-codex-generation-model.ts'], { cwd: root, env, encoding: 'utf8', timeout: 30_000 });
|
|
if (probe.status !== 0) throw new Error('could not resolve the Codex model profile');
|
|
model = probe.stdout.trim().split('\t')[0];
|
|
}
|
|
if (model) args.push('--model', model);
|
|
}
|
|
const rendered = spawnSync(process.execPath, args, { cwd: root, env, encoding: 'utf8', timeout: 120_000 });
|
|
if (rendered.status !== 0) throw new Error(`replacement generation failed for ${host}: ${rendered.stderr.trim().slice(-500)}`);
|
|
});
|
|
for (const target of candidates) {
|
|
const old = path.join(target.dir, OLD);
|
|
const next = path.join(target.dir, NEXT);
|
|
let temporary: string | undefined;
|
|
try {
|
|
if (exists(next) && !owned(next, root)) throw new Error(`replacement is a foreign skill: ${next}`);
|
|
const runtime = path.join(target.dir, 'gstack');
|
|
if (exists(runtime) && (
|
|
(fs.lstatSync(runtime).isSymbolicLink() && !linkIsOurs(runtime, root)) ||
|
|
(fs.existsSync(path.join(runtime, 'SKILL.md')) && !generated(path.join(runtime, 'SKILL.md')))
|
|
)) throw new Error(`runtime root is not gstack-managed: ${runtime}`);
|
|
for (const rel of RUNTIME_FILES) {
|
|
if (!fs.existsSync(path.join(root, rel))) throw new Error(`replacement runtime is missing ${rel}`);
|
|
const parent = path.join(runtime, path.dirname(rel));
|
|
if (fs.lstatSync(parent, { throwIfNoEntry: false })?.isSymbolicLink() && !linkIsOurs(parent, root)) {
|
|
throw new Error(`runtime asset directory is foreign: ${parent}`);
|
|
}
|
|
}
|
|
temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-claude-rename-'));
|
|
render(target.host, temporary);
|
|
const skill = path.join(temporary, target.subdir, 'skills', NEXT);
|
|
const content = fs.readFileSync(path.join(skill, 'SKILL.md'), 'utf8');
|
|
if (!generated(path.join(skill, 'SKILL.md')) || !/^name:\s*(?:gstack-)?claude-code\s*$/m.test(content)) {
|
|
throw new Error('replacement render has an unexpected skill name or no generated banner');
|
|
}
|
|
const canonical = path.join(root, target.subdir, 'skills', NEXT);
|
|
if (exists(canonical) && (fs.lstatSync(canonical).isSymbolicLink() || !owned(canonical, root))) {
|
|
throw new Error(`replacement render is not a managed directory: ${canonical}`);
|
|
}
|
|
copySkill(skill, canonical, root);
|
|
for (const rel of RUNTIME_FILES) {
|
|
const src = path.join(root, rel);
|
|
const dst = path.join(runtime, rel);
|
|
if (fs.existsSync(dst) && fs.realpathSync(dst) === fs.realpathSync(src)) continue;
|
|
atomicCopy(src, dst);
|
|
}
|
|
if (exists(next) && fs.lstatSync(next).isSymbolicLink()) fs.unlinkSync(next);
|
|
if (opts.copy || process.platform === 'win32' || exists(next)) {
|
|
copySkill(skill, next, root, true);
|
|
} else {
|
|
fs.mkdirSync(target.dir, { recursive: true });
|
|
fs.symlinkSync(canonical, next, 'dir');
|
|
}
|
|
if (!/^name:\s*(?:gstack-)?claude-code\s*$/m.test(fs.readFileSync(path.join(next, 'SKILL.md'), 'utf8'))) {
|
|
throw new Error('installed replacement could not be verified');
|
|
}
|
|
for (const rel of RUNTIME_FILES) fs.accessSync(path.join(runtime, rel), fs.constants.R_OK);
|
|
// Existing copied workflows must receive the same native host routing as
|
|
// the new wrapper, including when setup selected a different host. Only
|
|
// refresh installed managed entries; this never installs another host or
|
|
// a skill the user has removed. Links use the newly published render.
|
|
const renderedSkills = path.join(temporary, target.subdir, 'skills');
|
|
for (const name of fs.readdirSync(renderedSkills)) {
|
|
if (name === NEXT || name === OLD) continue;
|
|
const installed = path.join(target.dir, name);
|
|
if (!owned(installed, root) && !(name === 'gstack' && !fs.existsSync(path.join(installed, 'SKILL.md')))) continue;
|
|
const rendered = path.join(renderedSkills, name);
|
|
if (!generated(path.join(rendered, 'SKILL.md'))) continue;
|
|
// The root sidecar mixes runtime assets with SKILL.md; it is not a
|
|
// generated skill directory and must never be replaced as a whole.
|
|
if (name === 'gstack') {
|
|
// Legacy whole-repository runtime links share the tracked source
|
|
// SKILL.md. A host render must never replace that shared source file.
|
|
if (fs.realpathSync(installed) !== root) copySkill(rendered, installed, root, true);
|
|
continue;
|
|
}
|
|
const live = path.join(root, target.subdir, 'skills', name);
|
|
if (exists(live) && (fs.lstatSync(live).isSymbolicLink() || !owned(live, root))) {
|
|
throw new Error(`workflow render is not a managed directory: ${live}`);
|
|
}
|
|
copySkill(rendered, live, root);
|
|
if (!fs.lstatSync(installed).isSymbolicLink()) copySkill(rendered, installed, root, true);
|
|
}
|
|
if (fs.realpathSync(runtime) !== root) {
|
|
for (const [name, alias] of [['gstack-office-hours', 'office-hours'], ['gstack-upgrade', 'gstack-upgrade']]) {
|
|
const rendered = path.join(renderedSkills, name);
|
|
const installed = path.join(runtime, alias);
|
|
if (owned(installed, root) && generated(path.join(rendered, 'SKILL.md'))) copySkill(rendered, installed, root, true);
|
|
}
|
|
}
|
|
retire(old, root, oldSources);
|
|
result.migrated++;
|
|
} catch (error) {
|
|
result.pending.push(target.dir);
|
|
log(` kept ${old}: ${error instanceof Error ? error.message : String(error)}. Re-run ./setup to retry the rename.`);
|
|
} finally {
|
|
if (temporary) fs.rmSync(temporary, { recursive: true, force: true });
|
|
}
|
|
}
|
|
// A failed/colliding host can still depend on a shared old render. Keep all
|
|
// old renders until every known dependent installation has its replacement.
|
|
if (result.pending.length === 0 && candidates.length > 0 && env.GSTACK_DEFER_CLAUDE_RENAME_PRUNE !== '1') {
|
|
for (const subdir of new Set(targets.map(t => t.subdir))) {
|
|
const oldRender = path.join(root, subdir, 'skills', OLD);
|
|
if (fs.lstatSync(oldRender, { throwIfNoEntry: false })?.isDirectory() && generated(path.join(oldRender, 'SKILL.md'))) {
|
|
fs.rmSync(oldRender, { recursive: true, force: true });
|
|
}
|
|
}
|
|
}
|
|
if (result.migrated) log(` /claude is now /claude-code: migrated ${result.migrated} installed skill${result.migrated === 1 ? '' : 's'}. Consult sessions are preserved.`);
|
|
return result;
|
|
}
|