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

311 lines
12 KiB
TypeScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { test } from 'node:test';
import { fileURLToPath } from 'node:url';
import { assertCatalogComplete, CHECK_CATALOG, resolveCommand } from './checks.ts';
import { ALL_CHECKS, selectChecks, type CheckId, type SelectInput } from './model.ts';
function plan(changedFiles: string[], extra: Partial<SelectInput> = {}) {
return selectChecks({
changedFiles,
packageEntryFiles: ['src/index.ts', 'packages/selectors/src/index.ts'],
...extra,
});
}
function ids(changedFiles: string[]): CheckId[] {
return plan(changedFiles).checks;
}
test('production source selects static/build gates and delegates tests to Vitest', () => {
const result = plan(['packages/selectors/src/index.ts']);
assert.equal(result.failOpen, false);
for (const id of [
'format',
'lint',
'typecheck',
'layering',
'build',
'vitest-related',
] as const) {
assert.ok(result.checks.includes(id), `expected ${id}`);
}
assert.ok(!result.checks.includes('provider-integration'));
// Every selected check documents why it was chosen.
for (const id of result.checks) {
assert.ok(result.reasons.some((reason) => reason.check === id));
}
});
test('platform source additionally selects provider-integration', () => {
const result = ids(['src/platforms/apple/core/apps.ts']);
assert.ok(result.includes('provider-integration'));
assert.ok(result.includes('coverage'));
assert.ok(result.includes('vitest-related'));
});
test('unit test files delegate affected-test discovery to Vitest', () => {
const result = ids(['src/daemon/selectors.test.ts']);
assert.ok(result.includes('vitest-related'));
assert.ok(!result.includes('unit'));
assert.ok(!result.includes('provider-integration'));
});
test('Vitest owns project and support-module relationships through one check', () => {
for (const file of [
'test/integration/provider-scenarios/foo.test.ts',
'test/integration/provider-scenarios/fixtures.ts',
'test/integration/interaction-contract/fixtures.ts',
'test/output-economy/fixtures.ts',
'src/__tests__/test-utils/session.ts',
]) {
assert.ok(ids([file]).includes('vitest-related'), `expected Vitest ownership for ${file}`);
}
});
test('root node-integration support modules select the node integration suite', () => {
assert.ok(ids(['test/integration/test-helpers.ts']).includes('integration-node'));
});
test('android-adb stub test delegates project ownership to Vitest', () => {
const result = ids(['src/platforms/android/__tests__/notifications.test.ts']);
assert.ok(result.includes('vitest-related'));
});
test('Swift runner change selects the swift-runner build', () => {
assert.deepEqual(ids(['apple/runner/Sources/Runner/Main.swift']), ['swift-runner']);
assert.ok(ids(['src/platforms/apple/core/runner/Support.swift']).includes('swift-runner'));
});
test('Android helper change selects the android-helpers build', () => {
assert.deepEqual(ids(['android/snapshot-helper/src/Main.kt']), ['android-helpers']);
assert.deepEqual(ids(['android/ime-helper/AndroidManifest.xml']), ['android-helpers']);
});
test('MCP metadata change selects the mcp-metadata check', () => {
assert.deepEqual(ids(['server.json']), ['mcp-metadata']);
});
test('public package surface change selects the build and the published-package gate via exports', () => {
const result = ids(['src/index.ts']);
assert.ok(result.includes('build'));
// A public entry is the one surface a consumer resolves by name, so building it is not enough:
// check:package proves it still imports from an install with no workspace links.
assert.ok(result.includes('package'));
assert.ok(ids(['packages/selectors/src/index.ts']).includes('package'));
});
test('docs-only change selects no checks and records the docs paths', () => {
const result = plan(['docs/adr/0011.md', 'README.md', 'website/page.mdx.md']);
assert.equal(result.failOpen, false);
assert.deepEqual(result.checks, []);
assert.equal(result.docsOnlyPaths.length, 3);
});
test('test app source selects root lint and format plus its isolated typecheck', () => {
const result = plan(['examples/test-app/app/index.tsx']);
assert.equal(result.failOpen, false);
assert.deepEqual(result.checks, ['format', 'lint', 'test-app-typecheck']);
});
test('unknown path fails open to the full check set', () => {
const result = plan(['fixtures/unknown.data']);
assert.equal(result.failOpen, true);
assert.deepEqual(result.checks, [...ALL_CHECKS]);
assert.equal(result.failOpenReasons[0]?.rule, 'unknown-path');
});
test('a non-.ts fixture under an owned root fails open (format alone is not ownership)', () => {
const result = plan(['test/integration/provider-scenarios/fixtures/device.json']);
assert.equal(result.failOpen, true);
assert.deepEqual(result.checks, [...ALL_CHECKS]);
assert.equal(result.failOpenReasons[0]?.rule, 'ambiguous-path');
});
test('a frozen replay-compat corpus script selects the unit lane and the provenance verifier', () => {
const result = plan(['test/replay-compat/scripts/examples/gesture-lab.v0.16.8.ad']);
assert.equal(result.failOpen, false);
assert.ok(result.checks.includes('unit'));
assert.ok(result.checks.includes('replay-compat'));
});
test('a replay-compat manifest edit selects the provenance verifier', () => {
const result = plan(['test/replay-compat/manifest.ts']);
assert.equal(result.failOpen, false);
assert.ok(result.checks.includes('replay-compat'));
});
test('skills guidance change is docs-only', () => {
const result = plan(['skills/agent-device/SKILL.md']);
assert.equal(result.failOpen, false);
assert.deepEqual(result.docsOnlyPaths, ['skills/agent-device/SKILL.md']);
assert.deepEqual(result.checks, []);
});
test('workspace package source selects static gates, fallow, layering, and the build', () => {
for (const file of [
'packages/kernel/src/errors.ts',
'packages/contracts/src/facades/device.ts',
'packages/capture-kit/src/app-log-live-handle.ts',
]) {
const result = plan([file]);
assert.equal(result.failOpen, false, file);
for (const id of [
'format',
'lint',
'typecheck',
// Package source is inside fallow's scope; an extraction into packages/
// must not take a symbol's dead-code coverage with it.
'fallow',
'layering',
'build',
'vitest-related',
] as const) {
assert.ok(result.checks.includes(id), `expected ${id} for ${file}`);
}
}
});
test('a workspace package manifest fails open — it rewires resolution globally', () => {
const result = plan(['packages/kernel/package.json']);
assert.equal(result.failOpen, true);
assert.equal(result.failOpenReasons[0]?.rule, 'workflow-tooling');
});
test('workflow/tooling and selector-owning changes fail open', () => {
assert.equal(plan(['.github/workflows/ci.yml']).failOpenReasons[0]?.rule, 'workflow-tooling');
assert.equal(plan(['package.json']).failOpenReasons[0]?.rule, 'workflow-tooling');
assert.equal(plan(['vitest.config.ts']).failOpenReasons[0]?.rule, 'workflow-tooling');
assert.equal(
plan(['scripts/check-affected/model.ts']).failOpenReasons[0]?.rule,
'selector-owning',
);
// The Testing Matrix lives here; a matrix edit must outrank the docs-only
// short-circuit that its `docs/` path would otherwise take.
assert.equal(plan(['docs/agents/testing.md']).failOpenReasons[0]?.rule, 'selector-owning');
});
test('a fail-open path in a mixed changeset forces the full set', () => {
const result = plan(['packages/selectors/src/index.ts', 'bin/agent-device.mjs']);
assert.equal(result.failOpen, true);
assert.deepEqual(result.checks, [...ALL_CHECKS]);
});
test('empty changeset selects nothing', () => {
const result = plan([]);
assert.equal(result.failOpen, false);
assert.deepEqual(result.checks, []);
});
test('catalog covers exactly the CheckId universe', () => {
assert.doesNotThrow(assertCatalogComplete);
});
test('every catalog command resolves against package scripts', () => {
const scripts: Record<string, string> = {
'format:check': 'x',
lint: 'x',
typecheck: 'x',
'test-app:typecheck': 'x',
'check:layering': 'x',
'check:fallow': 'x',
'check:mcp-metadata': 'x',
build: 'x',
'check:package': 'x',
'check:unit': 'x',
'check:coverage-changed': 'x',
'test:coverage': 'x',
'test:integration:provider': 'x',
'test:integration:node': 'x',
'test:integration:progress:check': 'x',
'build:xcuitest': 'x',
'build:android-snapshot-helper': 'x',
'build:macos-helper': 'x',
'test:smoke:web': 'x',
'check:replay-compat': 'x',
'check:daemon-wire-compat': 'x',
};
for (const spec of CHECK_CATALOG) {
const command = resolveCommand(spec, scripts, 'origin/main');
assert.ok(command.length >= 2);
}
const fallow = CHECK_CATALOG.find((spec) => spec.id === 'fallow')!;
assert.deepEqual(resolveCommand(fallow, scripts, 'origin/dev'), [
'pnpm',
'run',
'check:fallow',
'--base',
'origin/dev',
]);
});
test('a missing package script makes command resolution throw', () => {
const spec = CHECK_CATALOG.find((entry) => entry.id === 'lint')!;
assert.throws(() => resolveCommand(spec, {}, 'origin/main'), /does not exist/);
});
test('unit and coverage checks preserve their package-script owners', () => {
const scripts = { 'check:unit': 'x', 'check:coverage-changed': 'x' };
const unit = CHECK_CATALOG.find((entry) => entry.id === 'unit')!;
const coverage = CHECK_CATALOG.find((entry) => entry.id === 'coverage')!;
assert.deepEqual(resolveCommand(unit, scripts, 'origin/main'), ['pnpm', 'run', 'check:unit']);
assert.deepEqual(resolveCommand(coverage, scripts, 'origin/main'), [
'pnpm',
'run',
'check:coverage-changed',
]);
});
test('vitest-related delegates changed paths to Vitest instead of modeling projects', () => {
const related = CHECK_CATALOG.find((entry) => entry.id === 'vitest-related')!;
assert.deepEqual(resolveCommand(related, {}, 'origin/main', ['src/a.ts', 'test/fixture.ts']), [
'pnpm',
'exec',
'vitest',
'related',
'--run',
'--passWithNoTests',
'src/a.ts',
'test/fixture.ts',
]);
});
// Guards the catalog against reality, not fixtures: the self-test above uses a
// hand-built scripts map, so this resolves every catalog entry against the real
// package.json. A renamed/removed script fails here instead of
// leaving `pnpm check:affected` broken on the exact command the docs advertise.
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
test('catalog resolves against the real package.json', () => {
const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')) as {
scripts?: Record<string, string>;
};
const scripts = pkg.scripts ?? {};
for (const spec of CHECK_CATALOG) {
assert.doesNotThrow(
() => resolveCommand(spec, scripts, 'origin/main'),
`catalog entry "${spec.id}" must resolve against the real package.json`,
);
}
});
test('every catalog CI job maps to a real workflow job (no fabricated checks)', () => {
const workflowsDir = path.join(repoRoot, '.github', 'workflows');
const workflows = fs
.readdirSync(workflowsDir)
.filter((file) => file.endsWith('.yml') || file.endsWith('.yaml'))
.map((file) => fs.readFileSync(path.join(workflowsDir, file), 'utf8'))
.join('\n');
for (const spec of CHECK_CATALOG) {
for (const job of spec.ciJobs) {
// GitHub renders check names as "<workflow> / <job>"; match on the job.
const jobName = job.includes(' / ') ? job.slice(job.lastIndexOf(' / ') + 3) : job;
assert.ok(
workflows.includes(`name: ${jobName}`),
`catalog check "${spec.id}" references CI job "${job}", but no workflow defines "${jobName}"`,
);
}
}
});