-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpack-artifacts.ts
More file actions
executable file
·1176 lines (1137 loc) · 45.8 KB
/
Copy pathpack-artifacts.ts
File metadata and controls
executable file
·1176 lines (1137 loc) · 45.8 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
#!/usr/bin/env bun
import * as BunRuntime from "@effect/platform-bun/BunRuntime";
import * as BunServices from "@effect/platform-bun/BunServices";
import { ChildProcess } from "effect/unstable/process";
import { Crypto, Data, Effect, FileSystem, Function, Layer, Path, Schema, Stream } from "effect";
import { runHermeticEvalReplay, sanitizeEvalReplay } from "../packages/evals/src/index";
import { copyCheckedRegularFile } from "./archive-security";
import {
CURSOR_LISTING_VERSION,
OPENAI_LISTING_VERSION,
checkGeneratedTargetConformance,
} from "./check-target-conformance";
export const HOSTS = ["openai", "cursor", "claude", "copilot", "gemini", "devin"] as const;
export type Host = (typeof HOSTS)[number];
const SKILLS = [
"research-hyperliquid",
"research-prediction-markets",
"research-spot-tokens",
"review-gina-account",
];
const PACKAGES = [
{
slug: "contracts",
name: "@askgina/contracts",
directory: "packages/contracts",
packageFiles: ["dist", "LICENSE", "README.md"],
compiledFiles: [/^index\.d\.ts$/u, /^index\.js$/u, /^index\.js\.map$/u],
},
{
slug: "sdk",
name: "@askgina/sdk",
directory: "packages/sdk",
packageFiles: ["dist", "LICENSE", "README.md"],
compiledFiles: [/^index\.d\.ts$/u, /^index\.js$/u, /^index\.js\.map$/u],
},
{
slug: "cli",
name: "@askgina/cli",
directory: "packages/cli",
packageFiles: ["dist", "LICENSE", "README.md"],
compiledFiles: [
/^bin\.d\.ts$/u,
/^bin\.js$/u,
/^bin\.js\.map$/u,
/^index\.d\.ts$/u,
/^index\.js$/u,
/^run-[A-Za-z0-9_-]+\.js$/u,
/^run-[A-Za-z0-9_-]+\.js\.map$/u,
],
},
{
slug: "plugin-core",
name: "@askgina/plugin-core",
directory: "plugins/ask-gina",
packageFiles: [
"dist",
"plugin.yaml",
"skills",
"evals/model/v1/activation.yaml",
"evals/model/v1/smoke.yaml",
"evals/model/v1/families",
"evals/model/v1/fixtures",
"LICENSE",
"README.md",
],
compiledFiles: [/^index\.d\.ts$/u, /^index\.js$/u, /^index\.js\.map$/u],
},
{
slug: "evals",
name: "@askgina/evals",
directory: "packages/evals",
packageFiles: ["dist", "LICENSE", "README.md"],
compiledFiles: [
/^bin\/check-codex-marketplace\.d\.ts$/u,
/^bin\/check-codex-marketplace\.js$/u,
/^bin\/check-codex-marketplace\.js\.map$/u,
/^bin\/export-public-results\.d\.ts$/u,
/^bin\/export-public-results\.js$/u,
/^bin\/export-public-results\.js\.map$/u,
/^bin\/live\.d\.ts$/u,
/^bin\/live\.js$/u,
/^bin\/live\.js\.map$/u,
/^bin\/replay\.d\.ts$/u,
/^bin\/replay\.js$/u,
/^bin\/replay\.js\.map$/u,
/^codex-cli-[A-Za-z0-9_-]+\.js$/u,
/^codex-cli-[A-Za-z0-9_-]+\.js\.map$/u,
/^index\.d\.ts$/u,
/^index\.js$/u,
/^omp-harness-[A-Za-z0-9_-]+\.d\.ts$/u,
/^publication-[A-Za-z0-9_-]+\.js$/u,
/^publication-[A-Za-z0-9_-]+\.js\.map$/u,
/^replay-[A-Za-z0-9_-]+\.js$/u,
/^replay-[A-Za-z0-9_-]+\.js\.map$/u,
/^report-[A-Za-z0-9_-]+\.js$/u,
/^report-[A-Za-z0-9_-]+\.js\.map$/u,
/^responses-api-[A-Za-z0-9_-]+\.js$/u,
/^responses-api-[A-Za-z0-9_-]+\.js\.map$/u,
/^runner-[A-Za-z0-9_-]+\.js$/u,
/^runner-[A-Za-z0-9_-]+\.js\.map$/u,
],
},
];
const TARGET_MANIFESTS: Readonly<Record<Host, string>> = {
openai: ".codex-plugin/plugin.json",
cursor: ".cursor-plugin/plugin.json",
claude: ".claude-plugin/plugin.json",
copilot: "plugin.json",
gemini: "gemini-extension.json",
devin: ".devin-plugin/plugin.json",
};
const SHA_256 = /^[a-f0-9]{64}$/u;
const GIT_COMMIT = /^[a-f0-9]{40}$/u;
const SEMVER =
/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
const MAX_GIT_PORCELAIN_BYTES = 64 * 1024;
const RAW_EVAL_FIELDS =
/"(?:prompts?|toolCalls?|tool_calls|payloads?|models?|accounts?|addresses?|final_answer|report)"\s*:/iu;
export class ArtifactPackError extends Data.TaggedError("ArtifactPackError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const stableJson = (value: unknown): string => `${JSON.stringify(value, null, 2)}\n`;
const fail = (message: string, cause?: unknown) =>
new ArtifactPackError(cause === undefined ? { message } : { message, cause });
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const toHex = (bytes: Uint8Array): string =>
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
const readText = (file: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs
.readFileString(file)
.pipe(Effect.mapError((cause) => fail(`cannot read ${file}`, cause)));
});
const readJson = (file: string) =>
readText(file).pipe(
Effect.flatMap((text) =>
Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown))(text).pipe(
Effect.mapError((cause) => fail(`cannot parse ${file}`, cause)),
),
),
);
const requiredString = (value: unknown, label: string) =>
typeof value === "string" && value.length > 0
? Effect.succeed(value)
: Effect.fail(fail(`${label} must be a non-empty string`));
const normalizedPackageFiles = (value: unknown, label: string) =>
Effect.gen(function* () {
const path = yield* Path.Path;
if (
!Array.isArray(value) ||
value.some((item) => typeof item !== "string" || item.length === 0)
) {
return yield* fail(`${label} must be an array of non-empty strings`);
}
const entries = value.filter((item): item is string => typeof item === "string");
const seen = new Set<string>();
for (const entry of entries) {
if (
entry.includes("\\") ||
path.isAbsolute(entry) ||
/^[A-Za-z]:\//u.test(entry) ||
path.normalize(entry) !== entry ||
entry
.split("/")
.some((segment) => segment.length === 0 || segment === "." || segment === "..") ||
seen.has(entry)
) {
return yield* fail(`${label} contains a non-normalized path: ${entry}`);
}
seen.add(entry);
}
return entries;
});
const hash = (bytes: Uint8Array | string) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const input = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
return toHex(
yield* crypto
.digest("SHA-256", input)
.pipe(Effect.mapError((cause) => fail("cannot calculate SHA-256", cause))),
);
});
const hashFile = (file: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const bytes = yield* fs
.readFile(file)
.pipe(Effect.mapError((cause) => fail(`cannot read ${file}`, cause)));
return yield* hash(bytes);
});
const childEnvironment = (): Readonly<Record<string, string>> => ({
PATH: "/usr/bin:/bin",
HOME: "/nonexistent",
GIT_CONFIG_GLOBAL: "/dev/null",
GIT_CONFIG_NOSYSTEM: "1",
GIT_OPTIONAL_LOCKS: "0",
LC_ALL: "C",
TZ: "UTC",
});
const commandOutput = (command: string, args: readonly string[], cwd: string) =>
Effect.scoped(
Effect.gen(function* () {
const child = yield* ChildProcess.make(command, args, {
cwd,
env: childEnvironment(),
extendEnv: false,
stdin: "ignore",
stderr: "ignore",
}).pipe(Effect.mapError((cause) => fail(`cannot start ${command}`, cause)));
const chunks = yield* child.stdout.pipe(
Stream.decodeText(),
Stream.runCollect,
Effect.mapError((cause) => fail(`cannot read ${command} output`, cause)),
);
const exitCode = yield* child.exitCode.pipe(
Effect.mapError((cause) => fail(`cannot wait for ${command}`, cause)),
);
return exitCode === 0 ? chunks.join("") : yield* fail(`${command} exited with ${exitCode}`);
}),
);
const commandHasBoundedOutput = (
command: string,
args: readonly string[],
cwd: string,
maximumBytes: number,
) =>
Effect.scoped(
Effect.gen(function* () {
const child = yield* ChildProcess.make(command, args, {
cwd,
env: childEnvironment(),
extendEnv: false,
stdin: "ignore",
stderr: "ignore",
}).pipe(Effect.mapError((cause) => fail(`cannot start ${command}`, cause)));
const result = yield* child.stdout.pipe(
Stream.decodeText(),
Stream.runFoldEffect(
() => ({ bytes: 0, hasOutput: false }),
(state, chunk) => {
const bytes = state.bytes + new TextEncoder().encode(chunk).byteLength;
return bytes <= maximumBytes
? Effect.succeed({ bytes, hasOutput: state.hasOutput || chunk.length > 0 })
: Effect.fail(fail(`${command} output exceeds ${maximumBytes} bytes`));
},
),
Effect.mapError((cause) => fail(`cannot read ${command} output`, cause)),
);
const exitCode = yield* child.exitCode.pipe(
Effect.mapError((cause) => fail(`cannot wait for ${command}`, cause)),
);
return exitCode === 0 ? result.hasOutput : yield* fail(`${command} exited with ${exitCode}`);
}),
);
const runCommand = (
command: string,
args: readonly string[],
cwd: string,
environment: Readonly<Record<string, string>> = {},
) =>
Effect.scoped(
Effect.gen(function* () {
const child = yield* ChildProcess.make(command, args, {
cwd,
env: { ...childEnvironment(), ...environment },
extendEnv: false,
stdin: "ignore",
stdout: "ignore",
stderr: "inherit",
}).pipe(Effect.mapError((cause) => fail(`cannot start ${command}`, cause)));
const exitCode = yield* child.exitCode.pipe(
Effect.mapError((cause) => fail(`cannot wait for ${command}`, cause)),
);
if (exitCode !== 0) return yield* fail(`${command} exited with ${exitCode}`);
}),
);
const filesBelow = (directory: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const visit = (current: string, prefix: string): Effect.Effect<string[], ArtifactPackError> =>
Effect.gen(function* () {
const names = yield* fs
.readDirectory(current)
.pipe(Effect.mapError((cause) => fail(`cannot list ${current}`, cause)));
const nested = yield* Effect.forEach(names.sort(), (name) =>
Effect.gen(function* () {
const absolute = path.join(current, name);
const relative = prefix.length > 0 ? `${prefix}/${name}` : name;
const symbolicLink = yield* fs
.readLink(absolute)
.pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
if (symbolicLink) {
return yield* fail(`archive input contains a symbolic link: ${relative}`);
}
const info = yield* fs
.stat(absolute)
.pipe(Effect.mapError((cause) => fail(`cannot inspect ${absolute}`, cause)));
if (info.type === "Directory") return yield* visit(absolute, relative);
if (info.type === "File") return [relative];
return yield* fail(`archive input contains unsupported content: ${relative}`);
}),
);
return nested.flat();
});
return yield* visit(directory, "");
});
const fileProofs = (directory: string, prefix = "") =>
Effect.gen(function* () {
const path = yield* Path.Path;
const files = yield* filesBelow(directory);
return yield* Effect.forEach(files, (file) =>
hashFile(path.join(directory, file)).pipe(
Effect.map((sha256) => ({ path: prefix.length > 0 ? `${prefix}/${file}` : file, sha256 })),
),
);
});
const packageDefinition = (name: string) => {
const definition = PACKAGES.find((candidate) => candidate.name === name);
return definition === undefined
? Effect.fail(fail(`unknown package definition: ${name}`))
: Effect.succeed(definition);
};
const verifyEmbeddedSourceMap = (
livePackageRoot: string,
sourcePackageRoot: string,
mapFile: string,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const value = yield* readJson(mapFile);
if (!isObject(value) || value.version !== 3) {
return yield* fail("compiled source map must be a version 3 object");
}
if (value.sourceRoot !== undefined && value.sourceRoot !== "") {
return yield* fail("compiled source map must not declare sourceRoot");
}
const companion = mapFile.slice(0, -".map".length);
const companionName = path.basename(companion);
if (value.file !== undefined && value.file !== companionName) {
return yield* fail("compiled source map file does not match its companion");
}
const compiled = yield* readText(companion);
if (!compiled.trimEnd().endsWith(`//# sourceMappingURL=${path.basename(mapFile)}`)) {
return yield* fail("compiled file does not reference its source map");
}
if (!Array.isArray(value.sources) || value.sources.length === 0) {
return yield* fail("compiled source map must contain sources");
}
if (
!Array.isArray(value.sourcesContent) ||
value.sourcesContent.length !== value.sources.length
) {
return yield* fail("compiled source map sourcesContent must match sources");
}
for (const [index, sourceValue] of value.sources.entries()) {
const content = value.sourcesContent[index];
if (typeof sourceValue !== "string" || sourceValue.length === 0) {
return yield* fail("compiled source map contains an invalid source path");
}
if (typeof content !== "string" || content.length === 0) {
return yield* fail("compiled source map contains empty sourcesContent");
}
if (
sourceValue.includes("\\") ||
sourceValue.startsWith("/") ||
/^[A-Za-z]:/u.test(sourceValue) ||
/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(sourceValue) ||
Array.from(sourceValue).some((character) => {
const code = character.charCodeAt(0);
return code <= 0x1f || code === 0x7f;
}) ||
sourceValue.split("/").some((segment) => segment.length === 0 || segment === ".")
) {
return yield* fail(`compiled source map contains an unsafe source path: ${sourceValue}`);
}
const liveSource = path.resolve(path.dirname(mapFile), sourceValue);
const packageRelative = path.relative(livePackageRoot, liveSource);
if (
packageRelative === ".." ||
packageRelative.startsWith("../") ||
packageRelative.startsWith("..\\") ||
path.isAbsolute(packageRelative) ||
!packageRelative.endsWith(".ts")
) {
return yield* fail(`compiled source map escapes its package: ${sourceValue}`);
}
const expected = yield* readText(path.join(sourcePackageRoot, packageRelative));
if (content !== expected) {
return yield* fail(`compiled source map content is stale: ${sourceValue}`);
}
}
});
export interface VerifiedCompiledPackageOutput {
readonly allowlist: readonly string[];
readonly files: readonly string[];
}
export type VerifyCompiledPackageOutputEffect = Effect.Effect<
VerifiedCompiledPackageOutput,
ArtifactPackError,
FileSystem.FileSystem | Path.Path
>;
const verifyCompiledPackageOutputImpl = (
liveRoot: string,
sourceRoot: string,
packageName: string,
): VerifyCompiledPackageOutputEffect =>
Effect.gen(function* () {
const definition = yield* packageDefinition(packageName);
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const livePackageRoot = path.join(liveRoot, definition.directory);
const sourcePackageRoot = path.join(sourceRoot, definition.directory);
const metadata = yield* readJson(path.join(sourcePackageRoot, "package.json"));
if (!isObject(metadata)) {
return yield* fail(`${definition.name} package.json must be an object`);
}
const allowlist = yield* normalizedPackageFiles(metadata.files, `${definition.name} files`);
if (stableJson(allowlist) !== stableJson(definition.packageFiles)) {
return yield* fail(`${definition.name} package files are inconsistent`);
}
const dist = path.join(livePackageRoot, "dist");
const files = yield* filesBelow(dist);
const committedDist = path.join(sourcePackageRoot, "dist");
const committedFiles = yield* filesBelow(committedDist);
if (files.join("\n") !== committedFiles.join("\n")) {
return yield* fail(`${definition.name} compiled output differs from source commit build`);
}
yield* Effect.forEach(files, (file) =>
Effect.gen(function* () {
const liveBytes = yield* fs
.readFile(path.join(dist, file))
.pipe(Effect.mapError((cause) => fail(`cannot read ${definition.name}:${file}`, cause)));
const committedBytes = yield* fs
.readFile(path.join(committedDist, file))
.pipe(
Effect.mapError((cause) =>
fail(`cannot read source commit build ${definition.name}:${file}`, cause),
),
);
if (
liveBytes.length !== committedBytes.length ||
liveBytes.some((byte, index) => byte !== committedBytes[index])
) {
return yield* fail(
`${definition.name} compiled output differs from source commit build: ${file}`,
);
}
}),
);
for (const pattern of definition.compiledFiles) {
if (files.filter((file) => pattern.test(file)).length !== 1) {
return yield* fail(
`${definition.name} compiled output is missing or ambiguous: ${pattern}`,
);
}
}
for (const file of files) {
if (definition.compiledFiles.filter((pattern) => pattern.test(file)).length !== 1) {
return yield* fail(`${definition.name} has unexpected compiled output: ${file}`);
}
}
yield* Effect.forEach(
files.filter((file) => file.endsWith(".d.ts")),
(file) =>
Effect.gen(function* () {
const declaration = yield* readText(path.join(dist, file));
const referencedMap = declaration.match(/\/\/# sourceMappingURL=([^\r\n]+)\s*$/u)?.[1];
if (
referencedMap !== undefined &&
(referencedMap !== `${path.basename(file)}.map` || !files.includes(`${file}.map`))
) {
return yield* fail(
`${definition.name} compiled declaration references a missing source map: ${file}`,
);
}
}),
);
const maps = files.filter((file) => file.endsWith(".map"));
if (maps.length === 0) return yield* fail(`${definition.name} has no compiled source maps`);
yield* Effect.forEach(maps, (file) =>
verifyEmbeddedSourceMap(livePackageRoot, sourcePackageRoot, path.join(dist, file)),
);
return { allowlist, files };
});
export const verifyCompiledPackageOutput: {
(
sourceRoot: string,
packageName: string,
): (liveRoot: string) => VerifyCompiledPackageOutputEffect;
(liveRoot: string, sourceRoot: string, packageName: string): VerifyCompiledPackageOutputEffect;
} = Function.dual(3, verifyCompiledPackageOutputImpl);
const rewriteWorkspaceRanges = (value: unknown, version: string): void => {
if (!isObject(value)) return;
for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {
const dependencies = Reflect.get(value, field);
if (!isObject(dependencies)) continue;
for (const [name, range] of Object.entries(dependencies)) {
if (typeof range === "string" && range.startsWith("workspace:")) dependencies[name] = version;
}
}
};
const stagePackageImpl = (
liveRoot: string,
sourceRoot: string,
packageName: string,
stage: string,
version: string,
) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const definition = yield* packageDefinition(packageName);
const sourcePackageRoot = path.join(sourceRoot, definition.directory);
const verified = yield* verifyCompiledPackageOutput(liveRoot, sourceRoot, definition.name);
const metadata = yield* readJson(path.join(sourcePackageRoot, "package.json"));
if (!isObject(metadata))
return yield* fail(`${definition.name} package.json must be an object`);
const name = yield* requiredString(metadata.name, `${definition.name} package name`);
const declaredVersion = yield* requiredString(
metadata.version,
`${definition.name} package version`,
);
if (name !== definition.name || declaredVersion !== version) {
return yield* fail(`${definition.name} package identity is inconsistent`);
}
const allowlist = verified.allowlist;
rewriteWorkspaceRanges(metadata, version);
const packageRoot = path.join(stage, "package");
yield* fs
.makeDirectory(packageRoot, { recursive: true })
.pipe(Effect.mapError((cause) => fail(`cannot create ${packageRoot}`, cause)));
yield* fs
.writeFileString(path.join(packageRoot, "package.json"), stableJson(metadata))
.pipe(Effect.mapError((cause) => fail(`cannot stage ${definition.name} metadata`, cause)));
yield* Effect.forEach(allowlist, (entry) =>
Effect.gen(function* () {
const source = path.join(sourcePackageRoot, entry);
const symbolicLink = yield* fs
.readLink(source)
.pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
if (symbolicLink) {
return yield* fail(`archive input contains a symbolic link: ${definition.name}:${entry}`);
}
const info = yield* fs
.stat(source)
.pipe(
Effect.mapError((cause) => fail(`cannot inspect ${definition.name}:${entry}`, cause)),
);
if (info.type === "Directory") yield* filesBelow(source);
else if (info.type !== "File") {
return yield* fail(
`archive input contains unsupported content: ${definition.name}:${entry}`,
);
}
yield* fs
.copy(source, path.join(packageRoot, entry), { overwrite: true })
.pipe(
Effect.mapError((cause) => fail(`cannot stage ${definition.name}:${entry}`, cause)),
);
}),
);
return yield* fileProofs(packageRoot, "package");
});
export const stagePackage: {
(
sourceRoot: string,
packageName: string,
stage: string,
version: string,
): (liveRoot: string) => ReturnType<typeof stagePackageImpl>;
(
liveRoot: string,
sourceRoot: string,
packageName: string,
stage: string,
version: string,
): ReturnType<typeof stagePackageImpl>;
} = Function.dual(5, stagePackageImpl);
const archive = (root: string, stage: string, output: string, entries: readonly string[]) =>
runCommand(
"tar",
[
"--sort=name",
"--mtime=@0",
"--owner=0",
"--group=0",
"--numeric-owner",
"-czf",
output,
"-C",
stage,
...entries,
],
root,
);
const snapshotAtCommit = (root: string, sourceCommit: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const temporary = yield* fs
.makeTempDirectoryScoped({ prefix: "askgina-pack-source-" })
.pipe(Effect.mapError((cause) => fail("cannot create source snapshot directory", cause)));
const archiveFile = path.join(temporary, "source.tar");
const snapshot = path.join(temporary, "source");
yield* fs
.makeDirectory(snapshot, { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot create source snapshot", cause)));
yield* runCommand(
"git",
["archive", "--format=tar", `--output=${archiveFile}`, sourceCommit],
root,
);
yield* runCommand("tar", ["--extract", "--file", archiveFile, "--directory", snapshot], root);
return snapshot;
});
const buildSnapshotPackages = (root: string, snapshot: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const node = Bun.which("node");
if (node === null) return yield* fail("Node 24 is unavailable for the source commit build");
const nodeVersion = (yield* commandOutput(node, ["--version"], root)).trim();
if (!/^v24\./u.test(nodeVersion)) {
return yield* fail(`source commit build requires Node 24, received ${nodeVersion}`);
}
const linkNodeModules = (relative: string, required: boolean) =>
Effect.gen(function* () {
const installed = path.join(root, relative, "node_modules");
if (!(yield* fs.exists(installed))) {
if (required) return yield* fail("installed dependencies are unavailable");
return;
}
const linked = path.join(snapshot, relative, "node_modules");
yield* fs
.makeDirectory(linked, { recursive: true })
.pipe(Effect.mapError((cause) => fail(`cannot create ${relative}/node_modules`, cause)));
const names = yield* fs
.readDirectory(installed)
.pipe(Effect.mapError((cause) => fail(`cannot list ${relative}/node_modules`, cause)));
yield* Effect.forEach(names.sort(), (name) =>
Effect.gen(function* () {
if (name === ".vite" || name === ".vite-temp") return;
if (name !== "@askgina") {
yield* fs
.symlink(path.join(installed, name), path.join(linked, name))
.pipe(
Effect.mapError((cause) =>
fail(`cannot link build dependency ${relative}/node_modules/${name}`, cause),
),
);
return;
}
const installedScope = path.join(installed, name);
const linkedScope = path.join(linked, name);
yield* fs
.makeDirectory(linkedScope, { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot link workspace dependencies", cause)));
const workspaceNames = yield* fs
.readDirectory(installedScope)
.pipe(Effect.mapError((cause) => fail("cannot list workspace dependencies", cause)));
yield* Effect.forEach(workspaceNames.sort(), (workspaceName) =>
Effect.gen(function* () {
const definition = PACKAGES.find(
(candidate) => candidate.name === `@askgina/${workspaceName}`,
);
if (definition === undefined) {
return yield* fail(`unknown workspace dependency: @askgina/${workspaceName}`);
}
yield* fs
.symlink(
path.join(snapshot, definition.directory),
path.join(linkedScope, workspaceName),
)
.pipe(
Effect.mapError((cause) =>
fail(`cannot link workspace dependency ${definition.name}`, cause),
),
);
}),
);
}),
);
});
yield* linkNodeModules("", true);
yield* Effect.forEach(PACKAGES, (definition) => linkNodeModules(definition.directory, false));
const buildBin = path.join(snapshot, ".build-bin");
yield* fs
.makeDirectory(buildBin)
.pipe(Effect.mapError((cause) => fail("cannot create snapshot build launcher", cause)));
yield* fs
.symlink(node, path.join(buildBin, "node"))
.pipe(Effect.mapError((cause) => fail("cannot link snapshot Node launcher", cause)));
yield* Effect.forEach(PACKAGES, (definition) =>
runCommand(node, ["node_modules/.bin/vp", "pack", "--filter", definition.slug], snapshot, {
PATH: `${buildBin}:/usr/bin:/bin`,
}),
);
});
const assertLiveSourceBoundary = (root: string, snapshot: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const visit = (
live: string,
committed: string,
relative: string,
): Effect.Effect<void, ArtifactPackError> =>
Effect.gen(function* () {
const symbolicLink = yield* fs
.readLink(live)
.pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
if (symbolicLink) return yield* fail(`archive input contains a symbolic link: ${relative}`);
const liveInfo = yield* fs
.stat(live)
.pipe(Effect.mapError((cause) => fail(`cannot inspect ${relative}`, cause)));
if (liveInfo.type !== "Directory" && liveInfo.type !== "File") {
return yield* fail(`archive input contains unsupported content: ${relative}`);
}
const committedLink = yield* fs
.readLink(committed)
.pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
if (committedLink) {
return yield* fail(`source commit contains a symbolic link: ${relative}`);
}
const committedInfo = yield* fs
.stat(committed)
.pipe(Effect.match({ onFailure: () => undefined, onSuccess: (info) => info }));
if (committedInfo === undefined) {
return yield* fail(`archive input is absent from source commit: ${relative}`);
}
if (committedInfo.type !== liveInfo.type) {
return yield* fail(`archive input type differs from source commit: ${relative}`);
}
if (liveInfo.type !== "Directory") return;
const names = yield* fs
.readDirectory(live)
.pipe(Effect.mapError((cause) => fail(`cannot list ${relative}`, cause)));
yield* Effect.forEach(names.sort(), (name) =>
name === "node_modules" ||
name === ".DS_Store" ||
(name === "dist" && PACKAGES.some((definition) => definition.directory === relative))
? Effect.void
: visit(path.join(live, name), path.join(committed, name), `${relative}/${name}`),
);
});
yield* Effect.forEach(PACKAGES, (definition) =>
visit(
path.join(root, definition.directory),
path.join(snapshot, definition.directory),
definition.directory,
),
);
});
type PluginTargetEffect = Effect.Effect<void, ArtifactPackError, FileSystem.FileSystem | Path.Path>;
export const validateTargetVersion: {
(host: Host, version: string): (pluginRoot: string) => PluginTargetEffect;
(pluginRoot: string, host: Host, version: string): PluginTargetEffect;
} = Function.dual(3, (pluginRoot: string, host: Host, version: string): PluginTargetEffect =>
Effect.gen(function* () {
const path = yield* Path.Path;
const manifestRoot =
host === "openai" || host === "cursor" || host === "devin"
? pluginRoot
: path.join(pluginRoot, "targets", host);
const value = yield* readJson(path.join(manifestRoot, TARGET_MANIFESTS[host]));
if (!isObject(value) || value.version !== version) {
return yield* fail(`${host} target version is inconsistent`);
}
}),
);
const validateVersions = (root: string) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const rootJson = yield* readJson(path.join(root, "package.json"));
const version = yield* requiredString(
isObject(rootJson) ? rootJson.version : undefined,
"root package version",
);
if (!SEMVER.test(version)) return yield* fail("root package version must be valid SemVer");
yield* Effect.forEach(PACKAGES, (definition) =>
Effect.gen(function* () {
const metadata = yield* readJson(path.join(root, definition.directory, "package.json"));
if (!isObject(metadata) || metadata.version !== version) {
return yield* fail(`${definition.name} version must equal ${version}`);
}
yield* normalizedPackageFiles(metadata.files, `${definition.name} files`);
}),
);
const pluginManifest = yield* readText(path.join(root, "plugins/ask-gina/plugin.yaml"));
if (pluginManifest.match(/^version:\s*([^\s]+)$/mu)?.[1] !== version) {
return yield* fail("plugin.yaml version is inconsistent");
}
const pluginRoot = path.join(root, "plugins/ask-gina");
yield* Effect.forEach(HOSTS, (host) =>
validateTargetVersion(
pluginRoot,
host,
host === "cursor"
? CURSOR_LISTING_VERSION
: host === "openai"
? OPENAI_LISTING_VERSION
: version,
),
);
return version;
});
const buildEvalReceipt = (root: string, version: string, sourceCommit: string) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const result = yield* runHermeticEvalReplay({
suitePath: path.join(root, "plugins/ask-gina/evals/model/v1/smoke.yaml"),
observationsPath: path.join(
root,
"plugins/ask-gina/evals/model/v1/fixtures/synthetic-observations.yaml",
),
}).pipe(Effect.mapError((cause) => fail("hermetic eval replay failed", cause)));
const aggregate = yield* sanitizeEvalReplay(result).pipe(
Effect.mapError((cause) => fail("hermetic eval sanitization failed", cause)),
);
if (RAW_EVAL_FIELDS.test(stableJson(aggregate))) {
return yield* fail("eval sanitizer emitted a forbidden aggregate");
}
return { releaseVersion: version, sourceCommit, aggregate };
});
export const stagePluginTarget: {
(plugin: string, stage: string): (host: Host) => PluginTargetEffect;
(host: Host, plugin: string, stage: string): PluginTargetEffect;
} = Function.dual(3, (host: Host, plugin: string, stage: string): PluginTargetEffect =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
if (host === "openai") {
yield* fs
.makeDirectory(stage, { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot create openai target stage", cause)));
yield* Effect.forEach([".codex-plugin", "assets"] as const, (entry) =>
Effect.gen(function* () {
const source = path.join(plugin, entry);
yield* filesBelow(source);
yield* fs
.copy(source, path.join(stage, entry), { overwrite: true })
.pipe(Effect.mapError((cause) => fail(`cannot stage openai ${entry}`, cause)));
}),
);
yield* copyCheckedRegularFile(
path.join(plugin, ".mcp.json"),
path.join(stage, ".mcp.json"),
).pipe(Effect.mapError((cause) => fail("cannot stage openai .mcp.json", cause)));
} else if (host === "cursor") {
yield* fs
.makeDirectory(stage, { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot create cursor target stage", cause)));
yield* Effect.forEach([".cursor-plugin", "assets", "rules", "commands"] as const, (entry) =>
Effect.gen(function* () {
const source = path.join(plugin, entry);
yield* filesBelow(source);
yield* fs
.copy(source, path.join(stage, entry), { overwrite: true })
.pipe(Effect.mapError((cause) => fail(`cannot stage cursor ${entry}`, cause)));
}),
);
yield* copyCheckedRegularFile(
path.join(plugin, "mcp.json"),
path.join(stage, "mcp.json"),
).pipe(Effect.mapError((cause) => fail("cannot stage cursor mcp.json", cause)));
yield* copyCheckedRegularFile(
path.join(plugin, "README.md"),
path.join(stage, "README.md"),
).pipe(Effect.mapError((cause) => fail("cannot stage cursor README.md", cause)));
} else if (host === "devin") {
yield* fs
.makeDirectory(stage, { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot create devin target stage", cause)));
const source = path.join(plugin, ".devin-plugin");
yield* filesBelow(source);
yield* fs
.copy(source, path.join(stage, ".devin-plugin"), { overwrite: true })
.pipe(Effect.mapError((cause) => fail("cannot stage devin manifest", cause)));
yield* copyCheckedRegularFile(
path.join(plugin, ".mcp.json"),
path.join(stage, ".mcp.json"),
).pipe(Effect.mapError((cause) => fail("cannot stage devin .mcp.json", cause)));
yield* fs
.makeDirectory(path.join(stage, "assets"), { recursive: true })
.pipe(Effect.mapError((cause) => fail("cannot create devin assets", cause)));
yield* copyCheckedRegularFile(
path.join(plugin, "assets", "icon.svg"),
path.join(stage, "assets", "icon.svg"),
).pipe(Effect.mapError((cause) => fail("cannot stage devin icon", cause)));
} else {
const sourceOverlay = path.join(plugin, "targets", host);
yield* filesBelow(sourceOverlay);
yield* fs
.copy(sourceOverlay, stage, { overwrite: true })
.pipe(Effect.mapError((cause) => fail(`cannot stage ${host} target`, cause)));
}
yield* fs
.makeDirectory(path.join(stage, "skills"), { recursive: true })
.pipe(Effect.mapError((cause) => fail(`cannot create ${host} skills`, cause)));
yield* Effect.forEach(SKILLS, (skill) =>
Effect.gen(function* () {
const destination = path.join(stage, "skills", skill);
yield* fs
.copy(path.join(plugin, "skills", skill), destination, { overwrite: true })
.pipe(Effect.mapError((cause) => fail(`cannot stage ${host}:${skill}`, cause)));
if (host !== "openai") {
yield* fs
.remove(path.join(destination, "agents"), { recursive: true, force: true })
.pipe(Effect.mapError((cause) => fail(`cannot remove ${host} overlay`, cause)));
}
}),
);
}),
);
export interface BuildArtifactsOptions {
readonly root: string;
readonly dist: string;
}
export const buildArtifacts = ({ root, dist }: BuildArtifactsOptions) =>
Effect.scoped(
Effect.gen(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const sourceCommit = (yield* commandOutput(
"git",
["rev-parse", "--verify", "HEAD"],
root,
)).trim();
if (!GIT_COMMIT.test(sourceCommit)) return yield* fail("source commit is invalid");
const source = yield* snapshotAtCommit(root, sourceCommit);
yield* assertLiveSourceBoundary(root, source);
const plugin = path.join(source, "plugins/ask-gina");
const version = yield* validateVersions(source);
const sourceDirty: boolean = yield* commandHasBoundedOutput(
"git",
["status", "--porcelain=v1", "--untracked-files=all"],
root,
MAX_GIT_PORCELAIN_BYTES,
);
if (sourceDirty) return yield* fail("artifact source tree must be clean");
yield* buildSnapshotPackages(root, source);
const contractSource = yield* readText(path.join(source, "packages/contracts/src/index.ts"));
const catalogSha = contractSource.match(/export const catalogSha = "([a-f0-9]{64})"/u)?.[1];
const contractVersion = contractSource.match(
/export const RELEASE_VERSION = "([^"\\]+)"/u,
)?.[1];
if (catalogSha === undefined || !SHA_256.test(catalogSha) || contractVersion !== version) {
return yield* fail("public contract version or catalog SHA is inconsistent");
}
yield* fs
.remove(dist, { recursive: true, force: true })
.pipe(Effect.mapError((cause) => fail("cannot clean dist", cause)));
yield* Effect.forEach(["packages", "targets", "skills", "receipts"], (directory) =>
fs
.makeDirectory(path.join(dist, directory), { recursive: true })
.pipe(Effect.mapError((cause) => fail(`cannot create dist/${directory}`, cause))),
);
const temporary = yield* fs
.makeTempDirectoryScoped({ prefix: "askgina-artifacts-" })
.pipe(
Effect.mapError((cause) => fail("cannot create temporary artifact directory", cause)),