forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate-pins.ts
More file actions
2097 lines (1990 loc) · 83.7 KB
/
Copy pathvalidate-pins.ts
File metadata and controls
2097 lines (1990 loc) · 83.7 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
/**
* Pin Validator (showcase-internal)
*
* Enforces showcase-internal pin discipline. The historical mode that
* compared `showcase/integrations/<slug>` against the external
* `examples/integrations/<source>` Dojo has been REMOVED: showcase and
* the external Dojo are intentionally divergent products on independent
* release cadences and a cross-product pin-parity gate was backwards.
*
* For each showcase package at `showcase/integrations/<slug>/`:
* 1. Read its dependency files (`package.json`, `requirements.txt`,
* `pyproject.toml`).
* 2. Every `@copilotkit/*` dep must pin to the canonical version
* declared in `showcase/scripts/showcase-canonical-pins.json`
* (`canonicalCopilotKitVersion`), OR to the per-slug per-dep value
* listed under `overrides[slug]`.
* 3. Every other framework / SDK dep (the FRAMEWORK_PATTERNS set —
* mastra, langchain, langgraph, crewai, agno, llama-index, etc.)
* must be an EXACT pin (no `^`/`~`/`>=`/`latest`/`next`/dist-tags/
* `workspace:*`/URLs).
* 4. Emit `[FAIL] <slug>: <dep> ...` for each violation.
*
* Definition of "exact pin":
* - npm: bare semver (`1.2.3`, `1.2.3-beta.1`). NO `^`, `~`, `>=`, `*`,
* `latest`, `next`, `workspace:*`, URLs, or git refs.
* - Python: `==<version>`. NO `>=`, `~=`, `*`, or unpinned names.
*
* Usage:
* npx tsx showcase/scripts/validate-pins.ts
*
* Exit codes:
* 0 — no FAIL violations (WARN/SKIP are non-fatal)
* 1 — one or more FAIL violations (pin drift detected)
* 2 — internal error (crash, unexpected exception). Distinct from 1 so
* CI callers can distinguish "pin drift" from "validator broken".
* Note: validate-parity.ts uses a different exit-code taxonomy
* (2=invalid-input, 3=unreadable, 4=internal); the tools are
* intentionally not aligned on code 2.
* 3 — unreadable input (e.g. VALIDATE_PINS_REPO_ROOT points at a
* non-directory or a path the process cannot access). Distinct from
* 2 so CI callers can route permissions/misconfig alerts separately
* from true crashes.
*
* Output routing:
* - [OK] and [SKIP] lines go to stdout.
* - [FAIL] and [WARN] lines go to stderr (per Unix convention).
*
* --- NOTE: SLUG_MAP / examples helpers ---
*
* The slug-map tables (`SLUG_MAP`, `FALLBACK_MAP`, `BORN_IN_SHOWCASE`)
* and the `resolveExampleDir` / `collectDojoDeps` helpers are NO LONGER
* USED by `validateAll` — the new invariant is showcase-internal. They
* are still EXPORTED so other consumers (audit.ts provenance, tests,
* future tooling that wants to peek at the live external Dojo) can
* import them. Removing those exports is out of scope for Phase 1.
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { BORN_IN_SHOWCASE, FALLBACK_MAP, SLUG_MAP } from "./lib/slug-map.js";
// SLUG_MAP / FALLBACK_MAP / BORN_IN_SHOWCASE are the single source of
// truth shared by audit.ts, validate-parity.ts, and this file. Re-exported
// at the bottom of this file so tests importing from "../validate-pins.js"
// see the same frozen tables.
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Exit-code constants. See the module docstring for the full taxonomy.
// `as const` narrows each to its literal numeric type; `PinsExitCode` is
// the closed union so callers (and `process.exitCode` assignments in
// this file) cannot accidentally drift to an unrelated number. Adding
// a new exit code is a deliberate edit to both the constant and the
// union — a pure `const X = 4` cannot participate in the union.
const EXIT_OK = 0 as const;
const EXIT_DRIFT = 1 as const;
const EXIT_INTERNAL = 2 as const;
const EXIT_UNREADABLE = 3 as const;
type PinsExitCode =
| typeof EXIT_OK
| typeof EXIT_DRIFT
| typeof EXIT_INTERNAL
| typeof EXIT_UNREADABLE;
/**
* Thrown when the repo-root input is present but unreadable or
* structurally wrong (e.g. points at a file, EACCES, ENOTDIR). The
* top-level catch uses `instanceof` to route these to EXIT_UNREADABLE
* instead of EXIT_INTERNAL so CI callers can distinguish a permissions
* misconfig from a true validator crash.
*/
class UnreadableInputError extends Error {
/**
* Optionally carries the partial report built up to the point the
* infra error was observed. The top-level catch uses this to print
* the FAIL/WARN/SKIP lines for slugs processed before the error so
* operators don't lose diagnostic output when a single slug has an
* infra problem mid-run. undefined for infra errors raised before
* the slug loop started (e.g. bad VALIDATE_PINS_REPO_ROOT, missing
* packages dir) where no report exists yet.
*/
readonly partialReport?: Report;
constructor(message: string, partialReport?: Report) {
super(message);
this.name = "UnreadableInputError";
this.partialReport = partialReport;
}
}
// REPO_ROOT resolution allows tests to override via env var. The override
// must be an absolute path pointing at an existing directory; a relative
// or non-existent override silently yielding an empty scan would turn a
// misconfiguration into a false green.
//
// Implementation note: `fs.existsSync` collapses ENOENT (does not
// exist) with EACCES (exists but unreadable by the current process)
// into a single false result, which produces a misleading "does not
// exist" error when the real problem is a permissions gap. Use
// `fs.statSync` with errno inspection so the message names the right
// failure mode.
function computeRepoRoot(): string {
const override = process.env.VALIDATE_PINS_REPO_ROOT;
if (override) {
if (!path.isAbsolute(override)) {
throw new Error(
`VALIDATE_PINS_REPO_ROOT must be an absolute path; got: ${override}`,
);
}
let st: fs.Stats;
try {
st = fs.statSync(override);
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err && err.code === "ENOENT") {
// ENOENT on the override is a bad-input/configuration error,
// not a validator crash — route to EXIT_UNREADABLE (3) so CI
// callers can distinguish misconfig from true internal errors.
throw new UnreadableInputError(
`VALIDATE_PINS_REPO_ROOT does not exist on disk: ${override}`,
);
}
if (err && err.code === "EACCES") {
throw new UnreadableInputError(
`VALIDATE_PINS_REPO_ROOT exists but is not readable (permission denied): ${override}`,
);
}
if (err && err.code === "ENOTDIR") {
throw new UnreadableInputError(
`VALIDATE_PINS_REPO_ROOT path component is not a directory: ${override}`,
);
}
// Surface the underlying error message so the caller sees the
// actual failure rather than a generic wrapper. Any stat failure
// on the override path is an infra-class problem (the caller
// configured a path we can't access), so route through
// UnreadableInputError → EXIT_UNREADABLE (3) instead of letting
// a plain Error misroute to EXIT_INTERNAL (2).
const msg = err && err.message ? err.message : String(e);
throw new UnreadableInputError(
`VALIDATE_PINS_REPO_ROOT stat failed: ${override}: ${msg}`,
);
}
// Override must be a directory — a file override would let the
// rest of the validator run with a bogus REPO_ROOT and produce
// misleading "nothing found" output rather than an immediate error.
if (!st.isDirectory()) {
throw new UnreadableInputError(
`VALIDATE_PINS_REPO_ROOT is not a directory: ${override}`,
);
}
return override;
}
return path.resolve(__dirname, "..", "..");
}
function paths() {
const repoRoot = computeRepoRoot();
return {
REPO_ROOT: repoRoot,
// EXAMPLES_DIR is retained for the legacy `resolveExampleDir` /
// `collectDojoDeps` helpers (still exported for non-validateAll
// consumers). validateAll no longer reads it.
EXAMPLES_DIR: path.join(repoRoot, "examples", "integrations"),
PACKAGES_DIR: path.join(repoRoot, "showcase", "integrations"),
CANONICAL_PINS_FILE: path.join(
repoRoot,
"showcase",
"scripts",
"showcase-canonical-pins.json",
),
};
}
// ---------------------------------------------------------------------------
// Canonical pins config
// ---------------------------------------------------------------------------
/**
* Schema for `showcase/scripts/showcase-canonical-pins.json`:
* {
* "canonicalCopilotKitVersion": "1.59.2",
* "overrides": {
* "<slug>": { "<dep-name>": "<allowed-spec>" }
* }
* }
*
* `canonicalCopilotKitVersion` is the canonical pin for every
* `@copilotkit/*` dep across all showcase integrations. `overrides[slug]`
* is a per-slug map of dep-name → allowed verbatim spec used when a
* specific integration legitimately deviates (e.g. a `pkg.pr.new` URL
* during a runtime upgrade, or a legacy stable for a harness fixture).
*/
export interface CanonicalPins {
canonicalCopilotKitVersion: string;
overrides: Readonly<Record<string, Readonly<Record<string, string>>>>;
}
class CanonicalPinsError extends Error {
constructor(message: string) {
super(message);
this.name = "CanonicalPinsError";
}
}
export function loadCanonicalPins(file: string): CanonicalPins {
let raw: string;
try {
raw = fs.readFileSync(file, "utf-8");
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err && err.code === "ENOENT") {
throw new UnreadableInputError(
`canonical pins file not found at ${file}`,
);
}
const msg = err && err.message ? err.message : String(e);
throw new UnreadableInputError(
`canonical pins file read failed (${err?.code ?? "unknown"}): ${file}: ${msg}`,
);
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
throw new CanonicalPinsError(`${file}: JSON syntax error: ${msg}`);
}
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new CanonicalPinsError(`${file}: expected top-level object`);
}
const obj = parsed as Record<string, unknown>;
const ver = obj.canonicalCopilotKitVersion;
if (typeof ver !== "string" || ver.length === 0) {
throw new CanonicalPinsError(
`${file}: 'canonicalCopilotKitVersion' must be a non-empty string`,
);
}
if (!isExactSpec(ver)) {
throw new CanonicalPinsError(
`${file}: 'canonicalCopilotKitVersion' must itself be an exact pin (got ${JSON.stringify(ver)})`,
);
}
const ovRaw = obj.overrides;
const overrides: Record<string, Record<string, string>> = {};
if (ovRaw !== undefined) {
if (typeof ovRaw !== "object" || ovRaw === null || Array.isArray(ovRaw)) {
throw new CanonicalPinsError(`${file}: 'overrides' must be an object`);
}
for (const [slug, depsRaw] of Object.entries(ovRaw)) {
if (
typeof depsRaw !== "object" ||
depsRaw === null ||
Array.isArray(depsRaw)
) {
throw new CanonicalPinsError(
`${file}: 'overrides.${slug}' must be an object`,
);
}
const inner: Record<string, string> = {};
for (const [dep, spec] of Object.entries(depsRaw)) {
if (typeof spec !== "string" || spec.length === 0) {
throw new CanonicalPinsError(
`${file}: 'overrides.${slug}.${dep}' must be a non-empty string`,
);
}
inner[dep] = spec;
}
overrides[slug] = Object.freeze(inner);
}
}
return Object.freeze({
canonicalCopilotKitVersion: ver,
overrides: Object.freeze(overrides),
});
}
// ---------------------------------------------------------------------------
// Slug resolution
// ---------------------------------------------------------------------------
// Reverse of SLUG_MAP: showcase slug → examples dir name(s).
// Precomputed at module load so each slug lookup is O(1) rather than
// a linear scan of SLUG_MAP. Frozen so runtime mutation attempts throw
// — the tables are meant to be effectively constant.
const REVERSE_MAP: Readonly<Record<string, readonly string[]>> = (() => {
const reverse: Record<string, string[]> = {};
for (const [example, slug] of SLUG_MAP) {
if (!reverse[slug]) reverse[slug] = [];
reverse[slug].push(example);
}
// Freeze inner arrays first, then outer record.
for (const k of Object.keys(reverse)) Object.freeze(reverse[k]);
return Object.freeze(reverse);
})();
export interface ResolveResult {
exampleDir: string | null;
// If a FALLBACK_MAP entry existed but pointed to a missing dir, the
// caller should emit a distinct WARN with this path for diagnostics.
missingFallbackTarget?: string;
}
function resolveExampleDirDetailed(
showcaseSlug: string,
pathsOverride?: ReturnType<typeof paths>,
): ResolveResult {
if (BORN_IN_SHOWCASE.has(showcaseSlug)) return { exampleDir: null };
// Accept an optional pre-computed `paths()` so validateAll can
// compute it ONCE per run rather than re-validating
// VALIDATE_PINS_REPO_ROOT per slug. Direct callers (tests, ad-hoc
// use) may omit it and pay the per-call cost.
const { EXAMPLES_DIR, REPO_ROOT } = pathsOverride ?? paths();
// Strategy: explicit-fallback > reverse-SLUG_MAP > direct-name-match.
// Each strategy can "fall through" if its candidate dir does not
// exist on disk, so that a stale FALLBACK_MAP entry doesn't block a
// later strategy from resolving correctly.
//
// Use `fs.statSync` + catch-ENOENT rather than `fs.existsSync` so
// that a permission error (EACCES) does not silently collapse to the
// "not present" branch. EACCES means "there is something there, but
// this process can't read it" — treating it as "absent" hides real
// misconfiguration. Other errors re-throw so they're surfaced at the
// top level rather than quietly skipped.
const existsAsDir = (p: string): boolean => {
try {
return fs.statSync(p).isDirectory();
} catch (e) {
const err = e as NodeJS.ErrnoException;
if (err && err.code === "ENOENT") return false;
// EACCES / ENOTDIR / EIO / ELOOP / etc. mean "there is something
// at this path, but we can't read it". Route through
// UnreadableInputError so the top-level catch maps this to
// EXIT_UNREADABLE (3) — a permissions/infra misconfig — rather
// than EXIT_INTERNAL (2) which signals a validator crash.
const code = err && err.code ? err.code : "unknown";
const msg = err && err.message ? err.message : String(e);
throw new UnreadableInputError(
`cannot stat candidate example dir (${code}): ${p}: ${msg}`,
);
}
};
// Strategy 1 — explicit fallback (documents SLUG_MAP staleness).
const fallback = FALLBACK_MAP[showcaseSlug];
let missingFallbackTarget: string | undefined;
if (fallback) {
const dir = path.join(EXAMPLES_DIR, fallback);
if (existsAsDir(dir)) return { exampleDir: dir };
// Display relative to REPO_ROOT so the WARN line reads
// `examples/integrations/<name>` rather than the ambiguous
// `integrations/<name>` (which hides where the missing dir is).
missingFallbackTarget = path.relative(REPO_ROOT, dir);
}
// Strategy 2 — reverse-map lookup from SLUG_MAP.
const candidates = REVERSE_MAP[showcaseSlug] || [];
for (const cand of candidates) {
const dir = path.join(EXAMPLES_DIR, cand);
if (existsAsDir(dir)) return { exampleDir: dir, missingFallbackTarget };
}
// Strategy 3 — direct name match (common case: showcase slug ===
// examples dir name).
const direct = path.join(EXAMPLES_DIR, showcaseSlug);
if (existsAsDir(direct)) return { exampleDir: direct, missingFallbackTarget };
return { exampleDir: null, missingFallbackTarget };
}
function resolveExampleDir(showcaseSlug: string): string | null {
return resolveExampleDirDetailed(showcaseSlug).exampleDir;
}
// ---------------------------------------------------------------------------
// Dependency extraction
// ---------------------------------------------------------------------------
// Heuristic: what counts as an agent framework / SDK that must be pinned.
// Applied as regex match (mostly anchored) against dependency NAMES only;
// versions are compared via exact string match per the
// INTEGRATION-CHECKLIST rule.
//
// Expected match set (non-exhaustive sanity list, with concrete examples
// rather than glob-like notation): @copilotkit/<anything>, copilotkit,
// @ag-ui/<anything>, ag-ui-<anything>, ag_ui_<anything>,
// @langchain/<anything>, langchain, langchain-<anything>, langgraph,
// langgraph-<anything>, langsmith, @mastra/<anything>, mastra, crewai,
// crewai-<anything>, pydantic-ai, pydantic-ai-<anything>, agno,
// llama-index, llama-index-<anything>, llama_index, llama_index_<anything>,
// llamaindex, google-adk, google-genai, strands-agents,
// strands-agents-<anything>, agent-framework, agent-framework-<anything>,
// @ai-sdk/<anything>, ai, @hashbrownai/<anything>, @anthropic-ai/<anything>,
// anthropic, openai, ag2, langroid, spring-ai, spring-ai-<anything>, and
// Spring's Maven coordinate form `org.springframework.ai:<artifact>` which
// appears in Java manifests as a colon-delimited group:artifact string.
const FRAMEWORK_PATTERNS: Array<RegExp> = [
// CopilotKit SDK
/^@copilotkit\//,
/^copilotkit$/,
// AG-UI
/^@ag-ui\//,
/^ag-ui[-_]/,
/^ag_ui[-_]/,
// LangChain / LangGraph
/^@langchain\//,
/^langchain$/,
/^langchain-/,
/^langgraph$/,
/^langgraph-/,
/^langgraph_/,
/^langsmith$/,
// Mastra
/^@mastra\//,
/^mastra$/,
// CrewAI
/^crewai$/,
/^crewai-/,
// Pydantic AI
/^pydantic-ai$/,
/^pydantic-ai-/,
// Agno
/^agno$/,
// LlamaIndex (dash and underscore forms)
/^llama-index$/,
/^llama-index-/,
/^llama_index$/,
/^llama_index_/,
/^llamaindex$/,
// Google ADK / GenAI
/^google-adk$/,
/^google-genai$/,
// Strands
/^strands-agents$/,
/^strands-agents-/,
// Microsoft Agent Framework
/^agent-framework$/,
/^agent-framework-/,
// AI SDK (Vercel)
/^@ai-sdk\//,
/^ai$/,
// Hashbrown / A2UI renderers travel with CopilotKit
/^@hashbrownai\//,
// Anthropic / OpenAI SDKs used directly by agents
/^@anthropic-ai\//,
/^anthropic$/,
/^openai$/,
// Other frameworks that show up in born-in-showcase packages
/^ag2$/,
/^ag2-/,
/^langroid$/,
/^langroid-/,
// Spring AI (Java coordinates appear with these prefixes)
/^spring-ai$/,
/^spring-ai-/,
// Maven coordinate form for Spring AI: `group:artifact` with group
// prefix `org.springframework.ai`. Matches `org.springframework.ai:foo`
// for any artifact `foo`.
/^org\.springframework\.ai:/,
];
function isFrameworkDep(name: string): boolean {
return FRAMEWORK_PATTERNS.some((re) => re.test(name));
}
export interface DepMap {
[name: string]: string; // name -> raw version specifier string
}
/**
* Extended parse result: includes the DepMap plus advisory diagnostics.
* Callers use these to surface WARN lines even when the parse did not
* outright fail. Tests still assert against the returned DepMap shape.
*/
export interface ParseResult {
deps: DepMap;
/**
* Entries the parser intentionally skipped (e.g. Poetry git-only deps,
* inline tables with no `version`, malformed requirements.txt lines).
* Non-fatal but surface as [WARN] in validateAll so CI has a paper
* trail.
*/
skipped: Array<{ name: string; reason: string }>;
/**
* Fully unparseable lines we dropped from requirements.txt. One entry
* per dropped line.
*/
dropped: string[];
}
/**
* Parse a package.json into a DepMap. May throw on I/O failure or
* malformed JSON; callers that tolerate partial failure should catch
* and record the error. Runtime validates the parsed JSON is a plain
* object (not null / array / scalar) before property access, and that
* each entry in `dependencies` / `devDependencies` / `peerDependencies`
* is a string. Non-string dep values throw.
*
* Note: dep values are validated as strings, but the shape of each
* individual key (semver validity, registry name validity, etc.) is
* NOT validated here — that is the caller's responsibility.
*
* @throws Error on fs.readFileSync / JSON.parse failure, when the
* parsed value is not a plain object, or when any declared
* dep value is not a string.
*/
function parsePackageJson(file: string): DepMap {
const raw = fs.readFileSync(file, "utf-8");
const parsed: unknown = JSON.parse(raw);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new Error(
`expected JSON object at top level, got ${
parsed === null
? "null"
: Array.isArray(parsed)
? "array"
: typeof parsed
}`,
);
}
// After the guard above we know `parsed` is a plain (non-null,
// non-array) object. Treat it as `Record<string, unknown>` so every
// bucket lookup is typed as `unknown` and MUST be shape-checked by
// validateBucket below. Casting to a specific shape
// (`{ dependencies?: Record<string, unknown>; … }`) would imply
// pre-validated shape and invite callers to trust the cast without
// runtime checks.
const pkg: Record<string, unknown> = parsed as Record<string, unknown>;
// Validate inner dep values are strings. A package.json with
// non-string dep values (objects, numbers, nulls) is structurally
// invalid per the npm schema; the JS spread below would otherwise
// silently admit them into the DepMap and downstream comparisons
// would throw or misbehave.
const validateBucket = (
bucket: unknown,
bucketName: string,
): Record<string, string> | undefined => {
if (bucket === undefined) return undefined;
if (
typeof bucket !== "object" ||
bucket === null ||
Array.isArray(bucket)
) {
throw new Error(
`expected '${bucketName}' to be an object of name→string, got ${
bucket === null
? "null"
: Array.isArray(bucket)
? "array"
: typeof bucket
}`,
);
}
const ok: Record<string, string> = {};
for (const [k, v] of Object.entries(bucket)) {
if (typeof v !== "string") {
throw new Error(
`expected '${bucketName}.${k}' to be a string, got ${typeof v}`,
);
}
ok[k] = v;
}
return ok;
};
const deps = validateBucket(pkg.dependencies, "dependencies");
const peerDeps = validateBucket(pkg.peerDependencies, "peerDependencies");
const devDeps = validateBucket(pkg.devDependencies, "devDependencies");
// Merge dependencies, devDependencies, and peerDependencies. Frameworks
// in JS apps often live in devDeps (e.g. Next.js starters), and pinning
// rules apply to them all. On overlap, later spread wins: dev > peer >
// runtime. That's fine because (a) the caller applies first-writer-wins
// at the FILE level, and (b) in practice these rarely overlap within
// one file.
return {
...deps,
...peerDeps,
...devDeps,
};
}
/**
* PEP 503 name normalization: lowercase, collapse runs of `-`, `_`, `.`
* into a single `-`. Used to compare Python dep names across underscore /
* hyphen spellings (e.g. `langgraph_checkpoint` vs `langgraph-checkpoint`).
*/
function canonicalizePythonName(name: string): string {
return name.toLowerCase().replace(/[-_.]+/g, "-");
}
/**
* Returns true iff `spec` is a monorepo workspace reference that the
* validator intentionally does NOT pin-check. Workspace refs (e.g.
* `workspace:*`, `workspace:^`, `workspace:1.2.3`) are resolved by the
* package manager against the local monorepo, not published — there is
* no "pin" semantics to check. Handled out-of-band from isExactSpec
* because isExactSpec merely classifies, while this classifies AND
* indicates the caller should emit a [SKIP] rather than a [FAIL].
*/
function isWorkspaceRef(spec: string): boolean {
if (!spec) return false;
return /^workspace:/.test(spec.trim());
}
/**
* Returns true iff `spec` is an EXACT pin per the INTEGRATION-CHECKLIST rule.
*
* Accepts:
* - Bare semver-ish strings: "1.2.3", "0.2.14", "1.0.0-beta.1"
* - PEP 440 forms: "1.2.3.post1", "1.2.3.dev1", "1.2.3rc1", "1.2.3a1",
* "1.2.3b2"
* - Python exact specs: "==1.2.3", "===1.2.3", "==0.2.14", "==1.2.3rc1"
*
* Rejects:
* - Range operators: ^, ~, >=, <=, >, <, ~=, !=
* - X-ranges / wildcards: "1.x", "1.2.x", "1.2.*", "*", "X.X.X"
* - Dist-tags: "latest", "next", "" (empty)
* - Workspace/monorepo refs: "workspace:*", "workspace:^", "file:"
* - URLs / git refs / paths
* - Malformed Python `==` bodies without a full MAJOR.MINOR (e.g. `==0`).
*/
function isExactSpec(spec: string): boolean {
if (!spec) return false;
const trimmed = spec.trim();
if (!trimmed) return false;
// Reject any wildcard marker anywhere in the string. `*`, `x`, or `X`
// appearing as a version component (e.g. "1.x", "1.2.*") is never exact.
// The Python `==` form also cannot contain wildcards.
if (/(^|[.\-_+])[xX*]([.\-_+]|$)/.test(trimmed)) return false;
if (/\*/.test(trimmed)) return false;
// Python == / === exact form.
// Body must match MAJOR.MINOR with optional numeric sub-segments,
// an optional PEP 440 pre-release tag (`a1`, `b2`, `rc3`, etc.)
// directly attached, an optional `.postN` / `.devN` segment, an
// optional `-pre` / `+local` suffix. The regex is anchored end-to-end
// so degenerate bodies like `==1.2.foo` (dotted letter segment that
// is not a recognized PEP 440 keyword) or `==1.2abc!` (illegal
// trailing punctuation) are rejected — a non-anchored `^\d+\.\d+`
// or a too-permissive tail like `(?:[-+.A-Za-z0-9]+)*` would accept
// those and mis-classify them as exact pins.
const pyMatch = trimmed.match(/^={2,3}\s*(\S+)$/);
if (pyMatch) {
return /^\d+\.\d+(?:\.\d+)*(?:[A-Za-z]+\d*)?(?:\.(?:post|dev)\d*)?(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/.test(
pyMatch[1],
);
}
// Anything starting with a range operator is NOT exact.
if (/^[\^~<>!]/.test(trimmed)) return false;
if (/^(>=|<=|==|~=|!=)/.test(trimmed)) return false;
// Tags, workspace refs, URLs, paths.
if (/^[A-Za-z]/.test(trimmed)) {
// Starts with a letter: dist-tag like "latest" or "next", or
// "workspace:*", "file:...", "github:user/repo", etc.
return false;
}
// Bare version must start with a digit and contain no ranges/spaces.
if (!/^\d/.test(trimmed)) return false;
if (/\s/.test(trimmed)) return false;
if (/[|]{1,2}/.test(trimmed)) return false; // "1.2.3 || 2.0.0"
// Comma-joined ranges (Poetry / PEP 440): "1.2.3,>=1.0" is composed
// of two constraints and cannot be a single exact pin.
if (/,/.test(trimmed)) return false;
// Bare version shape: MAJOR.MINOR[.PATCH] with an optional
// pre-release / build / PEP 440 suffix. Enforced by a concrete
// semver-shape regex so only digit-dotted-digit forms (plus
// permitted suffixes) pass, rejecting exotic bare-letter tails
// like `1x`, `2X`, and `1e2`.
//
// MAJOR.MINOR is required for bare versions so bare-spec acceptance
// is symmetric with the Python `==` form above (which rejects `==1`).
// MAJOR-only like `"1"` is rejected on both paths, keeping
// drift-report behavior consistent across ecosystems.
if (!/^\d+\.\d+(?:\.\d+)?(?:[-+.][A-Za-z0-9.-]+)*$/.test(trimmed)) {
return false;
}
return true;
}
// Parse a requirements.txt line. Strip comments, extras, env markers,
// pip hash flags, index-url flags, and `--find-links` flags.
//
// Returns:
// - `[name, versionSpec]` on a valid `name<spec>` form; `versionSpec`
// MAY be an empty string when the line is name-only (e.g.
// `langgraph`). The file-level walker is responsible for surfacing
// these as `skipped[]` since an empty spec is not a pin.
// - `null` when the line is unparseable (editable install, URL-only,
// operator-leading, pure flag line, etc.).
function parseRequirementsLine(line: string): [string, string] | null {
// Strip trailing comments.
const stripped = line.replace(/#.*$/, "").trim();
if (!stripped) return null;
// Editable installs / URLs — not supported.
if (/^-e\b/.test(stripped) || /^(https?|git\+)/.test(stripped)) return null;
// Split on environment marker (;) and take the LHS.
const lhs = stripped.split(";")[0].trim();
// Strip pip-install flags attached to a single line:
// `--hash=sha256:...`, `--index-url=...`, `--extra-index-url=...`,
// `--find-links=...`. These appear AFTER the spec. Single-pass
// alternation avoids order-dependency between sequential replaces
// (e.g. a `--extra-index-url=...` substring being partially consumed
// by a naïve `--index-url=\S+` regex run first).
const flagsStripped = lhs
.replace(/\s+--(?:hash|index-url|extra-index-url|find-links)=\S+/g, "")
.trim();
// Match: name [extras] version-spec
// name characters: letters, digits, -, _, .
const match = flagsStripped.match(
/^([A-Za-z0-9][A-Za-z0-9._-]*)(?:\[[^\]]*\])?\s*(.*)$/,
);
if (!match) return null;
const name = match[1];
const spec = (match[2] || "").trim();
return [name, spec];
}
/**
* Parse a requirements.txt file into a DepMap. Returns a ParseResult
* with the DepMap plus:
* - `skipped`: name-only requirements (e.g. `langgraph` with no
* version spec) that the parser intentionally did NOT admit to the
* DepMap. The file-level walker surfaces these as [WARN] so
* operators see the manifest has an unpinned dep rather than the
* entry being silently dropped.
* - `dropped`: fully unparseable lines — caller surfaces as [WARN].
*
* @throws Error on fs.readFileSync failure.
*/
function parseRequirementsTxtDetailed(file: string): ParseResult {
const raw = fs.readFileSync(file, "utf-8");
const out: DepMap = {};
const skipped: Array<{ name: string; reason: string }> = [];
const dropped: string[] = [];
for (const line of raw.split(/\r?\n/)) {
// Empty and comment lines are legitimate — don't flag them as dropped.
const stripped = line.replace(/#.*$/, "").trim();
if (!stripped) continue;
// Editable installs / URLs are valid requirements but we cannot
// extract a pin from them; they're intentional non-deps, not drops.
if (/^-e\b/.test(stripped) || /^(https?|git\+)/.test(stripped)) continue;
const parsed = parseRequirementsLine(line);
if (parsed) {
// First-writer-wins within a file (a given dep may appear
// multiple times with different pins; the earlier line wins).
// NOTE: pip's own resolver does not define a "first vs last
// writer" rule across identical lines — re-declaration within a
// single requirements file is already ambiguous input, and real
// installs are normally deduped upstream. We pick first-writer
// here so the rule matches collectDepsFromDir's first-writer
// file-level precedence (agent-scope wins over root-scope). If
// a concrete case demands pip's actual semantics, replace this
// block rather than layering an exception.
const [name, spec] = parsed;
if (!(name in out)) {
if (!spec) {
// Name-only line (e.g. `langgraph` with no spec): surface as
// skipped since it's not pinning anything. See
// INTEGRATION-CHECKLIST rule about exact pins.
skipped.push({
name,
reason: "name-only requirement (no version)",
});
} else {
out[name] = spec;
}
}
} else {
dropped.push(stripped);
}
}
return { deps: out, skipped, dropped };
}
/**
* Thin compatibility wrapper: returns a DepMap for callers that do not
* care about dropped-line or skipped-line diagnostics. Internally
* delegates to the detailed form.
*
* NOTE: This wrapper does NOT tolerate silent data loss. If the
* underlying detailed parse produces any `skipped[]` or `dropped[]`
* entries, this wrapper THROWS so the caller is forced to switch to
* `parseRequirementsTxtDetailed` rather than quietly losing those
* diagnostics. Callers that may legitimately encounter skipped/dropped
* entries MUST call `parseRequirementsTxtDetailed` directly.
*
* @throws Error on fs.readFileSync failure.
* @throws Error when the file contains skipped or dropped entries
* (use parseRequirementsTxtDetailed instead).
*/
function parseRequirementsTxt(file: string): DepMap {
const detailed = parseRequirementsTxtDetailed(file);
if (detailed.skipped.length > 0 || detailed.dropped.length > 0) {
throw new Error(
`parseRequirementsTxt: ${file} produced ${detailed.skipped.length} skipped and ` +
`${detailed.dropped.length} dropped entries; use parseRequirementsTxtDetailed ` +
`to access them instead of silently discarding.`,
);
}
return detailed.deps;
}
/**
* Scan `raw` starting at `openBracketIdx` (which must point at a `[`
* character) and return the index of the matching closing `]`, skipping
* over any `]` or `[` embedded in single- or double-quoted strings.
* Returns -1 if no matching bracket is found before end-of-string OR
* before a new TOML table header (`\n[...]` at column 0).
*
* This exists because the PEP 621 and PEP 621-extras arrays can legally
* contain entries like `"langchain[all]==1.2.3"` where the bracket
* character appears inside a quoted string. A non-greedy `[\s\S]*?\]`
* regex silently truncates such arrays at the first `]` and drops
* everything after — a silent miss that makes the validator emit [OK]
* against incomplete dependency sets.
*
* The scanner handles:
* - Basic double-quoted strings: `"..."` (escape `\"` permitted).
* - Basic single-quoted strings: `'...'` (escape `\'` permitted).
* - TOML comments: `#` to end-of-line are ignored outside strings so
* a `]` that appears inside a comment does NOT satisfy the search.
* - Table header termination: a `\n[` at column 0 while still at
* depth > 0 means the array was never closed before the next
* table header — return -1 so the caller can throw.
*
* It does NOT handle TOML multi-line basic strings (`"""..."""`) or
* nested arrays spanning multiple table bodies. A real TOML tokenizer
* would be more correct; the tradeoff is accepted because our fixtures
* are simple single-section arrays of strings.
*/
function findMatchingBracket(raw: string, openBracketIdx: number): number {
let depth = 0;
let i = openBracketIdx;
while (i < raw.length) {
const ch = raw[i];
// A new TOML table header `\n[` at depth >= 1 means the current
// array was never closed. The opening `[` of the header does NOT
// count as a nested-array bump — it's a new section starting.
// Only trigger this when we've already consumed the opening
// bracket (i > openBracketIdx) and the next char is `[`.
if (ch === "\n" && depth >= 1 && i + 1 < raw.length && raw[i + 1] === "[") {
return -1;
}
if (ch === '"') {
// Skip basic-string. Escapes: `\\` and `\"`.
i += 1;
while (i < raw.length) {
const c = raw[i];
if (c === "\\" && i + 1 < raw.length) {
i += 2;
continue;
}
if (c === '"') {
i += 1;
break;
}
i += 1;
}
continue;
}
if (ch === "'") {
// Skip literal-string.
i += 1;
while (i < raw.length && raw[i] !== "'") i += 1;
if (i < raw.length) i += 1;
continue;
}
if (ch === "#") {
// Skip to end-of-line. A `]` inside a comment must NOT close
// the array.
while (i < raw.length && raw[i] !== "\n") i += 1;
continue;
}
if (ch === "[") {
depth += 1;
i += 1;
continue;
}
if (ch === "]") {
depth -= 1;
if (depth === 0) return i;
i += 1;
continue;
}
i += 1;
}
return -1;
}
/**
* Extract quoted-string entries out of a TOML array body (the text
* between an opening `[` and its matching `]`), dispatching each entry
* through `parseRequirementsLine` and merging into `out` (first-writer-
* wins). Unparseable non-empty entries go into `dropped`.
*
* Name-only entries (e.g. bare `"langgraph"` in the array) are pushed
* to `skipped[]` rather than silently admitted to `out` with an empty
* spec. This mirrors `parseRequirementsTxtDetailed`'s file-level
* handling so pyproject and requirements.txt report the same
* diagnostics for the same input.
*/
function ingestArrayBody(
body: string,
out: DepMap,
dropped: string[],
skipped: Array<{ name: string; reason: string }>,
): void {
const quoteRe = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'/g;
let m: RegExpExecArray | null;
while ((m = quoteRe.exec(body))) {
const entry = m[1] ?? m[2] ?? "";
const parsed = parseRequirementsLine(entry);
if (parsed) {
const [name, spec] = parsed;
if (!(name in out)) {
if (!spec) {
// Name-only entry — not pinning anything. Surface as
// skipped so a [WARN] is emitted, matching requirements.txt
// handling. Without this, the DepMap silently gained an
// entry with an empty spec and downstream error messages
// read `(empty)` without explaining the cause.
skipped.push({
name,
reason: "name-only requirement (no version)",
});
} else {
out[name] = spec;
}
}
} else if (entry.trim()) {
dropped.push(entry);
}
}
}
/**
* Extremely small pyproject.toml reader. Handles:
*
* - Top-level `[project]` dependencies array (PEP 621).
* - Top-level `[project.optional-dependencies]` tables (PEP 621 extras)
* — every subkey's array is scanned.
* - Poetry `[tool.poetry.dependencies]` tables, including
* `[tool.poetry.group.<name>.dependencies]`.
*
* We avoid adding a full TOML dependency by using targeted regexes. The
* parser stops at the NEXT TOP-LEVEL table header (e.g. `[tool.foo]`) —
* crucially NOT at dotted subtables like `[project.optional-dependencies]`,
* which are children of `[project]`.
*
* @throws Error on fs.readFileSync failure, or when a top-level
* `dependencies = [` array in `[project]` is opened but a
* matching `]` is never found by the quote-aware scanner.
*/
function parsePyprojectTomlDetailed(file: string): ParseResult {
const raw = fs.readFileSync(file, "utf-8");
const out: DepMap = {};
const skipped: Array<{ name: string; reason: string }> = [];
const dropped: string[] = [];
// --- PEP 621: [project] table ---
// Find the [project] section body, stopping at the next header of any
// kind — whether a plain table like `[tool]` or a dotted table like
// `[tool.poetry]` / `[project.optional-dependencies]`. Dotted
// subtables under `[project]` (e.g. `[project.optional-dependencies]`)
// are handled by separate scanners that run against the raw file, so
// it is safe — and in fact required — to terminate [project] body at