Files
callstack__agent-device/test/integration/provider-scenarios/transcript.ts
Michał Pierzchała 76453add71 refactor: pnpm workspace + @agent-device/kernel pilot (#1490 W0) (#1494)
* refactor: pnpm workspace + @agent-device/kernel pilot (#1490 W0)

Extend the workspace with packages/* and move the kernel behind an
enforced public API: packages/kernel with nine consumer-earned subpath
exports (errors, device, snapshot, contracts, collections, rect,
redaction, daemon-error, bounds — the last absorbed from utils as Rect
vocabulary). Every kernel import repo-wide becomes the
@agent-device/kernel/<sub> specifier; kernel tests move to
src/__tests__/kernel/ and exercise the package surface. The root
declares the package in devDependencies (workspace:*), tsdown bundles
it (noExternal) so the published artifact and its runtime dependency
manifest are unchanged.

Gate rewiring in the same change, per the W0 brief:
- R1 kernel-sink retires (physically subsumed); new R11
  package-boundaries guards no-root-back-imports, relative tunnelling
  past exports maps, undeclared workspace deps, and non-exported
  subpaths, with runtime resolution pins via import.meta.resolve.
- resolveImportEdges and mutation ownership follow workspace
  specifiers through exports maps, keeping R4 cycle checks, depgraph,
  and derived test ownership connected across the seam (kernel-errors
  still owns 495 tests). listSourceFiles includes packages/*/src.
- kernel becomes an unranked zone; mutation registry, stryker mutate
  globs, and the mutation-affected workflow path filter move to
  packages/kernel/src/errors.ts.
- check:affected gains packages/ ownership (manifests fail open);
  vitest and coverage include packages/*/src; fallow ignores
  packages/** (its resolver cannot follow workspace specifiers).
- The affected-selector CI job installs dependencies: its closure now
  crosses workspace specifiers, and the R8 relative exception is
  unsafe for production src files (Node ESM does not realpath, so dual
  specifier/relative loads would instantiate modules twice). The R8
  zero-dep set is pinned empty with that rationale.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FUv7bvbWNryuXgSBuqTtep

* fix: address W0 review — mutation sandbox, exports-map resolution, tsc -b

Review findings on #1494, all five:

1. contracts-schema-public.test.ts reads the kernel source at its
   packages/ path (fs access invisible to the codemod and typecheck).
2. Mutation lane: Stryker sandboxes the tree but pnpm's node_modules
   symlink resolves @agent-device/* back to the real repo, so mutants
   in the sandbox never load and vitest.related finds no tests.
   vitest.mutation.config.ts now aliases each EXPORTED specifier to
   its source (derived from exports maps, never a wildcard), keeping
   resolution inside the mutated tree. Validated: kernel-errors module
   runs end to end (dry run 3,984 tests, mutants killed, exit 0).
3. Layering/depgraph resolve workspace specifiers through the
   exports-derived map (workspaceSpecifierTargets) instead of
   reconstructing paths, so '.'-facade packages resolve; the
   positional fallback remains only for map-less fixtures (P0 pin).
4. Per-package project references implemented: packages/kernel is
   composite (emitDeclarationOnly -> dist-types, gitignored), the root
   references it, and typecheck becomes tsc -b — probed to catch type
   errors on both sides under TypeScript 7 native.
5. R11's relative-route exception now requires membership in an actual
   R8 zero-dep job closure (zeroDepClosureFiles walks entries), not
   mere scripts/ placement — closing the dual-instantiation bypass.

Also from review discussion: daemon-error moves out of the kernel
package to src/client/ — its consumers (cli, client facade) rehydrate
wire DaemonErrors client-side; the daemon only produces them. Kernel
drops to 8 exported subpaths before any of them ship.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FUv7bvbWNryuXgSBuqTtep

* refactor: one exports-map reader for mutation alias and ownership

Fallow flagged workspaceExportAliases (cognitive 15, CRAP 90). The
manifest-reading logic already exists as workspaceSpecifierTargets in
scripts/layering/package-boundaries.ts, so both the Stryker sandbox
alias table and the mutation ownership walker now consume it instead
of carrying near-clones. Behavior unchanged; mutation suite 45/45 and
changed-code fallow green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FUv7bvbWNryuXgSBuqTtep

* fix: composite kernel without a root references edge

FreeRange runs plain `tsc -p tsconfig.json`, and a root `references`
entry makes non-build-mode TypeScript demand the referenced project's
built declarations (TS6305) — a standing "build first" tax on every
plain -p consumer (fr, editors). Keep the per-package composite
project and build it in typecheck (`tsc -b packages/kernel` before the
root and examples/sdk passes), but drop the root references edge: root
consumption resolves through exports to source, identical to runtime
and to the bundler. Probed: plain -p green with no prebuilt output;
kernel-side type errors still caught by its own build.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FUv7bvbWNryuXgSBuqTtep

* fix: R11 uses the layering parser; mutation config is a fallow entry

Review blockers on #1494:

- R11's private single-quote regex could miss a double-quoted or
  re-export route into packages/*/src. specifierSites now delegates to
  the layering model's parseImports (both quote styles, side-effect
  imports, re-exports, dynamic imports), with direct regressions for
  each formerly-invisible form.
- vitest.mutation.config.ts becomes a declared fallow entry instead of
  a tolerated unused-file finding: the full-repo audit now reports it
  reachable (unused files 2 -> 1; the remainder predates this PR).

FreeRange clean-checkout evidence: with packages/kernel/dist-types and
every *.tsbuildinfo deleted, `pnpm check:freerange` reports 0 findings
on this head — the TS6305 topology died with the root references edge
in the previous commit; check:freerange has no build precondition.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FUv7bvbWNryuXgSBuqTtep

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-07-30 12:12:46 +02:00

172 lines
5.8 KiB
TypeScript

import assert from 'node:assert/strict';
import { isDeepStrictEqual } from 'node:util';
import type { Platform } from '@agent-device/kernel/device';
export interface ProviderScenarioProviderScope {
deviceId?: string;
platform?: Platform;
}
export interface ProviderScenarioProviderEntry<
TResult = unknown,
> extends ProviderScenarioProviderScope {
command: string;
request?: unknown;
/** A factory is invoked per call, so repeated calls can return fresh results. */
result?: TResult | (() => TResult);
/**
* Serves every matching call instead of being consumed by the first, and never
* counts as unconsumed. Use it where the call COUNT is not the contract — a
* quiet UI returns the same tree to every capture, a busy one returns a fresh
* tree per capture (pair with a `result` factory). Scripting an exact count
* there would assert the runner's speed rather than the behaviour.
*
* A repeat is the FALLBACK for its command: matching one-shot entries are
* always served first, whatever order the entries are declared in, so a
* repeat can never strand one. Unsupported in ordered transcripts, where a
* repeat would never advance the queue.
*/
repeat?: boolean;
error?: Error | string;
}
export interface ProviderScenarioProviderCall<
TResult = unknown,
> extends ProviderScenarioProviderScope {
command: string;
request?: unknown;
result?: TResult;
}
export interface ProviderScenarioTranscript {
readonly calls: readonly ProviderScenarioProviderCall[];
readonly remaining: readonly ProviderScenarioProviderEntry[];
next<TResult = unknown>(
command: string,
request?: unknown,
scope?: ProviderScenarioProviderScope,
): TResult;
assertComplete(): void;
}
export function createProviderTranscript(
entries: readonly ProviderScenarioProviderEntry[],
options: { ordered?: boolean } = {},
): ProviderScenarioTranscript {
if (options.ordered && entries.some((entry) => entry.repeat)) {
throw new Error(
'Ordered provider transcripts cannot use `repeat` entries: ordered lookup only reads the head, so a repeat never advances and strands every entry behind it.',
);
}
const pending = [...entries];
const calls: ProviderScenarioProviderCall[] = [];
return {
get calls() {
return [...calls];
},
get remaining() {
return [...pending];
},
next<TResult = unknown>(
command: string,
request?: unknown,
scope: ProviderScenarioProviderScope = {},
): TResult {
const entryIndex = options.ordered ? 0 : findEntryIndex(pending, command, request, scope);
const entry = entryIndex >= 0 ? pending[entryIndex] : undefined;
assert.ok(entry, `Unexpected provider call: ${formatCall(command, scope)}`);
if (!entry.repeat) pending.splice(entryIndex, 1);
assert.equal(command, entry.command, 'Provider command mismatch');
assertScope(scope, entry);
if (Object.hasOwn(entry, 'request')) {
assert.deepEqual(request, entry.request, 'Provider request mismatch');
}
const result = resolveEntryResult(entry) as TResult;
const call = {
command,
request,
deviceId: scope.deviceId,
platform: scope.platform,
result,
};
calls.push(call);
if (entry.error) {
throw entry.error instanceof Error ? entry.error : new Error(entry.error);
}
return result;
},
assertComplete() {
const outstanding = pending.filter((entry) => !entry.repeat);
assert.equal(
outstanding.length,
0,
`Unconsumed provider transcript entries: ${outstanding.map(formatEntry).join(', ')}`,
);
},
};
}
export function createOrderedProviderTranscript(
entries: readonly ProviderScenarioProviderEntry[],
): ProviderScenarioTranscript {
return createProviderTranscript(entries, { ordered: true });
}
/**
* One-shot entries are served before repeats regardless of declaration order: a
* repeat is its command's fallback, so taking the first match would let one
* shadow a one-shot forever and strand it as permanently unconsumed.
*/
function findEntryIndex(
pending: readonly ProviderScenarioProviderEntry[],
command: string,
request: unknown,
scope: ProviderScenarioProviderScope,
): number {
const matches = (candidate: ProviderScenarioProviderEntry): boolean =>
providerEntryMatches(candidate, command, request, scope);
const oneShotIndex = pending.findIndex((candidate) => !candidate.repeat && matches(candidate));
return oneShotIndex >= 0 ? oneShotIndex : pending.findIndex(matches);
}
function resolveEntryResult(entry: ProviderScenarioProviderEntry): unknown {
return typeof entry.result === 'function' ? (entry.result as () => unknown)() : entry.result;
}
function providerEntryMatches(
entry: ProviderScenarioProviderEntry,
command: string,
request: unknown,
scope: ProviderScenarioProviderScope,
): boolean {
if (entry.command !== command) return false;
if (entry.deviceId && entry.deviceId !== scope.deviceId) return false;
if (entry.platform && entry.platform !== scope.platform) return false;
return !Object.hasOwn(entry, 'request') || isDeepStrictEqual(request, entry.request);
}
function assertScope(
actual: ProviderScenarioProviderScope,
expected: ProviderScenarioProviderEntry,
): void {
if (expected.deviceId) {
assert.equal(actual.deviceId, expected.deviceId, 'Provider device id mismatch');
}
if (expected.platform) {
assert.equal(actual.platform, expected.platform, 'Provider platform mismatch');
}
}
function formatCall(command: string, scope: ProviderScenarioProviderScope): string {
return formatEntry({ command, ...scope });
}
function formatEntry(entry: { command: string; deviceId?: string; platform?: Platform }): string {
const scope = [entry.platform, entry.deviceId].filter(Boolean).join(':');
return scope ? `${scope}.${entry.command}` : entry.command;
}