mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-29 16:11:58 +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>
145 lines
8.7 KiB
TypeScript
145 lines
8.7 KiB
TypeScript
/** Audited cache adapter for runWorkflowJudge only. Native/PTY evals stay fresh. */
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { isBuiltin } from 'node:module';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { DEFAULT_JUDGE_MAX_TOKENS, resolveEvalModel } from '../../lib/eval-model';
|
|
import { JUDGE_MS } from './eval-budgets';
|
|
import type { JudgeScore } from './llm-judge';
|
|
import { readWorkflowJudgeInput, buildWorkflowJudgePrompt } from './workflow-judge-input';
|
|
import { buildEvalInputIdentity, lookupEvalInputCache, storeEvalInputCache,
|
|
type EvalCacheValue, type EvalInputIdentity, type EvalPassingProof } from '../../scripts/eval-input-cache';
|
|
|
|
type Thresholds = { clarity: number; completeness: number; actionability: number };
|
|
export interface WorkflowCacheOptions {
|
|
root: string; testName: string; skillPath: string; startMarker: string; endMarker: string | null;
|
|
judgeContext: string; judgeGoal: string; model?: string; thresholds: Thresholds; prompt: string; attempt: number;
|
|
env?: NodeJS.ProcessEnv;
|
|
}
|
|
export interface WorkflowJudgeReuse {
|
|
key: string; source: EvalPassingProof['source'];
|
|
}
|
|
|
|
/** Follow literal module imports, including installed SDK bytes, without executing them. */
|
|
export function workflowJudgeDependencies(root: string, documents: string[]): string[] {
|
|
const seen = new Set<string>();
|
|
const scan = new Bun.Transpiler({ loader: 'tsx' });
|
|
const visit = (file: string) => {
|
|
file = path.resolve(file);
|
|
const relative = path.relative(root, file).split(path.sep).join('/');
|
|
if (relative.startsWith('../') || path.isAbsolute(relative)) throw new Error('Dependency outside checkout');
|
|
// Root version labels collector output only; its remaining semantic fields
|
|
// are hashed separately. Installed package manifests remain byte-exact.
|
|
if (relative === 'package.json') return;
|
|
if (seen.has(relative)) return;
|
|
seen.add(relative);
|
|
const source = fs.readFileSync(file, 'utf8');
|
|
if (!/\.[cm]?[jt]sx?$/.test(file)) return;
|
|
// Entrypoint scripts carry hashbangs, which scanImports does not accept.
|
|
// Strip only for parsing; buildEvalInputIdentity still hashes the full file.
|
|
for (const entry of scan.scanImports(source.replace(/^#![^\n]*(?:\n|$)/, '\n'))) {
|
|
if (isBuiltin(entry.path) || entry.path.startsWith('bun:')) continue;
|
|
const resolved = Bun.resolveSync(entry.path, path.dirname(file));
|
|
visit(resolved);
|
|
// Package export maps/defaults affect resolution independently of code.
|
|
let directory = path.dirname(resolved);
|
|
while (directory !== root && directory.startsWith(root + path.sep)) {
|
|
const manifest = path.join(directory, 'package.json');
|
|
if (fs.existsSync(manifest)) { visit(manifest); break; }
|
|
directory = path.dirname(directory);
|
|
}
|
|
}
|
|
};
|
|
for (const file of ['test/skill-llm-eval.test.ts', 'test/helpers/workflow-judge-cache.ts',
|
|
'test/helpers/llm-judge.ts', 'lib/eval-model.ts', 'test/helpers/eval-budgets.ts',
|
|
'scripts/test-paid-shards.ts', 'scripts/test-strict-output.ts', 'scripts/eval-select.ts',
|
|
'scripts/test-pr-profile.ts', '.github/workflows/evals.yml',
|
|
'package.json', 'bun.lock', '.github/docker/Dockerfile.ci', ...documents]) visit(path.join(root, file));
|
|
for (const file of ['bunfig.toml', 'tsconfig.json', 'jsconfig.json'])
|
|
if (fs.existsSync(path.join(root, file))) visit(path.join(root, file));
|
|
return [...seen].sort();
|
|
}
|
|
|
|
export function validWorkflowJudgeScore(value: EvalCacheValue, thresholds: Thresholds): value is JudgeScore & EvalCacheValue {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
|| Object.keys(value).sort().join(',') !== 'actionability,clarity,completeness,reasoning'
|
|
|| typeof value.reasoning !== 'string') return false;
|
|
return (['clarity', 'completeness', 'actionability'] as const).every(key =>
|
|
typeof value[key] === 'number' && Number.isInteger(value[key]) && value[key] >= thresholds[key] && value[key] <= 5);
|
|
}
|
|
|
|
export function prepareWorkflowJudgeCache(opts: WorkflowCacheOptions): {
|
|
lookup(): { scores: JudgeScore; reuse: WorkflowJudgeReuse } | null;
|
|
/** The attempt guard is rechecked after synchronous input/provenance reads. */
|
|
publish(scores: JudgeScore, isActive?: () => boolean): (() => void) | undefined;
|
|
} {
|
|
const env = opts.env ?? process.env;
|
|
const noCache = { lookup: () => null, publish: (_scores: JudgeScore) => undefined };
|
|
const pr = Number(env.EVALS_CACHE_PR);
|
|
// Runtime ID is the immutable CI image manifest, not a mutable image tag.
|
|
// Nonstandard Node/Bun preload code or custom model endpoints need a separate
|
|
// audited adapter: they can change the request outside the consumed source.
|
|
if (!env.EVALS_CACHE_DIR || !env.EVALS_CACHE_REPOSITORY || !Number.isSafeInteger(pr) || pr <= 0
|
|
|| !/^(?:sha256:)?[a-f0-9]{64}$/.test(env.EVALS_CACHE_RUNTIME_ID ?? '')
|
|
|| env.EVALS_TIER !== 'gate' || env.EVALS_FRESH === '1'
|
|
|| ['release', 'periodic'].includes(env.EVALS_CACHE_PURPOSE ?? '')
|
|
|| opts.attempt !== 1 || env.NODE_OPTIONS || env.BUN_OPTIONS
|
|
|| (env.ANTHROPIC_BASE_URL && env.ANTHROPIC_BASE_URL !== 'https://api.anthropic.com')) return noCache;
|
|
|
|
const currentIdentity = (): EvalInputIdentity | null => {
|
|
try {
|
|
const input = readWorkflowJudgeInput(opts);
|
|
const prompt = buildWorkflowJudgePrompt(opts, input);
|
|
// Never substitute this adapter's interpretation for the actual API input.
|
|
if (prompt !== opts.prompt) return null;
|
|
const { version: _releaseLabel, ...rootPackage } = JSON.parse(fs.readFileSync(path.join(opts.root, 'package.json'), 'utf8'));
|
|
const identity = buildEvalInputIdentity({ root: opts.root,
|
|
scope: { repository: env.EVALS_CACHE_REPOSITORY!, pullRequest: pr },
|
|
coverage: { dependencies: 'complete', prompts: 'complete', environment: 'complete' }, unknownDependencies: [],
|
|
files: workflowJudgeDependencies(opts.root, input.files.map(file => file.path)),
|
|
prompts: { [opts.testName]: prompt },
|
|
parameters: { rootPackage, thresholds: opts.thresholds, max_tokens: DEFAULT_JUDGE_MAX_TOKENS, temperature: null, budget_ms: JUDGE_MS,
|
|
request: 'messages.create/user', retries: 1 },
|
|
runtime: { image: env.EVALS_CACHE_RUNTIME_ID!, bun: Bun.version, node: process.versions.node,
|
|
platform: process.platform, arch: process.arch, judge: resolveEvalModel('judge', opts.model, env),
|
|
anthropic_base_url: env.ANTHROPIC_BASE_URL ?? 'https://api.anthropic.com',
|
|
anthropic_log: env.ANTHROPIC_LOG ?? null,
|
|
proxies: Object.fromEntries(['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy']
|
|
.map(name => [name, env[name] ?? null])) },
|
|
});
|
|
return identity.status === 'eligible' ? identity.identity : null;
|
|
} catch { return null; }
|
|
};
|
|
const before = currentIdentity();
|
|
if (!before) return noCache;
|
|
const common = { cacheDir: env.EVALS_CACHE_DIR, purpose: 'gate' as const };
|
|
return {
|
|
lookup() {
|
|
const result = lookupEvalInputCache({ ...common, identity: before,
|
|
validateResult: value => validWorkflowJudgeScore(value, opts.thresholds) });
|
|
return result.status === 'reused'
|
|
? { scores: result.result as JudgeScore, reuse: { key: result.key, source: result.source } } : null;
|
|
},
|
|
publish(scores, isActive = () => true) {
|
|
// Caller reaches here ONLY after its actual assertions passed. A later
|
|
// failed case in the file does not erase this independently completed case.
|
|
if (!isActive() || !validWorkflowJudgeScore(scores as unknown as EvalCacheValue, opts.thresholds)) return;
|
|
const after = currentIdentity();
|
|
const runId = env.GITHUB_RUN_ID ? `${env.GITHUB_RUN_ID}/${env.GITHUB_RUN_ATTEMPT ?? '1'}` : env.EVALS_RUN_ID;
|
|
if (!after || !runId || !isActive()) return;
|
|
const revision = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: opts.root, encoding: 'utf8', timeout: 3000 });
|
|
if (revision.status !== 0 || !isActive()) return;
|
|
const stored = storeEvalInputCache({ ...common, before, after, proof: {
|
|
execution: 'new', finalized: true, completeAttemptHistory: true, exitCode: 0, timedOut: false,
|
|
cancelled: false, skipped: 0, failed: 0, passed: 1,
|
|
cases: [{ id: opts.testName, outcome: 'passed', attempt: 1 }],
|
|
source: { runId, revision: revision.stdout.trim(), completedAt: Date.now() },
|
|
result: { clarity: scores.clarity, completeness: scores.completeness, actionability: scores.actionability, reasoning: scores.reasoning },
|
|
} });
|
|
// A slow synchronous write can consume the recording allowance. The
|
|
// caller withdraws this new receipt if its final deadline check fails.
|
|
if (stored.status === 'stored') return () => fs.rmSync(path.join(common.cacheDir, `${stored.key}.json`), { force: true });
|
|
},
|
|
};
|
|
}
|