create-stitchkit 0.6.23 → 0.8.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 (42) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +9 -1
  3. package/UPGRADING.md +93 -17
  4. package/dist/cli.js +82 -57
  5. package/examples/repository/packages/backend/src/surface.snapshot.json +175 -88
  6. package/examples/repository/project.json +0 -1
  7. package/examples/repository/scripts/runtime-smoke.ts +156 -126
  8. package/package.json +7 -4
  9. package/template/README.md +12 -2
  10. package/template/_gitignore +1 -0
  11. package/template/bun.lock +5 -10
  12. package/template/docs/ADDING_A_FEATURE.md +21 -7
  13. package/template/package.json +3 -3
  14. package/template/packages/backend/package.json +0 -1
  15. package/template/packages/backend/src/cli.ts +3 -2
  16. package/template/packages/backend/src/index.ts +6 -3
  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 +0 -1
  20. package/template/packages/config/src/app-identity.generated.ts +0 -1
  21. package/template/packages/config/src/declaration.ts +10 -0
  22. package/template/packages/db/package.json +0 -1
  23. package/template/packages/frontend/package.json +1 -2
  24. package/template/packages/shared/package.json +0 -1
  25. package/template/project.json +0 -1
  26. package/template/scripts/acceptance-environment.test.ts +59 -0
  27. package/template/scripts/acceptance-environment.ts +52 -0
  28. package/template/scripts/acceptance-local.ts +8 -28
  29. package/template/scripts/declaration.ts +4 -87
  30. package/template/scripts/env-variables.ts +83 -0
  31. package/template/scripts/runtime-smoke.test.ts +49 -0
  32. package/template/scripts/runtime-smoke.ts +2 -2
  33. package/template/scripts/surface-snapshot.ts +135 -14
  34. package/templates/agent/package.json +2 -2
  35. package/templates/agent/project.json +0 -1
  36. package/templates/agent/src/runtime.ts +1 -1
  37. package/templates/telegram-bot/package.json +1 -1
  38. package/templates/telegram-bot/project.json +0 -1
  39. package/template/.data/board.sqlite +0 -0
  40. package/template/packages/backend/src/surface-manifest.test.ts +0 -237
  41. package/template/packages/backend/src/surface-manifest.ts +0 -220
  42. package/template/scripts/surface-conformance.ts +0 -173
@@ -1,13 +1,10 @@
1
1
  import { resolve } from 'node:path';
2
- import type {
3
- ProjectDeclaration,
4
- ProjectEnvVariable,
5
- ProjectRole,
6
- } from 'stitchkit/declaration';
7
- import { z } from 'zod';
2
+ import type { ProjectDeclaration, ProjectRole } from 'stitchkit/declaration';
8
3
  import { appDeclaration } from '../packages/config/src/declaration';
9
4
  import * as shutdownBudgets from '../packages/config/src/shutdown';
10
- import { applicationVariables } from '../packages/config/src/variables';
5
+ import { renderEnvVariables } from './env-variables';
6
+
7
+ export { renderEnvVariables };
11
8
 
12
9
  /**
13
10
  * Everything derived from the project declaration.
@@ -60,86 +57,6 @@ export function terminationBudgetMs(role: ProjectRole): number {
60
57
  return role.drainFloorMs + FORCE_BUDGET_MS + CLEANUP_BUDGET_MS;
61
58
  }
62
59
 
63
- /**
64
- * JSON Schema types this projection can carry into the declaration.
65
- *
66
- * Mapping `number` to `integer` would misrepresent fractional values and make
67
- * the declaration disagree with its Zod source. A type with no faithful shape
68
- * is rejected: the
69
- * declaration format gains the shape, or the project stops declaring that type.
70
- */
71
- const SHAPE_BY_JSON_TYPE: Record<string, ProjectEnvVariable['shape']> = {
72
- integer: 'integer',
73
- boolean: 'boolean',
74
- };
75
-
76
- const JsonSchemaSchema = z.object({
77
- properties: z.record(
78
- z.string(),
79
- z.object({
80
- type: z.string().optional(),
81
- format: z.string().optional(),
82
- enum: z.array(z.unknown()).optional(),
83
- }),
84
- ),
85
- required: z.array(z.string()).optional(),
86
- });
87
-
88
- /**
89
- * The variables a deployment must supply, derived from the one Zod declaration.
90
- *
91
- * `required` follows the schema exactly: a variable with a default or an
92
- * `.optional()` is not required, and nothing here restates that judgement. An
93
- * enum carries its members, because "one of an unnamed set" tells a reader
94
- * without a TypeScript runtime nothing — and that reader is the whole point.
95
- */
96
- export function renderEnvVariables(
97
- variables: Record<string, z.ZodType> = applicationVariables,
98
- ): ProjectEnvVariable[] {
99
- const json = JsonSchemaSchema.parse(
100
- z.toJSONSchema(z.object(variables), { io: 'input', unrepresentable: 'any' }),
101
- );
102
- const required = new Set(json.required ?? []);
103
- return Object.entries(json.properties)
104
- .map(([name, property]) => describeVariable(name, property, required.has(name)))
105
- .sort((left, right) => left.name.localeCompare(right.name));
106
- }
107
-
108
- function describeVariable(
109
- name: string,
110
- property: { type?: string; format?: string; enum?: unknown[] },
111
- required: boolean,
112
- ): ProjectEnvVariable {
113
- if (property.enum) {
114
- // Members are rejected rather than stringified. `String(member)` would turn
115
- // numbers and booleans into text that does not match the value the Zod
116
- // schema accepts, so a deployment reading the declaration would supply
117
- // something the application then rejects — the declaration would be derived
118
- // and still wrong.
119
- const members = property.enum.filter((member) => typeof member === 'string');
120
- if (members.length !== property.enum.length) {
121
- throw new Error(
122
- `Environment variable ${name} declares a non-string enum member. The declaration format carries enum members as strings; declare it as a string enum, or extend the format first.`,
123
- );
124
- }
125
- return { name, shape: 'enum', required, members };
126
- }
127
- if (property.format === 'uri') return { name, shape: 'url', required };
128
- if (property.type === undefined || property.type === 'string') {
129
- return { name, shape: 'string', required };
130
- }
131
- const shape = SHAPE_BY_JSON_TYPE[property.type];
132
- if (!shape) {
133
- // Fail closed rather than describe the variable with the wrong shape: a
134
- // reader acting on `string` when the value is something else is worse off
135
- // than a reader told this project cannot describe it.
136
- throw new Error(
137
- `Cannot describe ${name}: no declaration shape for JSON Schema type "${property.type}".`,
138
- );
139
- }
140
- return { name, shape, required };
141
- }
142
-
143
60
  /** The declaration as it must appear on disk: authored fields plus derived ones. */
144
61
  export function renderProjectJson(): string {
145
62
  const declaration: ProjectDeclaration = {
@@ -0,0 +1,83 @@
1
+ import type { ProjectEnvVariable } from 'stitchkit/declaration';
2
+ import { z } from 'zod';
3
+ import { applicationVariables } from '../packages/config/src/variables';
4
+
5
+ /**
6
+ * JSON Schema types this projection can carry into the declaration.
7
+ *
8
+ * Mapping `number` to `integer` would misrepresent fractional values and make
9
+ * the declaration disagree with its Zod source. A type with no faithful shape
10
+ * is rejected: the declaration format gains the shape, or the project stops
11
+ * declaring that type.
12
+ */
13
+ const SHAPE_BY_JSON_TYPE: Record<string, ProjectEnvVariable['shape']> = {
14
+ integer: 'integer',
15
+ boolean: 'boolean',
16
+ };
17
+
18
+ const JsonSchemaSchema = z.object({
19
+ properties: z.record(
20
+ z.string(),
21
+ z.object({
22
+ type: z.string().optional(),
23
+ format: z.string().optional(),
24
+ enum: z.array(z.unknown()).optional(),
25
+ }),
26
+ ),
27
+ required: z.array(z.string()).optional(),
28
+ });
29
+
30
+ /**
31
+ * The variables a deployment must supply, derived from the one Zod declaration.
32
+ *
33
+ * `required` follows the schema exactly: a variable with a default or an
34
+ * `.optional()` is not required, and nothing here restates that judgement. An
35
+ * enum carries its members, because "one of an unnamed set" tells a reader
36
+ * without a TypeScript runtime nothing — and that reader is the whole point.
37
+ */
38
+ export function renderEnvVariables(
39
+ variables: Record<string, z.ZodType> = applicationVariables,
40
+ ): ProjectEnvVariable[] {
41
+ const json = JsonSchemaSchema.parse(
42
+ z.toJSONSchema(z.object(variables), { io: 'input', unrepresentable: 'any' }),
43
+ );
44
+ const required = new Set(json.required ?? []);
45
+ return Object.entries(json.properties)
46
+ .map(([name, property]) => describeVariable(name, property, required.has(name)))
47
+ .sort((left, right) => left.name.localeCompare(right.name));
48
+ }
49
+
50
+ function describeVariable(
51
+ name: string,
52
+ property: { type?: string; format?: string; enum?: unknown[] },
53
+ required: boolean,
54
+ ): ProjectEnvVariable {
55
+ if (property.enum) {
56
+ // Members are rejected rather than stringified. `String(member)` would turn
57
+ // numbers and booleans into text that does not match the value the Zod
58
+ // schema accepts, so a deployment reading the declaration would supply
59
+ // something the application then rejects — the declaration would be derived
60
+ // and still wrong.
61
+ const members = property.enum.filter((member) => typeof member === 'string');
62
+ if (members.length !== property.enum.length) {
63
+ throw new Error(
64
+ `Environment variable ${name} declares a non-string enum member. The declaration format carries enum members as strings; declare it as a string enum, or extend the format first.`,
65
+ );
66
+ }
67
+ return { name, shape: 'enum', required, members };
68
+ }
69
+ if (property.format === 'uri') return { name, shape: 'url', required };
70
+ if (property.type === undefined || property.type === 'string') {
71
+ return { name, shape: 'string', required };
72
+ }
73
+ const shape = SHAPE_BY_JSON_TYPE[property.type];
74
+ if (!shape) {
75
+ // Fail closed rather than describe the variable with the wrong shape: a
76
+ // reader acting on `string` when the value is something else is worse off
77
+ // than a reader told this project cannot describe it.
78
+ throw new Error(
79
+ `Cannot describe ${name}: no declaration shape for JSON Schema type "${property.type}".`,
80
+ );
81
+ }
82
+ return { name, shape, required };
83
+ }
@@ -1,8 +1,20 @@
1
1
  import { describe, expect, test } from 'bun:test';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { resolve } from 'node:path';
4
+ import {
5
+ assertSurfaceDiscovery,
6
+ assertSurfaceManifestSnapshot,
7
+ SurfaceManifestSchema,
8
+ } from 'stitchkit/testing';
9
+ import { createSurface } from '../packages/backend/src/surface';
4
10
  import { appDeclaration } from '../packages/config/src/declaration';
5
11
  import { declaredRoleReadiness } from './readiness';
12
+ import {
13
+ buildAppSurfaceManifest,
14
+ discoverCliCommands,
15
+ discoverMcpTools,
16
+ SURFACE_SNAPSHOT_PATH,
17
+ } from './surface-snapshot';
6
18
  import { planPortabilityCheck } from './web-surface-smoke';
7
19
 
8
20
  const dialled = 'http://127.0.0.1:3210';
@@ -175,3 +187,40 @@ describe('a role is ready when it answers, not when it is spawned', () => {
175
187
  ).toThrow(/WEB_PORT/);
176
188
  });
177
189
  });
190
+
191
+ describe('committed surface snapshot', () => {
192
+ const root = resolve(import.meta.dir, '..');
193
+
194
+ test('the committed snapshot matches the live contract manifest', async () => {
195
+ const snapshot = SurfaceManifestSchema.parse(
196
+ JSON.parse(readFileSync(resolve(root, SURFACE_SNAPSHOT_PATH), 'utf8')),
197
+ );
198
+ const { services, socket, hub, board } = await createSurface();
199
+ try {
200
+ const manifest = buildAppSurfaceManifest(services);
201
+ expect(() => assertSurfaceManifestSnapshot(manifest, snapshot)).not.toThrow();
202
+ } finally {
203
+ await Promise.allSettled([hub.close(), board.close(), socket.close()]);
204
+ }
205
+ });
206
+
207
+ test('the CLI surface observed from the spawned process matches the committed snapshot', async () => {
208
+ const snapshot = SurfaceManifestSchema.parse(
209
+ JSON.parse(readFileSync(resolve(root, SURFACE_SNAPSHOT_PATH), 'utf8')),
210
+ );
211
+ const commands = await discoverCliCommands(root);
212
+ expect(() => assertSurfaceDiscovery(snapshot, { CLI: commands })).not.toThrow();
213
+ });
214
+
215
+ test('a broken /mcp endpoint rejects discovery even when zero tools are expected', async () => {
216
+ const broken = Bun.serve({
217
+ port: 0,
218
+ fetch: () => new Response('not the MCP endpoint', { status: 404 }),
219
+ });
220
+ try {
221
+ await expect(discoverMcpTools(`http://127.0.0.1:${broken.port}`)).rejects.toThrow();
222
+ } finally {
223
+ broken.stop(true);
224
+ }
225
+ });
226
+ });
@@ -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.1"
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.3.0"
40
+ "bun": ">=1.4.0"
41
41
  },
42
42
  "packageManager": "bun@1.4.5"
43
43
  }
@@ -4,7 +4,6 @@
4
4
  "identity": {
5
5
  "slug": "stitchkit-agent-starter",
6
6
  "name": "Stitchkit Agent Starter",
7
- "version": "0.1.0",
8
7
  "description": {
9
8
  "en": "A durable terminal coding agent built with Stitchkit."
10
9
  }
@@ -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,
@@ -28,7 +28,7 @@
28
28
  "typescript": "^7.0.2"
29
29
  },
30
30
  "engines": {
31
- "bun": ">=1.3.0"
31
+ "bun": ">=1.4.0"
32
32
  },
33
33
  "packageManager": "bun@1.4.5"
34
34
  }
@@ -4,7 +4,6 @@
4
4
  "identity": {
5
5
  "slug": "stitchkit-telegram-bot-starter",
6
6
  "name": "Stitchkit Telegram Bot Starter",
7
- "version": "0.1.0",
8
7
  "description": {
9
8
  "en": "A long-polling Telegram bot assembled from Stitchkit primitives."
10
9
  }
Binary file