Skip to content

Commit d3adea4

Browse files
Project navigation contracts and add a network digest (#1208)
* test: record contract and digest spike selection Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: project navigation client and MCP contracts from executable definitions Collapse the three independent per-command projection declarations (facet clientMethod, public client method signature, MCP output schema) for the typed system navigation subset (home, back, rotate, app-switcher, tv-remote) onto a single colocated projection in src/contracts/navigation.ts. The family builder, public client type, and MCP schema map now derive from those five projections. Refs #1185 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat: add opt-in network response digest Preserve every network entry and top-level recovery/actionability signal while dropping only verbose per-entry header, body, and raw-log fields at digest response level. Record deterministic output-economy baselines and parity tests. Refs #1186 Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Michał Pierzchała <[email protected]> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 0a8ea3a commit d3adea4

16 files changed

Lines changed: 817 additions & 84 deletions
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
# Contract projection and output-economy spike
2+
3+
Issues: #1185, #1186
4+
5+
This report keeps the two experiments bounded: one typed command family for executable contract
6+
projection and one opt-in response family for digest expansion.
7+
8+
## Selection evidence
9+
10+
### Executable contract: typed system navigation
11+
12+
Selected commands:
13+
14+
- `home`
15+
- `back`
16+
- `rotate`
17+
- `app-switcher`
18+
- `tv-remote`
19+
20+
These commands already have closed neutral results in `src/contracts/navigation.ts`, typed
21+
`CommandResultMap` entries, executable definitions, Node client methods, and MCP output schemas.
22+
They do not overlap the broad-return client methods being changed under #1183.
23+
24+
The baseline has three independent command-to-surface declarations per selected command:
25+
26+
1. the facet's client-method mapping;
27+
2. the public client method signature;
28+
3. the keyed MCP output-schema entry.
29+
30+
That is 15 independent projection declarations around five executable definitions. The spike will
31+
make each executable definition the single command-to-client/MCP projection declaration and derive
32+
the client surface and MCP schema map from those five definitions. Success is five declarations
33+
instead of 15, without changing CLI, daemon, client, or MCP behavior.
34+
35+
The experiment stops at these five commands. It must not continue if it needs generated source, a
36+
schema DSL, a new dependency, a parallel registry, a new import back-edge, weaker parity checks,
37+
more hand-authored declarations, or a measurable cold-start or bundle regression.
38+
39+
### Digest response: network observations
40+
41+
Deterministic representative payloads rank the unregistered candidates as follows:
42+
43+
| Family | Default bytes | Conservative digest estimate | Reduction | Selection |
44+
|---|---:|---:|---:|---|
45+
| network (`include=all`) | 26,371 | 1,665 | 24,706 (93.7%) | selected |
46+
| events | 7,686 | 3,375 | 4,311 (56.1%) | rejected |
47+
| debug symbols | 4,804 | 2,054 | 2,750 (57.2%) | rejected |
48+
| recording | 3,132 | 2,427 | 705 (22.5%) | rejected |
49+
50+
The network estimate removes only repeated payload material from each entry (`headers`,
51+
`requestHeaders`, `responseHeaders`, `requestBody`, `responseBody`, and `raw`). It retains every
52+
entry and its method, URL, status, timestamp, duration, packet ID, and source line, plus top-level
53+
path/state/backend/include, limits, scan counts, notes, and additive fields.
54+
55+
The other candidates require less conservative compromises:
56+
57+
- event `details` can contain refs, error identity, request logs, and recovery data;
58+
- debug frames and matched images are the diagnostic evidence;
59+
- recording chunks and artifacts are retrieval handles.
60+
61+
The existing routine-workflow oracle remains the actionability floor: 2,276 total bytes across
62+
seven commands, zero fallback observations, exactly one retry, and all in-session recovery handles
63+
preserved. The network addition must keep those measurements unchanged and separately prove that a
64+
failed request remains identifiable and actionable from the digest.
65+
66+
## Measurement plan
67+
68+
- Declaration count: count independent selected-command projection declarations before and after.
69+
- Runtime: compare median cold imports of the MCP command-tool projection at the merge base and
70+
spike head.
71+
- Bundle: compare `pnpm size` raw/gzip totals and relevant chunks at the merge base and spike head.
72+
- Dependencies: run the layering/back-edge gate and verify no package dependency changes.
73+
- Output economy: commit default and digest bytes, then assert default byte identity, retained
74+
request identity/recovery notes, and unchanged routine-workflow fallback/retry counts.
75+
76+
The merge-base size baseline is 1,659,106 raw JS bytes, 529,658 gzip bytes, and 636,721 tarball
77+
bytes on Node 24.13.0.
78+
79+
## Contract projection results (#1185)
80+
81+
The five selected navigation commands now carry one colocated projection declaration each in
82+
`src/commands/system/navigation-projection.ts` (`NAVIGATION_COMMAND_PROJECTIONS`): client-method name, public option
83+
shape, closed result type, and MCP `outputSchema`. The family builder derives `clientCommandMethods`
84+
from those projections, `AgentDeviceCommandClient` derives the five navigation methods via
85+
`ProjectedNavigationCommandClient`, and `COMMAND_OUTPUT_SCHEMAS` spreads the projected schemas.
86+
87+
- Declarations: 15 -> 5 (10 fewer). Removed the per-command facet `clientMethod`, the hand-written
88+
client method signature, and the hand-authored MCP schema entry.
89+
- Behavior: CLI, daemon, client runtime, and MCP output schemas unchanged (unit/client/MCP tests pass).
90+
- Bundle: +773 B raw JS, +146 B gzip, +620 B tarball; no material chunk regression, no dependency change.
91+
- Runtime: CLI --version 20.3 ms / --help 39.5 ms median (20 runs); no cold-start regression.
92+
- Layering/Fallow: green; no new value back-edge (type-only import from client, value import only
93+
from the already-command-importing MCP schema map).
94+
95+
Recommendation: #1185 should CONTINUE incrementally, one already-typed closed-contract family at a
96+
time, re-measuring declarations and bundle each step and stopping on any stop condition.
97+
98+
## Digest expansion results (#1186)
99+
100+
Added one conservative, opt-in `network` response view in `src/daemon/response-views.ts`
101+
(registered as `RESPONSE_VIEWS.network`). It acts ONLY at `responseLevel: 'digest'`; `default`
102+
and `full` return the same object reference, so the default wire shape stays byte-identical
103+
(Maestro `.ad` recompare safe) and live metrics remain informational.
104+
105+
Transformation: the entire top-level dump (`path`, `exists`, `active`, `state`, `backend`,
106+
`include`, `scannedLines`, `matchedLines`, `limits`, `notes`, and any additive fields) is
107+
preserved, EVERY entry is preserved (none dropped, capped, or reordered), and only the verbose
108+
per-entry payload fields are removed: `headers`, `requestHeaders`, `responseHeaders`,
109+
`requestBody`, `responseBody`, `raw`. Each entry keeps its actionable identity — `method`, `url`,
110+
`status`, `timestamp`, `durationMs`, `packetId`, `line`, and any additive fields such as
111+
`metadata`.
112+
113+
Measured on the deterministic `selection.network` fixture (`network ... --include all`, 8 entries):
114+
115+
- Output bytes: 26,371 -> 1,665 (24,706 fewer / 93.7% reduction).
116+
- Entries preserved: 8 -> 8 (no follow-up refetch needed; identity intact).
117+
- Follow-up actionability: the failed POST keeps method/url/status/packetId/duration/timestamp and
118+
the top-level recovery note, so the retry path is unchanged (no extra follow-up calls implied).
119+
- Fallback observations: 0 (routine-workflow oracle unchanged).
120+
- Retries: 1 (routine-workflow oracle unchanged).
121+
- Recovery/session fields: preserved (routine-workflow oracle unchanged).
122+
123+
Defaults are unchanged; the digest is strictly opt-in via a non-default response level. Residual
124+
risk: the dropped-field set is intentionally specific to the known verbose network payload fields;
125+
if a backend introduces a new large per-entry field it would remain until added to the drop list
126+
(safe by default — unknown fields are preserved, never silently narrowed).

‎src/agent-device-client.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,10 @@ import { readSerializedSnapshotCaptureAnnotations } from './snapshot-capture-ann
6464
import { readSnapshotDiagnosticsSummary } from './snapshot-diagnostics.ts';
6565
import type { CommandFlags } from './core/dispatch-context.ts';
6666
import type { AgentArtifactsResult } from './cloud-artifacts.ts';
67+
import type { ProjectedNavigationCommandClient } from './commands/system/navigation-projection.ts';
6768

68-
type ProjectedSystemCommandClient = Pick<
69-
AgentDeviceCommandClient,
70-
'appState' | 'back' | 'home' | 'rotate' | 'appSwitcher' | 'keyboard' | 'clipboard' | 'tvRemote'
71-
>;
69+
type ProjectedSystemCommandClient = ProjectedNavigationCommandClient<InternalRequestOptions> &
70+
Pick<AgentDeviceCommandClient, 'appState' | 'keyboard' | 'clipboard'>;
7271

7372
export function createAgentDeviceClient(
7473
config: AgentDeviceClientConfig = {},

‎src/client/client-types.ts‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,17 @@ import type { BackMode } from '../contracts/back-mode.ts';
2323
import type { ClickButton } from '../core/click-button.ts';
2424
import type { RecordingExportQuality } from '../core/recording-export-quality.ts';
2525
import type { RecordingScope } from '../contracts/recording-scope.ts';
26-
import type { DeviceRotation } from '../contracts/device-rotation.ts';
27-
import type { TvRemoteButton } from '../contracts/tv-remote.ts';
2826
import type {
2927
ScrollDirection,
3028
SwipePattern,
3129
SwipePreset,
3230
TransformGestureParams,
3331
} from '../contracts/scroll-gesture.ts';
3432
import type { ScrollInputDirection } from '../commands/interaction/runtime/gestures.ts';
33+
import type {
34+
NavigationCommandOptions,
35+
ProjectedNavigationCommandClient,
36+
} from '../commands/system/navigation-projection.ts';
3537
import type { LogAction } from '../contracts/logs.ts';
3638
import type { SessionSurface } from '../contracts/session-surface.ts';
3739
import type { FindLocator } from '../selectors/find.ts';
@@ -534,17 +536,12 @@ export type AlertCommandResult = DaemonResponseData & {
534536

535537
export type AppStateCommandOptions = DeviceCommandBaseOptions;
536538

537-
export type BackCommandOptions = DeviceCommandBaseOptions & {
538-
mode?: BackMode;
539-
};
540-
541-
type HomeCommandOptions = DeviceCommandBaseOptions;
539+
export type BackCommandOptions = DeviceCommandBaseOptions & NavigationCommandOptions<'back'>;
542540

543-
export type RotateCommandOptions = DeviceCommandBaseOptions & {
544-
orientation: DeviceRotation;
545-
};
541+
export type RotateCommandOptions = DeviceCommandBaseOptions & NavigationCommandOptions<'rotate'>;
546542

547-
export type AppSwitcherCommandOptions = DeviceCommandBaseOptions;
543+
export type AppSwitcherCommandOptions = DeviceCommandBaseOptions &
544+
NavigationCommandOptions<'app-switcher'>;
548545

549546
export type KeyboardCommandOptions = DeviceCommandBaseOptions & {
550547
action?: 'status' | 'dismiss' | 'enter' | 'return';
@@ -559,10 +556,8 @@ export type ClipboardCommandOptions =
559556
text: string;
560557
});
561558

562-
export type TvRemoteCommandOptions = DeviceCommandBaseOptions & {
563-
button: TvRemoteButton;
564-
durationMs?: number;
565-
};
559+
export type TvRemoteCommandOptions = DeviceCommandBaseOptions &
560+
NavigationCommandOptions<'tv-remote'>;
566561

567562
export type ReactNativeCommandOptions = DeviceCommandBaseOptions & {
568563
action: 'dismiss-overlay';
@@ -583,17 +578,12 @@ export type ViewportCommandOptions = DeviceCommandBaseOptions & {
583578
height: number;
584579
};
585580

586-
export type AgentDeviceCommandClient = {
581+
type NonNavigationCommandClient = {
587582
wait: (options: WaitCommandOptions) => Promise<CommandResult<'wait'>>;
588583
alert: (options?: AlertCommandOptions) => Promise<CommandRequestResult>;
589584
appState: (options?: AppStateCommandOptions) => Promise<CommandResult<'appstate'>>;
590-
back: (options?: BackCommandOptions) => Promise<CommandResult<'back'>>;
591-
home: (options?: HomeCommandOptions) => Promise<CommandResult<'home'>>;
592-
rotate: (options: RotateCommandOptions) => Promise<CommandResult<'rotate'>>;
593-
appSwitcher: (options?: AppSwitcherCommandOptions) => Promise<CommandResult<'app-switcher'>>;
594585
keyboard: (options?: KeyboardCommandOptions) => Promise<CommandResult<'keyboard'>>;
595586
clipboard: (options: ClipboardCommandOptions) => Promise<CommandResult<'clipboard'>>;
596-
tvRemote: (options: TvRemoteCommandOptions) => Promise<CommandResult<'tv-remote'>>;
597587
reactNative: (options: ReactNativeCommandOptions) => Promise<CommandRequestResult>;
598588
doctor: (options?: DoctorCommandOptions) => Promise<CommandResult<'doctor'>>;
599589
/**
@@ -604,6 +594,9 @@ export type AgentDeviceCommandClient = {
604594
viewport: (options: ViewportCommandOptions) => Promise<CommandResult<'viewport'>>;
605595
};
606596

597+
export type AgentDeviceCommandClient = ProjectedNavigationCommandClient<DeviceCommandBaseOptions> &
598+
NonNavigationCommandClient;
599+
607600
type SelectorSnapshotCommandOptions = Pick<CaptureSnapshotOptions, 'depth' | 'scope' | 'raw'>;
608601
type FindSnapshotCommandOptions = Pick<CaptureSnapshotOptions, 'depth' | 'raw'>;
609602

‎src/commands/command-contract.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ export type ExecutableCommandContract<Name extends string, Input, Result> = Comm
3030
invoke: (client: AgentDeviceClient, input: unknown) => Promise<Result>;
3131
};
3232

33+
export type ExecutableCommandProjection<ClientMethod extends string = string> = {
34+
clientMethod: ClientMethod;
35+
outputSchema: JsonSchema;
36+
};
37+
3338
export type CliOutput = {
3439
data: unknown;
3540
jsonData?: unknown;
@@ -46,10 +51,32 @@ export function defineCommandMetadata<Name extends string, Input>(
4651
export function defineExecutableCommand<Name extends string, Input, Result>(
4752
metadata: CommandMetadata<Name, Input>,
4853
run: (client: AgentDeviceClient, input: Input) => Promise<Result>,
49-
): ExecutableCommandContract<Name, Input, Result> {
54+
): ExecutableCommandContract<Name, Input, Result>;
55+
56+
export function defineExecutableCommand<
57+
Name extends string,
58+
Input,
59+
Result,
60+
const ClientMethod extends string,
61+
>(
62+
metadata: CommandMetadata<Name, Input>,
63+
run: (client: AgentDeviceClient, input: Input) => Promise<Result>,
64+
projection: ExecutableCommandProjection<ClientMethod>,
65+
): ExecutableCommandContract<Name, Input, Result> & {
66+
projection: ExecutableCommandProjection<ClientMethod>;
67+
};
68+
69+
export function defineExecutableCommand<Name extends string, Input, Result>(
70+
metadata: CommandMetadata<Name, Input>,
71+
run: (client: AgentDeviceClient, input: Input) => Promise<Result>,
72+
projection?: ExecutableCommandProjection,
73+
): ExecutableCommandContract<Name, Input, Result> & {
74+
projection?: ExecutableCommandProjection;
75+
} {
5076
return {
5177
...metadata,
5278
run,
5379
invoke: async (client, input) => await run(client, metadata.readInput(input)),
80+
...(projection ? { projection } : {}),
5481
};
5582
}

‎src/commands/family/types.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import type { AgentDeviceClient } from '../../client/client-types.ts';
22
import type { CommandSchemaOverride } from '../../cli-schema/types.ts';
33
import type { CliReader, DaemonWriter } from '../cli-grammar/types.ts';
4-
import type { CommandMetadata, JsonSchema } from '../command-contract.ts';
4+
import type {
5+
CommandMetadata,
6+
ExecutableCommandProjection,
7+
JsonSchema,
8+
} from '../command-contract.ts';
59
import type { CliOutputFormatter } from '../output-common.ts';
610

711
export type AnyCommandMetadata<Name extends string = string> = CommandMetadata<Name, unknown>;
@@ -11,6 +15,7 @@ export type AnyCommandDefinition<Name extends string = string> = {
1115
description: string;
1216
inputSchema: JsonSchema;
1317
invoke: (client: AgentDeviceClient, input: unknown) => Promise<unknown>;
18+
projection?: ExecutableCommandProjection;
1419
};
1520

1621
export type CommandFamilyFacet<TCommandName extends string = string> = {
@@ -47,6 +52,13 @@ type CommandFacetDefinitions<TCommands extends readonly CommandFacet[]> = {
4752

4853
type CommandFacetName<TCommands extends readonly CommandFacet[]> = TCommands[number]['name'];
4954

55+
export type ProjectedCommandOutputSchemas<TDefinitions extends readonly AnyCommandDefinition[]> = {
56+
[TDefinition in Extract<
57+
TDefinitions[number],
58+
{ projection: ExecutableCommandProjection }
59+
> as TDefinition['name']]: JsonSchema;
60+
};
61+
5062
export function defineCommandFacet<
5163
const TCommandName extends string,
5264
const TCommand extends CommandFacet<TCommandName>,
@@ -68,13 +80,9 @@ export function defineCommandFamilyFromFacets<
6880
if (command.cliSchema) {
6981
addRecordEntry(cliSchemas, 'CLI schema', command.name, command.cliSchema);
7082
}
71-
if (command.clientMethod) {
72-
addRecordEntry(
73-
clientCommandMethods,
74-
'client command method',
75-
command.clientMethod,
76-
command.name,
77-
);
83+
const clientMethod = command.definition.projection?.clientMethod ?? command.clientMethod;
84+
if (clientMethod) {
85+
addRecordEntry(clientCommandMethods, 'client command method', clientMethod, command.name);
7886
}
7987
addRecordEntry(cliReaders, 'CLI reader', command.name, command.cliReader);
8088
if (command.daemonWriter) {
@@ -115,6 +123,23 @@ export function defineCommandFamilyFromFacets<
115123
};
116124
}
117125

126+
export function projectCommandOutputSchemas<
127+
const TDefinitions extends readonly AnyCommandDefinition[],
128+
>(definitions: TDefinitions): ProjectedCommandOutputSchemas<TDefinitions> {
129+
const schemas: Record<string, JsonSchema> = {};
130+
for (const definition of definitions) {
131+
if (definition.projection) {
132+
addRecordEntry(
133+
schemas,
134+
'command output schema',
135+
definition.name,
136+
definition.projection.outputSchema,
137+
);
138+
}
139+
}
140+
return schemas as ProjectedCommandOutputSchemas<TDefinitions>;
141+
}
142+
118143
function addRecordEntry<TValue>(
119144
record: Record<string, TValue>,
120145
label: string,

0 commit comments

Comments
 (0)