mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 01:46:55 +02:00
* test: delete test-infrastructure dead code (G) - exit-propagation drives the runner's real strict verdict (BunTestOutputClassifier + strictTestExitCode); delete the unused shardRunLooksTruncated predicate. - delete skill-coverage-matrix registry + its gate (nothing reads it; the floor already iterates skillCensus()). - delete touchfiles-facade export-parity tests (Bun fails missing imports at link time) and the duplicated E2E_TIERS tier-value test. - delete brain-cache-spec TRANSPORT_DEFAULT_POLICY, SKILL_RUN_RETENTION_DAYS and the now-unused BrainTrustPolicy type with their literal tests. AUTOPLAN_PREFLIGHT_BUDGET_BYTES stays: skill-preflight-budget enforces it against real resolver output. - delete audit-compliance's JSDoc-comment grep. * test: replace product tests that fake the product with real-boundary tests (F) - design: serve.test.ts drove an inline mirror server; now two tests run the real serve() on an ephemeral port (reload confinement, submit exit 0). - setup-gbrain: rollback + voyage tests execute the template-extracted init blocks (3 sites) instead of drifted local bash copies. - terminal-agent: internalHandler source greps replaced by a behavioral /internal/grant + /internal/revoke auth matrix (no/wrong/valid token). - /health: server-security-surface and the server-auth / security-audit-r2 / sidebar-tabs source greps fold into one liveness-only check on the real body; the L4 sidecar wiring gets a behavioral /pty-inject-scan test. - delete tautologies (browser-manager onDisconnect, memory-command #12), ios swiftui tap fixture self-check, memory-ingest put_page grep, detach source greps, sidebar-agent absence pins, dead-CSS pins + the dead CSS, security-audit-r2 Task 1 + the test-only meta-commands re-export, duplicate generated-SKILL.md checks. - make-pdf coverage-gaps cases move into their owner test files. * test: delete tests of dead eval code (A) - A1: the retired Eng lexical oracle (evaluateEngSeedCoverage, isEngSeedDecisionAUQ), the completion-handoff detector and the retained corpus had no paid caller since v1.87.6; delete their 26 replay files, ~2.6k helper LOC and fixtures, and the dead blocks in 8 mixed files (live hasNativePlanTerminal / batching assertions stay). - A2: dead viewport approvers in autoplan-artifact-permission and their 11 replay files + fixtures; recorder/launcher cases stay. - A3: never-wired oracles and seeders (autoplan-phase-order, eng-finding-fixture, ceo-paired-fixture, design-ui-scope, plan-skill-completion, pty-current-screen, required-reads, transcript-section-logger); plan-seed-submission now decodes through the production createPtyScreen; section manifests name their actual guard. - A4: zero-reference helper exports, plus execGit and invokeAndObserve found by the reachability pass. - 52 fixtures orphaned by the deletions; touchfile and selection-table entries for every deleted path. * test: clean up the paid eval lane (B1-B4, B6, B7) - B1: delete paid files that assert nothing or cannot pass meaningfully: skill-llm-eval-spec and skill-e2e-spec-execute (test.todo), gemini-e2e (+ gemini-session-runner; no gemini CLI in CI), ship-idempotency (red since v1.63), the two opus-4-7 *-sonnet overlay wrappers, conductor-prose (+ its source-evaluation replay), codex-e2e-plan-format; drop their keys, scripts and census rows. - B2: skill-llm-eval grades browse/sections/command-list.md with one union judge that also carries the baseline score pin; regression-vs-baseline deleted (paid run: pass, c4/c4/a4). - B3: memory-pipeline, ios-qa, ios-qa-swift-build and plan-tune-cathedral make no model calls; renamed out of the paid glob so they run on every PR. Swift builds need GSTACK_TEST_SWIFT=1; device stub deleted. - B4: codex-e2e*, outside-voice, aside and ios-device cannot run in the CI image; excluded from the weekly lane with a tracked re-entry condition. - B6: fold opus-47's negative routing controls into skill-routing-e2e journey-negatives (paid run: 3/3 unrouted) and delete the file. - B7: delete the never-green brain-privacy-gate eval; a free gstack-skill-start test now proves consent precedes artifacts egress. * test: retire the finding-count cluster and trim its helpers (C) - C0/C1: the five never-green evals (skill-e2e-autoplan-chain and skill-e2e-plan-{ceo,eng,design,devex}-finding-count) failed on harness and budget, never on skill behavior; delete them, their touchfile/tier ids, AUTOPLAN_CHAIN_BUDGET and the dedicated eighth periodic slice (--slices 7). - C2: delete the helper groups whose only paid consumers were those files (11 modules), trim claude-pty-runner and eng-seeded-coverage to the paid closure, and delete the free replay tests whose assertions exercised only that dead code (89 files, 135 orphaned fixtures). Blocks that used dead code only as input for a live subject keep their assertions: the multiSelect default moved to plan-review-decisions, runner PTY tests use inline caller policies, and the timer-safe budget checks moved to eng-finding-retry-budget. - The eight production-touching files stay except ceo-current-decision-record (its template read only feeds the retired counter). - CARVE_GUARDS.autoplan is behavioral 'none'; TODOS records the lost chain and per-finding cadence coverage with their re-entry tests. * test: fold per-incident replay series into their detector owners (D) Twelve detector families move into one owner test each: 73 incident files become describe blocks in ceo-section-loading-fixture (stale-fill race), model-overlays, coverage-audit-evidence, autoplan-phase-observer, native-auto-decide, outside-voice-evidence, eng-first-review, plan-count-completion, plan-count-file-permission, ceo-mode-option, plan-scope-selection and plan-count-prerequisite. Each block keeps its original code and fixture, so every case still runs; only tests asserting the incident file's own touchfile registration are dropped (41). Touchfile lists that named an incident now name its owner. * test: start the plan-count history PTY on its readiness marker (H) The fake CLI prints a startup marker and the runner waits for it instead of the fixed 8 s startup sleep (8.6 s -> 0.9 s locally). eng-semantic-terminal's sleeping registration cases went with C; plan-count-timeout keeps the fixed wait because it asserts deadline behavior. * test: derive paid touchfiles from each eval's static closure (E) touchfiles.test.ts now checks, per key, that the paid file's static test/helpers and test/fixtures closure (plus fixture paths it names in string literals) is covered, and names the file, path, chain and key to fix when it is not. Free *.test.ts files are no longer touchfiles, so editing a free replay test stops selecting paid evals: 950 entries removed, 653 real closure paths added. The hand-copied inventories go: periodic-fixture-selection, fake-impeccable-touchfiles and 45 per-file selection examples. Selection for the sample edits (plan-eng-review template, claude-pty-runner, plan-count-fixture, gstack-config) loses no case under either profile. CONTRIBUTING documents the rule and its lower bound. * test: skip hollow tier shards and census judges in the paid planner (B5) A paid file is now skipped for a tier lane only when every E2E id it registers is known statically and none has that tier; ids come from the touchfile registrations and literal testName/*IfSelected arguments, so a comment or skill path that quotes another id cannot unschedule it, and computed names keep today's scheduling. --list and the manifest show each skip as "skipped: no E2E_TIERS id has tier <tier>". The weekly gate census drops the LLM judges (--skip-judges); they still run in the periodic census and PR gate lanes. Gate lane 52 -> 42 files, census 41; periodic 77 -> 69. * test: run seven paid evals on the current default capture model (B8) skill-e2e-{auq-matrix,plan-format,qa-bugs,retro,workflow} pinned claude-opus-4-7 and skill-e2e-office-hours plus -brain-writeback pinned claude-sonnet-4-6; none tests a historical model, so they now capture with resolveEvalModel('capture'), and the free harness tests that execute these registrations receive the same resolver. The paid re-pin run passed all of them. skill-e2e-{design,office-hours-phase4,plan-prosons,plan} keep claude-opus-4-7: six of their cases failed on the default model (three timeouts, a missing report file, a format miss and a posture score of 3), so per the plan's fallback they keep their pins with a TODOS entry. The pre-spend estimate and drop threshold are in docs/test-audit-2026-09.md. * test: guard the reduced suite against new test-of-test files - test/test-of-test-ratchet.test.ts records the 228 free tests that import only test/ code and fails on a new one, naming the owner test to extend instead; a stale baseline entry fails with the remove instruction. - test/helpers/resolve-repo-path.ts is the one specifier/literal resolver for the ratchet and the touchfile closure invariant, with its own unit tests. - CONTRIBUTING "Test tiers" describes the paid-failure workflow (fix, then one row in the detector's owner test) and the ratchet; TEST_PORTFOLIO gains the detector -> owner-test table and no longer claims an Autoplan chain eval. - TODOS: automatic exclusion policy for chronically red periodic files (P3), the deferred native-completion table collapse, the unused CEO payment seeder; the PTY readiness item is narrowed to the paid runner. - docs/test-audit-2026-09.md collects the triage, security mapping, inventories, selection proof, behavior-commit decisions and retained false positives. * v1.91.8.0 test: smaller suite, derived paid selection, retired never-green evals Release metadata for the test-reduction branch: VERSION 1.91.8.0 (1.91.7.0 is claimed by #2983), CHANGELOG with the measured before/after table and a contributor section, durations re-recorded on Ubicloud standard-16 (857 files, 0 failures), the agents digest, CONTRIBUTING's after-measurement row, the B8 fallback TODOS entry, and the after metrics, kept-vs-plan notes, B8 run and census estimate in docs/test-audit-2026-09.md. * fix(ubicloud): skip retrieval globs that match nothing instead of reporting a failed pull * test: count issue-numbered Design findings in the UI-scope gate eval
389 lines
17 KiB
TypeScript
389 lines
17 KiB
TypeScript
// Swift-build invariant tests. Runs against the fixture iOS app at
|
|
// test/fixtures/ios-qa/FixtureApp/. Requires the Swift toolchain
|
|
// (Xcode CLI tools or stand-alone Swift). The swift build invariants run
|
|
// only with GSTACK_TEST_SWIFT=1; the parity and harness pins always run.
|
|
//
|
|
// Two invariants:
|
|
//
|
|
// 1. Debug-config build succeeds + the StateServer XCTest unit suite
|
|
// passes (validates that the Swift production code actually runs,
|
|
// not just compiles).
|
|
//
|
|
// 2. Release-config build excludes DebugBridge symbols. This is the
|
|
// structural Release-build guard from Package.swift's
|
|
// `.when(configuration: .debug)`. We verify by:
|
|
// a. swift build -c release succeeds
|
|
// b. nm -j against the built binary shows zero `DebugBridge*`
|
|
// symbols
|
|
// c. swift build -c release with --vv shows DebugBridge target
|
|
// gated (no compilation step for DebugBridgeCore/UI)
|
|
|
|
import { describe, test, expect } from 'bun:test';
|
|
import { CAPTURE_MS } from './helpers/eval-budgets';
|
|
import { spawnSync } from 'child_process';
|
|
import { readFileSync } from 'fs';
|
|
import { join } from 'path';
|
|
|
|
const ROOT = join(import.meta.dir, '..');
|
|
const FIXTURE_PATH = join(ROOT, 'test/fixtures/ios-qa/FixtureApp');
|
|
const TEMPLATES_PATH = join(ROOT, 'ios-qa/templates');
|
|
const GEN_ACCESSORS_PACKAGE = join(ROOT, 'ios-qa/scripts/gen-accessors-tool/Package.swift');
|
|
|
|
const COPIED_BRIDGE_TEMPLATES = [
|
|
['StateServer.swift.template', 'Sources/DebugBridgeCore/StateServer.swift'],
|
|
['DebugBridgeManager.swift.template', 'Sources/DebugBridgeCore/DebugBridgeManager.swift'],
|
|
['DebugOverlay.swift.template', 'Sources/DebugBridgeUI/DebugOverlay.swift'],
|
|
['Bridges.swift.template', 'Sources/DebugBridgeUI/Bridges.swift'],
|
|
['DebugBridgeTouch.h.template', 'Sources/DebugBridgeTouch/include/DebugBridgeTouch.h'],
|
|
['DebugBridgeTouch.m.template', 'Sources/DebugBridgeTouch/DebugBridgeTouch.m'],
|
|
] as const;
|
|
|
|
function readTemplate(name: string): string {
|
|
return readFileSync(join(TEMPLATES_PATH, name), 'utf-8');
|
|
}
|
|
|
|
function normalizeBridgePackage(source: string): string {
|
|
// Package.swift.template has a generated-file prologue while the fixture has
|
|
// a fixture-specific one. The tools-version declaration must remain first in
|
|
// both real files, but neither header is part of the copied bridge surface.
|
|
const importOffset = source.indexOf('import PackageDescription');
|
|
expect(importOffset).toBeGreaterThanOrEqual(0);
|
|
let packageBody = source.slice(importOffset);
|
|
|
|
// The fixture deliberately has its own package identity and XCTest target.
|
|
// Normalize only those fixture concerns; all three bridge products, targets,
|
|
// dependencies, settings, and paths must otherwise stay in lockstep.
|
|
packageBody = packageBody.replace(
|
|
/(let package = Package\(\s*name:)\s*"[^"]+"/,
|
|
'$1 "<bridge-package>"',
|
|
);
|
|
packageBody = packageBody.replace(
|
|
/\n\s*\.testTarget\(\s*\n\s*name:\s*"DebugBridgeCoreTests",[\s\S]*?\n\s{8}\),?/,
|
|
'',
|
|
);
|
|
|
|
// Ignore prose and formatting so a template-only explanatory comment does
|
|
// not conceal a meaningful manifest mismatch.
|
|
return packageBody
|
|
.replace(/\/\/.*$/gm, '')
|
|
.replace(/\s+/g, '')
|
|
.replace(/,([\])])/g, '$1');
|
|
}
|
|
|
|
function escapeRegExp(value: string): string {
|
|
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
function bracedBlock(source: string, openBraceOffset: number): string {
|
|
let depth = 0;
|
|
for (let offset = openBraceOffset; offset < source.length; offset++) {
|
|
if (source[offset] === '{') depth++;
|
|
if (source[offset] !== '}') continue;
|
|
depth--;
|
|
if (depth === 0) return source.slice(openBraceOffset, offset + 1);
|
|
}
|
|
return '';
|
|
}
|
|
|
|
// The fixture is where the bridge is compiled and exercised end-to-end. Every
|
|
// source copied into consuming apps must therefore be the canonical template,
|
|
// or device QA can pass against code that /ios-qa never installs.
|
|
describe('template ↔ fixture parity', () => {
|
|
for (const [templateName, fixtureDestination] of COPIED_BRIDGE_TEMPLATES) {
|
|
test(`${templateName} matches ${fixtureDestination}`, () => {
|
|
expect(readTemplate(templateName)).toBe(
|
|
readFileSync(join(FIXTURE_PATH, fixtureDestination), 'utf-8'),
|
|
);
|
|
});
|
|
}
|
|
|
|
test('Package.swift bridge declarations match after fixture-only normalization', () => {
|
|
const template = readTemplate('Package.swift.template');
|
|
const fixture = readFileSync(join(FIXTURE_PATH, 'Package.swift'), 'utf-8');
|
|
expect(normalizeBridgePackage(template)).toBe(normalizeBridgePackage(fixture));
|
|
});
|
|
|
|
test('Package.swift.template declares all 3 DebugBridge targets', () => {
|
|
const tmpl = readTemplate('Package.swift.template');
|
|
// Each target must be present as a library product AND a target definition.
|
|
for (const name of ['DebugBridgeCore', 'DebugBridgeUI', 'DebugBridgeTouch']) {
|
|
expect(tmpl).toContain(`name: "${name}"`);
|
|
}
|
|
// DebugBridgeUI must depend on the other two; that's how the consuming
|
|
// app gets the transitive set with one dependency entry.
|
|
expect(tmpl).toMatch(/name:\s*"DebugBridgeUI"[\s\S]*?dependencies:\s*\["DebugBridgeCore",\s*"DebugBridgeTouch"\]/);
|
|
});
|
|
|
|
test('generated Swift packages only reference shipped test directories', () => {
|
|
const genAccessorsPackage = readFileSync(GEN_ACCESSORS_PACKAGE, 'utf-8');
|
|
const debugBridgePackage = readFileSync(join(TEMPLATES_PATH, 'Package.swift.template'), 'utf-8');
|
|
|
|
expect(genAccessorsPackage).not.toContain('Tests/GenAccessorsTests');
|
|
expect(debugBridgePackage).not.toContain('Tests/DebugBridgeCoreTests');
|
|
});
|
|
|
|
test('Package.swift.template keeps swift-tools-version on the first line', () => {
|
|
const tmpl = readTemplate('Package.swift.template');
|
|
expect(tmpl.split(/\r?\n/, 1)[0]).toBe('// swift-tools-version:5.9');
|
|
});
|
|
});
|
|
|
|
describe('iOS tap harness regressions', () => {
|
|
test('manager receives app-owned generated accessors instead of a no-op package stub', () => {
|
|
const manager = readTemplate('DebugBridgeManager.swift.template');
|
|
const wiring = readTemplate('DebugBridgeWiring.swift.template');
|
|
const fixtureApp = readFileSync(
|
|
join(FIXTURE_PATH, 'Sources/FixtureApp/FixtureAppApp.swift'),
|
|
'utf-8',
|
|
);
|
|
|
|
expect(manager).toContain('func start<State>');
|
|
expect(manager).toContain('register: (State) -> Void');
|
|
expect(manager).toContain('register(appState)');
|
|
expect(manager).not.toContain('public enum AppStateAccessor');
|
|
expect(manager).not.toContain('protocol AppState');
|
|
|
|
expect(wiring).toContain('import DebugBridgeCore');
|
|
expect(wiring).toContain('import DebugBridgeUI');
|
|
expect(wiring).toContain('DebugBridgeUIWiring.installAll()');
|
|
expect(wiring.indexOf('DebugBridgeUIWiring.installAll()')).toBeLessThan(
|
|
wiring.indexOf('DebugBridgeManager.shared.start'),
|
|
);
|
|
expect(fixtureApp.indexOf('DebugBridgeUIWiring.installAll()')).toBeLessThan(
|
|
fixtureApp.indexOf('DebugBridgeManager.shared.start'),
|
|
);
|
|
expect(wiring).not.toContain('import DebugBridge\n');
|
|
expect(wiring).not.toContain('AccessibilityScanner');
|
|
expect(wiring).not.toContain('MutationDispatcher');
|
|
});
|
|
|
|
test('fixture uses an @Observable-compatible source marker, not a property wrapper', () => {
|
|
const state = readFileSync(
|
|
join(FIXTURE_PATH, 'Sources/FixtureApp/FixtureAppState.swift'),
|
|
'utf-8',
|
|
);
|
|
expect(state).toContain('@Observable');
|
|
expect(state.match(/\/\/ @Snapshotable/g)?.length).toBe(4);
|
|
expect(state).not.toContain('@propertyWrapper');
|
|
expect(state).not.toMatch(/^[\t ]*@Snapshotable[\t ]+(?:public[\t ]+)?var/m);
|
|
});
|
|
|
|
test('recurses through iOS automation elements to expose nested SwiftUI controls', () => {
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
expect(bridges).toContain('element.automationElements');
|
|
expect(bridges).toContain('debugBridgeAccessibilityChildren(of: element)');
|
|
expect(bridges).toContain('visited.insert(ObjectIdentifier(element)).inserted');
|
|
expect(bridges).toContain('var remaining = 2_048');
|
|
});
|
|
|
|
test('enables accessibility automation before SwiftUI AX is installed', () => {
|
|
const implementation = readTemplate('DebugBridgeTouch.m.template');
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
const helper = [...implementation.matchAll(
|
|
/static\s+void\s+([A-Za-z_]\w*)\s*\(\s*void\s*\)\s*\{/g,
|
|
)].find((candidate) => {
|
|
const body = bracedBlock(
|
|
implementation,
|
|
candidate.index! + candidate[0].lastIndexOf('{'),
|
|
);
|
|
return body.includes('_AXSAutomationEnabled') && body.includes('_AXSSetAutomationEnabled');
|
|
});
|
|
expect(helper).toBeDefined();
|
|
|
|
const helperName = helper![1];
|
|
const helperBody = bracedBlock(
|
|
implementation,
|
|
helper!.index! + helper![0].lastIndexOf('{'),
|
|
);
|
|
expect(helperBody).toContain('_AXSAutomationEnabled');
|
|
expect(helperBody).toContain('_AXSSetAutomationEnabled');
|
|
|
|
// Accept either Objective-C's eager +load hook or an explicit public
|
|
// bootstrap selector, but require the enabling helper to be called before
|
|
// Swift installs the resolver that walks SwiftUI's accessibility tree.
|
|
const bootstrap = [...implementation.matchAll(/\+\s*\(void\)\s*([A-Za-z_]\w*)\s*\{/g)]
|
|
.find((candidate) => bracedBlock(
|
|
implementation,
|
|
candidate.index! + candidate[0].lastIndexOf('{'),
|
|
).match(new RegExp(`\\b${escapeRegExp(helperName)}\\s*\\(`)));
|
|
expect(bootstrap).toBeDefined();
|
|
|
|
if (bootstrap![1] === 'load') {
|
|
expect(bootstrap!.index!).toBeLessThan(implementation.indexOf('+ (BOOL)sendTapAtPoint:'));
|
|
} else {
|
|
const bootstrapCall = bridges.search(
|
|
new RegExp(`DebugBridgeTouch\\.${escapeRegExp(bootstrap![1])}\\s*\\(`),
|
|
);
|
|
expect(bootstrapCall).toBeGreaterThanOrEqual(0);
|
|
expect(bootstrapCall).toBeLessThan(bridges.indexOf('ElementsBridge.resolver'));
|
|
}
|
|
});
|
|
|
|
test('renders screenshots at one pixel per window point', () => {
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
const declaration = bridges.match(
|
|
/(?:let|var)\s+([A-Za-z_]\w*)\s*=\s*UIGraphicsImageRendererFormat(?:\.default)?\(\)/,
|
|
);
|
|
expect(declaration).not.toBeNull();
|
|
|
|
const formatName = declaration![1];
|
|
const scalePattern = new RegExp(`\\b${escapeRegExp(formatName)}\\.scale\\s*=\\s*1(?:\\.0)?\\b`);
|
|
const rendererPattern = new RegExp(
|
|
`UIGraphicsImageRenderer\\(\\s*bounds:\\s*bounds,\\s*format:\\s*${escapeRegExp(formatName)}\\s*\\)`,
|
|
);
|
|
const declarationOffset = declaration!.index!;
|
|
const scaleOffset = bridges.search(scalePattern);
|
|
const rendererOffset = bridges.search(rendererPattern);
|
|
|
|
expect(scaleOffset).toBeGreaterThan(declarationOffset);
|
|
expect(rendererOffset).toBeGreaterThan(scaleOffset);
|
|
});
|
|
|
|
test('uses accessibilityActivate for SwiftUI while retaining synthesized-touch delivery', () => {
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
const tapStart = bridges.indexOf('private static func handleTap');
|
|
const tapEnd = bridges.indexOf('private static func handleType', tapStart);
|
|
expect(tapStart).toBeGreaterThanOrEqual(0);
|
|
expect(tapEnd).toBeGreaterThan(tapStart);
|
|
const handleTap = bridges.slice(tapStart, tapEnd);
|
|
|
|
const synthesizedTouchOffset = handleTap.indexOf('DebugBridgeTouch.sendTap');
|
|
const fallbackCall = handleTap.match(
|
|
/\b([A-Za-z_]\w*)\s*\(\s*at:\s*point\s*,\s*in:\s*window\s*\)/,
|
|
);
|
|
const activationOffset = handleTap.indexOf('.accessibilityActivate()');
|
|
expect(synthesizedTouchOffset).toBeGreaterThanOrEqual(0);
|
|
expect(fallbackCall).not.toBeNull();
|
|
expect(activationOffset).toBeGreaterThan(fallbackCall!.index!);
|
|
|
|
const fallbackName = fallbackCall![1];
|
|
expect(bridges).toMatch(
|
|
new RegExp(`(?:private\\s+)?static\\s+func\\s+${escapeRegExp(fallbackName)}\\s*\\(`),
|
|
);
|
|
});
|
|
|
|
test('finishes programmatic scrolls before returning success to the next tap', () => {
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
expect(bridges).toContain('setContentOffset(off, animated: false)');
|
|
expect(bridges).not.toContain('setContentOffset(off, animated: true)');
|
|
});
|
|
|
|
test('serializes accessibility traits without signed Int truncation', () => {
|
|
const bridges = readTemplate('Bridges.swift.template');
|
|
expect(bridges).toMatch(/\btraits\s*:\s*UInt64\b/);
|
|
expect(bridges).toContain('.uint64Value');
|
|
expect(bridges).not.toMatch(/\bInt(?:64)?\s*\(\s*view\.accessibilityTraits\.rawValue\s*\)/);
|
|
expect(bridges).not.toMatch(/accessibilityTraits[\s\S]{0,120}?\.intValue\b/);
|
|
});
|
|
|
|
test('validates every generated model before applying any snapshot state', () => {
|
|
const server = readTemplate('StateServer.swift.template');
|
|
const validationLoop = server.indexOf('for restore in atomicRestores');
|
|
const applyComment = server.indexOf('Phase two applies only after every model accepted');
|
|
const applyLoop = server.indexOf('for restore in atomicRestores', validationLoop + 1);
|
|
|
|
expect(server).toContain('typealias AtomicRestoreFn = (JSONDict, Bool) -> RestoreResult');
|
|
expect(server).toContain('restore(keys, false)');
|
|
expect(server).toContain('restore(keys, true)');
|
|
expect(validationLoop).toBeGreaterThanOrEqual(0);
|
|
expect(applyComment).toBeGreaterThan(validationLoop);
|
|
expect(applyLoop).toBeGreaterThan(applyComment);
|
|
});
|
|
|
|
test('turns non-JSON response bodies into an explicit HTTP 500', () => {
|
|
const server = readTemplate('StateServer.swift.template');
|
|
expect(server).toContain('JSONSerialization.isValidJSONObject(body)');
|
|
expect(server).toContain('responseStatus = 500');
|
|
expect(server).toContain('response_not_json_serializable');
|
|
expect(server).not.toContain('?? Data("{}".utf8)');
|
|
});
|
|
});
|
|
|
|
// Explicit opt-in, not tool presence: free shards run on hosts where Swift
|
|
// may be installed, and a full swift build does not belong in every PR run.
|
|
const describeIfSwift = process.env.GSTACK_TEST_SWIFT === '1' ? describe : describe.skip;
|
|
|
|
describeIfSwift('swift build invariants', () => {
|
|
// DebugBridgeUI + DebugBridgeTouch are iOS-only (they link UIKit). Plain
|
|
// `swift build` on macOS host can't resolve UIKit, so we scope these
|
|
// invariants to DebugBridgeCore (Swift, cross-platform) + its XCTest
|
|
// target. The iOS-only targets are covered by xcodebuild on the device
|
|
// path (test/skill-e2e-ios-device.test.ts).
|
|
test('Debug-config build succeeds (DebugBridgeCore)', () => {
|
|
const r = spawnSync('swift', ['build', '-c', 'debug', '--target', 'DebugBridgeCore'], {
|
|
cwd: FIXTURE_PATH,
|
|
stdio: 'pipe',
|
|
timeout: 120_000,
|
|
});
|
|
if (r.status !== 0) {
|
|
console.error('swift build stderr:', r.stderr?.toString().slice(0, 4000));
|
|
}
|
|
expect(r.status).toBe(0);
|
|
}, CAPTURE_MS);
|
|
|
|
test('XCTest suite for StateServer passes (validates real Swift impl)', () => {
|
|
const r = spawnSync('swift', ['test', '--filter', 'DebugBridgeCoreTests'], {
|
|
cwd: FIXTURE_PATH,
|
|
stdio: 'pipe',
|
|
timeout: 180_000,
|
|
});
|
|
const stdout = r.stdout?.toString() ?? '';
|
|
const stderr = r.stderr?.toString() ?? '';
|
|
const combined = stdout + stderr;
|
|
if (r.status !== 0) {
|
|
console.error('swift test failure:', combined.slice(-4000));
|
|
}
|
|
expect(r.status).toBe(0);
|
|
// --filter scopes the run to DebugBridgeCoreTests; the xctest summary
|
|
// line is "'Selected tests' passed" rather than "'All tests' passed".
|
|
expect(combined).toMatch(/'(?:All|Selected) tests' passed/);
|
|
// Guard against an empty pass-by-no-tests (filter typo / target rename):
|
|
// we expect at least one StateServer smoke test to actually execute.
|
|
expect(combined).toContain('StateServerSmokeTests');
|
|
}, CAPTURE_MS);
|
|
|
|
// Codex-flagged: Release-build guard must be STRUCTURAL, not advisory.
|
|
// The Package.swift's `.when(configuration: .debug)` setting causes Swift
|
|
// to compile-out the entire DebugBridgeCore target body in Release. Since
|
|
// every public symbol is gated `#if DEBUG`, the release build emits an
|
|
// empty module — zero symbols.
|
|
test('Release-config build excludes DebugBridge symbols', () => {
|
|
// Step 1: clean + release build (Core only — UI/Touch can't build on macOS)
|
|
spawnSync('swift', ['package', 'clean'], { cwd: FIXTURE_PATH, stdio: 'pipe', timeout: 60_000 });
|
|
const build = spawnSync('swift', ['build', '-c', 'release', '--target', 'DebugBridgeCore'], {
|
|
cwd: FIXTURE_PATH,
|
|
stdio: 'pipe',
|
|
timeout: 180_000,
|
|
});
|
|
if (build.status !== 0) {
|
|
console.error('release build stderr:', build.stderr?.toString().slice(0, 4000));
|
|
}
|
|
expect(build.status).toBe(0);
|
|
|
|
// Step 2: locate the built object file(s). SwiftPM puts .build artifacts
|
|
// under .build/<triple>/release/.
|
|
const oFiles = spawnSync('find', [
|
|
join(FIXTURE_PATH, '.build'),
|
|
'-path', '*/release/*',
|
|
'-name', '*.o',
|
|
'-path', '*DebugBridge*',
|
|
], { stdio: 'pipe', timeout: 30_000 });
|
|
const files = (oFiles.stdout?.toString() ?? '').trim().split('\n').filter(Boolean);
|
|
expect(files.length).toBeGreaterThan(0);
|
|
|
|
let foundForbidden = 0;
|
|
const forbidden = ['StateServer', 'handleRequest', 'sessionAcquire', 'authRotate', 'snapshotGet'];
|
|
for (const f of files) {
|
|
const nm = spawnSync('nm', ['-j', f], { stdio: 'pipe', timeout: 30_000 });
|
|
const syms = nm.stdout?.toString() ?? '';
|
|
for (const tok of forbidden) {
|
|
if (syms.includes(tok)) {
|
|
console.error(`Release symbol leak: ${tok} found in ${f}`);
|
|
foundForbidden++;
|
|
}
|
|
}
|
|
}
|
|
expect(foundForbidden).toBe(0);
|
|
}, CAPTURE_MS);
|
|
});
|