mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
829 lines
34 KiB
TypeScript
829 lines
34 KiB
TypeScript
import { generateAdversarialStep } from '../scripts/resolvers/outside-voice-steps';
|
|
import { RESOLVERS } from '../scripts/resolvers';
|
|
import { HOST_PATHS } from '../scripts/resolvers/types';
|
|
import { describe, test, expect } from 'bun:test';
|
|
import { spawnSync } from 'child_process';
|
|
import * as path from 'path';
|
|
import * as fs from 'fs';
|
|
import * as os from 'os';
|
|
|
|
const ROOT = path.resolve(import.meta.dir, '..');
|
|
const PROBE = path.join(ROOT, 'bin/gstack-codex-probe');
|
|
|
|
// Run a bash snippet that sources the probe and evaluates one of its functions.
|
|
// Controlled env + optional tempdir for HOME isolation.
|
|
function runProbe(opts: {
|
|
snippet: string;
|
|
env?: Record<string, string | undefined>;
|
|
home?: string;
|
|
}): { stdout: string; stderr: string; status: number } {
|
|
const env: Record<string, string> = {
|
|
// Start from a clean env so test-env vars from the parent don't leak in.
|
|
PATH: process.env.PATH ?? '',
|
|
_TEL: 'off',
|
|
};
|
|
if (opts.home) env.HOME = opts.home;
|
|
// Apply overrides; undefined means "remove".
|
|
if (opts.env) {
|
|
for (const [k, v] of Object.entries(opts.env)) {
|
|
if (v === undefined) {
|
|
delete env[k];
|
|
} else {
|
|
env[k] = v;
|
|
}
|
|
}
|
|
}
|
|
const script = `set +e\nsource "${PROBE}"\n${opts.snippet}\n`;
|
|
const result = spawnSync('bash', ['-c', script], {
|
|
env,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
timeout: 5000,
|
|
});
|
|
return {
|
|
stdout: (result.stdout ?? '').toString(),
|
|
stderr: (result.stderr ?? '').toString(),
|
|
status: result.status ?? -1,
|
|
};
|
|
}
|
|
|
|
function tempHome(): string {
|
|
return fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-probe-home-'));
|
|
}
|
|
|
|
describe('gstack-codex-probe: auth probe', () => {
|
|
test('CODEX_API_KEY set → AUTH_OK', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { CODEX_API_KEY: 'sk-test' },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_OK');
|
|
expect(r.status).toBe(0);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('OPENAI_API_KEY set → AUTH_OK', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { OPENAI_API_KEY: 'sk-openai' },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_OK');
|
|
expect(r.status).toBe(0);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('${CODEX_HOME:-~/.codex}/auth.json exists → AUTH_OK', () => {
|
|
const home = tempHome();
|
|
try {
|
|
fs.mkdirSync(path.join(home, '.codex'), { recursive: true });
|
|
fs.writeFileSync(path.join(home, '.codex', 'auth.json'), '{}');
|
|
const r = runProbe({ snippet: '_gstack_codex_auth_probe', home });
|
|
expect(r.stdout.trim()).toBe('AUTH_OK');
|
|
expect(r.status).toBe(0);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('no env + no file → AUTH_FAILED with exit 1', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({ snippet: '_gstack_codex_auth_probe', home });
|
|
expect(r.stdout.trim()).toBe('AUTH_FAILED');
|
|
expect(r.status).toBe(1);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('both CODEX_API_KEY and OPENAI_API_KEY set → AUTH_OK', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { CODEX_API_KEY: 'k1', OPENAI_API_KEY: 'k2' },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_OK');
|
|
expect(r.status).toBe(0);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('empty-string env vars + no file → AUTH_FAILED', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { CODEX_API_KEY: '', OPENAI_API_KEY: '' },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_FAILED');
|
|
expect(r.status).toBe(1);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('whitespace-only env vars + no file → AUTH_FAILED', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { CODEX_API_KEY: ' ', OPENAI_API_KEY: '\t\n' },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_FAILED');
|
|
expect(r.status).toBe(1);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('alternate $CODEX_HOME → checks the alternate path', () => {
|
|
const home = tempHome();
|
|
const altCodex = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-alt-codex-'));
|
|
try {
|
|
fs.writeFileSync(path.join(altCodex, 'auth.json'), '{}');
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_auth_probe',
|
|
env: { CODEX_HOME: altCodex },
|
|
home,
|
|
});
|
|
expect(r.stdout.trim()).toBe('AUTH_OK');
|
|
expect(r.status).toBe(0);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
fs.rmSync(altCodex, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// --- Group 2: Version check -------------------------------------------------
|
|
// Stub `codex --version` by putting a fake `codex` executable on PATH.
|
|
function tempStubCodex(versionOutput: string, bool_command_fails = false): {
|
|
dir: string;
|
|
pathEntry: string;
|
|
} {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-stub-'));
|
|
const bin = path.join(dir, 'codex');
|
|
const script = bool_command_fails
|
|
? '#!/bin/bash\nexit 1\n'
|
|
: `#!/bin/bash\nif [ "$1" = "--version" ]; then printf '%s' ${JSON.stringify(versionOutput)}; fi\n`;
|
|
fs.writeFileSync(bin, script);
|
|
fs.chmodSync(bin, 0o755);
|
|
return { dir, pathEntry: dir };
|
|
}
|
|
|
|
function runVersionCheck(versionOutput: string): string {
|
|
const stub = tempStubCodex(versionOutput);
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_version_check',
|
|
env: { PATH: `${stub.pathEntry}:${process.env.PATH}` },
|
|
});
|
|
return r.stdout + r.stderr;
|
|
} finally {
|
|
fs.rmSync(stub.dir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
describe('gstack-codex-probe: version check (anchored regex per Tension I)', () => {
|
|
// Matches (should WARN)
|
|
test('codex-cli 0.120.0 → WARN', () => {
|
|
const out = runVersionCheck('codex-cli 0.120.0\n');
|
|
expect(out).toContain('WARN:');
|
|
expect(out).toContain('0.120.0');
|
|
});
|
|
|
|
test('codex-cli 0.120.1 → WARN', () => {
|
|
const out = runVersionCheck('codex-cli 0.120.1\n');
|
|
expect(out).toContain('WARN:');
|
|
});
|
|
|
|
test('codex-cli 0.120.2 → WARN', () => {
|
|
const out = runVersionCheck('codex-cli 0.120.2\n');
|
|
expect(out).toContain('WARN:');
|
|
});
|
|
|
|
// Does NOT match (should be silent)
|
|
test('codex-cli 0.116.0 → OK (no warn)', () => {
|
|
const out = runVersionCheck('codex-cli 0.116.0\n');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
|
|
test('codex-cli 0.121.0 → OK (no warn)', () => {
|
|
const out = runVersionCheck('codex-cli 0.121.0\n');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
|
|
test('codex-cli 0.120.10 → OK (anchored regex prevents substring match)', () => {
|
|
const out = runVersionCheck('codex-cli 0.120.10\n');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
|
|
test('codex-cli 0.120.20 → OK (anchored regex prevents substring match)', () => {
|
|
const out = runVersionCheck('codex-cli 0.120.20\n');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
|
|
test('codex-cli 0.120.2-beta → WARN (still a bad release family)', () => {
|
|
// 0.120.2-beta: regex (^|[^0-9.])0\.120\.(0|1|2)([^0-9.]|$) treats '-' as a
|
|
// non-digit/non-dot boundary → matches.
|
|
const out = runVersionCheck('codex-cli 0.120.2-beta\n');
|
|
expect(out).toContain('WARN:');
|
|
});
|
|
|
|
test('empty output → OK (silent, no crash)', () => {
|
|
const out = runVersionCheck('');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
|
|
test('v-prefixed and multiline handled', () => {
|
|
const out = runVersionCheck('codex-cli v0.116.0\nsome debug line\n');
|
|
expect(out).not.toContain('WARN:');
|
|
});
|
|
});
|
|
|
|
// --- Group 3: Timeout wrapper + namespace hygiene ---------------------------
|
|
|
|
describe('gstack-codex-probe: timeout wrapper + namespace hygiene', () => {
|
|
test('bin/gstack-codex-probe is syntactically valid bash (bash -n)', () => {
|
|
const result = spawnSync('bash', ['-n', PROBE], { timeout: 5000 });
|
|
expect(result.status).toBe(0);
|
|
});
|
|
|
|
test('timeout wrapper executes command directly when neither binary present', () => {
|
|
// Clear PATH to simulate no timeout/gtimeout. Use only /bin for `echo`.
|
|
const r = runProbe({
|
|
snippet: `_gstack_codex_timeout_wrapper 5 echo hello_world`,
|
|
env: { PATH: '/bin:/usr/bin' }, // these usually lack gtimeout; timeout may exist on linux
|
|
});
|
|
// Regardless of whether timeout is on this PATH, echo hello_world should succeed.
|
|
expect(r.stdout.trim()).toBe('hello_world');
|
|
});
|
|
|
|
test('timeout wrapper resolves gtimeout preferentially when on PATH', () => {
|
|
// Create a stub gtimeout that prints a sentinel so we can verify it was chosen.
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-gto-stub-'));
|
|
try {
|
|
const stub = path.join(dir, 'gtimeout');
|
|
fs.writeFileSync(stub, '#!/bin/bash\necho gtimeout_chosen_$1\n');
|
|
fs.chmodSync(stub, 0o755);
|
|
const r = runProbe({
|
|
snippet: `_gstack_codex_timeout_wrapper 5 echo nope`,
|
|
env: { PATH: `${dir}:/bin:/usr/bin` },
|
|
});
|
|
expect(r.stdout.trim()).toBe('gtimeout_chosen_5');
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('bash-native watchdog kills a hung command at the deadline (exit 124, no timeout binary)', () => {
|
|
// Stock macOS ships neither gtimeout nor timeout(1) — the old fallback ran
|
|
// the command unwrapped, so a hung `codex exec` blocked the calling
|
|
// workflow forever. Force the fallback everywhere (Linux /bin has timeout
|
|
// via usrmerge) with a PATH holding ONLY bash and sleep, then prove a
|
|
// 30s sleep dies at the 1s deadline with timeout(1)'s exit code. The
|
|
// runProbe 5s spawnSync cap doubles as the "actually killed fast" bound.
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-watchdog-'));
|
|
try {
|
|
const which = (tool: string) =>
|
|
spawnSync('bash', ['-c', `command -v ${tool}`], { timeout: 30_000 }).stdout.toString().trim() || `/bin/${tool}`;
|
|
fs.symlinkSync(which('bash'), path.join(dir, 'bash'));
|
|
fs.symlinkSync(which('sleep'), path.join(dir, 'sleep'));
|
|
const r = runProbe({
|
|
snippet: `_gstack_codex_timeout_wrapper 1 sleep 30; echo "rc=$?"`,
|
|
env: { PATH: dir },
|
|
});
|
|
expect(r.stdout).toContain('rc=124');
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('bash-native watchdog reports its timeout while still retiring after TERM', () => {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-watchdog-race-'));
|
|
try {
|
|
for (const tool of ['bash', 'sleep']) {
|
|
const resolved = spawnSync('bash', ['-c', `command -v ${tool}`], { timeout: 5000 });
|
|
expect(resolved.status).toBe(0);
|
|
fs.symlinkSync(resolved.stdout.toString().trim(), path.join(dir, tool));
|
|
}
|
|
const r = runProbe({
|
|
snippet: `
|
|
kill() {
|
|
builtin kill "$@"
|
|
local rc=$?
|
|
if [ "$1" = -TERM ] && [ "$rc" -eq 0 ]; then sleep 0.2; fi
|
|
return "$rc"
|
|
}
|
|
_gstack_codex_timeout_wrapper 0.1 sleep 30
|
|
printf 'rc=%s\\n' "$?"
|
|
`,
|
|
env: { PATH: dir },
|
|
});
|
|
expect(r.status).toBe(0);
|
|
expect(r.stdout).toBe('rc=124\n');
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
for (const [name, command, expected] of [
|
|
['success', 'printf finished', 'finishedrc=0\n'],
|
|
['ordinary failure', "bash -c 'exit 7'", 'rc=7\n'],
|
|
['independent signal', "bash -c 'kill -TERM $$'", 'rc=143\n'],
|
|
]) test(`bash-native watchdog preserves ${name} without waiting for its deadline`, () => {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-watchdog-early-'));
|
|
try {
|
|
for (const tool of ['bash', 'sleep']) {
|
|
const resolved = spawnSync('bash', ['-c', `command -v ${tool}`], { timeout: 5000 });
|
|
expect(resolved.status).toBe(0);
|
|
fs.symlinkSync(resolved.stdout.toString().trim(), path.join(dir, tool));
|
|
}
|
|
const r = runProbe({
|
|
snippet: `
|
|
trap 'printf caller-term' TERM
|
|
output=$(_gstack_codex_timeout_wrapper 10 ${command}; printf 'rc=%s\\n' "$?")
|
|
printf '%s\\n' "$output"
|
|
trap -p TERM
|
|
`,
|
|
env: { PATH: dir },
|
|
});
|
|
expect(r.status).toBe(0);
|
|
expect(r.stdout).toBe(`${expected}trap -- 'printf caller-term' SIGTERM\n`);
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('sourcing probe does NOT set errexit/trap/IFS in caller shell (namespace hygiene)', () => {
|
|
// Capture `set -o` output before and after sourcing. Any drift means the
|
|
// probe polluted the caller.
|
|
const r = runProbe({
|
|
snippet: `
|
|
BEFORE=$(set -o | sort)
|
|
source "${PROBE}" # source again to catch accumulation
|
|
AFTER=$(set -o | sort)
|
|
if [ "$BEFORE" = "$AFTER" ]; then
|
|
echo "CLEAN"
|
|
else
|
|
echo "POLLUTED"
|
|
diff <(echo "$BEFORE") <(echo "$AFTER")
|
|
fi
|
|
`,
|
|
});
|
|
expect(r.stdout).toContain('CLEAN');
|
|
});
|
|
});
|
|
|
|
// --- Group 4: Telemetry event emission --------------------------------------
|
|
|
|
describe('gstack-codex-probe: telemetry event emission', () => {
|
|
test('_gstack_codex_log_event writes jsonl when _TEL != off', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: `_gstack_codex_log_event "codex_test_event" "42"; cat "$HOME/.gstack/analytics/skill-usage.jsonl"`,
|
|
env: { _TEL: 'community' },
|
|
home,
|
|
});
|
|
expect(r.stdout).toContain('"event":"codex_test_event"');
|
|
expect(r.stdout).toContain('"duration_s":"42"');
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('_gstack_codex_log_event skips write when _TEL = off', () => {
|
|
const home = tempHome();
|
|
try {
|
|
runProbe({
|
|
snippet: `_gstack_codex_log_event "codex_test_event" "99"`,
|
|
env: { _TEL: 'off' },
|
|
home,
|
|
});
|
|
const jsonl = path.join(home, '.gstack/analytics/skill-usage.jsonl');
|
|
expect(fs.existsSync(jsonl)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('payload never contains prompt content, env values, or auth tokens (schema check)', () => {
|
|
const home = tempHome();
|
|
try {
|
|
const r = runProbe({
|
|
snippet: `_gstack_codex_log_event "codex_test_event" "1"; cat "$HOME/.gstack/analytics/skill-usage.jsonl"`,
|
|
env: {
|
|
_TEL: 'community',
|
|
CODEX_API_KEY: 'SECRET_TOKEN_SHOULD_NOT_LEAK',
|
|
OPENAI_API_KEY: 'ANOTHER_SECRET',
|
|
},
|
|
home,
|
|
});
|
|
// The emitted JSON payload should ONLY have {skill, event, duration_s, ts}.
|
|
// Specifically, it must not contain any env values or auth material.
|
|
expect(r.stdout).not.toContain('SECRET_TOKEN_SHOULD_NOT_LEAK');
|
|
expect(r.stdout).not.toContain('ANOTHER_SECRET');
|
|
// Schema: exactly these keys, in any order.
|
|
const parsed = JSON.parse(r.stdout.trim().split('\n').pop() ?? '{}');
|
|
expect(Object.keys(parsed).sort()).toEqual(['duration_s', 'event', 'skill', 'ts']);
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ── Step 2A argv guard ─────────────────────────────────────────────────────
|
|
// Regression test for #1428: Codex CLI >=0.130.0 rejects passing a quoted
|
|
// prompt argument together with `--base <branch>`. Step 2A must never combine
|
|
// the two on the same line. Step 2A lives in the carved review-mode section
|
|
// (codex/sections/review-mode.md, generated from its .md.tmpl) — asserts
|
|
// across both the .tmpl source and the generated section so template drift
|
|
// can't silently re-introduce the bug.
|
|
|
|
describe('codex review-mode section Step 2A: PROMPT + --base mutual exclusion guard', () => {
|
|
function extractStep2A(filePath: string): string {
|
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
const startIdx = content.indexOf('## Step 2A: Review Mode');
|
|
expect(startIdx).toBeGreaterThan(-1);
|
|
// End at next `## ` heading (skill section boundary).
|
|
const tail = content.slice(startIdx);
|
|
const nextHeading = tail.slice(2).search(/\n## /);
|
|
const section = nextHeading === -1 ? tail : tail.slice(0, nextHeading + 2);
|
|
// Non-empty extraction: a carve/regen that leaves only the heading behind
|
|
// must fail here, not silently pass a vacuous scan.
|
|
expect(section.length).toBeGreaterThan(1000);
|
|
return section;
|
|
}
|
|
|
|
for (const relPath of ['codex/sections/review-mode.md.tmpl', 'codex/sections/review-mode.md']) {
|
|
test(`${relPath}: no \`codex review\` line combines a quoted prompt argument with --base`, () => {
|
|
const section = extractStep2A(path.join(ROOT, relPath));
|
|
// Find all lines invoking `codex review` (any prefix wrapper allowed).
|
|
const lines = section.split('\n');
|
|
const offendingLines: string[] = [];
|
|
for (const line of lines) {
|
|
// Skip prose lines that just discuss codex review. Only inspect lines
|
|
// that look like an actual shell invocation (codex review followed by
|
|
// a non-prose token).
|
|
const match = line.match(/\bcodex\s+review\b(.*)$/);
|
|
if (!match) continue;
|
|
const rest = match[1];
|
|
// Two regression patterns:
|
|
// codex review "..." --base <foo>
|
|
// codex review $VAR --base <foo>
|
|
// codex review -- "..." --base <foo>
|
|
// Acceptable: codex review --base <foo> (bare, no prompt arg)
|
|
const hasBase = /--base\b/.test(rest);
|
|
if (!hasBase) continue;
|
|
// Strip --base <token> and any trailing -c/--enable flags so they
|
|
// don't look like positional args. Anything that remains BEFORE
|
|
// --base and looks like a positional is the regression.
|
|
const beforeBase = rest.split(/--base\b/)[0].trim();
|
|
// Empty (or just whitespace) before --base => bare review, safe.
|
|
if (beforeBase === '') continue;
|
|
// Allow `--` separator that introduces nothing else (rare). Anything
|
|
// that looks like a quoted string OR variable expansion is the bug.
|
|
if (/^["'$]|^--\s*["']/.test(beforeBase)) {
|
|
offendingLines.push(line);
|
|
}
|
|
}
|
|
expect(offendingLines).toEqual([]);
|
|
});
|
|
|
|
test(`${relPath}: Step 2A still contains at least one fix-path invocation`, () => {
|
|
const section = extractStep2A(path.join(ROOT, relPath));
|
|
// At least one of: bare `codex review --base` OR `codex exec ...` must
|
|
// remain. Guards against accidental deletion of both fix paths.
|
|
const bareReview = /codex\s+review\s+--base\b/.test(section);
|
|
const execRoute = /codex\s+exec\b/.test(section);
|
|
expect(bareReview || execRoute).toBe(true);
|
|
});
|
|
}
|
|
});
|
|
|
|
// Regression guard for #1036. The wrapper added in #1056 was wired into
|
|
// codex/SKILL.md but not into the /review and /ship diff passes, which kept
|
|
// running under a bare 5-minute Bash gate. Measured on codex-cli 0.145.0: a
|
|
// pass was killed at 287s of a 300s budget mid-tool-call, and the same prompt
|
|
// completed in 336s. An unwrapped stall returns no exit code and no output,
|
|
// which downstream reads as "Codex reviewed and found nothing".
|
|
describe('codex timeout wrapper: /review + /ship diff passes', () => {
|
|
const WRAPPED_SITES = [
|
|
'scripts/resolvers/outside-voice-steps.ts', // generator (source of truth)
|
|
'review/sections/adversarial.md', // review section (Step 4.8 carved out of the skeleton)
|
|
'ship/sections/adversarial.md', // ship section source
|
|
];
|
|
|
|
// Outer Bash gate for the wrapped passes. The wrapper must be strictly
|
|
// shorter so IT fires first and the failure is a diagnosable exit 124.
|
|
const BASH_GATE_MS = 600000;
|
|
|
|
for (const relPath of WRAPPED_SITES) {
|
|
const read = () => relPath === 'scripts/resolvers/outside-voice-steps.ts'
|
|
? generateAdversarialStep({ host: 'claude', paths: HOST_PATHS.claude, skillName: 'review', tmplPath: 'review/SKILL.md.tmpl' })
|
|
: fs.readFileSync(path.join(ROOT, relPath), 'utf8');
|
|
|
|
test(`${relPath}: both diff-review Codex calls run under the wrapper`, () => {
|
|
const wrapped =
|
|
read().match(/_gstack_codex_timeout_wrapper\s+\d+\s+codex\s+(exec|review)\b/g) ?? [];
|
|
// Adversarial pass + structured review pass.
|
|
expect(wrapped.length).toBeGreaterThanOrEqual(2);
|
|
});
|
|
|
|
test(`${relPath}: does not claim \`timeout\` is unavailable on macOS`, () => {
|
|
// _gstack_codex_timeout_wrapper resolves gtimeout -> timeout -> unwrapped,
|
|
// so the coreutils-less case is already handled. The old claim is what
|
|
// steered these call sites away from the wrapper in the first place.
|
|
expect(read()).not.toMatch(/doesn't exist on macOS/);
|
|
});
|
|
|
|
test(`${relPath}: wrapper budget stays under the outer Bash gate`, () => {
|
|
const budgets = [...read().matchAll(/_gstack_codex_timeout_wrapper\s+(\d+)\s+codex\b/g)].map(
|
|
(m) => Number(m[1]) * 1000,
|
|
);
|
|
expect(budgets.length).toBeGreaterThan(0);
|
|
for (const ms of budgets) {
|
|
// Inverting this makes the wrapper unreachable: the harness kills the
|
|
// call first and the exit-124 branch below it becomes dead code.
|
|
expect(ms).toBeLessThan(BASH_GATE_MS);
|
|
}
|
|
});
|
|
}
|
|
});
|
|
|
|
// Regression guards for #2496 / #2524 / #2477 — three "guard reports success
|
|
// while doing nothing" defects in codex/SKILL.md:
|
|
// (a) the default `codex review` path set NO sandbox override, inheriting
|
|
// whatever ~/.codex/config.toml grants (write access on trusted
|
|
// projects) while the skill's Important Rules claimed read-only;
|
|
// (b) the severity-tag verdict gate could not fail on the default path — a
|
|
// non-zero exit, empty output, or untagged output all satisfied the
|
|
// "no [P1] found → PASS" branch as written;
|
|
// (c) Step 2A's Bash tool gate (300000 ms) sat BELOW the 330s wrapper
|
|
// budget, so the harness killed the call before the wrapper could emit
|
|
// its diagnosable exit-124 message — the same inversion #1036 fixed for
|
|
// /review and /ship.
|
|
// The three mode bodies are carved into codex/sections/*-mode.md (T9), so the
|
|
// sweep reads the skeleton+sections UNION on both the .tmpl side and the
|
|
// generated side — a regen or hand-edit of one but not the other can't
|
|
// silently reopen any of them. Each mode section starts with its own `## `
|
|
// heading, so the per-`## `-section split in check (c) still isolates each
|
|
// mode's gate/wrapper pair.
|
|
function readCodexUnion(kind: 'tmpl' | 'rendered'): string {
|
|
const sectionsDir = path.join(ROOT, 'codex', 'sections');
|
|
const skeleton = fs.readFileSync(
|
|
path.join(ROOT, 'codex', kind === 'tmpl' ? 'SKILL.md.tmpl' : 'SKILL.md'),
|
|
'utf-8',
|
|
);
|
|
const suffix = kind === 'tmpl' ? '.md.tmpl' : '.md';
|
|
const sections = fs.readdirSync(sectionsDir).sort()
|
|
.filter((f) => (kind === 'tmpl' ? f.endsWith('.md.tmpl') : f.endsWith('.md') && !f.endsWith('.md.tmpl')))
|
|
.map((f) => fs.readFileSync(path.join(sectionsDir, f), 'utf-8'));
|
|
expect(sections.length, `codex sections (*${suffix}) missing`).toBeGreaterThanOrEqual(3);
|
|
return [skeleton, ...sections].join('\n');
|
|
}
|
|
|
|
describe('codex skeleton+sections union: review sandbox + fail-closed gate + timeout ordering', () => {
|
|
for (const relPath of ['codex tmpl union', 'codex rendered union'] as const) {
|
|
const read = () => readCodexUnion(relPath === 'codex tmpl union' ? 'tmpl' : 'rendered');
|
|
|
|
test(`${relPath}: (a) every scoped codex review invocation pins sandbox_mode="read-only"`, () => {
|
|
const invocations = read()
|
|
.split('\n')
|
|
.filter((l) => /_gstack_codex_timeout_wrapper\s+\d+\s+codex\s+review\b/.test(l));
|
|
expect(invocations.length).toBeGreaterThanOrEqual(1);
|
|
for (const line of invocations) {
|
|
expect(line).toContain('sandbox_mode="read-only"');
|
|
// `codex review` has no -s/--sandbox flag (verified 0.147.0) — the
|
|
// config override is the only lever. `-s read-only` here would fail
|
|
// at argv parsing, which check (b) would then read as a gate FAIL.
|
|
expect(line).not.toMatch(/\s-s\s+read-only\b/);
|
|
}
|
|
});
|
|
|
|
test(`${relPath}: (b) the verdict gate fails closed — no default-PASS path`, () => {
|
|
const content = read();
|
|
// The old rule inferred PASS from the absence of a substring:
|
|
expect(content).not.toContain(
|
|
'If no `[P1]` markers are found (only `[P2]` or no findings) — the gate is **PASS**',
|
|
);
|
|
// The new rule: FAIL on non-zero exit, empty output, and untagged
|
|
// output; [P0] recognized as blocking; PASS reachable only through the
|
|
// explicit tagged-advisory-only branch.
|
|
expect(content).toContain('The gate FAILS CLOSED');
|
|
expect(content).toContain('`_CODEX_EXIT` is non-zero (including 124) → **GATE: FAIL**');
|
|
expect(content).toContain('empty or whitespace-only → **GATE: FAIL**');
|
|
expect(content).toContain('untagged output');
|
|
expect(content).toContain('`[P0]`');
|
|
expect(content).toContain('PASS is only reachable through check 5');
|
|
});
|
|
|
|
test(`${relPath}: (c) every Bash gate sits strictly above its section's wrapper budgets`, () => {
|
|
// Split on `## ` headings; within any section that declares BOTH a Bash
|
|
// tool gate (`timeout: N` in ms) and a wrapper budget
|
|
// (`_gstack_codex_timeout_wrapper S codex`), every gate must be strictly
|
|
// greater than every wrapper budget so the wrapper fires first.
|
|
const sections = read().split(/\n## /);
|
|
const inspected: string[] = [];
|
|
for (const section of sections) {
|
|
const gates = [...section.matchAll(/timeout:\s*(\d{4,})/g)].map((m) => Number(m[1]));
|
|
const wrappers = [...section.matchAll(/_gstack_codex_timeout_wrapper\s+(\d+)\s+codex\b/g)].map(
|
|
(m) => Number(m[1]) * 1000,
|
|
);
|
|
if (gates.length === 0 || wrappers.length === 0) continue;
|
|
inspected.push(section.split('\n')[0]);
|
|
for (const gate of gates) {
|
|
for (const wrapper of wrappers) {
|
|
expect(gate).toBeGreaterThan(wrapper);
|
|
}
|
|
}
|
|
}
|
|
// Review (2A), Challenge (2B), and Consult (2C) must all have been
|
|
// inspected — each declares both numbers. If a refactor drops either
|
|
// number from a section, this count catches the silent skip.
|
|
expect(inspected.length).toBeGreaterThanOrEqual(3);
|
|
});
|
|
}
|
|
});
|
|
|
|
// #2742: a Codex CLI that is on PATH but cannot execute (spawn ENOENT, missing
|
|
// vendor payload, non-executable binary) used to land in the model probe's
|
|
// fail-open bucket and resolve to CODEX_MODE: ready — so every Codex pass was
|
|
// skipped in silence. These pin the classification, the exit-code contract, and
|
|
// the fact that the fail-open path still exists for genuine transients.
|
|
describe('codex broken-install detection (#2742)', () => {
|
|
// A fake `codex` on PATH that reproduces the real failure: node's spawn dump
|
|
// on stderr, non-zero exit. `mode` picks which failure shape to emit.
|
|
function shimHome(mode: 'enoent' | 'notexec' | 'timeout' | 'model400' | 'oksuspicious') {
|
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-codex-shim-'));
|
|
const bin = path.join(home, 'bin');
|
|
fs.mkdirSync(bin, { recursive: true });
|
|
// auth.json so the auth probe passes and we reach the model probe.
|
|
fs.mkdirSync(path.join(home, '.codex'), { recursive: true });
|
|
fs.writeFileSync(path.join(home, '.codex/auth.json'), '{}');
|
|
const bodies: Record<string, string> = {
|
|
enoent:
|
|
`echo "Error: spawn /x/vendor/aarch64-apple-darwin/codex/codex ENOENT" >&2\n` +
|
|
`echo " errno: -2, code: 'ENOENT'" >&2\nexit 1\n`,
|
|
notexec: `echo "bash: codex: cannot execute binary file" >&2\nexit 126\n`,
|
|
timeout: `echo "network hiccup" >&2\nexit 124\n`,
|
|
model400: `echo "The 'gpt-x' model is not supported when using Codex with a ChatGPT account" >&2\nexit 1\n`,
|
|
oksuspicious: `echo "OK — note: the log you pasted mentions permission denied on /var/log"\nexit 0\n`,
|
|
};
|
|
fs.writeFileSync(path.join(bin, 'codex'), `#!/usr/bin/env bash\n${bodies[mode]}`, { mode: 0o755 });
|
|
return { home, bin };
|
|
}
|
|
|
|
const cases: Array<[string, 'enoent' | 'notexec', string]> = [
|
|
['spawn ENOENT', 'enoent', 'ENOENT'],
|
|
['non-executable binary (exit 126)', 'notexec', 'cannot execute binary file'],
|
|
];
|
|
|
|
for (const [label, mode, needle] of cases) {
|
|
test(`${label} is classified as a broken install, not a transient`, () => {
|
|
const { home, bin } = shimHome(mode);
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_model_probe; echo "EXIT:$?"',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
expect(r.stdout).toContain('MODEL_UNUSABLE_INSTALL');
|
|
// Exit 2 is what lets the preflight tell this apart from a model 400.
|
|
expect(r.stdout).toContain('EXIT:2');
|
|
// It must NOT fail open — that was the whole defect.
|
|
expect(r.stdout).not.toContain('MODEL_PROBE_INCONCLUSIVE');
|
|
// The remedy names the install, not the model pin.
|
|
expect(r.stdout).toContain('npm install -g @openai/codex');
|
|
expect(r.stdout.toLowerCase()).toContain(needle.toLowerCase());
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
}
|
|
|
|
test('a broken install is never cached — a reinstall is picked up next probe', () => {
|
|
const { home, bin } = shimHome('enoent');
|
|
try {
|
|
runProbe({
|
|
snippet: '_gstack_codex_model_probe >/dev/null 2>&1',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
const cache = path.join(home, '.codex-model-probe');
|
|
if (fs.existsSync(cache)) {
|
|
expect(fs.readFileSync(cache, 'utf8')).not.toContain('MODEL_OK');
|
|
}
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('a genuine transient (exit 124) still fails open', () => {
|
|
const { home, bin } = shimHome('timeout');
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_model_probe; echo "EXIT:$?"',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
expect(r.stdout).toContain('MODEL_PROBE_INCONCLUSIVE');
|
|
expect(r.stdout).toContain('EXIT:0');
|
|
expect(r.stdout).not.toContain('MODEL_UNUSABLE_INSTALL');
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('the model 400 still classifies as MODEL_UNUSABLE, not a broken install', () => {
|
|
const { home, bin } = shimHome('model400');
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_model_probe; echo "EXIT:$?"',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
expect(r.stdout).toContain('MODEL_UNUSABLE');
|
|
expect(r.stdout).not.toContain('MODEL_UNUSABLE_INSTALL');
|
|
expect(r.stdout).toContain('EXIT:1');
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test('version check warns instead of returning silently when codex cannot report a version', () => {
|
|
const { home, bin } = shimHome('enoent');
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_version_check; echo "EXIT:$?"',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
// Previously this printed nothing: `codex --version 2>/dev/null | head -1`
|
|
// captured head's status, so a CLI that only ever errored read as healthy.
|
|
expect(r.stdout).toContain('WARN');
|
|
expect(r.stdout).toContain('npm install -g @openai/codex');
|
|
// Still non-fatal — the version check has never gated anything.
|
|
expect(r.stdout).toContain('EXIT:0');
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Wave-amended (#2745 absorption): string signatures only count on a FAILED
|
|
// spawn — a SUCCESSFUL response whose text mentions "permission denied"
|
|
// (e.g. the model quoting a log the user pasted) must stay healthy.
|
|
test('exit-0 response mentioning "permission denied" is NOT a broken install', () => {
|
|
const { home, bin } = shimHome('oksuspicious');
|
|
try {
|
|
const r = runProbe({
|
|
snippet: '_gstack_codex_model_probe; echo "EXIT:$?"',
|
|
home,
|
|
env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GSTACK_HOME: home },
|
|
});
|
|
expect(r.stdout).not.toContain('MODEL_UNUSABLE_INSTALL');
|
|
expect(r.stdout).toContain('EXIT:0');
|
|
} finally {
|
|
fs.rmSync(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Wave-amended (#2745 absorption): autoplan's preflight chain is the one
|
|
// hand-maintained copy that isn't resolver-generated — it must capture the
|
|
// probe's exit code and route 2 to its own broken-install arm, or /autoplan
|
|
// prints the wrong remedy for a broken binary.
|
|
test('autoplan preflight (tmpl + rendered) captures the probe exit and routes 2 to broken-install', () => {
|
|
for (const rel of ['autoplan/SKILL.md.tmpl', 'autoplan/SKILL.md']) {
|
|
const raw = fs.readFileSync(path.join(ROOT, rel), 'utf-8');
|
|
const src = rel.endsWith('.tmpl') ? raw.replace('{{OUTSIDE_PREFLIGHT:autoplan}}', RESOLVERS.OUTSIDE_PREFLIGHT({ host: 'claude', paths: HOST_PATHS.claude, skillName: 'autoplan', tmplPath: rel }, ['autoplan'])) : raw;
|
|
expect(src).toContain('_gstack_codex_model_probe; _CODEX_MP=$?');
|
|
expect(src).toMatch(/_CODEX_MP" -eq 2/);
|
|
expect(src).toContain('binary cannot run');
|
|
expect(src).not.toContain('elif ! _gstack_codex_model_probe');
|
|
}
|
|
});
|
|
|
|
test('the preflight resolver routes exit 2 to broken_install', () => {
|
|
const src = fs.readFileSync(path.join(ROOT, 'scripts/resolvers/constants.ts'), 'utf8');
|
|
expect(src).toContain('broken_install');
|
|
// The chain must capture the probe's code; `elif ! _gstack_codex_model_probe`
|
|
// collapses 1 and 2 into one branch and loses the distinction.
|
|
expect(src).toContain('_CODEX_MP=$?');
|
|
});
|
|
});
|