forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-integration.test.ts
More file actions
1319 lines (1212 loc) · 44.5 KB
/
Copy pathcreate-integration.test.ts
File metadata and controls
1319 lines (1212 loc) · 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// create-integration.test.ts — exercises the real generator end-to-end
// against FULLY ISOLATED tmpdir-backed packages and workflows directories.
//
// Previously the test pointed the generator at the real `showcase/integrations/`
// and `.github/workflows/` trees and snapshotted the mutated files back to
// HEAD in `afterEach`. Under `fileParallelism: true` that collided with
// `generate-registry.test.ts` (concurrent `readdirSync` of
// `showcase/integrations/` saw partial state → ENOENT) AND with every suite that
// healed workflow YAMLs via `git checkout HEAD --` (`.git/index.lock`).
//
// The generator now honors `CREATE_INTEGRATION_PACKAGES_DIR` and
// `CREATE_INTEGRATION_WORKFLOWS_DIR` env overrides. This file creates a
// per-suite tmpdir, seeds it with copies of the real workflow YAMLs (so the
// generator's regex-based edits still match), and points both env vars
// there. No real tracked file is ever mutated — no restorer, no git
// invocation, no cross-suite shared state.
import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
import fs from "fs";
import os from "os";
import path from "path";
import { execFileSync } from "child_process";
import yaml from "yaml";
import Ajv from "ajv";
import addFormats from "ajv-formats";
import { execOptsFor } from "./test-cleanup";
import { SCRIPTS_DIR } from "./paths";
const SCHEMA_PATH = path.resolve(
SCRIPTS_DIR,
"..",
"shared",
"manifest.schema.json",
);
const FEATURE_REGISTRY_PATH = path.resolve(
SCRIPTS_DIR,
"..",
"shared",
"feature-registry.json",
);
const TEST_SLUG = "test-integration-tmp";
// Regression test uses its own slug so the generator always has fresh work to
// do; the primary slug is already consumed by earlier tests in the file.
const REGRESSION_SLUG = "test-integration-tmp-regression-guard";
const TEST_SLUGS: readonly string[] = [TEST_SLUG, REGRESSION_SLUG];
// Inline fixture workflow YAMLs — just enough structural anchors for the
// generator's regex-based edits to match. Previously the test seeded from
// the real `.github/workflows/*.yml` files, which meant any drift to
// those files silently broke the test via a hidden dependency (E4). The
// fixtures below are frozen mini-workflows: they carry only the
// anchors documented by `showcase/scripts/create-integration/index.ts`:
// - `options:` list (workflow_dispatch input)
// - `outputs:` map with `${{ ... }}` values
// - `filters: |` block with at least one nested key + list item
// - `starter:` block sequence for starter-smoke
// and nothing else. If the generator learns new anchors, add them here.
const WORKFLOW_FIXTURES: Record<string, string> = {
"showcase_deploy.yml": `name: Showcase Deploy
on:
workflow_dispatch:
inputs:
service:
description: Which service to deploy
required: false
default: all
type: choice
options:
- all
- fixture-a
- fixture-b
jobs:
detect-changes:
name: Detect Changes
runs-on: ubuntu-latest
outputs:
fixture_a: \${{ steps.changes.outputs.fixture_a }}
fixture_b: \${{ steps.changes.outputs.fixture_b }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v3
id: changes
with:
filters: |
fixture_a:
- 'showcase/integrations/fixture-a/**'
fixture_b:
- 'showcase/integrations/fixture-b/**'
check-lockfile:
name: Check Lockfile
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo ok
`,
"test_smoke-starter.yml": `name: Starter Smoke
on: { workflow_dispatch: {} }
jobs:
smoke:
strategy:
matrix:
starter:
- fixture-a
- fixture-b
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: echo ok
`,
};
const WORKFLOW_BASENAMES: readonly string[] = Object.keys(WORKFLOW_FIXTURES);
// Lazily populated in `beforeAll` — cast via ! below because TypeScript can't
// follow that these are always set before any test runs.
let TMP_ROOT!: string;
let TMP_PACKAGES_DIR!: string;
let TMP_WORKFLOWS_DIR!: string;
let TEST_DIR!: string;
let REGRESSION_DIR!: string;
// Per-suite baseline of each workflow's content, captured once after seeding
// so `cleanup()` can restore them without re-reading the real files.
const WORKFLOW_BASELINES = new Map<string, Buffer>();
function cleanup() {
// Remove any scaffolded package dirs the generator produced.
for (const slug of TEST_SLUGS) {
const dir = path.join(TMP_PACKAGES_DIR, slug);
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
// Restore each seeded workflow to its baseline so the next test starts
// with the same anchors the generator's regex edits expect.
for (const [p, baseline] of WORKFLOW_BASELINES) {
fs.writeFileSync(p, baseline);
}
}
beforeAll(() => {
TMP_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "create-integration-"));
TMP_PACKAGES_DIR = path.join(TMP_ROOT, "integrations");
TMP_WORKFLOWS_DIR = path.join(TMP_ROOT, "workflows");
TEST_DIR = path.join(TMP_PACKAGES_DIR, TEST_SLUG);
REGRESSION_DIR = path.join(TMP_PACKAGES_DIR, REGRESSION_SLUG);
fs.mkdirSync(TMP_PACKAGES_DIR, { recursive: true });
fs.mkdirSync(TMP_WORKFLOWS_DIR, { recursive: true });
// Seed our tmp workflows dir from frozen inline fixtures. Pre-fix (E4)
// this copied from `.github/workflows/` — any drift there silently
// broke the test because the regex anchors lived in a file outside
// this suite's control. The WORKFLOW_FIXTURES constants above carry
// the anchors the generator expects; the suite is now hermetic.
for (const basename of WORKFLOW_BASENAMES) {
const dst = path.join(TMP_WORKFLOWS_DIR, basename);
const content = Buffer.from(WORKFLOW_FIXTURES[basename]!, "utf-8");
fs.writeFileSync(dst, content);
WORKFLOW_BASELINES.set(dst, content);
}
});
beforeEach(cleanup);
afterAll(() => {
fs.rmSync(TMP_ROOT, { recursive: true, force: true });
});
/** Invoke `npx tsx create-integration/index.ts` with argv-style args so none
* of the slug / feature strings ever hit a shell parser. Previous revisions
* used `execSync(string)` with interpolated slugs — safe today because the
* slugs are constants, but a poor hygiene pattern worth stamping out.
*
* Sets `CREATE_INTEGRATION_{PACKAGES,WORKFLOWS}_DIR` so the generator
* writes entirely inside our per-suite tmpdir. */
function runGenerator(args: readonly string[]): { stdout: string } {
const baseOpts = execOptsFor(SCRIPTS_DIR);
const stdout = execFileSync(
"npx",
["tsx", "create-integration/index.ts", ...args],
{
...baseOpts,
env: {
...process.env,
CREATE_INTEGRATION_PACKAGES_DIR: TMP_PACKAGES_DIR,
CREATE_INTEGRATION_WORKFLOWS_DIR: TMP_WORKFLOWS_DIR,
},
},
);
return { stdout: stdout.toString() };
}
describe("Template Generator", () => {
it("generates a valid package structure", () => {
cleanup();
runGenerator([
"--name",
"Test Integration",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat,hitl-in-chat",
]);
// Check directory exists
expect(fs.existsSync(TEST_DIR)).toBe(true);
// Check required files
const requiredFiles = [
"manifest.yaml",
"package.json",
"Dockerfile",
"entrypoint.sh",
".env.example",
".gitignore",
"next.config.ts",
"tsconfig.json",
"playwright.config.ts",
"requirements.txt",
"src/agent_server.py",
"src/app/layout.tsx",
"src/app/globals.css",
"src/app/page.tsx",
"src/app/api/copilotkit/route.ts",
"src/app/api/health/route.ts",
];
for (const file of requiredFiles) {
expect(fs.existsSync(path.join(TEST_DIR, file))).toBe(true);
}
});
it("generates a manifest that passes schema validation", () => {
cleanup();
runGenerator([
"--name",
"Test Integration",
"--slug",
TEST_SLUG,
"--category",
"provider-sdk",
"--language",
"typescript",
"--features",
"agentic-chat,tool-rendering,mcp-apps",
]);
const manifest = yaml.parse(
fs.readFileSync(path.join(TEST_DIR, "manifest.yaml"), "utf-8"),
);
const schema = JSON.parse(fs.readFileSync(SCHEMA_PATH, "utf-8"));
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
const validate = ajv.compile(schema);
const valid = validate(manifest);
if (!valid) {
console.error("Validation errors:", validate.errors);
}
expect(valid).toBe(true);
// New fields should be present with defaults
expect(manifest.generative_ui).toEqual(["constrained-explicit"]);
expect(manifest.interaction_modalities).toEqual(["chat"]);
});
it("generates correct demo stubs for each feature", () => {
cleanup();
runGenerator([
"--name",
"Test Integration",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat,hitl-in-chat,subagents",
]);
const demoIds = ["agentic-chat", "hitl-in-chat", "subagents"];
for (const demoId of demoIds) {
const demoDir = path.join(TEST_DIR, "src", "app", "demos", demoId);
expect(fs.existsSync(demoDir)).toBe(true);
// Frontend page
expect(fs.existsSync(path.join(demoDir, "page.tsx"))).toBe(true);
const page = fs.readFileSync(path.join(demoDir, "page.tsx"), "utf-8");
expect(page).toContain("CopilotKit");
expect(page).toContain("CopilotChat");
// Agent file (Python for this test)
expect(fs.existsSync(path.join(demoDir, "agent.py"))).toBe(true);
// README
expect(fs.existsSync(path.join(demoDir, "README.md"))).toBe(true);
// E2E test
expect(
fs.existsSync(path.join(TEST_DIR, "tests", "e2e", `${demoId}.spec.ts`)),
).toBe(true);
// QA template
expect(fs.existsSync(path.join(TEST_DIR, "qa", `${demoId}.md`))).toBe(
true,
);
}
});
it("generates TypeScript agent files for TS integrations", () => {
cleanup();
runGenerator([
"--name",
"Test TS",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"typescript",
"--features",
"agentic-chat",
]);
const demoDir = path.join(TEST_DIR, "src", "app", "demos", "agentic-chat");
expect(fs.existsSync(path.join(demoDir, "agent.ts"))).toBe(true);
expect(fs.existsSync(path.join(demoDir, "agent.py"))).toBe(false);
// No requirements.txt for TS
expect(fs.existsSync(path.join(TEST_DIR, "requirements.txt"))).toBe(false);
});
it("generates manifest with all declared features and demos", () => {
cleanup();
const features = [
"agentic-chat",
"hitl-in-chat",
"tool-rendering",
"mcp-apps",
];
runGenerator([
"--name",
"Test",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
features.join(","),
]);
const manifest = yaml.parse(
fs.readFileSync(path.join(TEST_DIR, "manifest.yaml"), "utf-8"),
);
expect(manifest.features).toEqual(features);
expect(manifest.demos.length).toBe(features.length);
for (const demo of manifest.demos) {
expect(features).toContain(demo.id);
expect(demo.name).toBeTruthy();
expect(demo.description).toBeTruthy();
expect(demo.route).toMatch(/^\/demos\//);
expect(demo.tags.length).toBeGreaterThan(0);
}
});
it("refuses to create a package if directory already exists", () => {
cleanup();
// Create first
runGenerator([
"--name",
"Test",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
// Try to create again — the generator should refuse.
try {
runGenerator([
"--name",
"Test",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
expect.fail("Should have thrown");
} catch (e: any) {
const stream =
(e.stderr?.toString?.() ?? "") + (e.stdout?.toString?.() ?? "");
expect(stream).toContain("already exists");
}
});
it("validates feature IDs against the registry", () => {
const featureRegistry = JSON.parse(
fs.readFileSync(FEATURE_REGISTRY_PATH, "utf-8"),
);
// All features in the registry should have valid IDs
for (const feature of featureRegistry.features) {
expect(feature.id).toMatch(/^[a-z0-9-]+$/);
expect(feature.name).toBeTruthy();
expect(feature.category).toBeTruthy();
expect(feature.description).toBeTruthy();
}
// Registry should have all expected categories
const categories = new Set(
featureRegistry.categories.map((c: any) => c.id),
);
expect(categories.has("chat-ui")).toBe(true);
expect(categories.has("controlled-generative-ui")).toBe(true);
expect(categories.has("declarative-generative-ui")).toBe(true);
expect(categories.has("open-generative-ui")).toBe(true);
expect(categories.has("operational-generative-ui")).toBe(true);
expect(categories.has("agent-state")).toBe(true);
expect(categories.has("interactivity")).toBe(true);
expect(categories.has("multi-agent")).toBe(true);
expect(categories.has("platform")).toBe(true);
});
// Regression guard — the test-integration-tmp leak.
//
// Before the cleanup fix, running the generator scaffolded a package into
// showcase/integrations/ AND mutated two CI workflow YAMLs (showcase_deploy.yml
// and test_smoke-starter.yml). cleanup() only removed the package dir; the
// workflow mutations leaked into the working tree and on Node 20 CI produced
// `Timeout calling "onTaskUpdate"` -> ELIFECYCLE on every PR.
//
// This test asserts `cleanup()` restores every workflow YAML bit-for-bit.
// The same `cleanup()` function runs in `beforeEach`, so covering it here
// transitively covers the hook. The sentinel append below deliberately
// causes transient tracking drift on the workflow YAMLs for the duration
// of the test — a developer with a git GUI / file watcher will see flicker
// while this test runs; restore() heals it before the test returns.
it("cleanup restores workflow YAMLs after generator mutation (regression: test-integration-tmp leak)", () => {
cleanup();
// Verify we captured at least one workflow baseline to test against.
expect(WORKFLOW_BASELINES.size).toBeGreaterThan(0);
// Run the generator with a dedicated slug so it always has fresh work to
// do (the generator short-circuits once its slug is registered in any
// workflow file).
runGenerator([
"--name",
"Leak Guard",
"--slug",
REGRESSION_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
// Capture pre-sentinel content so we can prove the append was observed
// by the filesystem via a content check (stronger than byte-length:
// resistant to a hypothetical fs shim that updates stat but not bytes).
const preAppendContent = new Map<string, Buffer>();
for (const p of WORKFLOW_BASELINES.keys()) {
preAppendContent.set(p, fs.readFileSync(p));
}
// Defense in depth: force every snapshotted file to differ from its
// baseline regardless of generator output. Safe because we restore
// immediately below via cleanup().
const SENTINEL = "\n# regression-guard-sentinel\n";
const sentinelBuf = Buffer.from(SENTINEL, "utf-8");
for (const p of WORKFLOW_BASELINES.keys()) {
fs.appendFileSync(p, SENTINEL);
}
// Prove the sentinel actually landed on disk — the file must be
// pre-append content followed by sentinel bytes, exactly. Replaces the
// old tautological `anyMutated` check (which couldn't fail given the
// append ran unconditionally directly above it).
for (const p of WORKFLOW_BASELINES.keys()) {
const before = preAppendContent.get(p)!;
const expected = Buffer.concat([before, sentinelBuf]);
const actual = fs.readFileSync(p);
expect(
actual.equals(expected),
`sentinel append did not land on ${p}`,
).toBe(true);
}
// Run cleanup() and assert bit-for-bit restoration against the in-memory
// baseline (NOT a local re-read of disk — that would silently agree with
// a buggy cleanup()).
cleanup();
for (const [p, baseline] of WORKFLOW_BASELINES) {
const current = fs.readFileSync(p);
expect(
current.equals(baseline),
`workflow drift not restored: ${p}`,
).toBe(true);
}
// Both package dirs should be gone.
expect(fs.existsSync(TEST_DIR)).toBe(false);
expect(fs.existsSync(REGRESSION_DIR)).toBe(false);
});
// VT-M2-C regression: on an idempotent re-run against a slug that is
// already present in the `starter:` matrix of test_smoke-starter.yml,
// the generator must skip the insert quietly instead of throwing
// "found 'starter:' block in ... but it has zero entries". Previously
// the walker set `lastEntryIndex = -1` on already-present to signal
// "skip", which then fell into the same else branch as the degenerate
// zero-entries case and surfaced a misleading error for operators
// whose workflow was already correctly wired.
it("re-running against a slug already in the smoke-matrix is a no-op, not a throw (VT-M2-C)", () => {
cleanup();
const args = [
"--name",
"Idempotent Rerun",
"--slug",
REGRESSION_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
];
// First run: scaffolds the package, appends the slug to the
// `starter:` matrix in test_smoke-starter.yml, AND inserts
// options/outputs/filters/build-job entries into showcase_deploy.yml.
runGenerator(args);
const smokePath = path.join(TMP_WORKFLOWS_DIR, "test_smoke-starter.yml");
const deployPath = path.join(TMP_WORKFLOWS_DIR, "showcase_deploy.yml");
const afterFirstRun = fs.readFileSync(smokePath, "utf-8");
const deployAfterFirstRun = fs.readFileSync(deployPath, "utf-8");
expect(afterFirstRun).toMatch(
new RegExp(`^\\s+- ${REGRESSION_SLUG}\\s*$`, "m"),
);
// showcase_deploy.yml insertions use the underscored `slugVar`
// (hyphens → underscores). This is the form the idempotency
// guards must look for on re-run. (VT-M2-F regression anchor.)
const regressionSlugVar = REGRESSION_SLUG.replace(/-/g, "_");
expect(deployAfterFirstRun).toMatch(
new RegExp(`^\\s+${regressionSlugVar}: \\$\\{\\{`, "m"),
);
expect(deployAfterFirstRun).toMatch(
new RegExp(`^\\s*build-${regressionSlugVar}:`, "m"),
);
// Remove only the scaffolded package dir so the generator's pre-flight
// guard lets us run again — the workflow already contains the slug,
// which is the state we're exercising.
fs.rmSync(path.join(TMP_PACKAGES_DIR, REGRESSION_SLUG), {
recursive: true,
force: true,
});
// Second run must succeed (not throw). Expected output contains the
// already-present skip notice; it MUST NOT contain the
// "zero entries" degenerate-case error text.
const { stdout } = runGenerator(args);
expect(stdout).toMatch(/already present in starter matrix/);
expect(stdout).not.toMatch(/has zero entries/);
// test_smoke-starter.yml must be unchanged bit-for-bit across the
// second run (no duplicate insert, no formatting drift).
const afterSecondRun = fs.readFileSync(smokePath, "utf-8");
expect(afterSecondRun).toBe(afterFirstRun);
// showcase_deploy.yml MUST also be unchanged bit-for-bit across the
// second run. This is the VT-M2-F regression: prior to the fix the
// outputs/filters idempotency guard compared against the hyphenated
// `slug` while the insertion wrote the underscored `slugVar`, so a
// re-run against a hyphenated slug like `test-integration-tmp-
// regression-guard` would never match the guard and would append
// duplicate `<slugVar>:` entries under outputs: and filters: on
// every re-run, corrupting the YAML.
const deployAfterSecondRun = fs.readFileSync(deployPath, "utf-8");
expect(deployAfterSecondRun).toBe(deployAfterFirstRun);
// Belt-and-suspenders: there must be exactly one output entry and
// exactly one filter entry keyed by `<slugVar>:`, no duplicates.
const outputKeyMatches = deployAfterSecondRun.match(
new RegExp(`^\\s+${regressionSlugVar}: \\$\\{\\{`, "gm"),
);
expect(outputKeyMatches?.length).toBe(1);
const buildJobMatches = deployAfterSecondRun.match(
new RegExp(`^\\s*build-${regressionSlugVar}:`, "gm"),
);
expect(buildJobMatches?.length).toBe(1);
});
// Safety net: every seeded workflow must match its captured baseline
// bit-for-bit at the end of the suite. Operates against our tmpdir-backed
// copies — the real `.github/workflows/` YAMLs are never touched by this
// suite, so there's nothing in the real tree to drift-check.
it("leaves every seeded workflow byte-identical to its baseline", () => {
expect(WORKFLOW_BASELINES.size).toBeGreaterThan(0);
for (const [p, baseline] of WORKFLOW_BASELINES) {
const current = fs.readFileSync(p);
expect(current.equals(baseline), `workflow drift after suite: ${p}`).toBe(
true,
);
}
});
});
describe("Template Generator — hardening regressions", () => {
it("fails fast with a listed-ids error on unknown --features", async () => {
cleanup();
try {
runGenerator([
"--name",
"Bad",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat,not-a-real-feature",
]);
expect.fail("Should have rejected unknown feature id");
} catch (e: any) {
const combined = (e.stderr || "") + (e.stdout || "");
expect(combined).toMatch(/Unknown feature id/);
expect(combined).toContain("not-a-real-feature");
// Error message must enumerate known ids so the user can self-correct.
expect(combined).toContain("Known ids:");
expect(combined).toContain("agentic-chat");
}
// Partial directory must NOT be left behind on a validation failure.
expect(fs.existsSync(TEST_DIR)).toBe(false);
});
it("loadFeatureRegistry surfaces structured errors for read/parse/shape failures", async () => {
// Replace the vacuous SHOWCASE_FEATURE_REGISTRY env-var test with
// direct-import coverage. We spy on fs.readFileSync so we can inject
// each failure mode deterministically — ENOENT, invalid JSON, and
// shape-invalid (missing 'features' array) — and assert that the
// thrown error message names the registry path AND the failure mode
// rather than leaking a bare stack. The previous env-var approach
// was a no-op: create-integration/index.ts never reads that env var,
// and the test's own short-circuit (if /SHOWCASE_FEATURE_REGISTRY/
// matched) meant the asserts never ran.
const { loadFeatureRegistry } =
await import("../create-integration/index.ts");
const { vi } = await import("vitest");
// Capture the real readFileSync once so each case can delegate
// for paths that are NOT the feature registry. An unfiltered
// mockImplementation intercepts ALL readFileSync calls — including
// the ones vitest/tsx make internally to resolve source maps,
// transforms, etc. — and produces flaky failures that have nothing
// to do with the code under test. Mirror the pattern used in
// validate-parity.test.ts / manifest.test.ts.
const realRead = fs.readFileSync;
const delegate = (
p: fs.PathOrFileDescriptor,
...rest: unknown[]
): string | Buffer =>
(
realRead as unknown as (
p: fs.PathOrFileDescriptor,
...rest: unknown[]
) => string | Buffer
)(p, ...rest);
// Case 1: ENOENT (file missing).
{
const spy = vi.spyOn(fs, "readFileSync").mockImplementation(((
p: fs.PathOrFileDescriptor,
...rest: unknown[]
) => {
if (typeof p === "string" && p.endsWith("feature-registry.json")) {
const err = new Error(
"ENOENT: no such file or directory",
) as NodeJS.ErrnoException;
err.code = "ENOENT";
throw err;
}
return delegate(p, ...rest);
}) as typeof fs.readFileSync);
try {
expect(() => loadFeatureRegistry()).toThrow(
/Failed to read feature registry/i,
);
} finally {
spy.mockRestore();
}
}
// Case 2: invalid JSON.
{
const spy = vi.spyOn(fs, "readFileSync").mockImplementation(((
p: fs.PathOrFileDescriptor,
...rest: unknown[]
) => {
if (typeof p === "string" && p.endsWith("feature-registry.json")) {
return "{ this is not valid json }";
}
return delegate(p, ...rest);
}) as typeof fs.readFileSync);
try {
expect(() => loadFeatureRegistry()).toThrow(/not valid JSON/i);
} finally {
spy.mockRestore();
}
}
// Case 3: shape-invalid — top-level array.
{
const spy = vi.spyOn(fs, "readFileSync").mockImplementation(((
p: fs.PathOrFileDescriptor,
...rest: unknown[]
) => {
if (typeof p === "string" && p.endsWith("feature-registry.json")) {
return JSON.stringify([{ id: "x" }]);
}
return delegate(p, ...rest);
}) as typeof fs.readFileSync);
try {
expect(() => loadFeatureRegistry()).toThrow(
/must be a JSON object with a 'features' array/i,
);
} finally {
spy.mockRestore();
}
}
// Case 4: shape-invalid — object without 'features' key.
{
const spy = vi.spyOn(fs, "readFileSync").mockImplementation(((
p: fs.PathOrFileDescriptor,
...rest: unknown[]
) => {
if (typeof p === "string" && p.endsWith("feature-registry.json")) {
return JSON.stringify({ categories: [] });
}
return delegate(p, ...rest);
}) as typeof fs.readFileSync);
try {
expect(() => loadFeatureRegistry()).toThrow(
/must be a JSON object with a 'features' array/i,
);
} finally {
spy.mockRestore();
}
}
});
it("validates feature-registry shape (top-level object with 'features' array)", () => {
// The loader rejects registries that drop the { features: [...] } wrapper
// so a hand-edited file surfaces as a clear error at load time rather
// than as 'features is undefined' further down the call stack.
// We assert the shape that the loader depends on is actually present.
const raw = fs.readFileSync(FEATURE_REGISTRY_PATH, "utf-8");
const parsed = JSON.parse(raw);
expect(parsed).not.toBeNull();
expect(typeof parsed).toBe("object");
expect(Array.isArray(parsed.features)).toBe(true);
// And every entry has the shape the loader types against
for (const f of parsed.features) {
expect(typeof f.id).toBe("string");
expect(f.id.length).toBeGreaterThan(0);
}
});
it("generated health route has an in-process branch for TypeScript integrations", async () => {
cleanup();
runGenerator([
"--name",
"TS InProcess",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"typescript",
"--features",
"agentic-chat",
]);
const healthRoute = fs.readFileSync(
path.join(TEST_DIR, "src/app/api/health/route.ts"),
"utf-8",
);
// Must not probe a bogus agent URL for an in-process TS integration;
// instead the flag must be hard-wired and the runtime must short-circuit
// to the in-process status.
expect(healthRoute).toContain("IS_IN_PROCESS = true");
expect(healthRoute).toContain('"in-process"');
// And the happy-path must treat in-process as 200 alongside "ok"
expect(healthRoute).toMatch(
/agentStatus\s*===\s*"ok"\s*\|\|\s*agentStatus\s*===\s*"in-process"/,
);
});
it("generated health route has an out-of-process probe for Python integrations", async () => {
cleanup();
runGenerator([
"--name",
"Py OutOfProcess",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
const healthRoute = fs.readFileSync(
path.join(TEST_DIR, "src/app/api/health/route.ts"),
"utf-8",
);
expect(healthRoute).toContain("IS_IN_PROCESS = false");
expect(healthRoute).toContain("AbortSignal.timeout(3000)");
});
it("generated E2E test uses the real assistant-message class, not the phantom data-role selector", async () => {
cleanup();
runGenerator([
"--name",
"Locator",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
const testFile = fs.readFileSync(
path.join(TEST_DIR, "tests/e2e/agentic-chat.spec.ts"),
"utf-8",
);
// The old 'data-role="assistant"' attribute does not exist in the
// CopilotKit DOM. The real assistant message carries the
// copilotKitAssistantMessage class.
expect(testFile).not.toContain('data-role="assistant"');
expect(testFile).toContain(".copilotKitAssistantMessage");
});
it("generated layout.tsx contains bare backticks in the inline script, not literal \\`", async () => {
cleanup();
runGenerator([
"--name",
"Layout",
"--slug",
TEST_SLUG,
"--category",
"agent-framework",
"--language",
"python",
"--features",
"agentic-chat",
]);
const layout = fs.readFileSync(
path.join(TEST_DIR, "src/app/layout.tsx"),
"utf-8",
);
// Previously the generator emitted \\\` which produced a literal \` in
// the output, breaking the template-literal assignment to __html.
expect(layout).not.toContain("\\`");
// The legitimate bare backticks must still be present so the script
// body actually parses.
expect(layout).toMatch(/__html:\s*`/);
});
describe("parseArgs — unit coverage for argv-walking guards", () => {
// parseArgs reads process.argv and calls process.exit(1) on any invalid
// shape. We stub both so each failure mode is observed via a thrown
// "process.exit called" sentinel and the matching error text on stderr.
// Each branch below exercises one guard the hardening added so the
// argv-walking logic doesn't silently drop flags or accept bad values.
it("rejects a positional argument that doesn't start with --", async () => {
const { parseArgs } = await import("../create-integration/index.ts");
const { vi } = await import("vitest");
const argv = process.argv;
process.argv = ["node", "index.ts", "stray", "--name", "x"];
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((
code?: number,
) => {
throw new Error(`exit:${code}`);
}) as never);
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(() => parseArgs()).toThrow(/exit:1/);
const combined = errSpy.mock.calls.map((c) => c.join(" ")).join("\n");
expect(combined).toMatch(/Unexpected positional argument 'stray'/);
} finally {
process.argv = argv;
exitSpy.mockRestore();
errSpy.mockRestore();
}
});
it("rejects a --flag missing its value (end-of-args)", async () => {
const { parseArgs } = await import("../create-integration/index.ts");
const { vi } = await import("vitest");
const argv = process.argv;
process.argv = ["node", "index.ts", "--name"];
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((
code?: number,
) => {
throw new Error(`exit:${code}`);
}) as never);
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(() => parseArgs()).toThrow(/exit:1/);
const combined = errSpy.mock.calls.map((c) => c.join(" ")).join("\n");
expect(combined).toMatch(/Flag --name expects a value/);
expect(combined).toMatch(/end-of-args/);
} finally {
process.argv = argv;
exitSpy.mockRestore();
errSpy.mockRestore();
}
});
it("rejects a --flag followed by another --flag instead of a value", async () => {
const { parseArgs } = await import("../create-integration/index.ts");
const { vi } = await import("vitest");
const argv = process.argv;
process.argv = ["node", "index.ts", "--name", "--slug", "x"];
const exitSpy = vi.spyOn(process, "exit").mockImplementation(((
code?: number,
) => {
throw new Error(`exit:${code}`);
}) as never);
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(() => parseArgs()).toThrow(/exit:1/);
const combined = errSpy.mock.calls.map((c) => c.join(" ")).join("\n");
expect(combined).toMatch(/Flag --name expects a value/);
expect(combined).toMatch(/another flag \(--slug\)/);
} finally {
process.argv = argv;
exitSpy.mockRestore();
errSpy.mockRestore();
}
});
it("rejects an unknown --category value with the listed allowed set", async () => {
const { parseArgs } = await import("../create-integration/index.ts");
const { vi } = await import("vitest");
const argv = process.argv;
process.argv = [
"node",
"index.ts",
"--name",
"x",
"--slug",
"x",
"--category",
"not-a-category",