create-ailk 0.44.0 → 0.45.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.
@@ -0,0 +1,334 @@
1
+ /**
2
+ * @jest-environment node
3
+ */
4
+
5
+ /**
6
+ * `readServedMcpTools` against a `node:http` stub of the MCP server's
7
+ * anonymous `/mcp` route (#11951 spec AC-1, AC-2, §5.2): the four-step
8
+ * exchange in both transport modes, `nextCursor` paging, every failed-read
9
+ * shape resolving `null`, the 60-second shared answer and the user agent.
10
+ */
11
+
12
+ import {
13
+ MCP_DISCOVERY_USER_AGENT,
14
+ MCP_TOOLS_TIMEOUT_MS,
15
+ MCP_TOOLS_TTL_MS,
16
+ __resetServedMcpToolsForTests,
17
+ readServedMcpTools,
18
+ } from "../mcp-served-tools";
19
+
20
+ import {
21
+ refusedUrl,
22
+ startMcpStub,
23
+ type McpStub,
24
+ type McpStubOptions,
25
+ type StubTool,
26
+ } from "./fixtures/mcp-stub-server";
27
+
28
+ const SERVED: readonly StubTool[] = [
29
+ {
30
+ name: "capture_lead",
31
+ description: "Capture a lead.",
32
+ inputSchema: { type: "object", properties: { email: { type: "string" } } },
33
+ },
34
+ {
35
+ name: "zz_not_in_catalog",
36
+ description: "A tool newer than the web's catalog.",
37
+ inputSchema: { type: "object", properties: {} },
38
+ },
39
+ {
40
+ name: "list_pages",
41
+ description: "List pages.",
42
+ inputSchema: { type: "object", properties: {} },
43
+ },
44
+ ];
45
+
46
+ const stubs: McpStub[] = [];
47
+ async function stub(options: Partial<McpStubOptions> = {}): Promise<McpStub> {
48
+ const started = await startMcpStub({ mode: "stateless", tools: SERVED, ...options });
49
+ stubs.push(started);
50
+ return started;
51
+ }
52
+
53
+ beforeEach(() => {
54
+ __resetServedMcpToolsForTests();
55
+ });
56
+
57
+ afterEach(async () => {
58
+ jest.restoreAllMocks();
59
+ await Promise.all(stubs.splice(0).map((s) => s.close()));
60
+ });
61
+
62
+ describe("readServedMcpTools — the exchange (AC-1)", () => {
63
+ it.each(["stateless", "stateful"] as const)(
64
+ "%s: returns the served entries in the server's order",
65
+ async (mode) => {
66
+ const server = await stub({ mode });
67
+ expect(await readServedMcpTools(server.url)).toEqual(SERVED);
68
+ },
69
+ );
70
+
71
+ it("stateful: initialize, initialized, tools/list with the session, then DELETE", async () => {
72
+ const server = await stub({ mode: "stateful" });
73
+ await readServedMcpTools(server.url);
74
+
75
+ expect(server.requests.map((r) => [r.method, r.rpcMethod])).toEqual([
76
+ ["POST", "initialize"],
77
+ ["POST", "notifications/initialized"],
78
+ ["POST", "tools/list"],
79
+ ["DELETE", undefined],
80
+ ]);
81
+ for (const r of server.requests.slice(1)) {
82
+ expect(r.headers["mcp-session-id"]).toBe("stub-session-1");
83
+ expect(r.headers["mcp-protocol-version"]).toBe("2025-03-26");
84
+ }
85
+ expect(server.requests[3]?.headers["content-type"]).toBeUndefined();
86
+ });
87
+
88
+ it("stateless: no session header and no DELETE", async () => {
89
+ const server = await stub({ mode: "stateless" });
90
+ await readServedMcpTools(server.url);
91
+
92
+ expect(server.requests.map((r) => r.rpcMethod)).toEqual([
93
+ "initialize",
94
+ "notifications/initialized",
95
+ "tools/list",
96
+ ]);
97
+ for (const r of server.requests) {
98
+ expect(r.headers["mcp-session-id"]).toBeUndefined();
99
+ }
100
+ });
101
+
102
+ it.each(["stateless", "stateful"] as const)(
103
+ "%s: follows nextCursor across pages",
104
+ async (mode) => {
105
+ const server = await stub({ mode, pageSize: 2 });
106
+ expect((await readServedMcpTools(server.url))?.map((t) => t.name)).toEqual([
107
+ "capture_lead",
108
+ "zz_not_in_catalog",
109
+ "list_pages",
110
+ ]);
111
+ const lists = server.requests.filter((r) => r.rpcMethod === "tools/list");
112
+ expect(lists).toHaveLength(2);
113
+ expect(lists[0]?.params).toEqual({});
114
+ expect(lists[1]?.params).toEqual({ cursor: "2" });
115
+ },
116
+ );
117
+
118
+ it("keeps an entry's description optional", async () => {
119
+ const server = await stub({
120
+ tools: [{ name: "bare", inputSchema: { type: "object" } }],
121
+ });
122
+ expect(await readServedMcpTools(server.url)).toEqual([
123
+ { name: "bare", inputSchema: { type: "object" } },
124
+ ]);
125
+ });
126
+ });
127
+
128
+ describe("readServedMcpTools — a failed read is null, never a rejection (AC-2)", () => {
129
+ async function overriding(
130
+ override: NonNullable<McpStubOptions["override"]>,
131
+ mode: McpStubOptions["mode"] = "stateless",
132
+ ): Promise<string> {
133
+ return (await stub({ mode, override })).url;
134
+ }
135
+
136
+ const rpcBody = (id: unknown, result: unknown) =>
137
+ JSON.stringify({ jsonrpc: "2.0", id, result });
138
+
139
+ it("(i) the connection is refused", async () => {
140
+ await expect(readServedMcpTools(await refusedUrl())).resolves.toBeNull();
141
+ });
142
+
143
+ it("(ii) initialize answers 500", async () => {
144
+ const url = await overriding((r) =>
145
+ r.rpcMethod === "initialize" ? { status: 500 } : undefined,
146
+ );
147
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
148
+ });
149
+
150
+ it("(iii) tools/list answers a body that is not JSON", async () => {
151
+ const url = await overriding((r) =>
152
+ r.rpcMethod === "tools/list"
153
+ ? { status: 200, contentType: "application/json", body: "<html>oops" }
154
+ : undefined,
155
+ );
156
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
157
+ });
158
+
159
+ it(
160
+ "(iv) the server never answers — bounded by the deadline",
161
+ async () => {
162
+ const url = await overriding(() => "hang");
163
+ const started = Date.now();
164
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
165
+ expect(Date.now() - started).toBeLessThan(MCP_TOOLS_TIMEOUT_MS + 1000);
166
+ },
167
+ MCP_TOOLS_TIMEOUT_MS + 2000,
168
+ );
169
+
170
+ it("stateful: a failed tools/list still ends the session", async () => {
171
+ const server = await stub({
172
+ mode: "stateful",
173
+ override: (r) => (r.rpcMethod === "tools/list" ? { status: 503 } : undefined),
174
+ });
175
+ await expect(readServedMcpTools(server.url)).resolves.toBeNull();
176
+ expect(server.requests.at(-1)?.method).toBe("DELETE");
177
+ expect(server.requests.at(-1)?.headers["mcp-session-id"]).toBe("stub-session-1");
178
+ });
179
+
180
+ it("tools/list answers non-2xx", async () => {
181
+ const url = await overriding((r) =>
182
+ r.rpcMethod === "tools/list" ? { status: 503 } : undefined,
183
+ );
184
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
185
+ });
186
+
187
+ it("tools/list answers a JSON-RPC error", async () => {
188
+ const url = await overriding((r) =>
189
+ r.rpcMethod === "tools/list"
190
+ ? {
191
+ status: 200,
192
+ contentType: "application/json",
193
+ body: JSON.stringify({
194
+ jsonrpc: "2.0",
195
+ id: r.rpcId,
196
+ error: { code: -32603, message: "boom" },
197
+ }),
198
+ }
199
+ : undefined,
200
+ );
201
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
202
+ });
203
+
204
+ it("result.tools is not an array", async () => {
205
+ const url = await overriding((r) =>
206
+ r.rpcMethod === "tools/list"
207
+ ? { status: 200, contentType: "application/json", body: rpcBody(r.rpcId, { tools: {} }) }
208
+ : undefined,
209
+ );
210
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
211
+ });
212
+
213
+ it("an entry has no string name", async () => {
214
+ const url = await overriding((r) =>
215
+ r.rpcMethod === "tools/list"
216
+ ? {
217
+ status: 200,
218
+ contentType: "application/json",
219
+ body: rpcBody(r.rpcId, { tools: [{ name: 7, inputSchema: {} }] }),
220
+ }
221
+ : undefined,
222
+ );
223
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
224
+ });
225
+
226
+ it("an entry has no object inputSchema", async () => {
227
+ const url = await overriding((r) =>
228
+ r.rpcMethod === "tools/list"
229
+ ? {
230
+ status: 200,
231
+ contentType: "application/json",
232
+ body: rpcBody(r.rpcId, { tools: [{ name: "x" }] }),
233
+ }
234
+ : undefined,
235
+ );
236
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
237
+ });
238
+
239
+ it("the answer's id does not match the request's", async () => {
240
+ const url = await overriding((r) =>
241
+ r.rpcMethod === "tools/list"
242
+ ? {
243
+ status: 200,
244
+ contentType: "application/json",
245
+ body: JSON.stringify({ jsonrpc: "2.0", id: 999, result: { tools: [] } }),
246
+ }
247
+ : undefined,
248
+ );
249
+ await expect(readServedMcpTools(url)).resolves.toBeNull();
250
+ });
251
+
252
+ it("a tenth page still carries nextCursor", async () => {
253
+ const many: StubTool[] = Array.from({ length: 11 }, (_, i) => ({
254
+ name: `t${i}`,
255
+ inputSchema: { type: "object" },
256
+ }));
257
+ const server = await stub({ tools: many, pageSize: 1 });
258
+ await expect(readServedMcpTools(server.url)).resolves.toBeNull();
259
+ expect(server.requests.filter((r) => r.rpcMethod === "tools/list")).toHaveLength(10);
260
+ });
261
+
262
+ it("a default user agent is refused by the guard, so the constant is what passes", async () => {
263
+ const server = await stub();
264
+ const res = await fetch(server.url, {
265
+ method: "POST",
266
+ headers: {
267
+ accept: "application/json, text/event-stream",
268
+ "content-type": "application/json",
269
+ },
270
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),
271
+ });
272
+ expect(res.status).toBe(403);
273
+ expect(await readServedMcpTools(server.url)).toEqual(SERVED);
274
+ });
275
+ });
276
+
277
+ describe("readServedMcpTools — sharing and the user agent (§5.2)", () => {
278
+ const handshakes = (s: McpStub) =>
279
+ s.requests.filter((r) => r.rpcMethod === "initialize").length;
280
+
281
+ it("two concurrent calls make one handshake", async () => {
282
+ const server = await stub();
283
+ const [a, b] = await Promise.all([
284
+ readServedMcpTools(server.url),
285
+ readServedMcpTools(server.url),
286
+ ]);
287
+ expect(a).toEqual(SERVED);
288
+ expect(b).toEqual(SERVED);
289
+ expect(handshakes(server)).toBe(1);
290
+ });
291
+
292
+ it("a call inside the window makes none; one after it makes a new one", async () => {
293
+ const server = await stub();
294
+ const now = Date.now();
295
+ const clock = jest.spyOn(Date, "now").mockReturnValue(now);
296
+ await readServedMcpTools(server.url);
297
+ clock.mockReturnValue(now + MCP_TOOLS_TTL_MS - 1);
298
+ await readServedMcpTools(server.url);
299
+ expect(handshakes(server)).toBe(1);
300
+ clock.mockReturnValue(now + MCP_TOOLS_TTL_MS);
301
+ await readServedMcpTools(server.url);
302
+ expect(handshakes(server)).toBe(2);
303
+ });
304
+
305
+ it("a failure is shared too, inside the window", async () => {
306
+ const server = await stub({
307
+ override: (r) => (r.rpcMethod === "initialize" ? { status: 500 } : undefined),
308
+ });
309
+ expect(await readServedMcpTools(server.url)).toBeNull();
310
+ expect(await readServedMcpTools(server.url)).toBeNull();
311
+ expect(handshakes(server)).toBe(1);
312
+ });
313
+
314
+ it("a different URL makes its own", async () => {
315
+ const one = await stub();
316
+ const two = await stub({ tools: SERVED.slice(0, 1) });
317
+ expect(await readServedMcpTools(one.url)).toEqual(SERVED);
318
+ expect(await readServedMcpTools(two.url)).toEqual(SERVED.slice(0, 1));
319
+ expect(handshakes(one)).toBe(1);
320
+ expect(handshakes(two)).toBe(1);
321
+ });
322
+
323
+ it("every request carries MCP_DISCOVERY_USER_AGENT, which no built-in guard pattern matches", async () => {
324
+ const server = await stub({ mode: "stateful" });
325
+ await readServedMcpTools(server.url);
326
+ expect(server.requests.length).toBeGreaterThan(0);
327
+ for (const r of server.requests) {
328
+ expect(r.headers["user-agent"]).toBe(MCP_DISCOVERY_USER_AGENT);
329
+ }
330
+ for (const pattern of [/curl\//i, /node-fetch/i, /axios/i, /python-requests/i]) {
331
+ expect(MCP_DISCOVERY_USER_AGENT).not.toMatch(pattern);
332
+ }
333
+ });
334
+ });
@@ -200,16 +200,17 @@ if (SOURCE === "database") process.env.AILK_API_URL = "http://127.0.0.1:9";
200
200
  /**
201
201
  * Every page the snapshot holds, keyed by its cache tag
202
202
  * (`content:<workspace>:<type>:<slug>:<locale>`, `cache-tags.ts`), or why it
203
- * holds none. Read only under `database`.
203
+ * holds none, and whether the file is `absent` (#11941 D1). Read only under
204
+ * `database`.
204
205
  */
205
- function readHubPages(): {
206
+ function readHubPages(path = join(process.cwd(), SNAPSHOT_REL)): {
206
207
  pages: Array<{ locale: string; type: string; slug: string }>;
207
208
  problem: string | null;
209
+ absent: boolean;
208
210
  } {
209
- const path = join(process.cwd(), SNAPSHOT_REL);
210
211
  const build = "run `pnpm --filter web build` under CONTENT_ADAPTER=database to write it";
211
212
  if (!existsSync(path)) {
212
- return { pages: [], problem: `${path} does not exist — ${build}` };
213
+ return { pages: [], problem: `${path} does not exist — ${build}`, absent: true };
213
214
  }
214
215
  let parsed: { version?: unknown; pages?: unknown; lists?: unknown } | null;
215
216
  try {
@@ -226,7 +227,11 @@ function readHubPages(): {
226
227
  typeof parsed.lists !== "object" ||
227
228
  parsed.lists === null
228
229
  ) {
229
- return { pages: [], problem: `${path} is not a version-1 content snapshot — ${build}` };
230
+ return {
231
+ pages: [],
232
+ problem: `${path} is not a version-1 content snapshot — ${build}`,
233
+ absent: false,
234
+ };
230
235
  }
231
236
  const pages = Object.keys(parsed.pages).map((tag) => {
232
237
  const parts = tag.split(":");
@@ -237,12 +242,27 @@ function readHubPages(): {
237
242
  };
238
243
  });
239
244
  if (pages.length === 0) {
240
- return { pages, problem: `${path} holds no page — ${build}` };
245
+ return { pages, problem: `${path} holds no page — ${build}`, absent: false };
241
246
  }
242
- return { pages, problem: null };
247
+ return { pages, problem: null, absent: false };
248
+ }
249
+
250
+ const HUB = SOURCE === "database" ? readHubPages() : { pages: [], problem: null, absent: false };
251
+
252
+ /**
253
+ * #11941 D1 — why this run does not check the hub's pages, or null when it
254
+ * does. Only a database-served run with no snapshot file skips: that is
255
+ * `pnpm test` before any database build. A snapshot that is present but
256
+ * unreadable or empty still fails, and a files-served run never skips.
257
+ */
258
+ function snapshotSkipReason(
259
+ source: string,
260
+ hub: { problem: string | null; absent: boolean },
261
+ ): string | null {
262
+ return source === "database" && hub.absent ? hub.problem : null;
243
263
  }
244
264
 
245
- const HUB = SOURCE === "database" ? readHubPages() : { pages: [], problem: null };
265
+ const HUB_SKIP = snapshotSkipReason(SOURCE, HUB);
246
266
 
247
267
  /** The snapshot's (locale, type) pairs, in the shape the content walk takes. */
248
268
  function hubTypeDirs(): Array<{ locale: string; typeDir: string }> {
@@ -369,7 +389,12 @@ describe("structured data — every content page builds valid JSON-LD", () => {
369
389
 
370
390
  it("finds content to check", () => {
371
391
  if (SOURCE === "database") {
372
- // A hub-served site with no snapshot has nothing to check: misconfigured.
392
+ // #11941 D2 — no snapshot yet: the run is before any database build.
393
+ if (HUB_SKIP !== null) {
394
+ console.info(`structured-data: content walk not checked — ${HUB_SKIP}`);
395
+ return;
396
+ }
397
+ // A present snapshot that is unreadable or holds no page: misconfigured.
373
398
  expect(HUB.problem).toBeNull();
374
399
  return;
375
400
  }
@@ -378,7 +403,8 @@ describe("structured data — every content page builds valid JSON-LD", () => {
378
403
  expect(typeDirs.length).toBeGreaterThan(0);
379
404
  });
380
405
 
381
- it.each(typeDirs)(
406
+ // #11941 D2 — a run with no snapshot has no table to walk; it says so above.
407
+ if (HUB_SKIP === null) it.each(typeDirs)(
382
408
  "content/$locale/$typeDir — every page validates as its type",
383
409
  async ({ locale, typeDir }) => {
384
410
  if (!(SCHEMA_ORG_TYPES as readonly string[]).includes(typeDir)) {
@@ -831,6 +857,11 @@ describe("structured data — every route emits a valid JSON-LD script", () => {
831
857
  DEFAULT_LOCALE,
832
858
  );
833
859
  if (page === null) {
860
+ // #11941 D3 — no snapshot yet: name the route, do not fail it.
861
+ if (HUB_SKIP !== null) {
862
+ console.info(`structured-data: ${label} not checked — ${HUB_SKIP}`);
863
+ return;
864
+ }
834
865
  throw new Error(
835
866
  SOURCE === "database"
836
867
  ? `${label}: renders ${type}/${identity.slug}, but the hub serves no such page (${SNAPSHOT_REL}) — the route serves 404 in production.`
@@ -857,7 +888,9 @@ describe("structured data — every route emits a valid JSON-LD script", () => {
857
888
  slugs = served.map((p: ContentPage) => p.slug);
858
889
  if (slugs.length === 0) {
859
890
  console.info(
860
- `structured-data: ${label} has no ${type} content in ${DEFAULT_LOCALE}; every slug serves 404 in production — nothing to check`,
891
+ HUB_SKIP !== null
892
+ ? `structured-data: ${label} not checked — ${HUB_SKIP}`
893
+ : `structured-data: ${label} has no ${type} content in ${DEFAULT_LOCALE}; every slug serves 404 in production — nothing to check`,
861
894
  );
862
895
  return;
863
896
  }
@@ -1054,6 +1087,70 @@ describe("structured data — exemption(route, src) keys a standard magnet page
1054
1087
  });
1055
1088
  });
1056
1089
 
1090
+ // ── 2c. #11941 D4 — the skip rule, pinned in the default run ───────────────
1091
+
1092
+ describe("structured data — only a database run with no snapshot skips the hub's pages (#11941)", () => {
1093
+ // Reads a snapshot holding `body` (none when null) from a fresh temp dir.
1094
+ function readSnapshot(body: string | null) {
1095
+ const root = mkdtempSync(join(tmpdir(), "ailk-11941-sd-"));
1096
+ try {
1097
+ const path = join(root, "content-snapshot.json");
1098
+ if (body !== null) writeFileSync(path, body);
1099
+ return readHubPages(path);
1100
+ } finally {
1101
+ rmSync(root, { recursive: true, force: true });
1102
+ }
1103
+ }
1104
+ const UNREADABLE = "not json";
1105
+ const EMPTY = JSON.stringify({ version: 1, pages: {}, lists: {} });
1106
+ const ONE_PAGE = JSON.stringify({
1107
+ version: 1,
1108
+ pages: { "content:w:HomePage:home:en": {} },
1109
+ lists: {},
1110
+ });
1111
+
1112
+ it("reads an absent snapshot as absent, with the does-not-exist problem", () => {
1113
+ const hub = readSnapshot(null);
1114
+ expect(hub.absent).toBe(true);
1115
+ expect(hub.pages).toEqual([]);
1116
+ expect(hub.problem).toContain("does not exist");
1117
+ });
1118
+
1119
+ it("reads an unreadable snapshot as present, with the version-1 problem", () => {
1120
+ const hub = readSnapshot(UNREADABLE);
1121
+ expect(hub.absent).toBe(false);
1122
+ expect(hub.problem).toContain("is not a version-1 content snapshot");
1123
+ });
1124
+
1125
+ it("reads a snapshot with no page as present, with the holds-no-page problem", () => {
1126
+ const hub = readSnapshot(EMPTY);
1127
+ expect(hub.absent).toBe(false);
1128
+ expect(hub.problem).toContain("holds no page");
1129
+ });
1130
+
1131
+ it("reads a snapshot's pages from their cache tags", () => {
1132
+ const hub = readSnapshot(ONE_PAGE);
1133
+ expect(hub.absent).toBe(false);
1134
+ expect(hub.problem).toBeNull();
1135
+ expect(hub.pages).toEqual([{ type: "HomePage", slug: "home", locale: "en" }]);
1136
+ });
1137
+
1138
+ it("skips under database only when the snapshot is absent", () => {
1139
+ const absent = readSnapshot(null);
1140
+ expect(
1141
+ [absent, readSnapshot(UNREADABLE), readSnapshot(EMPTY), readSnapshot(ONE_PAGE)].map(
1142
+ (hub) => snapshotSkipReason("database", hub),
1143
+ ),
1144
+ ).toEqual([absent.problem, null, null, null]);
1145
+ });
1146
+
1147
+ it("never skips under a files-served source", () => {
1148
+ const absent = readSnapshot(null);
1149
+ expect(snapshotSkipReason("mdx", absent)).toBeNull();
1150
+ expect(snapshotSkipReason("projection", absent)).toBeNull();
1151
+ });
1152
+ });
1153
+
1057
1154
  // ── 3. The two defect shapes that shipped, pinned ───────────────────────────
1058
1155
  //
1059
1156
  // These prove the checks above reach the validator rule that rejects each
@@ -4,7 +4,7 @@
4
4
  * `@working-theory/license` renews the deployment's key before it lapses and
5
5
  * keeps the renewed key in a `LicenseKeyStore`. Its default store is a file,
6
6
  * which a redeploy wipes — and this app's one real `checkLicense()` caller
7
- * (`src/lib/commerce-claim.ts`, gating /purchase/* and /.well-known/mcp.json)
7
+ * (`src/lib/commerce-claim.ts`, gating /purchase/*)
8
8
  * would then run on the older `AILK_LICENSE_KEY` alone. With a database
9
9
  * configured, this registers the store backed by ONE deployment-wide
10
10
  * `SiteSetting` row, `(DEFAULT_WORKSPACE_ID, "license.renewed_key")`, shared