create-stitchkit 0.6.23 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +9 -1
- package/UPGRADING.md +72 -17
- package/dist/cli.js +83 -56
- package/examples/repository/packages/backend/src/surface.snapshot.json +175 -88
- package/examples/repository/scripts/runtime-smoke.ts +156 -126
- package/package.json +7 -4
- package/template/README.md +12 -2
- package/template/_gitignore +1 -0
- package/template/bun.lock +5 -5
- package/template/docs/ADDING_A_FEATURE.md +21 -7
- package/template/package.json +3 -3
- package/template/packages/backend/src/cli.ts +1 -0
- package/template/packages/backend/src/index.ts +3 -0
- package/template/packages/backend/src/surface.snapshot.json +90 -50
- package/template/packages/backend/src/tools.ts +1 -1
- package/template/packages/frontend/package.json +1 -1
- package/template/scripts/acceptance-environment.test.ts +59 -0
- package/template/scripts/acceptance-environment.ts +52 -0
- package/template/scripts/acceptance-local.ts +8 -28
- package/template/scripts/runtime-smoke.test.ts +49 -0
- package/template/scripts/runtime-smoke.ts +2 -2
- package/template/scripts/surface-snapshot.ts +135 -14
- package/templates/agent/package.json +2 -2
- package/templates/agent/src/runtime.ts +1 -1
- package/templates/telegram-bot/package.json +1 -1
- package/template/.data/board.sqlite +0 -0
- package/template/packages/backend/src/surface-manifest.test.ts +0 -237
- package/template/packages/backend/src/surface-manifest.ts +0 -220
- package/template/scripts/surface-conformance.ts +0 -173
|
@@ -1,21 +1,142 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* intended surface change and review the diff like any
|
|
3
|
+
* Committed surface snapshot and live-surface discovery check backed directly
|
|
4
|
+
* by `stitchkit/testing`. Run this script directly (`bun run surface:snapshot`)
|
|
5
|
+
* after an intended surface change and review the diff like any contract edit.
|
|
6
6
|
*/
|
|
7
|
-
import { writeFile } from 'node:fs/promises';
|
|
7
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
|
+
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
|
10
|
+
import type { ServiceDef } from 'stitchkit/server';
|
|
11
|
+
import {
|
|
12
|
+
assertSurfaceDiscovery,
|
|
13
|
+
assertSurfaceManifestSnapshot,
|
|
14
|
+
buildSurfaceManifest,
|
|
15
|
+
type SurfaceManifest,
|
|
16
|
+
SurfaceManifestSchema,
|
|
17
|
+
} from 'stitchkit/testing';
|
|
18
|
+
import { mountAgent } from 'stitchkit/tools/agent';
|
|
19
|
+
import { z } from 'zod';
|
|
9
20
|
import { createSurface } from '../packages/backend/src/surface';
|
|
10
|
-
import { buildSurfaceManifest } from '../packages/backend/src/surface-manifest';
|
|
11
|
-
import { SURFACE_SNAPSHOT_PATH } from './surface-conformance';
|
|
12
21
|
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
export const SURFACE_SNAPSHOT_PATH = 'packages/backend/src/surface.snapshot.json';
|
|
23
|
+
|
|
24
|
+
const OpenApiSnapshotSchema = z.object({
|
|
25
|
+
paths: z.record(z.string(), z.record(z.string(), z.unknown())),
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
export function buildAppSurfaceManifest(services: readonly ServiceDef[]): SurfaceManifest {
|
|
29
|
+
return buildSurfaceManifest({
|
|
30
|
+
groups: [{ pathPrefix: '/api', services: [...services] }],
|
|
31
|
+
toolSurfaces: {
|
|
32
|
+
MCP: { services },
|
|
33
|
+
AGENT: { services },
|
|
34
|
+
CLI: { services },
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Observe the CLI surface externally — spawn the real CLI process and parse
|
|
41
|
+
* its command table instead of re-deriving the list from in-process `services`.
|
|
42
|
+
*/
|
|
43
|
+
export async function discoverCliCommands(
|
|
44
|
+
root = process.cwd(),
|
|
45
|
+
timeoutMs = 30_000,
|
|
46
|
+
): Promise<string[]> {
|
|
47
|
+
const child = Bun.spawn({
|
|
48
|
+
cmd: ['bun', 'packages/backend/src/cli.ts', '--help'],
|
|
49
|
+
cwd: root,
|
|
50
|
+
stdout: 'pipe',
|
|
51
|
+
stderr: 'pipe',
|
|
52
|
+
});
|
|
53
|
+
let timedOut = false;
|
|
54
|
+
const timer = setTimeout(() => {
|
|
55
|
+
timedOut = true;
|
|
56
|
+
child.kill();
|
|
57
|
+
}, timeoutMs);
|
|
58
|
+
let output: string;
|
|
59
|
+
let errors: string;
|
|
60
|
+
let exitCode: number;
|
|
61
|
+
try {
|
|
62
|
+
[output, errors, exitCode] = await Promise.all([
|
|
63
|
+
new Response(child.stdout).text(),
|
|
64
|
+
new Response(child.stderr).text(),
|
|
65
|
+
child.exited,
|
|
66
|
+
]);
|
|
67
|
+
} finally {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
}
|
|
70
|
+
if (timedOut) {
|
|
71
|
+
throw new Error(`CLI --help timed out after ${timeoutMs}ms`);
|
|
72
|
+
}
|
|
73
|
+
if (exitCode !== 0) {
|
|
74
|
+
throw new Error(`CLI --help exited with ${exitCode}: ${errors || output}`);
|
|
75
|
+
}
|
|
76
|
+
const lines = output.split('\n');
|
|
77
|
+
const start = lines.findIndex((line) => line.trim() === 'Commands:');
|
|
78
|
+
if (start === -1) throw new Error('CLI --help output carries no "Commands:" section');
|
|
79
|
+
const commands: string[] = [];
|
|
80
|
+
for (const line of lines.slice(start + 1)) {
|
|
81
|
+
if (!line.startsWith(' ')) break;
|
|
82
|
+
const name = line.trim().split(/\s+/)[0];
|
|
83
|
+
if (name) commands.push(name);
|
|
84
|
+
}
|
|
85
|
+
return commands;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function discoverMcpTools(apiOrigin: string): Promise<string[]> {
|
|
89
|
+
const client = new Client(
|
|
90
|
+
{ name: 'surface-conformance', version: '1.0.0' },
|
|
91
|
+
{ versionNegotiation: { mode: { pin: '2026-07-28' } } },
|
|
92
|
+
);
|
|
93
|
+
const transport = new StreamableHTTPClientTransport(new URL(`${apiOrigin}/mcp`));
|
|
94
|
+
try {
|
|
95
|
+
await client.connect(transport);
|
|
96
|
+
if (!client.getServerCapabilities()?.tools) return [];
|
|
97
|
+
return (await client.listTools()).tools.map((tool) => tool.name);
|
|
98
|
+
} finally {
|
|
99
|
+
await client.close();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function assertLiveSurface(
|
|
104
|
+
apiOrigin: string,
|
|
105
|
+
root = process.cwd(),
|
|
106
|
+
): Promise<void> {
|
|
107
|
+
const { services, socket, hub, board } = await createSurface();
|
|
108
|
+
try {
|
|
109
|
+
const manifest = buildAppSurfaceManifest(services);
|
|
110
|
+
const snapshot = SurfaceManifestSchema.parse(
|
|
111
|
+
JSON.parse(await readFile(join(root, SURFACE_SNAPSHOT_PATH), 'utf8')),
|
|
112
|
+
);
|
|
113
|
+
assertSurfaceManifestSnapshot(manifest, snapshot);
|
|
114
|
+
const response = await fetch(`${apiOrigin}/openapi.json`, {
|
|
115
|
+
signal: AbortSignal.timeout(30_000),
|
|
116
|
+
});
|
|
117
|
+
if (!response.ok) {
|
|
118
|
+
throw new Error(`GET ${apiOrigin}/openapi.json returned ${response.status}`);
|
|
119
|
+
}
|
|
120
|
+
const openApi = OpenApiSnapshotSchema.parse(await response.json());
|
|
121
|
+
assertSurfaceDiscovery(manifest, {
|
|
122
|
+
openApi,
|
|
123
|
+
MCP: await discoverMcpTools(apiOrigin),
|
|
124
|
+
AGENT: Object.keys(mountAgent(services, { access: { open: 'local-operator' } })),
|
|
125
|
+
CLI: await discoverCliCommands(root),
|
|
126
|
+
});
|
|
127
|
+
} finally {
|
|
128
|
+
await Promise.allSettled([hub.close(), board.close(), socket.close()]);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (import.meta.main) {
|
|
133
|
+
const { services, socket, hub, board } = await createSurface();
|
|
134
|
+
try {
|
|
135
|
+
const manifest = buildAppSurfaceManifest(services);
|
|
136
|
+
const target = join(process.cwd(), SURFACE_SNAPSHOT_PATH);
|
|
137
|
+
await writeFile(target, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
138
|
+
console.log(`Wrote ${manifest.operations.length} operation(s) to ${SURFACE_SNAPSHOT_PATH}`);
|
|
139
|
+
} finally {
|
|
140
|
+
await Promise.allSettled([hub.close(), board.close(), socket.close()]);
|
|
141
|
+
}
|
|
21
142
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"version": "0.1.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"catalog": {
|
|
7
|
-
"stitchkit-tui": "^0.
|
|
7
|
+
"stitchkit-tui": "^0.5.0"
|
|
8
8
|
},
|
|
9
9
|
"overrides": {
|
|
10
10
|
"zod": "4.6.7"
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"typescript": "^7.0.2"
|
|
38
38
|
},
|
|
39
39
|
"engines": {
|
|
40
|
-
"bun": ">=1.
|
|
40
|
+
"bun": ">=1.4.0"
|
|
41
41
|
},
|
|
42
42
|
"packageManager": "bun@1.4.5"
|
|
43
43
|
}
|
|
@@ -110,7 +110,7 @@ export async function createStarterHarness(
|
|
|
110
110
|
tools: (context) =>
|
|
111
111
|
mountAgent([], {
|
|
112
112
|
runtimeTools: [...codingTools, ...resources.runtimeTools],
|
|
113
|
-
|
|
113
|
+
access: { gate: context.toolFenceLifecycle },
|
|
114
114
|
}),
|
|
115
115
|
loop: {
|
|
116
116
|
maxSteps: 50,
|
|
Binary file
|
|
@@ -1,237 +0,0 @@
|
|
|
1
|
-
import { describe, expect, test } from 'bun:test';
|
|
2
|
-
import { readFile } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import { createContractFactory } from 'stitchkit/contract';
|
|
5
|
-
import { generateOpenApiDocument, implement } from 'stitchkit/server';
|
|
6
|
-
import { z } from 'zod';
|
|
7
|
-
import { discoverCliCommands, discoverMcpTools } from '../../../scripts/surface-conformance';
|
|
8
|
-
import {
|
|
9
|
-
assertManifestMatchesSnapshot,
|
|
10
|
-
assertSurfaceConformance,
|
|
11
|
-
buildSurfaceManifest,
|
|
12
|
-
} from './surface-manifest';
|
|
13
|
-
|
|
14
|
-
const NoteParamsSchema = z.object({ id: z.string() });
|
|
15
|
-
const NoteSchema = z.object({ id: z.string() });
|
|
16
|
-
// Same address and presence flags as NoteSchema — a different TYPE, for the
|
|
17
|
-
// snapshot-digest test. Named here, never inline in a contract (the template's
|
|
18
|
-
// own schema-separate-from-contract policy).
|
|
19
|
-
const RetypedNoteSchema = z.object({ id: z.number() });
|
|
20
|
-
const { defineContract } = createContractFactory<'public'>();
|
|
21
|
-
|
|
22
|
-
const service = implement(
|
|
23
|
-
defineContract(
|
|
24
|
-
{ prefix: 'notes', scope: 'public' },
|
|
25
|
-
{
|
|
26
|
-
read: {
|
|
27
|
-
method: 'GET',
|
|
28
|
-
path: '/:id',
|
|
29
|
-
desc: 'Read a note',
|
|
30
|
-
params: NoteParamsSchema,
|
|
31
|
-
output: NoteSchema,
|
|
32
|
-
expose: ['HTTP', 'MCP', 'AGENT', 'CLI'],
|
|
33
|
-
},
|
|
34
|
-
},
|
|
35
|
-
),
|
|
36
|
-
{ read: ({ params }) => ({ id: params.id }) },
|
|
37
|
-
);
|
|
38
|
-
|
|
39
|
-
describe('surface conformance', () => {
|
|
40
|
-
test('derives matching HTTP and MCP discovery identities without calling handlers', () => {
|
|
41
|
-
const manifest = buildSurfaceManifest([service]);
|
|
42
|
-
const openApi = generateOpenApiDocument({
|
|
43
|
-
info: { title: 'Test', version: '1.0.0' },
|
|
44
|
-
groups: [{ pathPrefix: '/api', services: [service] }],
|
|
45
|
-
});
|
|
46
|
-
expect(manifest).toEqual([
|
|
47
|
-
{
|
|
48
|
-
service: 'notes',
|
|
49
|
-
action: 'read',
|
|
50
|
-
scope: 'public',
|
|
51
|
-
hasInput: false,
|
|
52
|
-
hasOutput: true,
|
|
53
|
-
inputShape: null,
|
|
54
|
-
outputShape: expect.stringMatching(/^[0-9a-f]{16}$/),
|
|
55
|
-
http: [{ method: 'GET', path: '/api/notes/{id}' }],
|
|
56
|
-
tools: { AGENT: 'read_note', CLI: 'read_note', MCP: 'read_note' },
|
|
57
|
-
},
|
|
58
|
-
]);
|
|
59
|
-
expect(() =>
|
|
60
|
-
assertSurfaceConformance({
|
|
61
|
-
manifest,
|
|
62
|
-
openApi,
|
|
63
|
-
mcpToolNames: ['read_note'],
|
|
64
|
-
agentToolNames: ['read_note'],
|
|
65
|
-
cliToolNames: ['read_note'],
|
|
66
|
-
}),
|
|
67
|
-
).not.toThrow();
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
test('fails with transport-specific expected and actual diagnostics', () => {
|
|
71
|
-
const manifest = buildSurfaceManifest([service]);
|
|
72
|
-
expect(() =>
|
|
73
|
-
assertSurfaceConformance({
|
|
74
|
-
manifest,
|
|
75
|
-
openApi: { paths: {} },
|
|
76
|
-
mcpToolNames: [],
|
|
77
|
-
agentToolNames: [],
|
|
78
|
-
cliToolNames: [],
|
|
79
|
-
}),
|
|
80
|
-
).toThrow('HTTP/OpenAPI surface mismatch');
|
|
81
|
-
expect(() =>
|
|
82
|
-
assertSurfaceConformance({
|
|
83
|
-
manifest: manifest.map((operation) => ({ ...operation, http: [] })),
|
|
84
|
-
openApi: { paths: {} },
|
|
85
|
-
mcpToolNames: ['unexpected'],
|
|
86
|
-
agentToolNames: ['read_note'],
|
|
87
|
-
cliToolNames: ['read_note'],
|
|
88
|
-
}),
|
|
89
|
-
).toThrow('MCP discovery surface mismatch');
|
|
90
|
-
});
|
|
91
|
-
|
|
92
|
-
test('missing Stitchkit metadata is an ERROR unless the standard-document mode is declared', () => {
|
|
93
|
-
const manifest = buildSurfaceManifest([service]);
|
|
94
|
-
const standardDocument = {
|
|
95
|
-
paths: {
|
|
96
|
-
'/api/notes/{id}': {
|
|
97
|
-
get: { responses: { 200: { description: 'Success' } } },
|
|
98
|
-
},
|
|
99
|
-
},
|
|
100
|
-
};
|
|
101
|
-
const names = {
|
|
102
|
-
mcpToolNames: ['read_note'],
|
|
103
|
-
agentToolNames: ['read_note'],
|
|
104
|
-
cliToolNames: ['read_note'],
|
|
105
|
-
};
|
|
106
|
-
// Without x-stitchkit-* metadata there is nothing to compare. The default
|
|
107
|
-
// mode rejects the document; opting out is an explicit decision.
|
|
108
|
-
expect(() =>
|
|
109
|
-
assertSurfaceConformance({ manifest, openApi: standardDocument, ...names }),
|
|
110
|
-
).toThrow(/no x-stitchkit-\* contract metadata/);
|
|
111
|
-
expect(() =>
|
|
112
|
-
assertSurfaceConformance({
|
|
113
|
-
manifest,
|
|
114
|
-
openApi: standardDocument,
|
|
115
|
-
...names,
|
|
116
|
-
metadata: 'ignore',
|
|
117
|
-
}),
|
|
118
|
-
).not.toThrow();
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
test('a missing AGENT tool and a missing CLI command each fail conformance', () => {
|
|
122
|
-
const manifest = buildSurfaceManifest([service]);
|
|
123
|
-
const openApi = generateOpenApiDocument({
|
|
124
|
-
info: { title: 'Test', version: '1.0.0' },
|
|
125
|
-
groups: [{ pathPrefix: '/api', services: [service] }],
|
|
126
|
-
});
|
|
127
|
-
expect(() =>
|
|
128
|
-
assertSurfaceConformance({
|
|
129
|
-
manifest,
|
|
130
|
-
openApi,
|
|
131
|
-
mcpToolNames: ['read_note'],
|
|
132
|
-
agentToolNames: [],
|
|
133
|
-
cliToolNames: ['read_note'],
|
|
134
|
-
}),
|
|
135
|
-
).toThrow('AGENT mount surface mismatch');
|
|
136
|
-
expect(() =>
|
|
137
|
-
assertSurfaceConformance({
|
|
138
|
-
manifest,
|
|
139
|
-
openApi,
|
|
140
|
-
mcpToolNames: ['read_note'],
|
|
141
|
-
agentToolNames: ['read_note'],
|
|
142
|
-
cliToolNames: [],
|
|
143
|
-
}),
|
|
144
|
-
).toThrow('CLI manifest surface mismatch');
|
|
145
|
-
});
|
|
146
|
-
|
|
147
|
-
test('the committed snapshot catches an expose edit that moves BOTH in-process sides together', () => {
|
|
148
|
-
// Removing AGENT/CLI from `expose`
|
|
149
|
-
// changes the manifest AND the in-process tool lists in lockstep. The
|
|
150
|
-
// snapshot is the anchor that does not move with the source.
|
|
151
|
-
const snapshot = buildSurfaceManifest([service]);
|
|
152
|
-
const narrowed = implement(
|
|
153
|
-
defineContract(
|
|
154
|
-
{ prefix: 'notes', scope: 'public' },
|
|
155
|
-
{
|
|
156
|
-
read: {
|
|
157
|
-
method: 'GET',
|
|
158
|
-
path: '/:id',
|
|
159
|
-
desc: 'Read a note',
|
|
160
|
-
params: NoteParamsSchema,
|
|
161
|
-
output: NoteSchema,
|
|
162
|
-
expose: ['HTTP', 'MCP'],
|
|
163
|
-
},
|
|
164
|
-
},
|
|
165
|
-
),
|
|
166
|
-
{ read: ({ params }) => ({ id: params.id }) },
|
|
167
|
-
);
|
|
168
|
-
expect(() =>
|
|
169
|
-
assertManifestMatchesSnapshot(buildSurfaceManifest([narrowed]), snapshot),
|
|
170
|
-
).toThrow(/diverged from the committed snapshot/);
|
|
171
|
-
expect(() =>
|
|
172
|
-
assertManifestMatchesSnapshot(buildSurfaceManifest([service]), snapshot),
|
|
173
|
-
).not.toThrow();
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
test('a schema TYPE change at the same method and path flips the shape digest', () => {
|
|
177
|
-
const snapshot = buildSurfaceManifest([service]);
|
|
178
|
-
const retyped = implement(
|
|
179
|
-
defineContract(
|
|
180
|
-
{ prefix: 'notes', scope: 'public' },
|
|
181
|
-
{
|
|
182
|
-
read: {
|
|
183
|
-
method: 'GET',
|
|
184
|
-
path: '/:id',
|
|
185
|
-
desc: 'Read a note',
|
|
186
|
-
params: NoteParamsSchema,
|
|
187
|
-
// Same address, same presence flags — different output TYPE.
|
|
188
|
-
output: RetypedNoteSchema,
|
|
189
|
-
expose: ['HTTP', 'MCP', 'AGENT', 'CLI'],
|
|
190
|
-
},
|
|
191
|
-
},
|
|
192
|
-
),
|
|
193
|
-
{ read: ({ params }) => ({ id: Number(params.id) }) },
|
|
194
|
-
);
|
|
195
|
-
expect(() =>
|
|
196
|
-
assertManifestMatchesSnapshot(buildSurfaceManifest([retyped]), snapshot),
|
|
197
|
-
).toThrow(/diverged from the committed snapshot/);
|
|
198
|
-
});
|
|
199
|
-
|
|
200
|
-
test('fails first on duplicate contract identity', () => {
|
|
201
|
-
expect(() => buildSurfaceManifest([service, service])).toThrow(
|
|
202
|
-
'Duplicate operation identity notes.read',
|
|
203
|
-
);
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
test('a broken /mcp endpoint rejects discovery — even when zero tools are expected', async () => {
|
|
207
|
-
const broken = Bun.serve({
|
|
208
|
-
port: 0,
|
|
209
|
-
fetch: () => new Response('not the MCP endpoint', { status: 404 }),
|
|
210
|
-
});
|
|
211
|
-
try {
|
|
212
|
-
await expect(discoverMcpTools(`http://127.0.0.1:${broken.port}`, [])).rejects.toThrow();
|
|
213
|
-
} finally {
|
|
214
|
-
broken.stop(true);
|
|
215
|
-
}
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
test('the CLI surface observed from the SPAWNED process matches the committed snapshot', async () => {
|
|
219
|
-
// External observation against the external anchor — neither side is the
|
|
220
|
-
// in-process `services` object, so they cannot move together.
|
|
221
|
-
const root = join(import.meta.dir, '../../..');
|
|
222
|
-
const commands = await discoverCliCommands(root);
|
|
223
|
-
const snapshot = SurfaceSnapshotCliSchema.parse(
|
|
224
|
-
JSON.parse(
|
|
225
|
-
await readFile(join(root, 'packages/backend/src/surface.snapshot.json'), 'utf8'),
|
|
226
|
-
),
|
|
227
|
-
);
|
|
228
|
-
const expected = snapshot
|
|
229
|
-
.flatMap((operation) => (operation.tools.CLI ? [operation.tools.CLI] : []))
|
|
230
|
-
.sort();
|
|
231
|
-
expect([...commands].sort()).toEqual(expected);
|
|
232
|
-
});
|
|
233
|
-
});
|
|
234
|
-
|
|
235
|
-
const SurfaceSnapshotCliSchema = z.array(
|
|
236
|
-
z.object({ tools: z.object({ CLI: z.string().optional() }) }),
|
|
237
|
-
);
|
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import type { HttpMethod } from 'stitchkit/contract';
|
|
3
|
-
import type { OpenApiDocument, ServiceDef } from 'stitchkit/server';
|
|
4
|
-
import { listToolNames } from 'stitchkit/tools';
|
|
5
|
-
import { z } from 'zod';
|
|
6
|
-
|
|
7
|
-
export interface SurfaceManifestOperation {
|
|
8
|
-
service: string;
|
|
9
|
-
action: string;
|
|
10
|
-
scope: string;
|
|
11
|
-
hasInput: boolean;
|
|
12
|
-
hasOutput: boolean;
|
|
13
|
-
/** Digest of the input JSON Schema — a TYPE change flips it, not just presence. */
|
|
14
|
-
inputShape: string | null;
|
|
15
|
-
/** Digest of the output JSON Schema. */
|
|
16
|
-
outputShape: string | null;
|
|
17
|
-
http: Array<{ method: HttpMethod; path: string }>;
|
|
18
|
-
tools: Partial<Record<'MCP' | 'AGENT' | 'CLI', string>>;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function schemaShape(schema: z.ZodType | undefined, io: 'input' | 'output'): string | null {
|
|
22
|
-
if (!schema) return null;
|
|
23
|
-
const document = z.toJSONSchema(schema, { io, unrepresentable: 'any' });
|
|
24
|
-
return createHash('sha256').update(JSON.stringify(document)).digest('hex').slice(0, 16);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
function joinPath(...parts: Array<string | undefined>): string {
|
|
28
|
-
const joined = parts
|
|
29
|
-
.filter((part): part is string => Boolean(part))
|
|
30
|
-
.map((part) => part.replace(/^\/+|\/+$/g, ''))
|
|
31
|
-
.filter(Boolean)
|
|
32
|
-
.join('/');
|
|
33
|
-
return `/${joined}`;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
function operationKey(service: string, action: string): string {
|
|
37
|
-
return `${service}\u0000${action}`;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function sorted(values: Iterable<string>): string[] {
|
|
41
|
-
return [...values].sort((left, right) => left.localeCompare(right));
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function assertSameSet(
|
|
45
|
-
label: string,
|
|
46
|
-
expectedValues: Iterable<string>,
|
|
47
|
-
actualValues: Iterable<string>,
|
|
48
|
-
) {
|
|
49
|
-
const expected = sorted(expectedValues);
|
|
50
|
-
const actual = sorted(actualValues);
|
|
51
|
-
if (
|
|
52
|
-
expected.length === actual.length &&
|
|
53
|
-
expected.every((value, index) => value === actual[index])
|
|
54
|
-
) {
|
|
55
|
-
return;
|
|
56
|
-
}
|
|
57
|
-
throw new Error(
|
|
58
|
-
`${label} surface mismatch\nexpected: ${expected.join(', ') || '(empty)'}\nactual: ${actual.join(', ') || '(empty)'}`,
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function buildSurfaceManifest(
|
|
63
|
-
services: readonly ServiceDef[],
|
|
64
|
-
pathPrefix = '/api',
|
|
65
|
-
): SurfaceManifestOperation[] {
|
|
66
|
-
const operations = new Map<string, SurfaceManifestOperation>();
|
|
67
|
-
for (const service of services) {
|
|
68
|
-
for (const method of Object.values(service.methods)) {
|
|
69
|
-
const key = operationKey(service.name, method.key);
|
|
70
|
-
if (operations.has(key)) {
|
|
71
|
-
throw new Error(`Duplicate operation identity ${service.name}.${method.key}`);
|
|
72
|
-
}
|
|
73
|
-
operations.set(key, {
|
|
74
|
-
service: service.name,
|
|
75
|
-
action: method.key,
|
|
76
|
-
scope: method.scope ?? service.scope,
|
|
77
|
-
hasInput: Boolean(method.inputSchema),
|
|
78
|
-
hasOutput: Boolean(method.outputSchema),
|
|
79
|
-
inputShape: schemaShape(method.inputSchema, 'input'),
|
|
80
|
-
outputShape: schemaShape(method.outputSchema, 'output'),
|
|
81
|
-
http:
|
|
82
|
-
!method.expose || method.expose.includes('HTTP')
|
|
83
|
-
? [
|
|
84
|
-
{
|
|
85
|
-
method: method.method,
|
|
86
|
-
path: joinPath(pathPrefix, service.prefix, method.path).replace(
|
|
87
|
-
/:([^/]+)/g,
|
|
88
|
-
'{$1}',
|
|
89
|
-
),
|
|
90
|
-
},
|
|
91
|
-
]
|
|
92
|
-
: [],
|
|
93
|
-
tools: {},
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
for (const tool of listToolNames({ services })) {
|
|
98
|
-
const operation = operations.get(operationKey(tool.service, tool.method));
|
|
99
|
-
if (!operation) {
|
|
100
|
-
throw new Error(`Tool ${tool.name} has no contract identity`);
|
|
101
|
-
}
|
|
102
|
-
for (const transport of tool.transports) {
|
|
103
|
-
if (transport !== 'HTTP') operation.tools[transport] = tool.name;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
return [...operations.values()].sort(
|
|
107
|
-
(left, right) =>
|
|
108
|
-
left.service.localeCompare(right.service) || left.action.localeCompare(right.action),
|
|
109
|
-
);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Compare the LIVE manifest against the committed snapshot — the external
|
|
114
|
-
* anchor that a source-level change (an `expose` edit, a schema type change, a
|
|
115
|
-
* scope change) cannot move along with itself. Regenerate deliberately with
|
|
116
|
-
* `bun run surface:snapshot` and review the diff.
|
|
117
|
-
*/
|
|
118
|
-
export function assertManifestMatchesSnapshot(
|
|
119
|
-
manifest: readonly SurfaceManifestOperation[],
|
|
120
|
-
snapshot: readonly SurfaceManifestOperation[],
|
|
121
|
-
): void {
|
|
122
|
-
const actual = JSON.stringify(manifest, null, 2);
|
|
123
|
-
const expected = JSON.stringify(snapshot, null, 2);
|
|
124
|
-
if (actual !== expected) {
|
|
125
|
-
throw new Error(
|
|
126
|
-
`Declared surface diverged from the committed snapshot — if the change is intended, regenerate it with "bun run surface:snapshot" and review the diff.\nsnapshot: ${expected}\nactual: ${actual}`,
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
export function assertSurfaceConformance({
|
|
132
|
-
manifest,
|
|
133
|
-
openApi,
|
|
134
|
-
mcpToolNames,
|
|
135
|
-
agentToolNames,
|
|
136
|
-
cliToolNames,
|
|
137
|
-
metadata = 'require',
|
|
138
|
-
}: {
|
|
139
|
-
manifest: readonly SurfaceManifestOperation[];
|
|
140
|
-
openApi: Pick<OpenApiDocument, 'paths'>;
|
|
141
|
-
mcpToolNames: readonly string[];
|
|
142
|
-
agentToolNames: readonly string[];
|
|
143
|
-
cliToolNames: readonly string[];
|
|
144
|
-
/**
|
|
145
|
-
* `'require'` (default) — the OpenAPI document must carry `x-stitchkit-*`
|
|
146
|
-
* metadata and it is compared; `'ignore'` — an explicitly declared mode for
|
|
147
|
-
* standard documents. A silent skip is not an option.
|
|
148
|
-
*/
|
|
149
|
-
metadata?: 'require' | 'ignore';
|
|
150
|
-
}): void {
|
|
151
|
-
const openApiOperations = Object.entries(openApi.paths).flatMap(([path, item]) =>
|
|
152
|
-
Object.entries(item)
|
|
153
|
-
.filter(([method]) => ['get', 'post', 'put', 'patch', 'delete', 'head'].includes(method))
|
|
154
|
-
.map(([method, operation]) => ({ method: method.toUpperCase(), path, operation })),
|
|
155
|
-
);
|
|
156
|
-
assertSameSet(
|
|
157
|
-
'HTTP/OpenAPI',
|
|
158
|
-
manifest.flatMap((operation) =>
|
|
159
|
-
operation.http.map((entry) => `${entry.method}:${entry.path}`),
|
|
160
|
-
),
|
|
161
|
-
openApiOperations.map(({ method, path }) => `${method}:${path}`),
|
|
162
|
-
);
|
|
163
|
-
const carriesContractMetadata = openApiOperations.some(({ operation }) =>
|
|
164
|
-
OpenApiOperationMetadataPresenceSchema.parse(operation),
|
|
165
|
-
);
|
|
166
|
-
if (metadata === 'require' && openApiOperations.length > 0 && !carriesContractMetadata) {
|
|
167
|
-
throw new Error(
|
|
168
|
-
'OpenAPI document carries no x-stitchkit-* contract metadata — pass metadata: "ignore" only for a deliberately standard document',
|
|
169
|
-
);
|
|
170
|
-
}
|
|
171
|
-
if (metadata === 'require' && carriesContractMetadata) {
|
|
172
|
-
assertSameSet(
|
|
173
|
-
'HTTP/OpenAPI contract metadata',
|
|
174
|
-
manifest.flatMap((operation) =>
|
|
175
|
-
operation.http.map(
|
|
176
|
-
(entry) =>
|
|
177
|
-
`${entry.method}:${entry.path}:${operation.scope}:${operation.hasInput}:${operation.hasOutput}`,
|
|
178
|
-
),
|
|
179
|
-
),
|
|
180
|
-
openApiOperations.map(({ method, path, operation }) => {
|
|
181
|
-
const metadata = OpenApiOperationMetadataSchema.parse(operation);
|
|
182
|
-
return `${method}:${path}:${metadata['x-stitchkit-scope']}:${metadata['x-stitchkit-has-input']}:${metadata['x-stitchkit-has-output']}`;
|
|
183
|
-
}),
|
|
184
|
-
);
|
|
185
|
-
}
|
|
186
|
-
assertSameSet(
|
|
187
|
-
'MCP discovery',
|
|
188
|
-
manifest.flatMap((operation) => (operation.tools.MCP ? [operation.tools.MCP] : [])),
|
|
189
|
-
mcpToolNames,
|
|
190
|
-
);
|
|
191
|
-
assertSameSet(
|
|
192
|
-
'AGENT mount',
|
|
193
|
-
manifest.flatMap((operation) => (operation.tools.AGENT ? [operation.tools.AGENT] : [])),
|
|
194
|
-
agentToolNames,
|
|
195
|
-
);
|
|
196
|
-
assertSameSet(
|
|
197
|
-
'CLI manifest',
|
|
198
|
-
manifest.flatMap((operation) => (operation.tools.CLI ? [operation.tools.CLI] : [])),
|
|
199
|
-
cliToolNames,
|
|
200
|
-
);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const OpenApiOperationMetadataSchema = z.object({
|
|
204
|
-
'x-stitchkit-scope': z.string(),
|
|
205
|
-
'x-stitchkit-has-input': z.boolean(),
|
|
206
|
-
'x-stitchkit-has-output': z.boolean(),
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
const OpenApiOperationMetadataPresenceSchema = z
|
|
210
|
-
.object({
|
|
211
|
-
'x-stitchkit-scope': z.unknown().optional(),
|
|
212
|
-
'x-stitchkit-has-input': z.unknown().optional(),
|
|
213
|
-
'x-stitchkit-has-output': z.unknown().optional(),
|
|
214
|
-
})
|
|
215
|
-
.transform(
|
|
216
|
-
(metadata) =>
|
|
217
|
-
metadata['x-stitchkit-scope'] !== undefined ||
|
|
218
|
-
metadata['x-stitchkit-has-input'] !== undefined ||
|
|
219
|
-
metadata['x-stitchkit-has-output'] !== undefined,
|
|
220
|
-
);
|