create-stitchkit 0.6.22 → 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.
Files changed (34) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +9 -1
  3. package/UPGRADING.md +84 -16
  4. package/dist/cli.js +83 -56
  5. package/examples/repository/packages/backend/src/surface.snapshot.json +175 -88
  6. package/examples/repository/scripts/runtime-smoke.ts +156 -126
  7. package/package.json +12 -9
  8. package/template/README.md +12 -2
  9. package/template/_gitignore +1 -0
  10. package/template/bun.lock +12 -12
  11. package/template/docs/ADDING_A_FEATURE.md +21 -7
  12. package/template/package.json +5 -5
  13. package/template/packages/backend/package.json +1 -1
  14. package/template/packages/backend/src/cli.ts +1 -0
  15. package/template/packages/backend/src/index.ts +3 -0
  16. package/template/packages/backend/src/lib/live.ts +3 -1
  17. package/template/packages/backend/src/surface.snapshot.json +90 -50
  18. package/template/packages/backend/src/tools.ts +1 -1
  19. package/template/packages/config/package.json +1 -1
  20. package/template/packages/frontend/package.json +2 -2
  21. package/template/packages/shared/package.json +1 -1
  22. package/template/scripts/acceptance-environment.test.ts +59 -0
  23. package/template/scripts/acceptance-environment.ts +52 -0
  24. package/template/scripts/acceptance-local.ts +8 -28
  25. package/template/scripts/runtime-smoke.test.ts +49 -0
  26. package/template/scripts/runtime-smoke.ts +2 -2
  27. package/template/scripts/surface-snapshot.ts +135 -14
  28. package/templates/agent/package.json +7 -7
  29. package/templates/agent/src/runtime.ts +1 -1
  30. package/templates/telegram-bot/package.json +3 -3
  31. package/template/.data/board.sqlite +0 -0
  32. package/template/packages/backend/src/surface-manifest.test.ts +0 -237
  33. package/template/packages/backend/src/surface-manifest.ts +0 -220
  34. package/template/scripts/surface-conformance.ts +0 -173
@@ -2,7 +2,7 @@ import { systemContract } from '@app/shared';
2
2
  import { createClient, createHttpClient } from 'stitchkit';
3
3
  import { z } from 'zod';
4
4
  import { assertDeploymentIsAnswering } from './deployment-preflight';
5
- import { runSurfaceConformance } from './surface-conformance';
5
+ import { assertLiveSurface } from './surface-snapshot';
6
6
  import { loadToolingEnv } from './tooling-env';
7
7
  import { assertArtifactIsPlacementFree, assertPublicWebSurface } from './web-surface-smoke';
8
8
 
@@ -37,7 +37,7 @@ if (!Object.keys(openApi.paths).includes('/api/system/status')) {
37
37
  throw new Error('System status contract is missing from OpenAPI');
38
38
  }
39
39
 
40
- await runSurfaceConformance({ apiOrigin });
40
+ await assertLiveSurface(apiOrigin);
41
41
  await assertPublicWebSurface(toolingEnv.SMOKE_WEB_ORIGIN);
42
42
  await assertArtifactIsPlacementFree(toolingEnv.SMOKE_WEB_ORIGIN, {
43
43
  origin: toolingEnv.PUBLIC_WEB_ORIGIN,
@@ -1,21 +1,142 @@
1
1
  #!/usr/bin/env bun
2
2
  /**
3
- * Regenerate the committed surface snapshot — the anchor `surface-conformance`
4
- * compares the live contract surface against. Run it deliberately after an
5
- * intended surface change and review the diff like any other contract change.
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 { services, socket } = await createSurface();
14
- try {
15
- const manifest = buildSurfaceManifest(services);
16
- const target = join(process.cwd(), SURFACE_SNAPSHOT_PATH);
17
- await writeFile(target, `${JSON.stringify(manifest, null, 2)}\n`);
18
- console.log(`Wrote ${manifest.length} operation(s) to ${SURFACE_SNAPSHOT_PATH}`);
19
- } finally {
20
- await socket.close();
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.4.4"
7
+ "stitchkit-tui": "^0.5.0"
8
8
  },
9
9
  "overrides": {
10
10
  "zod": "4.6.7"
@@ -21,9 +21,9 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "^2.4.0",
23
23
  "@openrouter/ai-sdk-provider": "^3.1.0",
24
- "@opentui/core": "^0.9.2",
25
- "@opentui/react": "^0.9.2",
26
- "ai": "^7.0.173",
24
+ "@opentui/core": "^0.9.7",
25
+ "@opentui/react": "^0.9.7",
26
+ "ai": "^7.0.179",
27
27
  "react": "^19.3.1",
28
28
  "stitchkit": "link:../../../core",
29
29
  "stitchkit-tui": "link:../../../tui",
@@ -31,13 +31,13 @@
31
31
  },
32
32
  "devDependencies": {
33
33
  "@biomejs/biome": "2.6.8",
34
- "@types/bun": "^1.4.4",
34
+ "@types/bun": "^1.4.5",
35
35
  "@types/react": "^19.3.0",
36
36
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
37
37
  "typescript": "^7.0.2"
38
38
  },
39
39
  "engines": {
40
- "bun": ">=1.3.0"
40
+ "bun": ">=1.4.0"
41
41
  },
42
- "packageManager": "bun@1.4.4"
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
- lifecycle: context.toolFenceLifecycle,
113
+ access: { gate: context.toolFenceLifecycle },
114
114
  }),
115
115
  loop: {
116
116
  maxSteps: 50,
@@ -23,12 +23,12 @@
23
23
  },
24
24
  "devDependencies": {
25
25
  "@biomejs/biome": "2.6.8",
26
- "@types/bun": "^1.4.4",
26
+ "@types/bun": "^1.4.5",
27
27
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
28
28
  "typescript": "^7.0.2"
29
29
  },
30
30
  "engines": {
31
- "bun": ">=1.3.0"
31
+ "bun": ">=1.4.0"
32
32
  },
33
- "packageManager": "bun@1.4.4"
33
+ "packageManager": "bun@1.4.5"
34
34
  }
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
- );