mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-16 09:55:29 +02:00
v1.86.0.0 feat: route outside reviews by harness (#2850)
* feat: add a restricted and supervised Claude Code runner Preserve configured authentication and models while enforcing tool access, strict completion JSON, bounded output and process cleanup. Cover argv, failure handling, session metadata and Windows process containment. * feat: route outside reviews by harness and migrate wrapper installs Use Claude Code from Codex and Codex from other supported hosts, with shared invocation rendering, positive gate validation and per-phase provenance. Rename /claude to /claude-code, repair managed shared and copied installations safely, and generate native Kiro skills. Add installed-workflow, failure-injection and live cross-harness regression coverage. * test: recognize CEO mode labels without terminal spacing The paid workflow rendered SCOPEEXPANSION at option 4, but its driver required a literal space. Match the leading mode title without cursor-spacing artifacts and ignore adjacent preview text. Preserve missing-target failures and downstream posture assertions. * test: isolate plan-count fixtures before starting review workflows Seed the complete test plan in a private git repository before launching Claude, so a bare slash command cannot review the live workspace while a delayed fixture message remains queued. Preserve count thresholds, parsers and budgets. Add initial-context and installed-discovery tests, and retain startup/terminal diagnostics on failed evaluations. * test: stabilize review fixtures and Claude eval startup Preserve source boundaries in workflow judge inputs, isolate CEO mode plans, and wait for interactive trust input readiness. Keep startup failure evidence and retain existing models, budgets, and assertions. Co-Authored-By: OpenAI Codex <noreply@openai.com> * test: classify collapsed review modes and isolate seeded findings Keep review questions out of the setup count when terminal cursor positioning removes spaces. State existing webhook safeguards so the five-finding control measures its seeded defects without accidental extra security and concurrency gaps. Preserve question bands and the paired control. Co-Authored-By: OpenAI Codex <noreply@openai.com> * test: isolate browser daemon state across free shards Co-Authored-By: OpenAI Codex <noreply@openai.com> * test: stabilize native review counting and interactive navigation Co-Authored-By: OpenAI Codex <noreply@openai.com> * chore: prepare v1.82.0.0 release Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: eliminate browser and process-cleanup test flakes Pin every CI surface to Bun 1.4.0 to avoid extra-stdio finalizers closing reused live sockets. Add an isolated GC/listener regression that fails on Bun 1.3.13, and prevent coordinated rollback to an affected CI runtime. Check renderer cleanup against the render's own staging directory so concurrent renders cannot invalidate the assertion. Make the no-pgrep process-tree walk tolerate disappearing /proc entries, and synchronize its test fixture through child readiness and pipe EOF instead of sleeps. Validation: 9,157 passed, 31 skipped, zero failures across 556 files with retries disabled. Build, all-host generation freshness, and skill checks passed. All three races have failing-before/passing-after regressions. * fix: count completed native review questions in evals * fix: drive review navigation from confirmed native choices * fix: require complete section-loading eval reports * test: isolate telemetry HTTP transport from local assertions * fix: keep review input on the active native question * test: let tunnel revocation daemon choose an available port * test: allocate available ports for pairing and watchdog fixtures * fix: stabilize planning eval navigation and phase reporting * test: isolate installed runtime paths in planning evals * test: stabilize review evidence and concurrent refresh fixtures * fix: resolve design findings before editing the plan * fix: honor and persist disabled outside plan reviews * fix: preserve planning decisions and terminal evidence Load installed host reviews at autoplan phase entry and wait for completed reviewers and saved artifacts. Reuse approved remedies while preserving individual finding decisions. Drive interactive evals from the current terminal viewport, bind native questions across scrolling, and require complete native report evidence. Cover captured stale menus, permission lifecycles, setup classification, and disabled-review tool availability with deterministic regressions. Advance release metadata and the upgrade migration to the unclaimed 1.83.0.0 slot. * fix: drive native review questions and preserve current plans Use the native single-choice keyboard protocol and current terminal viewport, with per-question navigation inside packets and completed-call coverage. Keep permissions, multi-select menus, and Submit controls distinct. Send Autoplan reviewers the amended implementation plan, keep its review record separate, and supply retained application contracts in the chain fixture. Clarify individual DevEx decisions and complete CEO fix options; use one active plan destination for the section-loading report. * fix: preserve complete plan-review decisions * fix: recognize native plan dialogs and reviewer controls * fix: preserve review decisions and phase completion * fix: recognize completed reviews without losing findings * fix: preserve review continuity and native eval completion * test: fix native review completion and eval retry isolation * test: handle native review menus and complete eval fixtures * test: fix native review setup, completion, and isolation failures * test: limit native skill discovery to runtime assets * fix: bind Autoplan reviews to full ordered phase inputs * test: fix planning eval routing, counting, and timeout handling * chore: advance queued release to v1.84.0.0 * fix: preserve complete review inputs and planning decisions * fix: reconcile review approvals and preserve phase obligations * fix: preserve review obligations and unblock eval permissions Carry recorded Autoplan requirements into blind phase inputs, require Eng review approvals before exit, and exercise combined asynchronous flows in CEO reviews. Correct native finding and handoff classification and unblock repeated report edits using scoped request identities. * fix: retain plan requirements and complete native review dialogs * fix: complete native review prompts and retain plan references * fix: preserve review inputs and classify native eval evidence * fix: check competing completion orders in CEO reviews * fix: recognize review decisions and require phase methodology Require the current phase methodology before Autoplan snapshots. Correct substantive decision, closed handoff, and cache-finding classification, and honor the recommended implementation approach in native review dialogs. Add captured-transcript regressions without changing review thresholds, provider models, retries, or deadlines. * test: bind native review decisions and close completed handoffs * fix: complete review dialogs and verify methodology delivery * fix: preserve review evidence and unblock native eval prompts * fix: handle native review question completions * fix: recognize native review narration and controls * fix: count native review decisions and isolate eval fixtures * test: verify seeded review coverage and current artifact permissions * test: isolate model and brain-aware skill renders * fix: repair native workflow evaluation and clarify review steps * fix: stabilize workflow eval evidence and review guidance * test: repair native workflow observation and fixture isolation * fix: recognize completed workflow evidence and owned skill reads * test: repair seeded workflow delivery and completion evidence * test: recognize current review evidence across native forms * test: handle native review variants and permission redraws * fix: honor review preferences and recognize native eval evidence * test: recognize completed review decisions and queued permissions * test: match current review contracts and partial-line edits * test: recognize completed workflow evidence and bounded human waits * fix: preserve review entry gates and native eval interactions * fix: recognize native workflow evidence and preserve review gates * test: recognize current review evidence and preconfigure workflow fixtures * test: recognize completed review findings and scoped artifact permissions * fix: stabilize native workflow review and permission evidence * fix: recognize current review evidence and scoped edit confirmations Clarify Design and engineering review entry instructions and Design scoring. Recognize required legacy coverage and public Autoplan completion recaps. Bind the pending Edit confirmation to its exact file, ordered digest, and one-request approval when a preceding command display remains visible. Keep reviews within their existing size limits and preserve scope gates when extracting workflow fixtures from either supported preamble header. Keep failure outcomes, review thresholds, provider choices, and eval budgets. * fix: recover review workflow progress and eval evidence * fix: recognize valid review evidence and scope selection * test: fix review evidence parsing and repeated artifact prompts * test: recognize valid review decisions and pending native cards * fix(plan-eng-review): keep final navigation consistent with approved tasks * test: recognize valid review evidence and bind legacy diff requests * fix: stabilize review eval evidence and harness repair guidance * docs: update project documentation for v1.85.0.0 Co-Authored-By: OpenAI Codex <noreply@openai.com> * test: fix Windows CI fixtures and credential scan Rebase captured JSON values and filesystem evidence using the appropriate path convention. Compile native fake CLIs on Windows and synchronize pipe holder readiness, with cleanup retained when assertions fail. Assemble synthetic credential fixtures at runtime so the added-line scan keeps enforcing the same gate without flagging its own rejection controls. Discover generated skills directly for the empty-find regression check, avoiding a recursive scan through saved evaluation artifacts and dependencies. * fix: preserve source renders on Windows Compare canonical generator paths using native separators so an output sidecar pointing at the source cannot overwrite its skill or metadata. Keep the regression fixture isolated from the real checkout and expose freshness diagnostics before asserting subprocess status. Detach Windows drain-test pipe holders from the fake provider's automatic child cleanup while preserving the enclosing runner job and its assertions. * fix: clarify outside review fallback and CEO decisions Render one applicable own-harness fallback path and retain native review, disabled policy, and missing-coverage semantics. Align report field names and mode labels, and make the existing per-cut scope approval explicit. Regenerate skill outputs and keep the workflow judge's model, thresholds, and retry policy unchanged. * chore: move release to free version slot (v1.86.0.0) PR #2852 now claims v1.85.0.0. Align the release metadata and rename migration so upgrades from that version still receive it. Co-Authored-By: OpenAI Codex <noreply@openai.com> * fix: include engineering review prerequisites and restore branch context * fix: recognize coverage diagrams and clarify design review instructions * fix: preserve file identities and join Windows test processes --------- Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
co-authored by
OpenAI Codex
parent
71f6048e8a
commit
9f81911136
@@ -0,0 +1,264 @@
|
||||
/** 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) {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/** Windows lifetime containment for the dedicated gstack-claude-code process. */
|
||||
|
||||
export class WindowsReviewSupervisionError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`Claude Code Windows process supervision could not initialize: ${message}. No reviewer was started. Update Bun or check the host's process policy, then retry.`);
|
||||
this.name = 'WindowsReviewSupervisionError';
|
||||
}
|
||||
}
|
||||
|
||||
// This handle is intentionally never closed in JavaScript: closing it would
|
||||
// terminate this runner too. The OS closes it when the dedicated CLI exits,
|
||||
// after its JSON has flushed, and kills every remaining descendant with it.
|
||||
// Keep the native library alive for the same lifetime.
|
||||
let lifetime: { handle: number | bigint; library: unknown } | undefined;
|
||||
|
||||
/**
|
||||
* Join an unnamed, non-inheritable job BEFORE spawning the provider. Children
|
||||
* inherit membership, not the handle. Unlike taskkill /T, job membership still
|
||||
* contains a descendant after its immediate parent has exited.
|
||||
*
|
||||
* Call only from claudeCodeMain in its dedicated CLI process, never from the
|
||||
* reusable runClaudeCode API or a host/test process that owns other work.
|
||||
* https://learn.microsoft.com/windows/win32/procthread/job-objects
|
||||
*/
|
||||
export async function initializeWindowsReviewJob(): Promise<void> {
|
||||
if (process.platform !== 'win32' || lifetime) return;
|
||||
let library: Awaited<ReturnType<typeof openKernel>> | undefined;
|
||||
let job: number | bigint = 0n;
|
||||
let currentProcess: number | bigint = 0n;
|
||||
try {
|
||||
library = await openKernel();
|
||||
const api = library.symbols;
|
||||
// NULL security attributes make this handle non-inheritable; NULL name
|
||||
// makes the job private to this invocation.
|
||||
job = api.CreateJobObjectW(null, null);
|
||||
if (!job) throw new Error(`CreateJobObjectW failed (${api.GetLastError()})`);
|
||||
|
||||
// JOBOBJECT_EXTENDED_LIMIT_INFORMATION on Windows' 64-bit ABI:
|
||||
// basic limits (64), IO_COUNTERS (48), then four SIZE_T fields (32).
|
||||
// LimitFlags is the DWORD at byte 16 in the basic-limit structure.
|
||||
const limits = Buffer.alloc(144);
|
||||
limits.writeUInt32LE(0x00002000, 16); // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
const { ptr } = await import('bun:ffi');
|
||||
if (!api.SetInformationJobObject(job, 9, ptr(limits), limits.byteLength)) {
|
||||
throw new Error(`SetInformationJobObject failed (${api.GetLastError()})`);
|
||||
}
|
||||
// AssignProcessToJobObject requires PROCESS_SET_QUOTA | PROCESS_TERMINATE.
|
||||
currentProcess = api.OpenProcess(0x0101, 0, process.pid);
|
||||
if (!currentProcess) throw new Error(`OpenProcess failed (${api.GetLastError()})`);
|
||||
if (!api.AssignProcessToJobObject(job, currentProcess)) {
|
||||
throw new Error(`AssignProcessToJobObject failed (${api.GetLastError()})`);
|
||||
}
|
||||
lifetime = { handle: job, library };
|
||||
api.CloseHandle(currentProcess);
|
||||
} catch (error) {
|
||||
// These failures occur before assignment. Never close a job that already
|
||||
// contains this process: preserve its handle until the CLI reports failure.
|
||||
if (library && !lifetime) {
|
||||
if (currentProcess) library.symbols.CloseHandle(currentProcess);
|
||||
if (job) library.symbols.CloseHandle(job);
|
||||
library.close();
|
||||
}
|
||||
throw new WindowsReviewSupervisionError(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
}
|
||||
|
||||
async function openKernel() {
|
||||
const { dlopen, FFIType } = await import('bun:ffi');
|
||||
// HANDLE is an integer token, not an address. Bun explicitly requires an
|
||||
// integer FFI type here; ptr is reserved for the actual buffer parameters.
|
||||
return dlopen('kernel32.dll', {
|
||||
CreateJobObjectW: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.u64 },
|
||||
SetInformationJobObject: { args: [FFIType.u64, FFIType.u32, FFIType.ptr, FFIType.u32], returns: FFIType.i32 },
|
||||
OpenProcess: { args: [FFIType.u32, FFIType.i32, FFIType.u32], returns: FFIType.u64 },
|
||||
AssignProcessToJobObject: { args: [FFIType.u64, FFIType.u64], returns: FFIType.i32 },
|
||||
CloseHandle: { args: [FFIType.u64], returns: FFIType.i32 },
|
||||
GetLastError: { args: [], returns: FFIType.u32 },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/** Restricted, supervised Claude Code invocation for outside reviews. */
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { resolveClaudeCommand, type ClaudeCommand } from './claude-bin';
|
||||
import { initializeWindowsReviewJob, WindowsReviewSupervisionError } from './claude-code-windows-job';
|
||||
|
||||
export const CLAUDE_CODE_OUTPUT_LIMIT = 32 * 1024 * 1024;
|
||||
const DRAIN_TIMEOUT_MS = 500;
|
||||
|
||||
export interface ClaudeCodeOptions {
|
||||
cwd: string;
|
||||
access: 'none' | 'read-only';
|
||||
timeoutMs: number;
|
||||
prompt: string;
|
||||
resume?: string;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export interface ClaudeCodeResult {
|
||||
status: 'completed' | 'unavailable' | 'error';
|
||||
provider: 'claude-code';
|
||||
result: string;
|
||||
error?: { code: string; message: string };
|
||||
session_id?: string;
|
||||
usage?: Record<string, unknown>;
|
||||
modelUsage?: Record<string, unknown>;
|
||||
model?: string;
|
||||
exit_code?: number | null;
|
||||
stderr?: string;
|
||||
}
|
||||
|
||||
function failure(code: string, message: string, unavailable = false): ClaudeCodeResult {
|
||||
return { status: unavailable ? 'unavailable' : 'error', provider: 'claude-code', result: '', error: { code, message } };
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** Keep argument construction separate so wrappers never interpolate a prompt. */
|
||||
export function claudeCodeArgs(options: Pick<ClaudeCodeOptions, 'access' | 'resume'>, command: ClaudeCommand, env: NodeJS.ProcessEnv = process.env): string[] {
|
||||
const args = [
|
||||
...command.argsPrefix, '-p', '--output-format', 'json',
|
||||
'--disable-slash-commands',
|
||||
'--tools', options.access === 'none' ? '' : 'Read,Grep,Glob',
|
||||
'--disallowedTools', 'mcp__*',
|
||||
'--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
|
||||
'--settings', '{"disableAllHooks":true}',
|
||||
'--permission-mode', 'default',
|
||||
];
|
||||
if (options.access === 'none') {
|
||||
// The CLI's default coding prompt can otherwise elicit simulated tool
|
||||
// transcripts even with an empty tool list. State the actual capability
|
||||
// separately from the caller's unmodified prompt; missing context stays missing.
|
||||
args.push('--append-system-prompt',
|
||||
'No tools are available in this invocation. Analyze only the supplied prompt and review material. '
|
||||
+ 'Do not attempt or simulate tool calls, command output, repository inspection, or file changes. '
|
||||
+ 'Return your findings and the conclusion requested by the caller directly. '
|
||||
+ 'If essential context is missing, identify it explicitly instead of inventing observations.');
|
||||
}
|
||||
if (options.access === 'read-only') args.push('--allowedTools', 'Read,Grep,Glob');
|
||||
// An explicit gstack override wins; otherwise leave native CLI configuration
|
||||
// and ANTHROPIC_MODEL intact instead of replacing the user's selected model.
|
||||
if (env.GSTACK_CLAUDE_MODEL) args.push('--model', env.GSTACK_CLAUDE_MODEL);
|
||||
if (options.resume) args.push('--resume', options.resume);
|
||||
return args;
|
||||
}
|
||||
|
||||
/** Kill only the process tree owned by this invocation, never other sessions. */
|
||||
function killTree(child: ChildProcess): void {
|
||||
if (typeof child.pid !== 'number') return;
|
||||
if (process.platform === 'win32') {
|
||||
const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
||||
const timer = setTimeout(() => { killer.kill(); child.kill(); }, DRAIN_TIMEOUT_MS);
|
||||
timer.unref();
|
||||
killer.once('error', () => { clearTimeout(timer); child.kill(); });
|
||||
killer.once('close', () => { clearTimeout(timer); child.kill(); });
|
||||
killer.unref();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
process.kill(-child.pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
|
||||
try { child.kill('SIGKILL'); } catch { /* Already reaped. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse only a completed invocation; a valid JSON error must never pass a gate. */
|
||||
export function parseClaudeCodeResult(stdout: string, stderr: string, exitCode: number | null): ClaudeCodeResult {
|
||||
const diagnostic = stderr.trim().slice(0, 16 * 1024);
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(stdout); } catch { /* Classified below, after CLI failure. */ }
|
||||
const obj = isObject(raw) ? raw : undefined;
|
||||
const response = typeof obj?.result === 'string' ? obj.result : typeof obj?.response === 'string' ? obj.response : '';
|
||||
const actualFailure = exitCode !== 0 || !obj || Boolean(obj.is_error) || !response.trim();
|
||||
let result: ClaudeCodeResult;
|
||||
if (actualFailure && /\b(?:authentication(?:[_ ](?:failed|error))?|unauthorized|not authenticated|invalid (?:x-)?api[- ]key|login required|please (?:run .*login|log in)|not logged in)\b/i.test(`${diagnostic}\n${response}\n${stdout.slice(0, 4096)}`)) {
|
||||
result = failure('authentication', 'Claude Code authentication failed. Run claude interactively in this execution context to authenticate.', true);
|
||||
} else if (exitCode !== 0) {
|
||||
result = failure('exit', `Claude Code exited with ${exitCode === null ? 'a signal' : `code ${exitCode}`}.${response ? ` ${response.slice(0, 4096)}` : ''}`);
|
||||
} else if (raw === undefined) {
|
||||
result = failure('invalid-json', 'Claude Code returned invalid JSON. Check the CLI installation and diagnostic output.');
|
||||
} else if (!obj) {
|
||||
result = failure('invalid-response', 'Claude Code returned JSON that is not an object.');
|
||||
} else if (obj.is_error || (typeof obj.subtype === 'string' && obj.subtype.startsWith('error'))) {
|
||||
result = failure('provider-error', `Claude Code reported an error.${response ? ` ${response.slice(0, 4096)}` : ''}`);
|
||||
} else if (!response.trim()) {
|
||||
result = failure('empty-response', 'Claude Code returned no response text.');
|
||||
} else {
|
||||
result = { status: 'completed', provider: 'claude-code', result: response };
|
||||
}
|
||||
if (obj) {
|
||||
if (typeof obj.session_id === 'string' && obj.session_id) result.session_id = obj.session_id;
|
||||
if (isObject(obj.usage)) result.usage = obj.usage;
|
||||
if (isObject(obj.modelUsage)) result.modelUsage = obj.modelUsage;
|
||||
// Do not choose one model from modelUsage: fallback/multi-model sessions
|
||||
// must retain all their attribution, and absent identity stays unknown.
|
||||
if (typeof obj.model === 'string' && obj.model) result.model = obj.model;
|
||||
}
|
||||
result.exit_code = exitCode;
|
||||
if (diagnostic) result.stderr = diagnostic;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Prompt stdin, direct argv, bounded output and process-group supervision. */
|
||||
export async function runClaudeCode(options: ClaudeCodeOptions): Promise<ClaudeCodeResult> {
|
||||
if (!options.cwd || !['none', 'read-only'].includes(options.access) ||
|
||||
!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > 2_147_483_647 ||
|
||||
!options.prompt.trim() || (options.resume !== undefined && !options.resume.trim())) {
|
||||
return failure('arguments', 'Provide --cwd, --access none|read-only, a positive --timeout-ms, and a nonempty prompt on stdin.');
|
||||
}
|
||||
const env = options.env ?? process.env;
|
||||
const command = resolveClaudeCommand(env);
|
||||
if (!command) return failure('not-found', 'Claude Code CLI not found. Install Claude Code or set GSTACK_CLAUDE_BIN, then retry.', true);
|
||||
|
||||
let child: ChildProcess;
|
||||
try {
|
||||
child = spawn(command.command, claudeCodeArgs(options, command, env), {
|
||||
cwd: options.cwd, env, stdio: ['pipe', 'pipe', 'pipe'],
|
||||
detached: process.platform !== 'win32', windowsHide: true,
|
||||
});
|
||||
} catch (error) {
|
||||
return failure('spawn', `Claude Code could not start: ${(error as Error).message}`, true);
|
||||
}
|
||||
|
||||
return await new Promise<ClaudeCodeResult>((resolve) => {
|
||||
let settled = false;
|
||||
let stopped: ClaudeCodeResult | undefined;
|
||||
let exitCode: number | null = null;
|
||||
let bytes = 0;
|
||||
const stdout: Buffer[] = [];
|
||||
const stderr: Buffer[] = [];
|
||||
let drainTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeoutTimer);
|
||||
clearTimeout(drainTimer);
|
||||
process.off('SIGINT', onInterrupt);
|
||||
process.off('SIGTERM', onTerminate);
|
||||
process.off('exit', onParentExit);
|
||||
killTree(child);
|
||||
child.stdin?.destroy();
|
||||
child.stdout?.destroy();
|
||||
child.stderr?.destroy();
|
||||
child.unref();
|
||||
const err = Buffer.concat(stderr).toString('utf8');
|
||||
if (stopped) {
|
||||
stopped.exit_code = exitCode;
|
||||
if (err.trim()) stopped.stderr = err.trim().slice(0, 16 * 1024);
|
||||
resolve(stopped);
|
||||
} else {
|
||||
resolve(parseClaudeCodeResult(Buffer.concat(stdout).toString('utf8'), err, exitCode));
|
||||
}
|
||||
};
|
||||
const boundDrain = () => {
|
||||
drainTimer ??= setTimeout(() => {
|
||||
stopped ??= failure('output-drain', 'Claude Code output pipes did not close after execution. Outside coverage is unavailable.', true);
|
||||
finish();
|
||||
}, DRAIN_TIMEOUT_MS);
|
||||
};
|
||||
const stop = (result: ClaudeCodeResult) => {
|
||||
stopped ??= result;
|
||||
killTree(child);
|
||||
boundDrain();
|
||||
};
|
||||
const collect = (chunks: Buffer[], chunk: Buffer | string) => {
|
||||
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
||||
const remaining = CLAUDE_CODE_OUTPUT_LIMIT - bytes;
|
||||
bytes += data.byteLength;
|
||||
if (remaining > 0) chunks.push(data.subarray(0, remaining));
|
||||
if (bytes > CLAUDE_CODE_OUTPUT_LIMIT) stop(failure('output-limit', 'Claude Code output exceeded the 32 MiB limit.'));
|
||||
};
|
||||
const onInterrupt = () => stop(failure('interrupted', 'Claude Code outside review was interrupted (SIGINT).', true));
|
||||
const onTerminate = () => stop(failure('interrupted', 'Claude Code outside review was interrupted (SIGTERM).', true));
|
||||
const onParentExit = () => killTree(child);
|
||||
const timeoutTimer = setTimeout(() => stop(failure('timeout', `Claude Code timed out after ${options.timeoutMs}ms.`, true)), options.timeoutMs);
|
||||
process.on('SIGINT', onInterrupt);
|
||||
process.on('SIGTERM', onTerminate);
|
||||
process.on('exit', onParentExit);
|
||||
child.stdout?.on('data', (chunk) => collect(stdout, chunk));
|
||||
child.stderr?.on('data', (chunk) => collect(stderr, chunk));
|
||||
child.once('error', (error) => {
|
||||
stopped = failure('spawn', `Claude Code could not start: ${error.message}`, true);
|
||||
finish();
|
||||
});
|
||||
child.once('exit', (code) => {
|
||||
exitCode = code;
|
||||
// Allow already-written output to drain naturally. A descendant holding
|
||||
// the pipes past this bound is unavailable coverage, even if killing it
|
||||
// would make an otherwise valid response look like a clean completion.
|
||||
boundDrain();
|
||||
});
|
||||
child.once('close', (code) => { exitCode = code; finish(); });
|
||||
child.stdin?.on('error', (error: NodeJS.ErrnoException) => {
|
||||
// A rejected/auth-failed CLI may exit before reading its whole prompt;
|
||||
// retain that actual provider error instead of replacing it with EPIPE.
|
||||
if (error.code !== 'EPIPE' && error.code !== 'ERR_STREAM_DESTROYED') {
|
||||
stop(failure('stdin', `Claude Code could not read its prompt: ${error.message}`, true));
|
||||
}
|
||||
});
|
||||
child.stdin?.end(options.prompt);
|
||||
});
|
||||
}
|
||||
|
||||
export async function claudeCodeMain(argv: string[]): Promise<number> {
|
||||
let result: ClaudeCodeResult;
|
||||
try {
|
||||
const values = new Map<string, string>();
|
||||
for (let i = 0; i < argv.length; i += 2) {
|
||||
if (!['--cwd', '--access', '--timeout-ms', '--resume'].includes(argv[i]) || values.has(argv[i]) || argv[i + 1] === undefined) {
|
||||
throw new Error('Usage: gstack-claude-code --cwd <repo> --access none|read-only --timeout-ms <n> [--resume <session-id>] (prompt on stdin)');
|
||||
}
|
||||
values.set(argv[i], argv[i + 1]);
|
||||
}
|
||||
const cwd = values.get('--cwd') ?? '';
|
||||
const access = values.get('--access') as ClaudeCodeOptions['access'];
|
||||
const timeoutMs = Number(values.get('--timeout-ms'));
|
||||
if (!cwd || !['none', 'read-only'].includes(access) || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {
|
||||
throw new Error('Provide --cwd, --access none|read-only, and a positive --timeout-ms.');
|
||||
}
|
||||
// This entry runs in a dedicated process. Its Windows job owns the CLI and
|
||||
// descendants even after the immediate provider process exits; the final
|
||||
// process.exit happens only after the result below has flushed to stdout.
|
||||
await initializeWindowsReviewJob();
|
||||
result = await runClaudeCode({ cwd, access, timeoutMs, resume: values.get('--resume'), prompt: await Bun.stdin.text() });
|
||||
} catch (error) {
|
||||
result = error instanceof WindowsReviewSupervisionError
|
||||
? failure('supervision', error.message, true)
|
||||
: failure('arguments', (error as Error).message);
|
||||
}
|
||||
// The CLI shim exits immediately after this promise. Wait for backpressure:
|
||||
// otherwise a valid multi-megabyte review is truncated in a pipe at exit.
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
process.stdout.write(`${JSON.stringify(result)}\n`, (error) => error ? reject(error) : resolve());
|
||||
});
|
||||
return result.status === 'completed' ? 0 : 1;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Review-specific completion evidence, separate from provider transport success. */
|
||||
export type OutsideGate = 'review' | 'structured' | 'spec';
|
||||
export function validateOutsideReview(text: string, gate: OutsideGate): { completed: boolean; reason?: string; score?: number; gate?: 'pass' | 'fail' } {
|
||||
if (!text.trim()) return { completed: false, reason: 'empty response' };
|
||||
// "I cannot find any issues" is a legitimate clean conclusion. Match a
|
||||
// refused/unavailable review, not every use of a negative auxiliary verb.
|
||||
if (/\b(?:(?:I (?:cannot|can't|won't|will not|am unable to)|I'm unable to)\s+(?:review|analy[sz]e|evaluate|assess|inspect|access|complete|perform|provide|assist|help|proceed)|unable to (?:review|analy[sz]e)|I must (?:decline|refuse))\b/i.test(text)) return { completed: false, reason: 'review refused' };
|
||||
if (gate === 'spec') {
|
||||
const scores = [...text.matchAll(/^SCORE:[\t ]*(10|[0-9])[\t ]*\r?$/gm)];
|
||||
const ambiguities = [...text.matchAll(/^AMBIGUITIES:[\t ]*(\S[^\r\n]*)\r?$/gm)];
|
||||
if (scores.length !== 1 || ambiguities.length !== 1) return { completed: false, reason: 'missing or invalid SCORE/AMBIGUITIES markers' };
|
||||
const score = Number(scores[0][1]);
|
||||
return { completed: true, score, gate: score >= 7 ? 'pass' : 'fail' };
|
||||
}
|
||||
if (gate === 'structured') {
|
||||
const plain = plainReview(text);
|
||||
const severity = /\[P[0-3]\]|^P[0-3]:/m.test(plain);
|
||||
const clear = /\bNO_FINDINGS\b|\bno (?:actionable |significant |new |concrete )?(?:bugs|issues|findings|problems)\b|\b(?:did not|didn't) (?:find|identify) any (?:actionable |new |concrete )?(?:bugs|issues|findings|problems)\b/i.test(text);
|
||||
if (!severity && !clear) return { completed: false, reason: 'missing severity or explicit no-findings conclusion' };
|
||||
return { completed: true, gate: /\[P1\]|^P1:/m.test(plain) ? 'fail' : 'pass' };
|
||||
}
|
||||
// Formatting the requested marker in bold, inline code, or a list does not
|
||||
// invalidate a completed review. Preserve the explicit action + reason gate.
|
||||
const plain = plainReview(text);
|
||||
if (!/^Recommendation:[\t ]*[^\r\n]+\bbecause\b[\t ]*\S[^\r\n]+$/im.test(plain)) return { completed: false, reason: 'missing review completion recommendation' };
|
||||
return { completed: true };
|
||||
}
|
||||
function plainReview(text: string): string {
|
||||
return text.split(/\r?\n/).map(line => line.replace(/^[\t ]*(?:#{1,6}[\t ]+|[-+*][\t ]+)?/, '').replace(/[*_`]/g, '')).join('\n');
|
||||
}
|
||||
if (import.meta.main) {
|
||||
const [gate, path] = process.argv.slice(2);
|
||||
if (!['review', 'structured', 'spec'].includes(gate) || !path) { console.error('Usage: outside-review-result.ts review|structured|spec <response-file>'); process.exit(2); }
|
||||
try {
|
||||
const result = validateOutsideReview(await Bun.file(path).text(), gate as OutsideGate);
|
||||
if (!result.completed) { console.error(`Outside review unavailable: ${result.reason}; missing coverage.`); process.exit(1); }
|
||||
} catch (error) { console.error(`Outside review unavailable: ${error}`); process.exit(1); }
|
||||
}
|
||||
Reference in New Issue
Block a user