Files
Michał Pierzchała 05a1d76f2e test: add daemon RPC wire-surface compatibility gate (#1717)
* test: gate daemon RPC wire compatibility against the last released tag (#1432)

ADR 0006 fixes exactly when DAEMON_RPC_PROTOCOL_VERSION must be bumped, and
nothing checked that it was. The runtime guard (readRemoteDaemonHealth) refuses
a mismatched peer, but only fires when someone remembered the bump — a wire
change that skipped it left both sides advertising protocol 2 while parsing
different payloads, which is the failure ADR 0006 exists to prevent.

Local daemons cannot skew (isReusableDaemonInfo takes over on any package
version mismatch). Cross-machine is skewed by design — proxy, cloud/limrun, a
remote macOS host — and ADR 0006 explicitly rules package version out as the
compatibility gate there, so the one boundary where skew is intended was the
one boundary with no gate.

test/wire-compat/surface.ts declares the wire surface grouped by the ADR bullet
each group serves, quoting it, with an `uncovered` note where a bullet is only
partly digestible (the /health and /rpc literals inside http-server.ts stay
reviewer-owned: a moved route 404s at connect time rather than misparsing).
ledger.json records what each declaration hashes to, at which protocol version.

Two gates, split for the same reason the replay-compat corpus splits:
- unit-core holds the ledger to its source and prints the digest to paste;
- Released-Surface Compatibility reads the ledger at the last RELEASED tag and
  requires the drift since then to carry a bump or a compatibleChanges ack.

From one commit a bumped ledger and an unbumped one are both just an edited
file, so only a released baseline can tell them apart. Acks are keyed by the
digest they cover, so one "added an optional field" cannot launder later
changes. Digests ignore comments and formatting; the manifest's closure is
derived from the AST, so a field typed by an unlisted sibling fails rather than
sitting outside the gate.

CI cost: one added job (checkout + toolchain + two node scripts, ~1 min),
mirroring the existing full-history replay-compat job.

* test: close wire-surface overclaim and make the closure fail closed (#1432)

Addresses both review P1s on #1717.

P1 — the manifest materially overclaimed ADR 0006 coverage. It quoted all four
bullets while digesting only the payload TYPES, so the producer and consumer
seams could break a skewed peer without moving a listed digest. Now listed on
both sides of every boundary: JSON-RPC method sets and the projections that
turn each method's params into a DaemonRequest, createRpcError/sendJson/
writeRpcResponseEnvelope, resolveToken and the auth-hook types, upload
preflight/finalize/308 handlers and the resumable ticket shape, artifact route
and download/inventory framing, REST error mapping, and the client's own
payload builder, lease-method mapping, response parser and error projection.
57 -> 117 declarations.

What stays out is now named rather than implied: createDaemonHttpServer's
dispatch wiring and the /health and /rpc literals inside it. Everything it
dispatches WITH is digested individually, and a moved route 404s at connect
time rather than misparsing — the loud failure, not the silent one.

P1 — imported and re-exported payload shapes escaped the closure.
declarationHomes() scanned only the manifest's own files and the walk
continued silently when a name could not be placed, so a listed type could
gain foo?: ImportedShape from a new module and stay green. Resolution is now
explicit and fails closed: relative imports, workspace specifiers (through the
owning package's own exports map, so a re-pointed export cannot drop a type),
and facade re-export chains. Every referenced name must land on a listed
declaration, a waiver with a written reason, a declared external module, or the
TS/Node global set. Fixed two extractor blind spots the walk exposed: a
declaration's own generic parameters and `as const` were being reported as
references.

Planted-red proofs (wire-mutations.test.ts): 13 cases independently mutate
method naming, response serialization, response parsing, auth projection,
upload ticket shape, 308 framing, artifact framing, REST error mapping, and
progress framing, each asserting the digest moves; 3 probes prove the closure
really reaches across a package boundary, a facade re-export, and a plain
relative import. Mutations apply inside the declaration's own span — a
whole-file replace silently hit a sibling sharing the substring, which is how
the first draft of one case passed vacuously.

The largest waiver pair (InternalRequestOptions, CommandFlags) rests on ADR
0006's own additive rule: they reach the peer inside DaemonRequest's untyped
flags/input bags, and the decision says a new flag needs no bump. Digesting
them would fire the gate on every new CLI flag and train reviewers to
rubber-stamp acks.

* test: list the consumer half of the auxiliary HTTP boundaries (#1432)

Addresses the remaining review P1 on #1717. The manifest claimed both sides of
response/upload/artifact framing while listing nothing from upload-client.ts,
daemon-artifacts.ts, or the health consumer in daemon-client-transport.ts, so
those parsers could narrow without moving a listed digest or protocol 2.

Now listed (117 -> 141 declarations):

- /health consumer: RemoteDaemonHealth, readHealthPayload, readDaemonHttpHealth,
  readRemoteDaemonHealth. This is the sharpest of the three — narrowing the
  reader or the comparison disables the very refusal ADR 0006 exists to
  guarantee, and nothing else in the repo would notice.
- /upload consumer: UploadResponse, UploadPreflightResponse, UploadPreflightResult,
  parseUploadPreflightResult, requestUploadPreflight, uploadDirectArtifact,
  tryDirectUploadWithResume, shouldRetryDirectUpload, finalizeDirectUpload,
  uploadLegacyArtifact, ARTIFACT_HASH_ALGORITHM, isStringRecord, and
  PreparedUploadArtifact — whose sha256/sizeBytes/fileName/artifactType/
  contentType fields ARE the preflight body the daemon parses.
- /artifacts/* consumer: DaemonArtifactEndpoint, buildDaemonArtifactUrl,
  isRemoteDaemon, DownloadRemoteArtifactParams, downloadRemoteArtifact,
  materializeRemoteArtifacts, resolveMaterializedArtifactPath.

Running the closure fail-closed over the new files surfaced three more stops,
each decided rather than skipped: PreparedUploadArtifact listed (it is payload),
UploadProgressSink waived (client-local rendering, never leaves the process),
and src/daemon/types.ts#DaemonArtifact waived as a re-export alias of the listed
kernel type, matching its DaemonRequest/DaemonResponse siblings.

10 more planted-red mutations cover the new seams: health version-read and
mismatch-refusal defeated, RemoteDaemonHealth field dropped, preflight parser
narrowed, preflight/legacy response shapes narrowed, finalize body key renamed,
ticket field renamed, artifact tenant header dropped, artifact URL moved. A
fourth closure probe proves the upload-consumer files are genuinely reached by
the walk rather than merely listed. 22 -> 33 tests.

The README now states the coverage as a producer/consumer table per boundary,
so the claim is checkable at a glance instead of asserted in prose.

* test: list the client half of the resumable 308 contract (#1432)

Addresses the third review P1 on #1717. Listing the daemon's
handleResumableUpload proved it still PRODUCES 308; nothing proved the client
still CONSUMES the released one. src/remote/upload-stream.ts owns that half and
was entirely outside the manifest, so a newer client could stop accepting
`upload-offset`, change how it reads `Range: bytes=0-N`, or emit a different
resumed `Content-Range` without moving one of the 141 listed digests.

Now listed (141 -> 151): UploadStreamResponse, streamFileToHttpRequest,
streamFileToHttpRequestAttempt, buildUploadRequestHeaders, isUploadResumeStatus,
isUploadRedirectStatus, parseUploadResumeOffset, parseNonNegativeIntegerHeader,
firstHeaderValue, MAX_UPLOAD_REDIRECTS.

streamFileToHttpRequestAttempt is listed despite its size, unlike
createDaemonHttpServer which stays in `uncovered`. The distinction is stated at
the declaration: the HTTP server only dispatches to handlers that are each
digested, while the attempt loop IS the resume state machine — it decides
whether a 308 continues the upload and what the next request carries, so its
sequencing alone can break a released daemon while every helper keeps its digest.

6 new planted-red mutations prove the client half moves the ledger: a dropped
`upload-offset` fallback, narrowed Range parsing, a changed resumed
Content-Range, 308 no longer treated as continue, a narrowed UploadStreamResponse,
and dropped header-value coercion. 33 -> 39 tests.

Closure fail-closed surfaced two more stops: UploadStreamProgressOptions waived
(local byte-progress rendering) and URL/URLSearchParams added to the global set.

README now carries a `/upload` resume row in the producer/consumer table, and
names the pattern behind three rounds of review: the coverage sentence kept
getting written ahead of the coverage, so the table and the `uncovered` notes
are the claims to trust — they are checkable against surface.ts, prose is not.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-10 20:52:29 +02:00

514 lines
16 KiB
TypeScript

// Derived, fail-open check selector for `pnpm check:affected --base <ref>`.
//
// The model turns a set of changed paths into a plan of local checks with
// stable, machine-readable reasoning. It is intentionally source-of-truth
// derived rather than a hand-maintained path-to-check registry (issue #1181):
//
// - Vitest owns affected-test discovery through its native `related`
// command and static module graph; this model only decides when that
// existing tool applies;
// - the lint/typecheck/layering/fallow gates are always-on for their input
// categories, so they are never silently skipped (issue constraint);
// - a small explicit build-ownership layer covers Swift, Android helpers,
// the macOS helper, MCP metadata, and the public package surface — the
// only paths whose owning build the sources of truth cannot derive.
//
// Anything the model cannot confidently classify fails open to the full check
// set: unknown paths, workflow/tooling, the selector's own sources, and
// ambiguous files under an owned root that only resolve to `format` (e.g. a
// non-.ts fixture whose owning suite cannot be derived). Existing GitHub CI
// remains authoritative; this only optimizes local/agent feedback.
import { WIRE_SURFACE_FILES } from '../../test/wire-compat/surface.ts';
export type CheckId =
| 'format'
| 'lint'
| 'typecheck'
| 'test-app-typecheck'
| 'layering'
| 'fallow'
| 'mcp-metadata'
| 'build'
| 'package'
| 'vitest-related'
| 'unit'
| 'coverage'
| 'provider-integration'
| 'integration-node'
| 'integration-progress'
| 'swift-runner'
| 'android-helpers'
| 'macos-helper'
| 'web-smoke'
| 'replay-compat'
| 'daemon-wire-compat';
// The complete local check universe. A fail-open plan selects all of these;
// keep it in sync with the catalog in checks.ts (asserted by the self-test).
export const ALL_CHECKS: readonly CheckId[] = [
'format',
'lint',
'typecheck',
'test-app-typecheck',
'layering',
'fallow',
'mcp-metadata',
'build',
'package',
// Real daemon/process integration owns host-global lifecycle state and must
// run before the high-parallelism coverage workload heats the host.
'integration-node',
'vitest-related',
'unit',
'coverage',
'provider-integration',
'integration-progress',
'swift-runner',
'android-helpers',
'macos-helper',
'web-smoke',
'replay-compat',
'daemon-wire-compat',
];
export type SelectionReason = {
check: CheckId;
path: string;
rule: string;
detail: string;
};
export type FailOpenReason = {
path: string;
rule: 'workflow-tooling' | 'selector-owning' | 'unknown-path' | 'ambiguous-path';
detail: string;
};
export type CheckPlan = {
failOpen: boolean;
checks: CheckId[];
reasons: SelectionReason[];
failOpenReasons: FailOpenReason[];
docsOnlyPaths: string[];
};
export type SelectInput = {
changedFiles: readonly string[];
// Public package entry source files, derived from package.json `exports`.
packageEntryFiles?: readonly string[];
};
// --- Path classification helpers -------------------------------------------
const ROOT_TOOLING = new Set([
'package.json',
'pnpm-lock.yaml',
'pnpm-workspace.yaml',
'tsconfig.json',
'tsconfig.lib.json',
'tsdown.config.ts',
'vitest.config.ts',
'.oxlintrc.json',
'.oxfmtrc.json',
'.npmrc',
]);
// Prose that specifies this selector's own behavior — the Testing Matrix these
// ownership rules mirror. It is docs by path, but editing it can invalidate the
// derivation below, and the selector cannot tell whether it did. Keep this in
// sync when the matrix moves; the docs short-circuit would otherwise treat it as
// inert Markdown.
const SELECTOR_OWNING_DOCS = new Set(['docs/agents/testing.md']);
function isSelectorOwning(file: string): boolean {
return (
SELECTOR_OWNING_DOCS.has(file) ||
(file.startsWith('scripts/check-affected/') && !file.endsWith('.md'))
);
}
function isWorkflowTooling(file: string): boolean {
// A workspace package manifest or tsconfig rewires module resolution for
// every consumer, so it fails open like root tooling does.
const packageTooling = /^packages\/[^/]+\/(?:package\.json|tsconfig\.json)$/.test(file);
return (
file.startsWith('.github/') ||
file.startsWith('scripts/') ||
packageTooling ||
ROOT_TOOLING.has(file)
);
}
function isDocs(file: string): boolean {
// skills/ Markdown is agent guidance prose with no owning suite (the
// SkillGym harness was removed), so it classifies as docs like the rest.
return (
file.startsWith('docs/') ||
file.startsWith('website/') ||
file === 'README.md' ||
file === 'LICENSE' ||
file.endsWith('.md')
);
}
function isTestPath(file: string): boolean {
return /\.test\.ts$/.test(file) || /(?:^|\/)__tests__\//.test(file);
}
// --- Ownership rules --------------------------------------------------------
// Each rule inspects one changed file and returns the reasons it contributes.
// Splitting the selection into small, independent rules keeps every function
// simple and makes the derivation self-documenting.
type FileFacts = {
file: string;
isTs: boolean;
underSrc: boolean;
underTest: boolean;
isSrcProd: boolean;
};
type OwnershipRule = (facts: FileFacts, input: SelectInput) => SelectionReason[];
function reason(check: CheckId, file: string, rule: string, detail: string): SelectionReason {
return { check, path: file, rule, detail };
}
const formatGate: OwnershipRule = ({ file, underSrc, underTest }) =>
underSrc || underTest
? [reason('format', file, 'gate:format', 'oxfmt covers src/ and test/')]
: [];
const staticTsGates: OwnershipRule = ({ file, isTs, underSrc, underTest }) =>
isTs && (underSrc || underTest)
? [
reason('lint', file, 'gate:lint', 'oxlint covers the source tree'),
reason('typecheck', file, 'gate:typecheck', 'tsc includes src/ and test/'),
reason('fallow', file, 'gate:fallow', 'fallow audits changed TypeScript for dead code'),
]
: [];
const srcProdGate: OwnershipRule = ({ file, isSrcProd }) => {
if (!isSrcProd) return [];
const selections = [
reason('layering', file, 'gate:layering', 'layering guard reads production src/ modules'),
reason('build', file, 'src-prod', 'production source is compiled by the build'),
];
if (file.startsWith('src/platforms/')) {
selections.push(
reason(
'provider-integration',
file,
'platform-src',
'platform source shapes device/provider wire behavior',
),
reason(
'coverage',
file,
'platform-src',
'Testing Matrix requires coverage for platform/device-response changes',
),
);
}
return selections;
};
function isNodeIntegrationPath(file: string): boolean {
return (
file.startsWith('test/integration/') &&
!file.slice('test/integration/'.length).includes('/') &&
file.endsWith('.ts')
);
}
const vitestRelatedOwnership: OwnershipRule = ({ file, isTs, underSrc, underTest }) =>
isTs && (underSrc || underTest) && !isNodeIntegrationPath(file)
? [
reason(
'vitest-related',
file,
'vitest:related',
'Vitest resolves affected tests through its static module graph',
),
]
: [];
// Workspace package source (#1490 W0): bundled into the published artifact,
// type-checked in the root graph, covered by Vitest's module graph, and
// guarded by layering R11. Fallow scans it too — the W0 ignorePatterns entry
// claimed its resolver could not follow workspace specifiers, which stopped
// being true (it resolves @agent-device/* through each exports map), so an
// extraction into packages/ no longer takes its own dead code out of scope.
const workspacePackageOwnership: OwnershipRule = ({ file, isTs }) => {
if (!isTs || !/^packages\/[^/]+\/src\//.test(file)) return [];
const selections = [
reason('format', file, 'gate:format', 'oxfmt covers packages/'),
reason('lint', file, 'gate:lint', 'oxlint covers packages/'),
reason('typecheck', file, 'gate:typecheck', 'tsc includes packages/'),
reason('fallow', file, 'gate:fallow', 'fallow audits changed TypeScript for dead code'),
reason('layering', file, 'package-src', 'layering R11 guards workspace package boundaries'),
reason(
'vitest-related',
file,
'vitest:related',
'Vitest resolves affected tests through its static module graph',
),
];
if (!isTestPath(file)) {
selections.push(
reason('build', file, 'package-src', 'package source is bundled into the published artifact'),
);
}
return selections;
};
const platformPackageScenarioOwnership: OwnershipRule = ({ file, isTs }) => {
if (!isTs || !/^packages\/platform-[^/]+\/src\//.test(file)) {
return [];
}
return [
reason(
'unit',
file,
'platform-package-contract',
'platform packages must satisfy the shared runtime contract scenarios',
),
reason(
'provider-integration',
file,
'platform-package-provider',
'platform packages participate in provider-first ownership scenarios',
),
reason(
'coverage',
file,
'platform-package-coverage',
'platform package changes require affected contract coverage evidence',
),
];
};
const nodeIntegrationOwnership: OwnershipRule = ({ file }) =>
isNodeIntegrationPath(file)
? [reason('integration-node', file, 'node-integration', 'node --test integration smoke')]
: [];
const testAppOwnership: OwnershipRule = ({ file }) => {
if (!file.startsWith('examples/test-app/')) return [];
if (!/\.(?:[cm]?[jt]sx?|json)$/.test(file)) return [];
return [
reason('format', file, 'gate:format', 'oxfmt covers the Expo test app'),
reason('lint', file, 'gate:lint', 'oxlint covers the Expo test app'),
reason(
'test-app-typecheck',
file,
'own:test-app',
'the Expo test app has an isolated TypeScript dependency graph',
),
];
};
// The frozen replay-compat corpus (#1417). `.ad` fixture data would otherwise
// fail open on its extension: its only consumer is the unit-lane corpus test.
// Any corpus change — script or manifest — also runs the history-backed
// provenance verifier, which is the only gate that can prove an entry's blob
// really came from the release tag it names.
const replayCompatOwnership: OwnershipRule = ({ file }) => {
if (!file.startsWith('test/replay-compat/')) return [];
const selections = [
reason(
'replay-compat',
file,
'own:replay-compat-provenance',
'corpus provenance is re-derived from released git blobs',
),
];
if (file.endsWith('.ad')) {
selections.push(
reason(
'unit',
file,
'own:replay-compat',
'frozen replay-compat corpus is asserted by the unit-lane corpus test',
),
);
}
return selections;
};
// The daemon RPC wire ledger (#1432). The wire SOURCE files are the ones that
// would otherwise slip: editing `packages/kernel/src/contracts.ts` selects
// vitest-related, but the wire gate reads that file as TEXT rather than
// importing it, so it is invisible to the module graph Vitest walks. The file
// list is read from the manifest instead of restated here, so a declaration
// added under a new file selects the gate the day it is listed.
//
// `ledger.json` needs the rule for the second reason `.ad` corpus data does:
// a non-.ts file under test/ resolves to `format` alone and would fail open.
// (`scripts/wire-compat/` needs no branch — all of scripts/ already fails open.)
const daemonWireCompatOwnership: OwnershipRule = ({ file }) => {
if (!file.startsWith('test/wire-compat/') && !WIRE_SURFACE_FILES.includes(file)) return [];
return [
reason(
'daemon-wire-compat',
file,
'own:daemon-wire-compat',
'the wire ledger is compared against the last released tag',
),
reason(
'unit',
file,
'own:daemon-wire-compat',
'the wire ledger is held to its source by the unit-lane gate',
),
];
};
const BUILD_OWNERSHIP: ReadonlyArray<{
check: CheckId;
rule: string;
detail: string;
owns: (file: string) => boolean;
}> = [
{
check: 'swift-runner',
rule: 'own:swift',
detail: 'Swift runner sources require the XCUITest build',
owns: (file) => file.startsWith('apple/runner/') || file.endsWith('.swift'),
},
{
check: 'android-helpers',
rule: 'own:android-helpers',
detail: 'Android helper packages have their own build',
owns: (file) =>
file.startsWith('android/snapshot-helper/') || file.startsWith('android/ime-helper/'),
},
{
check: 'macos-helper',
rule: 'own:macos-helper',
detail: 'macOS helper is a separate Swift package build',
owns: (file) => file.startsWith('apple/macos-helper/'),
},
{
check: 'mcp-metadata',
rule: 'own:mcp',
detail: 'MCP registry metadata must stay in sync',
owns: (file) => file === 'server.json' || file === 'smithery.yaml',
},
];
const buildOwnership: OwnershipRule = ({ file }, input) => {
const selections = BUILD_OWNERSHIP.filter((entry) => entry.owns(file)).map((entry) =>
reason(entry.check, file, entry.rule, entry.detail),
);
if ((input.packageEntryFiles ?? []).includes(file)) {
selections.push(
reason('build', file, 'own:public-surface', 'public package entry affects declarations'),
reason(
'package',
file,
'own:public-surface',
'a public entry must still resolve from a clean install',
),
);
}
return selections;
};
const OWNERSHIP_RULES: readonly OwnershipRule[] = [
formatGate,
staticTsGates,
srcProdGate,
vitestRelatedOwnership,
workspacePackageOwnership,
platformPackageScenarioOwnership,
nodeIntegrationOwnership,
testAppOwnership,
replayCompatOwnership,
daemonWireCompatOwnership,
buildOwnership,
];
function fileFacts(file: string): FileFacts {
const isTs = file.endsWith('.ts') && !file.endsWith('.d.ts');
const underSrc = file.startsWith('src/');
return {
file,
isTs,
underSrc,
underTest: file.startsWith('test/'),
isSrcProd: underSrc && isTs && !isTestPath(file),
};
}
function failOpenFor(file: string): FailOpenReason | null {
if (isSelectorOwning(file)) {
return {
path: file,
rule: 'selector-owning',
detail: 'change to the affected-check selector cannot be trusted to select itself',
};
}
if (isWorkflowTooling(file)) {
return {
path: file,
rule: 'workflow-tooling',
detail: 'workflow/tooling change can alter any gate',
};
}
return null;
}
// --- Selection --------------------------------------------------------------
export function selectChecks(input: SelectInput): CheckPlan {
const reasons: SelectionReason[] = [];
const failOpenReasons: FailOpenReason[] = [];
const docsOnlyPaths: string[] = [];
for (const file of input.changedFiles) {
const failOpen = failOpenFor(file);
if (failOpen) {
failOpenReasons.push(failOpen);
continue;
}
if (isDocs(file)) {
docsOnlyPaths.push(file);
continue;
}
const facts = fileFacts(file);
const selections = OWNERSHIP_RULES.flatMap((rule) => rule(facts, input));
if (selections.length === 0) {
failOpenReasons.push({
path: file,
rule: 'unknown-path',
detail: 'path has no derivable owner; run the full set to stay safe',
});
continue;
}
// `format` is an always-on gate, not evidence of test/build ownership. A
// file we can only route to formatting (e.g. a non-.ts fixture under
// test/) has no derivable suite owner, so treat it as ambiguous and fail
// open rather than silently narrowing to just `format`.
if (!selections.some((selection) => selection.check !== 'format')) {
failOpenReasons.push({
path: file,
rule: 'ambiguous-path',
detail: 'only formatting is derivable; no test/build owner, so run the full set',
});
continue;
}
reasons.push(...selections);
}
if (failOpenReasons.length > 0) {
return { failOpen: true, checks: [...ALL_CHECKS], reasons, failOpenReasons, docsOnlyPaths };
}
const selected = new Set(reasons.map((entry) => entry.check));
return {
failOpen: false,
checks: ALL_CHECKS.filter((check) => selected.has(check)),
reasons,
failOpenReasons,
docsOnlyPaths,
};
}