Files
gstack/scripts/test-pr-profile.ts
T
01593aa67c v1.91.2.0 fix: consolidate gstack reliability wave (#2959)
* 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>
2026-09-26 18:57:53 -04:00

191 lines
10 KiB
TypeScript

/** Fast PR policy. Cadence changes here never remove cases from the broad census. */
import { E2E_TOUCHFILES, E2E_TIERS, GLOBAL_TOUCHFILES, LLM_JUDGE_TOUCHFILES } from '../test/helpers/touchfiles-data';
import { matchGlob, TOUCHFILES_DATA_PATH } from '../test/helpers/test-selection';
import { isPaidTestFile } from '../test/helpers/paid-test-set';
/** Existing short behavioral probes; intersect with changed-input selection. */
export const PR_PROFILE_CASE_IDS = [
'hermetic-canary', 'hermetic-sentinel',
'browse-basic', 'browse-snapshot', 'skillmd-setup-discovery',
'qa-bootstrap', 'review-sql-injection', 'review-coverage-audit',
'plan-ceo-review-benefits', 'plan-eng-coverage-audit', 'plan-review-report',
'auq-format-gate', 'plan-design-review-no-ui-scope', 'office-hours-spec-review',
'tpa-present', 'tpa-absent-linux',
'ship-local-workflow', 'ship-coverage-audit', 'docsync-spawned',
'ship-managed-hook-refresh', 'ship-unmanaged-hook-consent', 'ship-local-hook-preservation',
'setup-deploy-workflow', 'context-restore-loads-latest', 'plan-tune-inspect',
'skillify-provenance-refusal', 'diagram-triplet', 'learnings-show',
'gstack-upgrade-happy-path',
'investigate-owned-completion', 'investigate-owned-abort', 'investigate-owned-ending-error',
] as const;
/** Audited ownership: unknown/direct-describe files remain broad coverage. */
export const PR_PROFILE_FILES: Record<string, readonly string[]> = {
'test/skill-e2e-investigate-owned-completion.test.ts': ['investigate-owned-completion'],
'test/skill-e2e-investigate-owned-termination.test.ts': ['investigate-owned-abort', 'investigate-owned-ending-error'],
'test/skill-e2e-hermetic-canary.test.ts': ['hermetic-canary', 'hermetic-sentinel'],
'test/skill-e2e-bws.test.ts': ['browse-basic', 'browse-snapshot', 'skillmd-setup-discovery'],
'test/skill-e2e-qa-workflow.test.ts': ['qa-bootstrap'],
'test/skill-e2e-review.test.ts': ['review-sql-injection'],
'test/skill-e2e-coverage-audit.test.ts': ['review-coverage-audit', 'plan-eng-coverage-audit'],
'test/skill-e2e-plan.test.ts': ['plan-ceo-review-benefits', 'plan-review-report', 'office-hours-spec-review'],
'test/skill-e2e-ask-user-question-format-compliance.test.ts': ['auq-format-gate'],
'test/skill-e2e-design.test.ts': ['plan-design-review-no-ui-scope'],
'test/skill-e2e-third-party-actions.test.ts': ['tpa-present', 'tpa-absent-linux'],
'test/skill-e2e-workflow.test.ts': ['ship-local-workflow', 'ship-coverage-audit', 'gstack-upgrade-happy-path'],
'test/skill-e2e-ship-hook-refresh.test.ts': ['ship-managed-hook-refresh'],
'test/skill-e2e-ship-hook-consent.test.ts': ['ship-unmanaged-hook-consent', 'ship-local-hook-preservation'],
'test/skill-e2e-docsync-spawned.test.ts': ['docsync-spawned'],
'test/skill-e2e-deploy.test.ts': ['setup-deploy-workflow'],
'test/skill-e2e-session-intelligence.test.ts': ['context-restore-loads-latest'],
'test/skill-e2e-plan-tune.test.ts': ['plan-tune-inspect'],
'test/skill-e2e-skillify.test.ts': ['skillify-provenance-refusal'],
'test/skill-e2e-diagram.test.ts': ['diagram-triplet'],
'test/skill-e2e-learnings.test.ts': ['learnings-show'],
};
export interface PrProfileMaps {
e2eTouchfiles: Record<string, string[]>;
judgeTouchfiles: Record<string, string[]>;
tiers: Record<string, 'gate' | 'periodic'>;
globalTouchfiles: readonly string[];
}
export const PR_PROFILE_MAPS: PrProfileMaps = {
e2eTouchfiles: E2E_TOUCHFILES, judgeTouchfiles: LLM_JUDGE_TOUCHFILES,
tiers: E2E_TIERS, globalTouchfiles: GLOBAL_TOUCHFILES,
};
export interface PrProfileSelection {
mode: 'pr' | 'full-fallback';
e2e: string[];
judges: string[];
deferred: Array<{ id: string; tier: 'gate' | 'periodic'; reason: string }>;
unknownFiles: string[];
deferredPromptFiles: string[];
missingCoverage: string[];
needsFullValidation: boolean;
reasons: string[];
}
/** Reject stale profile registrations and deferred cases with no scheduled home. */
export function validatePrProfileInventory(
maps: PrProfileMaps = PR_PROFILE_MAPS,
profile: readonly string[] = PR_PROFILE_CASE_IDS,
): void {
if (new Set(profile).size !== profile.length) throw new Error('Duplicate PR profile case');
for (const id of profile) {
if (!Object.hasOwn(maps.e2eTouchfiles, id) || maps.tiers[id] !== 'gate') {
throw new Error(`PR profile case must exist in the broad gate census: ${id}`);
}
}
for (const id of Object.keys(maps.e2eTouchfiles)) {
if (maps.tiers[id] !== 'gate' && maps.tiers[id] !== 'periodic') {
throw new Error(`E2E case has no broad gate/periodic census: ${id}`);
}
}
}
function expandSelection(selected: readonly string[] | null, inventory: Record<string, unknown>): string[] {
const ids = [...new Set(selected ?? Object.keys(inventory))].sort();
for (const id of ids) {
if (!Object.hasOwn(inventory, id)) throw new Error(`Unregistered selected case: ${id}`);
}
return ids;
}
function matches(file: string, patterns: readonly string[]): boolean {
return patterns.some(pattern => matchGlob(file, pattern));
}
export const FREE_ONLY_PR_FILES = [
'scripts/test-free-shards.ts',
'test/helpers/auq-parallel-worker.ts',
] as const;
function knownNonBehaviorFile(file: string): boolean {
// A mapped dependency still wins over these exemptions. New helper/fixture,
// runtime, dependency, or workflow files are deliberately not exempted.
return /^(?:docs\/|(?:README|CONTRIBUTING|ARCHITECTURE|CHANGELOG|TODOS)\.md$|VERSION$)/.test(file)
// Hermetic skill views exclude checkout instructions; these are maintained
// by free doc/generation checks and are not copied into paid fixtures.
|| ['AGENTS.md', 'CLAUDE.md', 'agents-digest/gstack-AGENTS.md'].includes(file)
|| FREE_ONLY_PR_FILES.some(freeOnly => freeOnly === file)
|| (file.startsWith('test/') && /\.test\.tsx?$/.test(file) && !isPaidTestFile(file));
}
/** Only the release version may be ignored; dependency/script changes still matter. */
export function packageChangeOnlyVersion(before: string, after: string): boolean {
try {
const old = JSON.parse(before), current = JSON.parse(after);
if (typeof old?.version !== 'string' || typeof current?.version !== 'string') return false;
delete old.version; delete current.version;
return JSON.stringify(old) === JSON.stringify(current);
} catch { return false; }
}
function isPromptFile(file: string): boolean {
return file.endsWith('.tmpl') || /(?:^|\/)SKILL\.md$/.test(file)
|| /^[^/]+\/sections\/.+\.md$/.test(file);
}
/**
* Diff selection → fast case intersection → explicit deferred coverage.
* Unknown dependencies restore the full gate, while periodic work stays visible.
* A changed prompt without a relevant retained check requires full validation.
*/
export function selectPrProfile(options: {
selectedE2E: readonly string[] | null;
selectedJudges: readonly string[] | null;
changedFiles: readonly string[];
maps?: PrProfileMaps;
profile?: readonly string[];
/** Generated artifacts may inherit the identity of their verified source template. */
sourceAliases?: Readonly<Record<string, string>>;
}): PrProfileSelection {
const maps = options.maps ?? PR_PROFILE_MAPS;
const profile = options.profile ?? PR_PROFILE_CASE_IDS;
validatePrProfileInventory(maps, profile);
const selectedE2E = expandSelection(options.selectedE2E, maps.e2eTouchfiles);
const selectedJudges = expandSelection(options.selectedJudges, maps.judgeTouchfiles);
const files = [...new Set(options.changedFiles.map(file => file.replace(/\\/g, '/')))].sort();
const depends = (file: string, patterns: readonly string[]) => matches(file, patterns)
|| (!!options.sourceAliases?.[file] && matches(options.sourceAliases[file], patterns));
const dependencyPatterns = [...new Set([
...Object.values(maps.e2eTouchfiles).flat(), ...Object.values(maps.judgeTouchfiles).flat(),
...maps.globalTouchfiles,
])];
const unknownFiles = files.filter(file => file !== TOUCHFILES_DATA_PATH
&& !depends(file, dependencyPatterns) && !knownNonBehaviorFile(file));
const fallback = unknownFiles.length > 0;
const candidates = fallback ? Object.keys(maps.e2eTouchfiles).sort() : selectedE2E;
const e2e = candidates.filter(id => maps.tiers[id] === 'gate' && (fallback || profile.includes(id)));
const judges = fallback ? Object.keys(maps.judgeTouchfiles).sort() : selectedJudges;
const kept = new Set(e2e);
const deferred = candidates.filter(id => !kept.has(id)).map(id => ({
id, tier: maps.tiers[id],
reason: maps.tiers[id] === 'periodic'
? 'Broad periodic/release coverage; not executed by the PR gate'
: 'Broad gate census/release coverage; outside the fast PR profile',
}));
const noQuickCoverage = files.filter(file => isPromptFile(file)
&& !(depends(file, maps.globalTouchfiles) && (e2e.length > 0 || judges.length > 0))
&& !e2e.some(id => depends(file, maps.e2eTouchfiles[id]))
&& !judges.some(id => depends(file, maps.judgeTouchfiles[id])));
const hasQuickDependency = (file: string) => profile.some(id => depends(file, maps.e2eTouchfiles[id]))
|| Object.values(maps.judgeTouchfiles).some(patterns => depends(file, patterns));
const deferredPromptFiles = noQuickCoverage.filter(file => !hasQuickDependency(file)
&& Object.values(maps.e2eTouchfiles).some(patterns => depends(file, patterns)));
const missingCoverage = noQuickCoverage.filter(file => !deferredPromptFiles.includes(file));
const reasons = fallback
? [`Unknown dependencies restore every gate case and judge: ${unknownFiles.join(', ')}`]
: ['Changed-input selection intersected with the fast PR profile; selected judges retained'];
if (deferred.length) reasons.push(`${deferred.length} selected behaviors remain scheduled/release coverage, not PR passes`);
if (deferredPromptFiles.length) reasons.push(`No quick live coverage; known broad prompt checks deferred: ${deferredPromptFiles.join(', ')}`);
if (missingCoverage.length) reasons.push(`Full validation required for prompts without a relevant PR check: ${missingCoverage.join(', ')}`);
return {
mode: fallback ? 'full-fallback' : 'pr', e2e, judges, deferred,
unknownFiles, deferredPromptFiles, missingCoverage, needsFullValidation: missingCoverage.length > 0, reasons,
};
}