@srobroek/pi-code-challenge 0.0.0-stage → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/LICENSE +202 -0
  3. package/README.md +73 -2
  4. package/agents/code-challenger.md +64 -0
  5. package/agents/refactor-challenger.md +81 -0
  6. package/extensions/index.js +3862 -0
  7. package/formulas/code-challenge.formula.toml +102 -0
  8. package/formulas/mol-challenge-challenge.formula.toml +66 -0
  9. package/formulas/mol-challenge-decide.formula.toml +58 -0
  10. package/formulas/mol-challenge-deliver.formula.toml +70 -0
  11. package/formulas/mol-challenge-intake.formula.toml +68 -0
  12. package/formulas/mol-challenge-lens.formula.toml +59 -0
  13. package/formulas/mol-challenge-refute.formula.toml +77 -0
  14. package/formulas/mol-challenge-research.formula.toml +61 -0
  15. package/formulas/mol-challenge-scan.formula.toml +61 -0
  16. package/package.json +38 -4
  17. package/skills/code-challenge/SKILL.md +83 -0
  18. package/skills/code-challenge/references/decide.md +31 -0
  19. package/skills/code-challenge/references/decisions.schema.json +21 -0
  20. package/skills/code-challenge/references/evidence.md +17 -0
  21. package/skills/code-challenge/references/intake-questions.md +49 -0
  22. package/skills/code-challenge/references/lens-dead-code.md +20 -0
  23. package/skills/code-challenge/references/lens-efficiency.md +21 -0
  24. package/skills/code-challenge/references/lens-hand-rolled-library.md +18 -0
  25. package/skills/code-challenge/references/lens-hand-rolled-stdlib.md +20 -0
  26. package/skills/code-challenge/references/lens-observability.md +20 -0
  27. package/skills/code-challenge/references/lens-optimisation.md +20 -0
  28. package/skills/code-challenge/references/lens-over-engineering.md +21 -0
  29. package/skills/code-challenge/references/lens-performance.md +18 -0
  30. package/skills/code-challenge/references/lens-scope.md +31 -0
  31. package/skills/code-challenge/references/lens-simplification.md +23 -0
  32. package/skills/code-challenge/references/lens-stability.md +21 -0
  33. package/skills/code-challenge/references/lens-structure.md +26 -0
  34. package/skills/code-challenge/references/lens-tests.md +20 -0
  35. package/skills/code-challenge/references/library-scoring.md +54 -0
  36. package/skills/code-challenge/references/report.schema.json +125 -0
  37. package/skills/code-challenge/references/run-storage.md +22 -0
  38. package/skills/code-challenge/references/scan.md +36 -0
  39. package/skills/code-challenge/references/schemas.md +37 -0
@@ -0,0 +1,3862 @@
1
+ // @bun
2
+ // Generated by scripts/build.ts. Do not edit.
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ if (mod && typeof mod === "object" || typeof mod === "function") {
24
+ for (let key of __getOwnPropNames(mod))
25
+ if (!__hasOwnProp.call(to, key))
26
+ __defProp(to, key, {
27
+ get: __accessProp.bind(mod, key),
28
+ enumerable: true
29
+ });
30
+ }
31
+ if (canCache)
32
+ cache.set(mod, to);
33
+ return to;
34
+ };
35
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
36
+
37
+ // node_modules/spdx-license-ids/index.json
38
+ var require_spdx_license_ids = __commonJS(function(exports, module) {
39
+ module.exports = [
40
+ "0BSD",
41
+ "3D-Slicer-1.0",
42
+ "AAL",
43
+ "ADSL",
44
+ "AFL-1.1",
45
+ "AFL-1.2",
46
+ "AFL-2.0",
47
+ "AFL-2.1",
48
+ "AFL-3.0",
49
+ "AGPL-1.0-only",
50
+ "AGPL-1.0-or-later",
51
+ "AGPL-3.0-only",
52
+ "AGPL-3.0-or-later",
53
+ "ALGLIB-Documentation",
54
+ "AMD-newlib",
55
+ "AMDPLPA",
56
+ "AML",
57
+ "AML-glslang",
58
+ "AMPAS",
59
+ "ANTLR-PD",
60
+ "ANTLR-PD-fallback",
61
+ "APAFML",
62
+ "APL-1.0",
63
+ "APSL-1.0",
64
+ "APSL-1.1",
65
+ "APSL-1.2",
66
+ "APSL-2.0",
67
+ "ASWF-Digital-Assets-1.0",
68
+ "ASWF-Digital-Assets-1.1",
69
+ "Abstyles",
70
+ "AdaCore-doc",
71
+ "Adobe-2006",
72
+ "Adobe-Display-PostScript",
73
+ "Adobe-Glyph",
74
+ "Adobe-Utopia",
75
+ "Advanced-Cryptics-Dictionary",
76
+ "Afmparse",
77
+ "Aladdin",
78
+ "Apache-1.0",
79
+ "Apache-1.1",
80
+ "Apache-2.0",
81
+ "App-s2p",
82
+ "Arphic-1999",
83
+ "Artistic-1.0",
84
+ "Artistic-1.0-Perl",
85
+ "Artistic-1.0-cl8",
86
+ "Artistic-2.0",
87
+ "Artistic-dist",
88
+ "Aspell-RU",
89
+ "BOLA-1.1",
90
+ "BSD-1-Clause",
91
+ "BSD-2-Clause",
92
+ "BSD-2-Clause-Darwin",
93
+ "BSD-2-Clause-Patent",
94
+ "BSD-2-Clause-Views",
95
+ "BSD-2-Clause-first-lines",
96
+ "BSD-2-Clause-pkgconf-disclaimer",
97
+ "BSD-2-Clause-pos-unchanged",
98
+ "BSD-3-Clause",
99
+ "BSD-3-Clause-Attribution",
100
+ "BSD-3-Clause-Clear",
101
+ "BSD-3-Clause-HP",
102
+ "BSD-3-Clause-LBNL",
103
+ "BSD-3-Clause-Modification",
104
+ "BSD-3-Clause-No-Military-License",
105
+ "BSD-3-Clause-No-Nuclear-License",
106
+ "BSD-3-Clause-No-Nuclear-License-2014",
107
+ "BSD-3-Clause-No-Nuclear-Warranty",
108
+ "BSD-3-Clause-Open-MPI",
109
+ "BSD-3-Clause-OpenWebUI",
110
+ "BSD-3-Clause-Sun",
111
+ "BSD-3-Clause-Tso",
112
+ "BSD-3-Clause-acpica",
113
+ "BSD-3-Clause-flex",
114
+ "BSD-4-Clause",
115
+ "BSD-4-Clause-Shortened",
116
+ "BSD-4-Clause-UC",
117
+ "BSD-4.3RENO",
118
+ "BSD-4.3TAHOE",
119
+ "BSD-Advertising-Acknowledgement",
120
+ "BSD-Attribution-HPND-disclaimer",
121
+ "BSD-Inferno-Nettverk",
122
+ "BSD-Mark-Modifications",
123
+ "BSD-Protection",
124
+ "BSD-Source-Code",
125
+ "BSD-Source-Code-no-disclaimer",
126
+ "BSD-Source-alt-GPL",
127
+ "BSD-Source-beginning-file",
128
+ "BSD-Systemics",
129
+ "BSD-Systemics-W3Works",
130
+ "BSD-ask-to-endorse",
131
+ "BSL-1.0",
132
+ "BUSL-1.1",
133
+ "Baekmuk",
134
+ "Bahyph",
135
+ "Barr",
136
+ "Beerware",
137
+ "BitTorrent-1.0",
138
+ "BitTorrent-1.1",
139
+ "Bitstream-Charter",
140
+ "Bitstream-Vera",
141
+ "BlueOak-1.0.0",
142
+ "Boehm-GC",
143
+ "Boehm-GC-without-fee",
144
+ "Borceux",
145
+ "Brian-Gladman-2-Clause",
146
+ "Brian-Gladman-3-Clause",
147
+ "Brian-Gladman-3-Clause-no-conversion",
148
+ "Buddy",
149
+ "Bugroff",
150
+ "C-UDA-1.0",
151
+ "CAL-1.0",
152
+ "CAL-1.0-Combined-Work-Exception",
153
+ "CAPEC-tou",
154
+ "CATOSL-1.1",
155
+ "CC-BY-1.0",
156
+ "CC-BY-2.0",
157
+ "CC-BY-2.5",
158
+ "CC-BY-2.5-AU",
159
+ "CC-BY-3.0",
160
+ "CC-BY-3.0-AT",
161
+ "CC-BY-3.0-AU",
162
+ "CC-BY-3.0-DE",
163
+ "CC-BY-3.0-IGO",
164
+ "CC-BY-3.0-NL",
165
+ "CC-BY-3.0-US",
166
+ "CC-BY-4.0",
167
+ "CC-BY-NC-1.0",
168
+ "CC-BY-NC-2.0",
169
+ "CC-BY-NC-2.5",
170
+ "CC-BY-NC-3.0",
171
+ "CC-BY-NC-3.0-DE",
172
+ "CC-BY-NC-3.0-IGO",
173
+ "CC-BY-NC-4.0",
174
+ "CC-BY-NC-ND-1.0",
175
+ "CC-BY-NC-ND-2.0",
176
+ "CC-BY-NC-ND-2.5",
177
+ "CC-BY-NC-ND-3.0",
178
+ "CC-BY-NC-ND-3.0-DE",
179
+ "CC-BY-NC-ND-3.0-IGO",
180
+ "CC-BY-NC-ND-4.0",
181
+ "CC-BY-NC-SA-1.0",
182
+ "CC-BY-NC-SA-2.0",
183
+ "CC-BY-NC-SA-2.0-DE",
184
+ "CC-BY-NC-SA-2.0-FR",
185
+ "CC-BY-NC-SA-2.0-UK",
186
+ "CC-BY-NC-SA-2.5",
187
+ "CC-BY-NC-SA-3.0",
188
+ "CC-BY-NC-SA-3.0-DE",
189
+ "CC-BY-NC-SA-3.0-IGO",
190
+ "CC-BY-NC-SA-4.0",
191
+ "CC-BY-ND-1.0",
192
+ "CC-BY-ND-2.0",
193
+ "CC-BY-ND-2.5",
194
+ "CC-BY-ND-3.0",
195
+ "CC-BY-ND-3.0-DE",
196
+ "CC-BY-ND-4.0",
197
+ "CC-BY-SA-1.0",
198
+ "CC-BY-SA-2.0",
199
+ "CC-BY-SA-2.0-UK",
200
+ "CC-BY-SA-2.1-JP",
201
+ "CC-BY-SA-2.5",
202
+ "CC-BY-SA-3.0",
203
+ "CC-BY-SA-3.0-AT",
204
+ "CC-BY-SA-3.0-DE",
205
+ "CC-BY-SA-3.0-IGO",
206
+ "CC-BY-SA-4.0",
207
+ "CC-PDDC",
208
+ "CC-PDM-1.0",
209
+ "CC-SA-1.0",
210
+ "CC0-1.0",
211
+ "CDDL-1.0",
212
+ "CDDL-1.1",
213
+ "CDL-1.0",
214
+ "CDLA-Permissive-1.0",
215
+ "CDLA-Permissive-2.0",
216
+ "CDLA-Sharing-1.0",
217
+ "CECILL-1.0",
218
+ "CECILL-1.1",
219
+ "CECILL-2.0",
220
+ "CECILL-2.1",
221
+ "CECILL-B",
222
+ "CECILL-C",
223
+ "CERN-OHL-1.1",
224
+ "CERN-OHL-1.2",
225
+ "CERN-OHL-P-2.0",
226
+ "CERN-OHL-S-2.0",
227
+ "CERN-OHL-W-2.0",
228
+ "CFITSIO",
229
+ "CMU-Mach",
230
+ "CMU-Mach-nodoc",
231
+ "CNRI-Jython",
232
+ "CNRI-Python",
233
+ "CNRI-Python-GPL-Compatible",
234
+ "COIL-1.0",
235
+ "CPAL-1.0",
236
+ "CPL-1.0",
237
+ "CPOL-1.02",
238
+ "CUA-OPL-1.0",
239
+ "Caldera",
240
+ "Caldera-no-preamble",
241
+ "Catharon",
242
+ "ClArtistic",
243
+ "Clips",
244
+ "Community-Spec-1.0",
245
+ "Condor-1.1",
246
+ "Cornell-Lossless-JPEG",
247
+ "Cronyx",
248
+ "Crossword",
249
+ "CryptoSwift",
250
+ "CrystalStacker",
251
+ "Cube",
252
+ "D-FSL-1.0",
253
+ "DEC-3-Clause",
254
+ "DL-DE-BY-2.0",
255
+ "DL-DE-ZERO-2.0",
256
+ "DOC",
257
+ "DRL-1.0",
258
+ "DRL-1.1",
259
+ "DSDP",
260
+ "DocBook-DTD",
261
+ "DocBook-Schema",
262
+ "DocBook-Stylesheet",
263
+ "DocBook-XML",
264
+ "Dotseqn",
265
+ "ECL-1.0",
266
+ "ECL-2.0",
267
+ "EFL-1.0",
268
+ "EFL-2.0",
269
+ "EPICS",
270
+ "EPL-1.0",
271
+ "EPL-2.0",
272
+ "ESA-PL-permissive-2.4",
273
+ "ESA-PL-strong-copyleft-2.4",
274
+ "ESA-PL-weak-copyleft-2.4",
275
+ "EUDatagrid",
276
+ "EUPL-1.0",
277
+ "EUPL-1.1",
278
+ "EUPL-1.2",
279
+ "Elastic-2.0",
280
+ "Entessa",
281
+ "ErlPL-1.1",
282
+ "Eurosym",
283
+ "FBM",
284
+ "FDK-AAC",
285
+ "FDK-MPEG-H",
286
+ "FSFAP",
287
+ "FSFAP-no-warranty-disclaimer",
288
+ "FSFUL",
289
+ "FSFULLR",
290
+ "FSFULLRSD",
291
+ "FSFULLRWD",
292
+ "FSL-1.1-ALv2",
293
+ "FSL-1.1-MIT",
294
+ "FTL",
295
+ "Fair",
296
+ "Ferguson-Twofish",
297
+ "Frameworx-1.0",
298
+ "FreeBSD-DOC",
299
+ "FreeImage",
300
+ "Furuseth",
301
+ "GCR-docs",
302
+ "GD",
303
+ "GFDL-1.1-invariants-only",
304
+ "GFDL-1.1-invariants-or-later",
305
+ "GFDL-1.1-no-invariants-only",
306
+ "GFDL-1.1-no-invariants-or-later",
307
+ "GFDL-1.1-only",
308
+ "GFDL-1.1-or-later",
309
+ "GFDL-1.2-invariants-only",
310
+ "GFDL-1.2-invariants-or-later",
311
+ "GFDL-1.2-no-invariants-only",
312
+ "GFDL-1.2-no-invariants-or-later",
313
+ "GFDL-1.2-only",
314
+ "GFDL-1.2-or-later",
315
+ "GFDL-1.3-invariants-only",
316
+ "GFDL-1.3-invariants-or-later",
317
+ "GFDL-1.3-no-invariants-only",
318
+ "GFDL-1.3-no-invariants-or-later",
319
+ "GFDL-1.3-only",
320
+ "GFDL-1.3-or-later",
321
+ "GL2PS",
322
+ "GLWTPL",
323
+ "GPL-1.0-only",
324
+ "GPL-1.0-or-later",
325
+ "GPL-2.0-only",
326
+ "GPL-2.0-or-later",
327
+ "GPL-3.0-only",
328
+ "GPL-3.0-or-later",
329
+ "Game-Programming-Gems",
330
+ "Giftware",
331
+ "Glide",
332
+ "Glulxe",
333
+ "Graphics-Gems",
334
+ "Gutmann",
335
+ "HDF5",
336
+ "HIDAPI",
337
+ "HP-1986",
338
+ "HP-1989",
339
+ "HPND",
340
+ "HPND-DEC",
341
+ "HPND-Fenneberg-Livingston",
342
+ "HPND-INRIA-IMAG",
343
+ "HPND-Intel",
344
+ "HPND-Kevlin-Henney",
345
+ "HPND-MIT-disclaimer",
346
+ "HPND-Markus-Kuhn",
347
+ "HPND-Netrek",
348
+ "HPND-Pbmplus",
349
+ "HPND-SMC",
350
+ "HPND-UC",
351
+ "HPND-UC-export-US",
352
+ "HPND-doc",
353
+ "HPND-doc-sell",
354
+ "HPND-export-US",
355
+ "HPND-export-US-acknowledgement",
356
+ "HPND-export-US-modify",
357
+ "HPND-export2-US",
358
+ "HPND-merchantability-variant",
359
+ "HPND-sell-MIT-disclaimer-xserver",
360
+ "HPND-sell-regexpr",
361
+ "HPND-sell-variant",
362
+ "HPND-sell-variant-MIT-disclaimer",
363
+ "HPND-sell-variant-MIT-disclaimer-rev",
364
+ "HPND-sell-variant-critical-systems",
365
+ "HTMLTIDY",
366
+ "HaskellReport",
367
+ "Hippocratic-2.1",
368
+ "Hippocratic-3.0-core",
369
+ "IBM-pibs",
370
+ "ICU",
371
+ "IEC-Code-Components-EULA",
372
+ "IJG",
373
+ "IJG-short",
374
+ "IPA",
375
+ "IPL-1.0",
376
+ "ISC",
377
+ "ISC-Veillard",
378
+ "ISO-permission",
379
+ "ImageMagick",
380
+ "Imlib2",
381
+ "Info-ZIP",
382
+ "Informatica",
383
+ "Inner-Net-2.0",
384
+ "InnoSetup",
385
+ "Intel",
386
+ "Intel-ACPI",
387
+ "Interbase-1.0",
388
+ "JPL-image",
389
+ "JPNIC",
390
+ "JSON",
391
+ "Jam",
392
+ "JasPer-2.0",
393
+ "Kastrup",
394
+ "Kazlib",
395
+ "Knuth-CTAN",
396
+ "LAL-1.2",
397
+ "LAL-1.3",
398
+ "LGPL-2.0-only",
399
+ "LGPL-2.0-or-later",
400
+ "LGPL-2.1-only",
401
+ "LGPL-2.1-or-later",
402
+ "LGPL-3.0-only",
403
+ "LGPL-3.0-or-later",
404
+ "LGPLLR",
405
+ "LOOP",
406
+ "LPD-document",
407
+ "LPL-1.0",
408
+ "LPL-1.02",
409
+ "LPPL-1.0",
410
+ "LPPL-1.1",
411
+ "LPPL-1.2",
412
+ "LPPL-1.3a",
413
+ "LPPL-1.3c",
414
+ "LZMA-SDK-9.11-to-9.20",
415
+ "LZMA-SDK-9.22",
416
+ "Latex2e",
417
+ "Latex2e-translated-notice",
418
+ "Leptonica",
419
+ "LiLiQ-P-1.1",
420
+ "LiLiQ-R-1.1",
421
+ "LiLiQ-Rplus-1.1",
422
+ "Libpng",
423
+ "Linux-OpenIB",
424
+ "Linux-man-pages-1-para",
425
+ "Linux-man-pages-copyleft",
426
+ "Linux-man-pages-copyleft-2-para",
427
+ "Linux-man-pages-copyleft-var",
428
+ "Lucida-Bitmap-Fonts",
429
+ "MIPS",
430
+ "MIT",
431
+ "MIT-0",
432
+ "MIT-CMU",
433
+ "MIT-Click",
434
+ "MIT-Festival",
435
+ "MIT-Khronos-old",
436
+ "MIT-Modern-Variant",
437
+ "MIT-STK",
438
+ "MIT-Wu",
439
+ "MIT-advertising",
440
+ "MIT-enna",
441
+ "MIT-feh",
442
+ "MIT-open-group",
443
+ "MIT-testregex",
444
+ "MITNFA",
445
+ "MMIXware",
446
+ "MMPL-1.0.1",
447
+ "MPEG-SSG",
448
+ "MPL-1.0",
449
+ "MPL-1.1",
450
+ "MPL-2.0",
451
+ "MPL-2.0-no-copyleft-exception",
452
+ "MS-LPL",
453
+ "MS-PL",
454
+ "MS-RL",
455
+ "MTLL",
456
+ "MVT-1.1",
457
+ "Mackerras-3-Clause",
458
+ "Mackerras-3-Clause-acknowledgment",
459
+ "MakeIndex",
460
+ "Martin-Birgmeier",
461
+ "McPhee-slideshow",
462
+ "Minpack",
463
+ "MirOS",
464
+ "Motosoto",
465
+ "MulanPSL-1.0",
466
+ "MulanPSL-2.0",
467
+ "Multics",
468
+ "Mup",
469
+ "NAIST-2003",
470
+ "NASA-1.3",
471
+ "NBPL-1.0",
472
+ "NCBI-PD",
473
+ "NCGL-UK-2.0",
474
+ "NCL",
475
+ "NCSA",
476
+ "NGPL",
477
+ "NICTA-1.0",
478
+ "NIST-PD",
479
+ "NIST-PD-TNT",
480
+ "NIST-PD-fallback",
481
+ "NIST-Software",
482
+ "NLOD-1.0",
483
+ "NLOD-2.0",
484
+ "NLPL",
485
+ "NOSL",
486
+ "NPL-1.0",
487
+ "NPL-1.1",
488
+ "NPOSL-3.0",
489
+ "NRL",
490
+ "NTIA-PD",
491
+ "NTP",
492
+ "NTP-0",
493
+ "Naumen",
494
+ "NetCDF",
495
+ "Newsletr",
496
+ "Nokia",
497
+ "Noweb",
498
+ "O-UDA-1.0",
499
+ "OAR",
500
+ "OCCT-PL",
501
+ "OCLC-2.0",
502
+ "ODC-By-1.0",
503
+ "ODbL-1.0",
504
+ "OFFIS",
505
+ "OFL-1.0",
506
+ "OFL-1.0-RFN",
507
+ "OFL-1.0-no-RFN",
508
+ "OFL-1.1",
509
+ "OFL-1.1-RFN",
510
+ "OFL-1.1-no-RFN",
511
+ "OGC-1.0",
512
+ "OGDL-Taiwan-1.0",
513
+ "OGL-Canada-2.0",
514
+ "OGL-UK-1.0",
515
+ "OGL-UK-2.0",
516
+ "OGL-UK-3.0",
517
+ "OGTSL",
518
+ "OLDAP-1.1",
519
+ "OLDAP-1.2",
520
+ "OLDAP-1.3",
521
+ "OLDAP-1.4",
522
+ "OLDAP-2.0",
523
+ "OLDAP-2.0.1",
524
+ "OLDAP-2.1",
525
+ "OLDAP-2.2",
526
+ "OLDAP-2.2.1",
527
+ "OLDAP-2.2.2",
528
+ "OLDAP-2.3",
529
+ "OLDAP-2.4",
530
+ "OLDAP-2.5",
531
+ "OLDAP-2.6",
532
+ "OLDAP-2.7",
533
+ "OLDAP-2.8",
534
+ "OLFL-1.3",
535
+ "OML",
536
+ "OPL-1.0",
537
+ "OPL-UK-3.0",
538
+ "OPUBL-1.0",
539
+ "OSC-1.0",
540
+ "OSET-PL-2.1",
541
+ "OSL-1.0",
542
+ "OSL-1.1",
543
+ "OSL-2.0",
544
+ "OSL-2.1",
545
+ "OSL-3.0",
546
+ "OSSP",
547
+ "OpenMDW-1.0",
548
+ "OpenPBS-2.3",
549
+ "OpenSSL",
550
+ "OpenSSL-standalone",
551
+ "OpenVision",
552
+ "PADL",
553
+ "PDDL-1.0",
554
+ "PHP-3.0",
555
+ "PHP-3.01",
556
+ "PPL",
557
+ "PSF-2.0",
558
+ "ParaType-Free-Font-1.3",
559
+ "Parity-6.0.0",
560
+ "Parity-7.0.0",
561
+ "Pixar",
562
+ "Plexus",
563
+ "PolyForm-Noncommercial-1.0.0",
564
+ "PolyForm-Small-Business-1.0.0",
565
+ "PostgreSQL",
566
+ "Python-2.0",
567
+ "Python-2.0.1",
568
+ "QPL-1.0",
569
+ "QPL-1.0-INRIA-2004",
570
+ "Qhull",
571
+ "RHeCos-1.1",
572
+ "RPL-1.1",
573
+ "RPL-1.5",
574
+ "RPSL-1.0",
575
+ "RSA-MD",
576
+ "RSCPL",
577
+ "Rdisc",
578
+ "Ruby",
579
+ "Ruby-pty",
580
+ "SAX-PD",
581
+ "SAX-PD-2.0",
582
+ "SCEA",
583
+ "SGI-B-1.0",
584
+ "SGI-B-1.1",
585
+ "SGI-B-2.0",
586
+ "SGI-OpenGL",
587
+ "SGMLUG-PM",
588
+ "SGP4",
589
+ "SHL-0.5",
590
+ "SHL-0.51",
591
+ "SISSL",
592
+ "SISSL-1.2",
593
+ "SL",
594
+ "SMAIL-GPL",
595
+ "SMLNJ",
596
+ "SMPPL",
597
+ "SNIA",
598
+ "SOFA",
599
+ "SPL-1.0",
600
+ "SSH-OpenSSH",
601
+ "SSH-short",
602
+ "SSLeay-standalone",
603
+ "SSPL-1.0",
604
+ "SUL-1.0",
605
+ "SWL",
606
+ "Saxpath",
607
+ "SchemeReport",
608
+ "Sendmail",
609
+ "Sendmail-8.23",
610
+ "Sendmail-Open-Source-1.1",
611
+ "SimPL-2.0",
612
+ "Sleepycat",
613
+ "Soundex",
614
+ "Spencer-86",
615
+ "Spencer-94",
616
+ "Spencer-99",
617
+ "SugarCRM-1.1.3",
618
+ "Sun-PPP",
619
+ "Sun-PPP-2000",
620
+ "SunPro",
621
+ "Symlinks",
622
+ "TAPR-OHL-1.0",
623
+ "TCL",
624
+ "TCP-wrappers",
625
+ "TGPPL-1.0",
626
+ "TMate",
627
+ "TORQUE-1.1",
628
+ "TOSL",
629
+ "TPDL",
630
+ "TPL-1.0",
631
+ "TTWL",
632
+ "TTYP0",
633
+ "TU-Berlin-1.0",
634
+ "TU-Berlin-2.0",
635
+ "TekHVC",
636
+ "TermReadKey",
637
+ "ThirdEye",
638
+ "TrustedQSL",
639
+ "UCAR",
640
+ "UCL-1.0",
641
+ "UMich-Merit",
642
+ "UPL-1.0",
643
+ "URT-RLE",
644
+ "Ubuntu-font-1.0",
645
+ "UnRAR",
646
+ "Unicode-3.0",
647
+ "Unicode-DFS-2015",
648
+ "Unicode-DFS-2016",
649
+ "Unicode-TOU",
650
+ "UnixCrypt",
651
+ "Unlicense",
652
+ "Unlicense-libtelnet",
653
+ "Unlicense-libwhirlpool",
654
+ "VOSTROM",
655
+ "VSL-1.0",
656
+ "Vim",
657
+ "Vixie-Cron",
658
+ "W3C",
659
+ "W3C-19980720",
660
+ "W3C-20150513",
661
+ "WTFNMFPL",
662
+ "WTFPL",
663
+ "Watcom-1.0",
664
+ "Widget-Workshop",
665
+ "WordNet",
666
+ "Wsuipa",
667
+ "X11",
668
+ "X11-distribute-modifications-variant",
669
+ "X11-no-permit-persons",
670
+ "X11-swapped",
671
+ "XFree86-1.1",
672
+ "XSkat",
673
+ "Xdebug-1.03",
674
+ "Xerox",
675
+ "Xfig",
676
+ "Xnet",
677
+ "YPL-1.0",
678
+ "YPL-1.1",
679
+ "ZPL-1.1",
680
+ "ZPL-2.0",
681
+ "ZPL-2.1",
682
+ "Zed",
683
+ "Zeeff",
684
+ "Zend-2.0",
685
+ "Zimbra-1.3",
686
+ "Zimbra-1.4",
687
+ "Zlib",
688
+ "any-OSI",
689
+ "any-OSI-perl-modules",
690
+ "atc-game",
691
+ "bcrypt-Solar-Designer",
692
+ "blessing",
693
+ "bzip2-1.0.6",
694
+ "check-cvs",
695
+ "checkmk",
696
+ "copyleft-next-0.3.0",
697
+ "copyleft-next-0.3.1",
698
+ "curl",
699
+ "cve-tou",
700
+ "diffmark",
701
+ "dtoa",
702
+ "dvipdfm",
703
+ "eGenix",
704
+ "etalab-2.0",
705
+ "fwlw",
706
+ "gSOAP-1.3b",
707
+ "generic-xts",
708
+ "gnuplot",
709
+ "gtkbook",
710
+ "hdparm",
711
+ "hyphen-bulgarian",
712
+ "iMatix",
713
+ "jove",
714
+ "libpng-1.6.35",
715
+ "libpng-2.0",
716
+ "libselinux-1.0",
717
+ "libtiff",
718
+ "libutil-David-Nugent",
719
+ "lsof",
720
+ "magaz",
721
+ "mailprio",
722
+ "man2html",
723
+ "metamail",
724
+ "mpi-permissive",
725
+ "mpich2",
726
+ "mplus",
727
+ "ngrep",
728
+ "pkgconf",
729
+ "pnmstitch",
730
+ "psfrag",
731
+ "psutils",
732
+ "python-ldap",
733
+ "radvd",
734
+ "snprintf",
735
+ "softSurfer",
736
+ "ssh-keyscan",
737
+ "swrule",
738
+ "threeparttable",
739
+ "ulem",
740
+ "w3m",
741
+ "wwl",
742
+ "xinetd",
743
+ "xkeyboard-config-Zinoviev",
744
+ "xlock",
745
+ "xpp",
746
+ "xzoom",
747
+ "zlib-acknowledgement"
748
+ ];
749
+ });
750
+
751
+ // node_modules/spdx-license-ids/deprecated.json
752
+ var require_deprecated = __commonJS(function(exports, module) {
753
+ module.exports = [
754
+ "AGPL-1.0",
755
+ "AGPL-3.0",
756
+ "BSD-2-Clause-FreeBSD",
757
+ "BSD-2-Clause-NetBSD",
758
+ "GFDL-1.1",
759
+ "GFDL-1.2",
760
+ "GFDL-1.3",
761
+ "GPL-1.0",
762
+ "GPL-2.0",
763
+ "GPL-2.0-with-GCC-exception",
764
+ "GPL-2.0-with-autoconf-exception",
765
+ "GPL-2.0-with-bison-exception",
766
+ "GPL-2.0-with-classpath-exception",
767
+ "GPL-2.0-with-font-exception",
768
+ "GPL-3.0",
769
+ "GPL-3.0-with-GCC-exception",
770
+ "GPL-3.0-with-autoconf-exception",
771
+ "LGPL-2.0",
772
+ "LGPL-2.1",
773
+ "LGPL-3.0",
774
+ "Net-SNMP",
775
+ "Nunit",
776
+ "StandardML-NJ",
777
+ "bzip2-1.0.5",
778
+ "eCos-2.0",
779
+ "wxWindows"
780
+ ];
781
+ });
782
+
783
+ // node_modules/spdx-exceptions/index.json
784
+ var require_spdx_exceptions = __commonJS(function(exports, module) {
785
+ module.exports = [
786
+ "389-exception",
787
+ "Asterisk-exception",
788
+ "Autoconf-exception-2.0",
789
+ "Autoconf-exception-3.0",
790
+ "Autoconf-exception-generic",
791
+ "Autoconf-exception-generic-3.0",
792
+ "Autoconf-exception-macro",
793
+ "Bison-exception-1.24",
794
+ "Bison-exception-2.2",
795
+ "Bootloader-exception",
796
+ "Classpath-exception-2.0",
797
+ "CLISP-exception-2.0",
798
+ "cryptsetup-OpenSSL-exception",
799
+ "DigiRule-FOSS-exception",
800
+ "eCos-exception-2.0",
801
+ "Fawkes-Runtime-exception",
802
+ "FLTK-exception",
803
+ "fmt-exception",
804
+ "Font-exception-2.0",
805
+ "freertos-exception-2.0",
806
+ "GCC-exception-2.0",
807
+ "GCC-exception-2.0-note",
808
+ "GCC-exception-3.1",
809
+ "Gmsh-exception",
810
+ "GNAT-exception",
811
+ "GNOME-examples-exception",
812
+ "GNU-compiler-exception",
813
+ "gnu-javamail-exception",
814
+ "GPL-3.0-interface-exception",
815
+ "GPL-3.0-linking-exception",
816
+ "GPL-3.0-linking-source-exception",
817
+ "GPL-CC-1.0",
818
+ "GStreamer-exception-2005",
819
+ "GStreamer-exception-2008",
820
+ "i2p-gpl-java-exception",
821
+ "KiCad-libraries-exception",
822
+ "LGPL-3.0-linking-exception",
823
+ "libpri-OpenH323-exception",
824
+ "Libtool-exception",
825
+ "Linux-syscall-note",
826
+ "LLGPL",
827
+ "LLVM-exception",
828
+ "LZMA-exception",
829
+ "mif-exception",
830
+ "OCaml-LGPL-linking-exception",
831
+ "OCCT-exception-1.0",
832
+ "OpenJDK-assembly-exception-1.0",
833
+ "openvpn-openssl-exception",
834
+ "PS-or-PDF-font-exception-20170817",
835
+ "QPL-1.0-INRIA-2004-exception",
836
+ "Qt-GPL-exception-1.0",
837
+ "Qt-LGPL-exception-1.1",
838
+ "Qwt-exception-1.0",
839
+ "SANE-exception",
840
+ "SHL-2.0",
841
+ "SHL-2.1",
842
+ "stunnel-exception",
843
+ "SWI-exception",
844
+ "Swift-exception",
845
+ "Texinfo-exception",
846
+ "u-boot-exception-2.0",
847
+ "UBDL-exception",
848
+ "Universal-FOSS-exception-1.0",
849
+ "vsftpd-openssl-exception",
850
+ "WxWindows-exception-3.1",
851
+ "x11vnc-openssl-exception"
852
+ ];
853
+ });
854
+
855
+ // node_modules/spdx-expression-parse/scan.js
856
+ var require_scan = __commonJS(function(exports, module) {
857
+ var licenses = [].concat(require_spdx_license_ids()).concat(require_deprecated());
858
+ var exceptions = require_spdx_exceptions();
859
+ module.exports = function(source) {
860
+ var index = 0;
861
+ function hasMore() {
862
+ return index < source.length;
863
+ }
864
+ function read(value) {
865
+ if (value instanceof RegExp) {
866
+ var chars = source.slice(index);
867
+ var match = chars.match(value);
868
+ if (match) {
869
+ index += match[0].length;
870
+ return match[0];
871
+ }
872
+ } else {
873
+ if (source.indexOf(value, index) === index) {
874
+ index += value.length;
875
+ return value;
876
+ }
877
+ }
878
+ }
879
+ function skipWhitespace() {
880
+ read(/[ ]*/);
881
+ }
882
+ function operator() {
883
+ var string;
884
+ var possibilities = [/^WITH/i, /^AND/i, /^OR/i, "(", ")", ":", "+"];
885
+ for (var i = 0;i < possibilities.length; i++) {
886
+ string = read(possibilities[i]);
887
+ if (string) {
888
+ break;
889
+ }
890
+ }
891
+ if (string === "+" && index > 1 && source[index - 2] === " ") {
892
+ throw new Error("Space before `+`");
893
+ }
894
+ return string && {
895
+ type: "OPERATOR",
896
+ string: string.toUpperCase()
897
+ };
898
+ }
899
+ function idstring() {
900
+ return read(/[A-Za-z0-9-.]+/);
901
+ }
902
+ function expectIdstring() {
903
+ var string = idstring();
904
+ if (!string) {
905
+ throw new Error("Expected idstring at offset " + index);
906
+ }
907
+ return string;
908
+ }
909
+ function documentRef() {
910
+ if (read("DocumentRef-")) {
911
+ var string = expectIdstring();
912
+ return { type: "DOCUMENTREF", string };
913
+ }
914
+ }
915
+ function licenseRef() {
916
+ if (read("LicenseRef-")) {
917
+ var string = expectIdstring();
918
+ return { type: "LICENSEREF", string };
919
+ }
920
+ }
921
+ function identifier() {
922
+ var begin = index;
923
+ var string = idstring();
924
+ if (licenses.indexOf(string) !== -1) {
925
+ return {
926
+ type: "LICENSE",
927
+ string
928
+ };
929
+ } else if (exceptions.indexOf(string) !== -1) {
930
+ return {
931
+ type: "EXCEPTION",
932
+ string
933
+ };
934
+ }
935
+ index = begin;
936
+ }
937
+ function parseToken() {
938
+ return operator() || documentRef() || licenseRef() || identifier();
939
+ }
940
+ var tokens = [];
941
+ while (hasMore()) {
942
+ skipWhitespace();
943
+ if (!hasMore()) {
944
+ break;
945
+ }
946
+ var token = parseToken();
947
+ if (!token) {
948
+ throw new Error("Unexpected `" + source[index] + "` at offset " + index);
949
+ }
950
+ tokens.push(token);
951
+ }
952
+ return tokens;
953
+ };
954
+ });
955
+
956
+ // node_modules/spdx-expression-parse/parse.js
957
+ var require_parse = __commonJS(function(exports, module) {
958
+ module.exports = function(tokens) {
959
+ var index = 0;
960
+ function hasMore() {
961
+ return index < tokens.length;
962
+ }
963
+ function token() {
964
+ return hasMore() ? tokens[index] : null;
965
+ }
966
+ function next() {
967
+ if (!hasMore()) {
968
+ throw new Error;
969
+ }
970
+ index++;
971
+ }
972
+ function parseOperator(operator) {
973
+ var t = token();
974
+ if (t && t.type === "OPERATOR" && operator === t.string) {
975
+ next();
976
+ return t.string;
977
+ }
978
+ }
979
+ function parseWith() {
980
+ if (parseOperator("WITH")) {
981
+ var t = token();
982
+ if (t && t.type === "EXCEPTION") {
983
+ next();
984
+ return t.string;
985
+ }
986
+ throw new Error("Expected exception after `WITH`");
987
+ }
988
+ }
989
+ function parseLicenseRef() {
990
+ var begin = index;
991
+ var string = "";
992
+ var t = token();
993
+ if (t.type === "DOCUMENTREF") {
994
+ next();
995
+ string += "DocumentRef-" + t.string + ":";
996
+ if (!parseOperator(":")) {
997
+ throw new Error("Expected `:` after `DocumentRef-...`");
998
+ }
999
+ }
1000
+ t = token();
1001
+ if (t === null) {
1002
+ throw new Error("Unexpected end of input");
1003
+ }
1004
+ if (t.type === "LICENSEREF") {
1005
+ next();
1006
+ string += "LicenseRef-" + t.string;
1007
+ var node = { license: string };
1008
+ var exception = parseWith();
1009
+ if (exception) {
1010
+ node.exception = exception;
1011
+ }
1012
+ return node;
1013
+ }
1014
+ index = begin;
1015
+ }
1016
+ function parseLicense() {
1017
+ var t = token();
1018
+ if (t && t.type === "LICENSE") {
1019
+ next();
1020
+ var node = { license: t.string };
1021
+ if (parseOperator("+")) {
1022
+ node.plus = true;
1023
+ }
1024
+ var exception = parseWith();
1025
+ if (exception) {
1026
+ node.exception = exception;
1027
+ }
1028
+ return node;
1029
+ }
1030
+ }
1031
+ function parseParenthesizedExpression() {
1032
+ var left = parseOperator("(");
1033
+ if (!left) {
1034
+ return;
1035
+ }
1036
+ var expr = parseExpression();
1037
+ if (!parseOperator(")")) {
1038
+ throw new Error("Expected `)`");
1039
+ }
1040
+ return expr;
1041
+ }
1042
+ function parseAtom() {
1043
+ return parseParenthesizedExpression() || parseLicenseRef() || parseLicense();
1044
+ }
1045
+ function makeBinaryOpParser(operator, nextParser) {
1046
+ return function parseBinaryOp() {
1047
+ var left = nextParser();
1048
+ if (!left) {
1049
+ return;
1050
+ }
1051
+ if (!parseOperator(operator)) {
1052
+ return left;
1053
+ }
1054
+ var right = parseBinaryOp();
1055
+ if (!right) {
1056
+ throw new Error("Expected expression");
1057
+ }
1058
+ return {
1059
+ left,
1060
+ conjunction: operator.toLowerCase(),
1061
+ right
1062
+ };
1063
+ };
1064
+ }
1065
+ var parseAnd = makeBinaryOpParser("AND", parseAtom);
1066
+ var parseExpression = makeBinaryOpParser("OR", parseAnd);
1067
+ var node = parseExpression();
1068
+ if (!node || hasMore()) {
1069
+ throw new Error("Syntax error");
1070
+ }
1071
+ return node;
1072
+ };
1073
+ });
1074
+
1075
+ // node_modules/spdx-expression-parse/index.js
1076
+ var require_spdx_expression_parse = __commonJS(function(exports, module) {
1077
+ var scan = require_scan();
1078
+ var parse = require_parse();
1079
+ module.exports = function(source) {
1080
+ return parse(scan(source));
1081
+ };
1082
+ });
1083
+
1084
+ // plugins/code-challenge/opencode/src/lenses.ts
1085
+ var LENSES = [
1086
+ "scope",
1087
+ "simplification",
1088
+ "over-engineering",
1089
+ "optimisation",
1090
+ "performance",
1091
+ "efficiency",
1092
+ "stability",
1093
+ "hand-rolled-stdlib",
1094
+ "hand-rolled-library",
1095
+ "dead-code",
1096
+ "observability",
1097
+ "structure",
1098
+ "tests"
1099
+ ];
1100
+ var DEPTHS = ["quick", "standard", "deep"];
1101
+
1102
+ // plugins/code-challenge/opencode/src/command.ts
1103
+ var COMMAND = "code-challenge";
1104
+ var SKILL = "code-challenge";
1105
+ var COMMAND_DESCRIPTION = "challenge code for simplification, performance and structure: [auto] [quick|standard|deep] [target]";
1106
+ var LOAD_SKILL = {
1107
+ opencode: `Load the \`${SKILL}\` skill with the skill tool and follow it.`,
1108
+ pi: `Read the \`${SKILL}\` skill (\`skill://${SKILL}\` in OMP) and follow it.`
1109
+ };
1110
+ function parseInvocation(args) {
1111
+ const words = args.trim().split(/\s+/).filter(Boolean);
1112
+ let autonomous = false;
1113
+ let depth;
1114
+ for (;; ) {
1115
+ const word = words[0]?.toLowerCase();
1116
+ if (word === "auto" && !autonomous)
1117
+ autonomous = true;
1118
+ else if (depth === undefined && DEPTHS.includes(word))
1119
+ depth = word;
1120
+ else
1121
+ break;
1122
+ words.shift();
1123
+ }
1124
+ return { autonomous, depth, target: words.join(" ") };
1125
+ }
1126
+ function challengePrompt(args, host = "opencode") {
1127
+ const { autonomous, depth, target } = parseInvocation(args);
1128
+ return [
1129
+ LOAD_SKILL[host],
1130
+ `Mode: ${autonomous ? "autonomous (ask only what INTAKE cannot infer; never post)" : "interactive"}.`,
1131
+ depth ? `Depth: ${depth}.` : "Depth: not given; INTAKE decides (default standard).",
1132
+ target ? `Target: ${target}` : "Target: not given; INTAKE asks or infers it from the branch diff."
1133
+ ].join(`
1134
+
1135
+ `);
1136
+ }
1137
+
1138
+ // plugins/code-challenge/opencode/src/formulas.ts
1139
+ import { dirname, join as join2, resolve as resolve2 } from "path";
1140
+ import { fileURLToPath } from "url";
1141
+
1142
+ // lib/src/formulas.ts
1143
+ import { copyFileSync, lstatSync, mkdirSync, readFileSync } from "fs";
1144
+ import { isAbsolute, join, resolve } from "path";
1145
+ function symlinkBelow(repo) {
1146
+ for (const path of [join(repo, ".beads"), join(repo, ".beads", "formulas")])
1147
+ if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink())
1148
+ return path;
1149
+ return null;
1150
+ }
1151
+ function installFormulas(options) {
1152
+ const { workspace, cwd, names, sourceDir, force = false } = options;
1153
+ const repo = isAbsolute(workspace) ? workspace : resolve(cwd, workspace);
1154
+ const beads = join(repo, ".beads");
1155
+ const destination = join(beads, "formulas");
1156
+ const fail = (text) => ({ ok: false, text, copied: [], unchanged: [], destination });
1157
+ const link = symlinkBelow(repo);
1158
+ if (link)
1159
+ return fail(`refusing symlinked path: ${link}`);
1160
+ if (!lstatSync(beads, { throwIfNoEntry: false })?.isDirectory())
1161
+ return fail(`not a beads workspace: ${repo} has no .beads/ (run bd init there first)`);
1162
+ const destStat = lstatSync(destination, { throwIfNoEntry: false });
1163
+ if (destStat && !destStat.isDirectory())
1164
+ return fail(`formula destination is not a directory: ${destination}`);
1165
+ const copies = [];
1166
+ const unchanged = [];
1167
+ const divergent = [];
1168
+ for (const name of names) {
1169
+ const src = join(sourceDir, `${name}.formula.toml`);
1170
+ const dest = join(destination, `${name}.formula.toml`);
1171
+ const srcStat = lstatSync(src, { throwIfNoEntry: false });
1172
+ if (!srcStat?.isFile() || srcStat.isSymbolicLink())
1173
+ return fail(`shipped formula missing or unsafe: ${src}`);
1174
+ const st = lstatSync(dest, { throwIfNoEntry: false });
1175
+ if (st && (st.isSymbolicLink() || !st.isFile()))
1176
+ return fail(`refusing non-file formula destination: ${dest}`);
1177
+ if (st && readFileSync(src).equals(readFileSync(dest))) {
1178
+ unchanged.push(name);
1179
+ continue;
1180
+ }
1181
+ if (st)
1182
+ divergent.push(dest);
1183
+ copies.push({ src, dest, name });
1184
+ }
1185
+ if (divergent.length > 0 && !force)
1186
+ return fail(`refusing to overwrite divergent formulas (pass force=true to replace them): ${divergent.join(", ")}`);
1187
+ mkdirSync(destination, { recursive: true });
1188
+ for (const { src, dest } of copies)
1189
+ copyFileSync(src, dest);
1190
+ const copied = copies.map(({ name }) => name);
1191
+ const text = copied.length > 0 ? `copied ${copied.join(", ")} into ${destination}` : `every formula already in ${destination}`;
1192
+ return { ok: true, text, copied, unchanged, destination };
1193
+ }
1194
+
1195
+ // plugins/code-challenge/opencode/src/formulas.ts
1196
+ var SETUP_TOOL = "challenge_setup";
1197
+ var SETUP_DESCRIPTION = `Copy the code-challenge beads formulas into a beads workspace's .beads/formulas/.
1198
+ ` + "Covers the code-challenge full run and the mol-challenge-<phase> formulas, so bd mol pour finds them. Identical " + "copies stay; divergent ones are refused unless force=true; symlinked paths are always refused.";
1199
+ var SETUP_INPUT = {
1200
+ type: "object",
1201
+ properties: {
1202
+ workspace: { type: "string", description: "Beads workspace root (contains .beads/); default the session directory" },
1203
+ force: { type: "boolean", description: "Overwrite code-challenge formulas that differ from the shipped ones" }
1204
+ },
1205
+ additionalProperties: false
1206
+ };
1207
+ var FORMULAS = [
1208
+ "code-challenge",
1209
+ "mol-challenge-intake",
1210
+ "mol-challenge-scan",
1211
+ "mol-challenge-challenge",
1212
+ "mol-challenge-lens",
1213
+ "mol-challenge-research",
1214
+ "mol-challenge-refute",
1215
+ "mol-challenge-decide",
1216
+ "mol-challenge-deliver"
1217
+ ];
1218
+ var FORMULAS_DIR = join2(dirname(fileURLToPath(import.meta.url)), "..", "formulas");
1219
+ var USAGE = [
1220
+ "Pour a full run with: bd mol pour code-challenge --var target=<paths> --var run_id=<run-id>",
1221
+ "Bond one lens scout with: bd mol bond mol-challenge-lens <step-id> --var lens=<lens> --var target=<paths> --var run_id=<run-id>",
1222
+ "Pour one phase with: bd mol pour mol-challenge-<phase> --var target=<paths> --var run_id=<run-id> --var depth=<depth> --var mode=<mode>"
1223
+ ];
1224
+ function installFormulas2(workspace, cwd, force = false) {
1225
+ const result = installFormulas({ workspace, cwd, force, names: FORMULAS, sourceDir: FORMULAS_DIR });
1226
+ return result.ok ? { ...result, text: [result.text, ...USAGE].join(`
1227
+ `) } : result;
1228
+ }
1229
+ async function runSetup(input, call, authorize) {
1230
+ const { workspace, force } = input ?? {};
1231
+ if (workspace !== undefined && (typeof workspace !== "string" || workspace === ""))
1232
+ return { content: `${SETUP_TOOL}: workspace must be a non-empty string`, metadata: { ok: false } };
1233
+ const cwd = await call.directory();
1234
+ const target = resolve2(cwd, typeof workspace === "string" ? workspace : ".");
1235
+ await authorize?.(target, force === true);
1236
+ const result = installFormulas2(target, cwd, force === true);
1237
+ return {
1238
+ content: result.ok ? result.text : `${SETUP_TOOL}: ${result.text}`,
1239
+ metadata: { ok: result.ok, copied: result.copied, unchanged: result.unchanged }
1240
+ };
1241
+ }
1242
+
1243
+ // plugins/code-challenge/opencode/src/lib-facts/index.ts
1244
+ import { execFile } from "child_process";
1245
+
1246
+ // plugins/code-challenge/opencode/src/lib-facts/cache.ts
1247
+ import { createHash } from "crypto";
1248
+ import { mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from "fs";
1249
+ import { homedir } from "os";
1250
+ import { join as join3 } from "path";
1251
+ var CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
1252
+ var MAX_ENTRY_BYTES = 256 * 1024;
1253
+ var MAX_ENTRIES = 2000;
1254
+ var CACHE_SCHEMA = "v2";
1255
+ function defaultCacheDir(xdgCacheHome = process.env.XDG_CACHE_HOME) {
1256
+ return join3(xdgCacheHome || join3(homedir(), ".cache"), "opencode", "code-challenge", "lib-facts");
1257
+ }
1258
+ function cacheFileName(key) {
1259
+ return `${CACHE_SCHEMA}-${createHash("sha256").update(key).digest("hex")}.json`;
1260
+ }
1261
+ var isEntry = (value) => {
1262
+ if (value === null || typeof value !== "object" || Array.isArray(value))
1263
+ return false;
1264
+ const entry = value;
1265
+ return Number.isFinite(entry.at) && "body" in entry && (entry.link === null || typeof entry.link === "string");
1266
+ };
1267
+ function remove(file) {
1268
+ try {
1269
+ unlinkSync(file);
1270
+ } catch {}
1271
+ }
1272
+
1273
+ class DiskCache {
1274
+ dir;
1275
+ now;
1276
+ ttlMs;
1277
+ maxEntries;
1278
+ swept = false;
1279
+ constructor(dir, now = Date.now, ttlMs = CACHE_TTL_MS, maxEntries = MAX_ENTRIES) {
1280
+ this.dir = dir;
1281
+ this.now = now;
1282
+ this.ttlMs = ttlMs;
1283
+ this.maxEntries = maxEntries;
1284
+ }
1285
+ get(key, valid = () => true) {
1286
+ const file = join3(this.dir, cacheFileName(key));
1287
+ try {
1288
+ if (statSync(file).size > MAX_ENTRY_BYTES)
1289
+ throw new Error("oversized");
1290
+ const entry = JSON.parse(readFileSync2(file, "utf8"));
1291
+ if (isEntry(entry) && this.now() - entry.at < this.ttlMs && valid(entry.body))
1292
+ return { body: entry.body, link: entry.link };
1293
+ } catch {}
1294
+ remove(file);
1295
+ return;
1296
+ }
1297
+ put(key, value) {
1298
+ try {
1299
+ const text = JSON.stringify({ at: this.now(), ...value });
1300
+ if (Buffer.byteLength(text) > MAX_ENTRY_BYTES)
1301
+ return;
1302
+ mkdirSync2(this.dir, { recursive: true });
1303
+ this.sweep();
1304
+ const target = join3(this.dir, cacheFileName(key));
1305
+ const temp = `${target}.${process.pid}.tmp`;
1306
+ writeFileSync(temp, text);
1307
+ utimesSync(temp, this.now() / 1000, this.now() / 1000);
1308
+ renameSync(temp, target);
1309
+ } catch {}
1310
+ }
1311
+ sweep() {
1312
+ if (this.swept)
1313
+ return;
1314
+ this.swept = true;
1315
+ const live = [];
1316
+ for (const name of readdirSync(this.dir)) {
1317
+ const file = join3(this.dir, name);
1318
+ try {
1319
+ const at = statSync(file).mtimeMs;
1320
+ const otherSchema = name.endsWith(".json") && !name.startsWith(`${CACHE_SCHEMA}-`);
1321
+ if (otherSchema || this.now() - at >= this.ttlMs)
1322
+ remove(file);
1323
+ else if (name.endsWith(".json"))
1324
+ live.push({ file, at });
1325
+ } catch {}
1326
+ }
1327
+ live.sort((a, b) => a.at - b.at);
1328
+ for (const { file } of live.slice(0, Math.max(0, live.length - (this.maxEntries - 1))))
1329
+ remove(file);
1330
+ }
1331
+ }
1332
+
1333
+ // plugins/code-challenge/opencode/src/lib-facts/licence.ts
1334
+ var import_spdx_expression_parse = __toESM(require_spdx_expression_parse(), 1);
1335
+ var ALLOWED_LICENCES = new Set([
1336
+ "MIT",
1337
+ "MIT-0",
1338
+ "Apache-2.0",
1339
+ "BSD-2-Clause",
1340
+ "BSD-3-Clause",
1341
+ "ISC",
1342
+ "0BSD",
1343
+ "Unlicense",
1344
+ "CC0-1.0",
1345
+ "Zlib",
1346
+ "BlueOak-1.0.0",
1347
+ "Python-2.0",
1348
+ "PSF-2.0",
1349
+ "MPL-2.0",
1350
+ "EPL-2.0",
1351
+ "LGPL-2.1-only",
1352
+ "LGPL-2.1-or-later",
1353
+ "LGPL-3.0-only",
1354
+ "LGPL-3.0-or-later"
1355
+ ]);
1356
+ function satisfied(node) {
1357
+ if ("conjunction" in node)
1358
+ return node.conjunction === "or" ? satisfied(node.left) || satisfied(node.right) : satisfied(node.left) && satisfied(node.right);
1359
+ return ALLOWED_LICENCES.has(node.license);
1360
+ }
1361
+ function expressionAllowed(expression) {
1362
+ try {
1363
+ return satisfied(import_spdx_expression_parse.default(expression));
1364
+ } catch {
1365
+ return false;
1366
+ }
1367
+ }
1368
+ function licenceBlocked(licences) {
1369
+ if (licences === null || licences.length === 0)
1370
+ return null;
1371
+ return !licences.every(expressionAllowed);
1372
+ }
1373
+
1374
+ // plugins/code-challenge/opencode/src/lib-facts/sources.ts
1375
+ var DEPS_DEV = "https://api.deps.dev";
1376
+ var OSV = "https://api.osv.dev/v1/querybatch";
1377
+ var GITHUB = "https://api.github.com";
1378
+ var DEPS_SYSTEM = { npm: "NPM", pypi: "PYPI", crates: "CARGO", go: "GO" };
1379
+ var OSV_ECOSYSTEM = { npm: "npm", pypi: "PyPI", crates: "crates.io", go: "Go" };
1380
+ var obj = (value) => value !== null && typeof value === "object" ? value : {};
1381
+ var arr = (value) => Array.isArray(value) ? value : [];
1382
+ var str = (value) => typeof value === "string" && value !== "" ? value : null;
1383
+ var num = (value) => typeof value === "number" ? value : null;
1384
+ var bool = (value) => typeof value === "boolean" ? value : null;
1385
+ function canonicalName(ecosystem, name) {
1386
+ return ecosystem === "pypi" ? name.toLowerCase().replace(/[-_.]+/g, "-") : name;
1387
+ }
1388
+ var goEscape = (path) => path.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`);
1389
+ var npmPath = (name) => encodeURIComponent(name).replace(/^%40/, "@");
1390
+ async function depsDevVersions(http, ecosystem, name) {
1391
+ const { body } = await http.get(`${DEPS_DEV}/v3/systems/${DEPS_SYSTEM[ecosystem]}/packages/${encodeURIComponent(name)}`);
1392
+ return arr(obj(body).versions).map((entry) => {
1393
+ const v = obj(entry);
1394
+ return {
1395
+ version: str(obj(v.versionKey).version) ?? "",
1396
+ publishedAt: str(v.publishedAt),
1397
+ isDefault: v.isDefault === true,
1398
+ isDeprecated: bool(v.isDeprecated)
1399
+ };
1400
+ });
1401
+ }
1402
+ var versionUrl = (ecosystem, name, version) => `${DEPS_DEV}/v3/systems/${DEPS_SYSTEM[ecosystem]}/packages/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}`;
1403
+ async function depsDevVersion(http, ecosystem, name, version) {
1404
+ const { body } = await http.get(versionUrl(ecosystem, name, version));
1405
+ const data = obj(body);
1406
+ const repoLink = arr(data.links).map(obj).find((link) => link.label === "SOURCE_REPO");
1407
+ const related = arr(data.relatedProjects).map((p) => str(obj(obj(p).projectKey).id)).find((id) => id?.startsWith("github.com/"));
1408
+ return {
1409
+ licences: arr(data.licenses).filter((l) => typeof l === "string"),
1410
+ repo: related ?? str(repoLink?.url),
1411
+ isDeprecated: bool(data.isDeprecated)
1412
+ };
1413
+ }
1414
+ async function depsDevDependencies(http, ecosystem, name, version) {
1415
+ const { body } = await http.get(`${versionUrl(ecosystem, name, version)}:dependencies`);
1416
+ const nodes = arr(obj(body).nodes).map(obj);
1417
+ return {
1418
+ direct: nodes.filter((n) => n.relation === "DIRECT").length,
1419
+ transitive: nodes.filter((n) => n.relation === "INDIRECT").length
1420
+ };
1421
+ }
1422
+ async function depsDevDependents(http, ecosystem, name, version) {
1423
+ const { body } = await http.get(`${versionUrl(ecosystem, name, version).replace("/v3/", "/v3alpha/")}:dependents`);
1424
+ return num(obj(body).dependentCount);
1425
+ }
1426
+ async function depsDevProject(http, slug) {
1427
+ const { body } = await http.get(`${DEPS_DEV}/v3/projects/${encodeURIComponent(`github.com/${slug.owner}/${slug.repo}`)}`);
1428
+ const data = obj(body);
1429
+ return { stars: num(data.starsCount), openIssues: num(data.openIssuesCount) };
1430
+ }
1431
+ var EMPTY_REGISTRY = {
1432
+ version: null,
1433
+ publishedAt: null,
1434
+ licence: null,
1435
+ deprecated: null,
1436
+ yanked: null,
1437
+ unpackedBytes: null,
1438
+ downloadBytes: null,
1439
+ types: null,
1440
+ modules: null,
1441
+ repo: null,
1442
+ downloads: null
1443
+ };
1444
+ function moduleFormat(manifest) {
1445
+ const exportsText = JSON.stringify(manifest.exports ?? "");
1446
+ const esm = manifest.type === "module" || manifest.module !== undefined || /"(import|module)"/.test(exportsText);
1447
+ const cjs = manifest.type !== "module" || /"require"/.test(exportsText);
1448
+ return esm && cjs ? "dual" : esm ? "esm" : "cjs";
1449
+ }
1450
+ function npmFacts(manifest) {
1451
+ const dist = obj(manifest.dist);
1452
+ const license = manifest.license;
1453
+ return {
1454
+ version: str(manifest.version),
1455
+ licence: typeof license === "string" ? license : str(obj(license).type),
1456
+ deprecated: typeof manifest.deprecated === "string",
1457
+ unpackedBytes: num(dist.unpackedSize),
1458
+ types: manifest.types !== undefined || manifest.typings !== undefined || /"types"/.test(JSON.stringify(manifest.exports ?? "")),
1459
+ modules: moduleFormat(manifest),
1460
+ repo: str(obj(manifest.repository).url) ?? str(manifest.repository)
1461
+ };
1462
+ }
1463
+ function pypiFacts(doc) {
1464
+ const info = obj(doc.info);
1465
+ const files = arr(doc.urls).map(obj);
1466
+ const classifiers = arr(info.classifiers);
1467
+ const licence = str(info.license_expression) ?? str(info.license);
1468
+ return {
1469
+ version: str(info.version),
1470
+ publishedAt: str(files[0]?.upload_time_iso_8601),
1471
+ licence: licence && licence.length <= 64 ? licence : null,
1472
+ yanked: info.yanked === true || files.some((f) => f.yanked === true),
1473
+ downloadBytes: files.reduce((sum, f) => num(f.size) === null ? sum : (sum ?? 0) + (num(f.size) ?? 0), null),
1474
+ types: classifiers.includes("Typing :: Typed")
1475
+ };
1476
+ }
1477
+ function cratesFacts(doc, version) {
1478
+ const crate = obj(doc.crate);
1479
+ const wanted = version ?? str(crate.max_stable_version) ?? str(crate.max_version);
1480
+ const entry = arr(doc.versions).map(obj).find((v) => v.num === wanted);
1481
+ return {
1482
+ version: entry ? wanted : null,
1483
+ publishedAt: str(entry?.created_at),
1484
+ licence: str(entry?.license),
1485
+ yanked: bool(entry?.yanked),
1486
+ downloadBytes: num(entry?.crate_size),
1487
+ repo: str(crate.repository),
1488
+ downloads: { lastWeek: null, lastMonth: null, last90Days: num(crate.recent_downloads) }
1489
+ };
1490
+ }
1491
+ async function registryFacts(http, ecosystem, name, version) {
1492
+ switch (ecosystem) {
1493
+ case "npm": {
1494
+ const url = `https://registry.npmjs.org/${npmPath(name)}/${version ? encodeURIComponent(version) : "latest"}`;
1495
+ return { ...EMPTY_REGISTRY, ...npmFacts(obj((await http.get(url)).body)) };
1496
+ }
1497
+ case "pypi": {
1498
+ const url = `https://pypi.org/pypi/${encodeURIComponent(name)}/${version ? `${encodeURIComponent(version)}/` : ""}json`;
1499
+ return { ...EMPTY_REGISTRY, ...pypiFacts(obj((await http.get(url)).body)) };
1500
+ }
1501
+ case "crates": {
1502
+ const doc = obj((await http.get(`https://crates.io/api/v1/crates/${encodeURIComponent(name)}`)).body);
1503
+ return { ...EMPTY_REGISTRY, ...cratesFacts(doc, version) };
1504
+ }
1505
+ case "go": {
1506
+ const tail = version ? `@v/${goEscape(version)}.info` : "@latest";
1507
+ const info = obj((await http.get(`https://proxy.golang.org/${goEscape(name)}/${tail}`)).body);
1508
+ return { ...EMPTY_REGISTRY, version: str(info.Version), publishedAt: str(info.Time) };
1509
+ }
1510
+ }
1511
+ }
1512
+ function downloadSources(http, ecosystem, name) {
1513
+ if (ecosystem === "npm") {
1514
+ const period = (label, key) => ({
1515
+ label: `npm downloads ${label}`,
1516
+ run: async () => ({
1517
+ [key]: num(obj((await http.get(`https://api.npmjs.org/downloads/point/${label}/${npmPath(name)}`)).body).downloads)
1518
+ })
1519
+ });
1520
+ return [period("last-week", "lastWeek"), period("last-month", "lastMonth")];
1521
+ }
1522
+ if (ecosystem === "pypi")
1523
+ return [
1524
+ {
1525
+ label: "pypistats",
1526
+ run: async () => {
1527
+ const data = obj(obj((await http.get(`https://pypistats.org/api/packages/${encodeURIComponent(name)}/recent`)).body).data);
1528
+ return { lastWeek: num(data.last_week), lastMonth: num(data.last_month) };
1529
+ }
1530
+ }
1531
+ ];
1532
+ return [];
1533
+ }
1534
+ async function osvVulnerabilities(http, ecosystem, name, versions) {
1535
+ const queries = versions.map((version) => ({ package: { name, ecosystem: OSV_ECOSYSTEM[ecosystem] }, version }));
1536
+ const { body } = await http.post(OSV, { queries });
1537
+ const results = obj(body).results;
1538
+ if (!Array.isArray(results) || results.length !== versions.length)
1539
+ throw new Error("malformed response api.osv.dev");
1540
+ return results.map((result) => {
1541
+ if (result === null || typeof result !== "object" || Array.isArray(result))
1542
+ throw new Error("malformed response api.osv.dev");
1543
+ const entry = obj(result);
1544
+ if (entry.next_page_token !== undefined)
1545
+ throw new Error("truncated response api.osv.dev");
1546
+ if (entry.vulns === undefined)
1547
+ return [];
1548
+ if (!Array.isArray(entry.vulns))
1549
+ throw new Error("malformed response api.osv.dev");
1550
+ return entry.vulns.map((v) => {
1551
+ const id = str(obj(v).id);
1552
+ if (id === null)
1553
+ throw new Error("malformed response api.osv.dev");
1554
+ return id;
1555
+ });
1556
+ });
1557
+ }
1558
+ var OWNER = /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/;
1559
+ var REPO = /^[A-Za-z0-9._-]{1,100}$/;
1560
+ var TAIL = String.raw`(?:\.git)?\/?(?:(?:#|\/(?:tree|blob)\/)[^\s\\]*)?$`;
1561
+ var FORMS = [
1562
+ new RegExp(String.raw`^(?:git\+)?https?:\/\/(?:www\.)?github\.com\/([^/]+)\/([^/#?]+?)${TAIL}`, "i"),
1563
+ new RegExp(String.raw`^git:\/\/github\.com\/([^/]+)\/([^/#?]+?)${TAIL}`, "i"),
1564
+ new RegExp(String.raw`^(?:git\+)?ssh:\/\/git@github\.com\/([^/]+)\/([^/#?]+?)${TAIL}`, "i"),
1565
+ new RegExp(String.raw`^git@github\.com:([^/]+)\/([^/#?]+?)${TAIL}`, "i"),
1566
+ new RegExp(String.raw`^github\.com\/([^/]+)\/([^/#?]+?)${TAIL}`, "i"),
1567
+ new RegExp(String.raw`^github:([^/]+)\/([^/#?]+?)${TAIL}`, "i")
1568
+ ];
1569
+ function githubSlug(url) {
1570
+ if (url === null)
1571
+ return null;
1572
+ for (const form of FORMS) {
1573
+ const match = form.exec(url.trim());
1574
+ const owner = match?.[1];
1575
+ const repo = match?.[2];
1576
+ if (owner === undefined || repo === undefined)
1577
+ continue;
1578
+ if (!OWNER.test(owner) || !REPO.test(repo) || repo === "." || repo === "..")
1579
+ return null;
1580
+ return { owner, repo };
1581
+ }
1582
+ return null;
1583
+ }
1584
+ function lastPage(link) {
1585
+ const match = link?.match(/[?&]page=(\d+)[^>]*>;\s*rel="last"/);
1586
+ return match ? Number(match[1]) : null;
1587
+ }
1588
+ var nullable = (value, type) => value === null || typeof value === type;
1589
+ var hasOnly = (value, keys) => {
1590
+ if (value === null || typeof value !== "object" || Array.isArray(value))
1591
+ return false;
1592
+ const found = Object.keys(value);
1593
+ return found.length === keys.length && keys.every((key) => found.includes(key));
1594
+ };
1595
+ async function githubFacts(http, slug, token) {
1596
+ const headers = { accept: "application/vnd.github+json" };
1597
+ if (token)
1598
+ headers.authorization = `Bearer ${token}`;
1599
+ const base = `${GITHUB}/repos/${encodeURIComponent(slug.owner)}/${encodeURIComponent(slug.repo)}`;
1600
+ const failures = [];
1601
+ const attempt = async (label, url, projection) => {
1602
+ try {
1603
+ return (await http.get(url, headers, projection)).body;
1604
+ } catch (error) {
1605
+ failures.push(`github ${label}: ${error instanceof Error ? error.message : "failed"}`);
1606
+ return;
1607
+ }
1608
+ };
1609
+ const [repo, pulls, commit, contributors] = await Promise.all([
1610
+ attempt("repo", base, {
1611
+ project: ({ body }) => ({
1612
+ stars: num(obj(body).stargazers_count),
1613
+ openAndPulls: num(obj(body).open_issues_count),
1614
+ archived: bool(obj(body).archived)
1615
+ }),
1616
+ valid: (v) => hasOnly(v, ["stars", "openAndPulls", "archived"]) && nullable(obj(v).stars, "number") && nullable(obj(v).openAndPulls, "number") && nullable(obj(v).archived, "boolean")
1617
+ }),
1618
+ attempt("pulls", `${GITHUB}/search/issues?q=${encodeURIComponent(`repo:${slug.owner}/${slug.repo} type:pr state:open`)}&per_page=1`, { project: ({ body }) => num(obj(body).total_count), valid: (v) => nullable(v, "number") }),
1619
+ attempt("commits", `${base}/commits?per_page=1`, {
1620
+ project: ({ body }) => str(obj(obj(obj(arr(body)[0]).commit).committer).date),
1621
+ valid: (v) => nullable(v, "string")
1622
+ }),
1623
+ attempt("contributors", `${base}/contributors?per_page=1&anon=true`, {
1624
+ project: ({ body, link }) => lastPage(link) ?? arr(body).length,
1625
+ valid: (v) => nullable(v, "number")
1626
+ })
1627
+ ]);
1628
+ const openPullRequests = pulls ?? null;
1629
+ const facts = {
1630
+ stars: repo?.stars ?? null,
1631
+ openIssues: repo?.openAndPulls != null && openPullRequests !== null ? Math.max(0, repo.openAndPulls - openPullRequests) : null,
1632
+ openPullRequests,
1633
+ lastCommit: commit ?? null,
1634
+ contributors: contributors ?? null,
1635
+ archived: repo?.archived ?? null
1636
+ };
1637
+ return { facts, failures };
1638
+ }
1639
+
1640
+ // plugins/code-challenge/opencode/src/lib-facts/facts.ts
1641
+ var MONTH_MS = 30.4375 * 24 * 60 * 60 * 1000;
1642
+ function cadence(versions, now) {
1643
+ const times = versions.flatMap((v) => v.publishedAt ? [Date.parse(v.publishedAt)] : []).filter(Number.isFinite);
1644
+ if (times.length === 0)
1645
+ return null;
1646
+ const within = (months) => times.filter((t) => now.getTime() - t <= months * MONTH_MS).length;
1647
+ return {
1648
+ last12Months: within(12),
1649
+ last24Months: within(24),
1650
+ monthsSinceLast: Math.round((now.getTime() - Math.max(...times)) / MONTH_MS * 10) / 10
1651
+ };
1652
+ }
1653
+ function pickLatest(versions) {
1654
+ return versions.find((v) => v.isDefault) ?? [...versions].sort((a, b) => Date.parse(b.publishedAt ?? "") - Date.parse(a.publishedAt ?? "")).at(0);
1655
+ }
1656
+ async function collectPackage(ecosystem, request, collector) {
1657
+ const { http } = collector;
1658
+ const name = canonicalName(ecosystem, request.name);
1659
+ const requested = request.version ?? null;
1660
+ const missing = [];
1661
+ const attempt = async (source, run) => {
1662
+ try {
1663
+ return await run();
1664
+ } catch (error) {
1665
+ missing.push(`${source}: ${error instanceof Error ? error.message : "failed"}`);
1666
+ return;
1667
+ }
1668
+ };
1669
+ const versions = await attempt("deps.dev packages", () => depsDevVersions(http, ecosystem, name));
1670
+ const newest = versions ? pickLatest(versions) : undefined;
1671
+ let registry = await attempt("registry", () => registryFacts(http, ecosystem, name, newest?.version || null));
1672
+ if (registry && newest?.version && registry.version !== newest.version) {
1673
+ missing.push(`registry: describes ${registry.version ?? "no version"}, not ${newest.version}`);
1674
+ registry = undefined;
1675
+ }
1676
+ const version = newest?.version || registry?.version || null;
1677
+ const publishedAt = newest?.publishedAt ?? registry?.publishedAt ?? null;
1678
+ if (version === null) {
1679
+ return {
1680
+ ...blank(request.name, requested),
1681
+ missing: [...missing, "latest version unknown: nothing else could be looked up"],
1682
+ gates: { unpatchedCve: null, licenceNotAllowed: null, failed: [] }
1683
+ };
1684
+ }
1685
+ const [detail, dependencies, dependents, downloads, osv] = await Promise.all([
1686
+ attempt("deps.dev version", () => depsDevVersion(http, ecosystem, name, version)),
1687
+ attempt("deps.dev dependencies", () => depsDevDependencies(http, ecosystem, name, version)),
1688
+ attempt("deps.dev dependents", () => depsDevDependents(http, ecosystem, name, version)),
1689
+ collectDownloads(http, ecosystem, name, registry?.downloads ?? null, attempt),
1690
+ attempt("osv", () => osvVulnerabilities(http, ecosystem, name, requested ? [version, requested] : [version]))
1691
+ ]);
1692
+ const slug = githubSlug(detail?.repo ?? registry?.repo ?? null);
1693
+ const repo = slug ? await repoFacts(slug, collector, attempt, missing) : null;
1694
+ const licence = detail && detail.licences.length > 0 ? detail.licences : registry?.licence ? [registry.licence] : null;
1695
+ const vulnerabilities = osv ? { latest: osv[0] ?? [], requested: requested ? osv[1] ?? [] : null } : null;
1696
+ const unpatchedCve = vulnerabilities ? vulnerabilities.latest.length > 0 : null;
1697
+ const licenceNotAllowed = licenceBlocked(licence);
1698
+ return {
1699
+ name: request.name,
1700
+ requestedVersion: requested,
1701
+ latest: { version, publishedAt },
1702
+ releases: versions ? cadence(versions, collector.now()) : null,
1703
+ deprecated: deprecation([detail?.isDeprecated, newest?.isDeprecated, registry?.deprecated]),
1704
+ yanked: registry?.yanked ?? null,
1705
+ licence,
1706
+ downloads: downloads ?? null,
1707
+ dependents: dependents ?? null,
1708
+ repo: repo && slug ? { url: `https://github.com/${slug.owner}/${slug.repo}`, ...repo } : null,
1709
+ dependencies: dependencies ?? null,
1710
+ size: registry ? sizeOf(registry) : null,
1711
+ types: registry?.types ?? null,
1712
+ modules: registry?.modules ?? null,
1713
+ vulnerabilities,
1714
+ gates: {
1715
+ unpatchedCve,
1716
+ licenceNotAllowed,
1717
+ failed: [...unpatchedCve ? ["unpatched-cve"] : [], ...licenceNotAllowed ? ["licence-not-allowed"] : []]
1718
+ },
1719
+ missing
1720
+ };
1721
+ }
1722
+ function deprecation(answers) {
1723
+ const known = answers.filter((a) => typeof a === "boolean");
1724
+ return known.length === 0 ? null : known.some(Boolean);
1725
+ }
1726
+ async function collectDownloads(http, ecosystem, name, fromRegistry, attempt) {
1727
+ const parts = await Promise.all(downloadSources(http, ecosystem, name).map((s) => attempt(s.label, s.run)));
1728
+ const got = parts.filter((p) => p !== undefined);
1729
+ if (got.length === 0 && fromRegistry === null)
1730
+ return null;
1731
+ return Object.assign({ lastWeek: null, lastMonth: null, last90Days: null }, fromRegistry, ...got);
1732
+ }
1733
+ var sizeOf = (r) => r.unpackedBytes === null && r.downloadBytes === null ? null : { unpackedBytes: r.unpackedBytes, downloadBytes: r.downloadBytes };
1734
+ async function repoFacts(slug, collector, attempt, missing) {
1735
+ const github = await githubFacts(collector.http, slug, await collector.token());
1736
+ missing.push(...github.failures);
1737
+ const facts = github.facts;
1738
+ if (facts.stars !== null && facts.openIssues !== null)
1739
+ return facts;
1740
+ const fallback = await attempt("deps.dev project", () => depsDevProject(collector.http, slug));
1741
+ const openIssues = facts.openIssues ?? (fallback?.openIssues != null && facts.openPullRequests !== null ? Math.max(0, fallback.openIssues - facts.openPullRequests) : null);
1742
+ return { ...facts, stars: facts.stars ?? fallback?.stars ?? null, openIssues };
1743
+ }
1744
+ function blank(name, requestedVersion) {
1745
+ return {
1746
+ name,
1747
+ requestedVersion,
1748
+ latest: null,
1749
+ releases: null,
1750
+ deprecated: null,
1751
+ yanked: null,
1752
+ licence: null,
1753
+ downloads: null,
1754
+ dependents: null,
1755
+ repo: null,
1756
+ dependencies: null,
1757
+ size: null,
1758
+ types: null,
1759
+ modules: null,
1760
+ vulnerabilities: null
1761
+ };
1762
+ }
1763
+
1764
+ // plugins/code-challenge/opencode/src/lib-facts/http.ts
1765
+ var REQUEST_TIMEOUT_MS = 1e4;
1766
+ var CONCURRENCY = 6;
1767
+ var MAX_BODY_BYTES = 5 * 1024 * 1024;
1768
+ var MAX_REDIRECTS = 3;
1769
+
1770
+ class HttpError extends Error {
1771
+ status;
1772
+ constructor(status, url) {
1773
+ super(`${status} ${new URL(url).host}`);
1774
+ this.status = status;
1775
+ }
1776
+ }
1777
+ var AGENT = { "user-agent": "opencode-code-challenge" };
1778
+
1779
+ class Http {
1780
+ options;
1781
+ active = 0;
1782
+ waiting = [];
1783
+ limit;
1784
+ constructor(options) {
1785
+ this.options = options;
1786
+ this.limit = options.concurrency ?? CONCURRENCY;
1787
+ }
1788
+ async slot(run) {
1789
+ if (this.active >= this.limit)
1790
+ await new Promise((resolve) => this.waiting.push(resolve));
1791
+ this.active++;
1792
+ try {
1793
+ return await run();
1794
+ } finally {
1795
+ this.active--;
1796
+ this.waiting.shift()?.();
1797
+ }
1798
+ }
1799
+ async readJson(response, url) {
1800
+ const max = this.options.maxBodyBytes ?? MAX_BODY_BYTES;
1801
+ const tooLarge = () => new Error(`response too large ${new URL(url).host}`);
1802
+ if (Number(response.headers.get("content-length")) > max)
1803
+ throw tooLarge();
1804
+ const reader = response.body?.getReader();
1805
+ if (!reader)
1806
+ return response.json();
1807
+ const chunks = [];
1808
+ let size = 0;
1809
+ for (;; ) {
1810
+ const { done, value } = await reader.read();
1811
+ if (done)
1812
+ break;
1813
+ size += value.byteLength;
1814
+ if (size > max) {
1815
+ await reader.cancel().catch(() => {});
1816
+ throw tooLarge();
1817
+ }
1818
+ chunks.push(value);
1819
+ }
1820
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
1821
+ }
1822
+ send(url, init) {
1823
+ return this.slot(async () => {
1824
+ const timeout = AbortSignal.timeout(this.options.timeoutMs ?? REQUEST_TIMEOUT_MS);
1825
+ const signal = this.options.signal ? AbortSignal.any([timeout, this.options.signal]) : timeout;
1826
+ const origin = new URL(url);
1827
+ let target = url;
1828
+ try {
1829
+ for (let hop = 0;hop <= MAX_REDIRECTS; hop++) {
1830
+ const response = await this.options.fetch(target, { ...init, signal, redirect: "manual" });
1831
+ if (response.status >= 300 && response.status < 400) {
1832
+ const location = response.headers.get("location");
1833
+ const next = location ? new URL(location, target) : undefined;
1834
+ if (next?.protocol !== "https:" || next.host !== origin.host)
1835
+ throw new Error(`redirect refused ${origin.host}`);
1836
+ target = next.href;
1837
+ continue;
1838
+ }
1839
+ if (!response.ok)
1840
+ throw new HttpError(response.status, target);
1841
+ return { body: await this.readJson(response, target), link: response.headers.get("link") };
1842
+ }
1843
+ throw new Error(`too many redirects ${origin.host}`);
1844
+ } catch (error) {
1845
+ if (timeout.aborted && !this.options.signal?.aborted)
1846
+ throw new Error(`timed out ${origin.host}`, { cause: error });
1847
+ throw error;
1848
+ }
1849
+ });
1850
+ }
1851
+ async get(url, headers = {}, projection) {
1852
+ const hit = this.options.cache.get(url, projection?.valid);
1853
+ if (hit)
1854
+ return hit;
1855
+ const raw = await this.send(url, { headers: { accept: "application/json", ...AGENT, ...headers } });
1856
+ const reply = projection ? { body: projection.project(raw), link: null } : raw;
1857
+ this.options.cache.put(url, reply);
1858
+ return reply;
1859
+ }
1860
+ post(url, payload) {
1861
+ return this.send(url, {
1862
+ method: "POST",
1863
+ headers: { "content-type": "application/json", ...AGENT },
1864
+ body: JSON.stringify(payload)
1865
+ });
1866
+ }
1867
+ }
1868
+
1869
+ // plugins/code-challenge/opencode/src/lib-facts/names.ts
1870
+ var MAX_NAME = 214;
1871
+ var MAX_VERSION = 128;
1872
+ var NAME = {
1873
+ npm: /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/i,
1874
+ pypi: /^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i,
1875
+ crates: /^[a-z][a-z0-9_-]*$/i,
1876
+ go: /^[a-z0-9][a-z0-9._~-]*(?:\/[a-z0-9._~-]+)*$/i
1877
+ };
1878
+ var VERSION = /^[a-z0-9][a-z0-9._+!~-]*$/i;
1879
+ function nameProblem(ecosystem, name) {
1880
+ if (name.length > MAX_NAME)
1881
+ return `package name over ${MAX_NAME} characters`;
1882
+ if (!NAME[ecosystem].test(name) || name.split("/").some((part) => part === "." || part === ".."))
1883
+ return `invalid ${ecosystem} package name`;
1884
+ return;
1885
+ }
1886
+ function versionProblem(version) {
1887
+ return version.length <= MAX_VERSION && VERSION.test(version) ? undefined : "invalid version";
1888
+ }
1889
+
1890
+ // plugins/code-challenge/opencode/src/lib-facts/types.ts
1891
+ var ECOSYSTEMS = ["npm", "pypi", "crates", "go"];
1892
+
1893
+ // plugins/code-challenge/opencode/src/lib-facts/index.ts
1894
+ var LIB_FACTS_TOOL = "challenge_lib_facts";
1895
+ var MAX_PACKAGES = 6;
1896
+ var LIB_FACTS_DESCRIPTION = `Registry, OSV and GitHub facts for 1-6 packages (npm, pypi, crates, go); facts only, no verdict.
1897
+ ` + "Per package: latest version and date, releases in 12 and 24 months, licence, downloads, dependents, " + "GitHub activity, dependency counts, size, types, ESM/CJS, OSV advisories (always fresh), and the hard gates " + "unpatchedCve and licenceNotAllowed. A failed source is listed in `missing`; the call still succeeds. " + "Everything but OSV is cached for 7 days.";
1898
+ var LIB_FACTS_INPUT = {
1899
+ type: "object",
1900
+ properties: {
1901
+ ecosystem: { type: "string", enum: [...ECOSYSTEMS], description: "Package ecosystem" },
1902
+ packages: {
1903
+ type: "array",
1904
+ minItems: 1,
1905
+ maxItems: MAX_PACKAGES,
1906
+ description: "Packages to look up; a version adds its OSV advisories",
1907
+ items: {
1908
+ type: "object",
1909
+ properties: { name: { type: "string" }, version: { type: "string" } },
1910
+ required: ["name"],
1911
+ additionalProperties: false
1912
+ }
1913
+ }
1914
+ },
1915
+ required: ["ecosystem", "packages"],
1916
+ additionalProperties: false
1917
+ };
1918
+ function readRequest(input) {
1919
+ const { ecosystem, packages } = input ?? {};
1920
+ if (!ECOSYSTEMS.includes(ecosystem))
1921
+ return `ecosystem must be one of ${ECOSYSTEMS.join(", ")}`;
1922
+ if (!Array.isArray(packages) || packages.length < 1 || packages.length > MAX_PACKAGES)
1923
+ return `packages must hold 1 to ${MAX_PACKAGES} entries`;
1924
+ const parsed = [];
1925
+ for (const entry of packages) {
1926
+ const { name, version } = entry ?? {};
1927
+ if (typeof name !== "string" || name.trim() === "")
1928
+ return "each package needs a non-empty name";
1929
+ const nameIssue = nameProblem(ecosystem, name.trim());
1930
+ if (nameIssue)
1931
+ return `${nameIssue}: ${JSON.stringify(name.slice(0, 80))}`;
1932
+ if (version === undefined) {
1933
+ parsed.push({ name: name.trim() });
1934
+ continue;
1935
+ }
1936
+ if (typeof version !== "string" || versionProblem(version.trim()))
1937
+ return `invalid version: ${JSON.stringify(String(version).slice(0, 80))}`;
1938
+ parsed.push({ name: name.trim(), version: version.trim() });
1939
+ }
1940
+ return { ecosystem, packages: parsed };
1941
+ }
1942
+ function ghToken() {
1943
+ return new Promise((resolve) => {
1944
+ execFile("gh", ["auth", "token"], { timeout: 5000 }, (error, stdout) => {
1945
+ const token = error ? "" : stdout.trim();
1946
+ resolve(token === "" ? undefined : token);
1947
+ });
1948
+ });
1949
+ }
1950
+ async function lookupLibFacts(ecosystem, packages, overrides = {}, signal) {
1951
+ const now = overrides.now ?? (() => new Date);
1952
+ const cache = new DiskCache(overrides.cacheDir ?? defaultCacheDir(), () => now().getTime());
1953
+ const http = new Http({
1954
+ fetch: overrides.fetch ?? fetch,
1955
+ cache,
1956
+ signal,
1957
+ timeoutMs: overrides.timeoutMs,
1958
+ maxBodyBytes: overrides.maxBodyBytes,
1959
+ concurrency: overrides.concurrency
1960
+ });
1961
+ let token;
1962
+ const collector = { http, now, token: () => token ??= (overrides.token ?? ghToken)() };
1963
+ const results = await Promise.all(packages.map((p) => collectPackage(ecosystem, p, collector)));
1964
+ signal?.throwIfAborted();
1965
+ return { ecosystem, fetchedAt: now().toISOString(), packages: results };
1966
+ }
1967
+ async function runLibFacts(input, call, overrides = {}) {
1968
+ const request = readRequest(input);
1969
+ if (typeof request === "string")
1970
+ return { content: `${LIB_FACTS_TOOL}: ${request}`, metadata: { ok: false } };
1971
+ const facts = await lookupLibFacts(request.ecosystem, request.packages, overrides, call.signal);
1972
+ return { content: JSON.stringify(facts, null, 1), metadata: { ok: true, facts } };
1973
+ }
1974
+
1975
+ // plugins/code-challenge/opencode/src/scan/index.ts
1976
+ import { realpathSync as realpathSync3 } from "fs";
1977
+ import { isAbsolute as isAbsolute4, resolve as resolve6 } from "path";
1978
+
1979
+ // plugins/code-challenge/opencode/src/scan/run.ts
1980
+ import { existsSync, mkdtempSync, realpathSync as realpathSync2, rmSync, statSync as statSync3 } from "fs";
1981
+ import { tmpdir } from "os";
1982
+ import { extname as extname2, join as join9, resolve as resolve5 } from "path";
1983
+
1984
+ // lib/src/subprocess.ts
1985
+ import { constants } from "os";
1986
+ var EXIT_GRACE_MS = 2000;
1987
+ var EXIT_POLL_MS = 100;
1988
+ function goneWatch(graceMs, pollMs) {
1989
+ const polls = Math.max(1, Math.ceil(graceMs / Math.max(1, pollMs)));
1990
+ let since = null;
1991
+ let seen = 0;
1992
+ return (alive) => {
1993
+ if (alive) {
1994
+ since = null;
1995
+ seen = 0;
1996
+ return false;
1997
+ }
1998
+ since ??= Date.now();
1999
+ seen++;
2000
+ return seen > polls && Date.now() - since >= graceMs;
2001
+ };
2002
+ }
2003
+ function processAlive(pid) {
2004
+ try {
2005
+ process.kill(pid, 0);
2006
+ return true;
2007
+ } catch (error) {
2008
+ return error.code === "EPERM";
2009
+ }
2010
+ }
2011
+ function killChild(child, group) {
2012
+ if (group) {
2013
+ try {
2014
+ process.kill(-child.pid, "SIGKILL");
2015
+ return;
2016
+ } catch {}
2017
+ }
2018
+ try {
2019
+ child.kill("SIGKILL");
2020
+ } catch {}
2021
+ }
2022
+ function unref(timer) {
2023
+ timer.unref?.();
2024
+ }
2025
+ function capture(stream) {
2026
+ if (!(stream instanceof ReadableStream))
2027
+ return { text: Promise.resolve(""), snapshot: () => "", cancel: () => {} };
2028
+ const reader = stream.getReader();
2029
+ const decoder = new TextDecoder;
2030
+ let collected = "";
2031
+ const text = (async () => {
2032
+ try {
2033
+ for (;; ) {
2034
+ const chunk = await reader.read();
2035
+ if (chunk.done)
2036
+ break;
2037
+ collected += decoder.decode(chunk.value, { stream: true });
2038
+ }
2039
+ } catch {}
2040
+ collected += decoder.decode();
2041
+ return collected;
2042
+ })();
2043
+ const cancel = () => {
2044
+ try {
2045
+ reader.cancel().catch(() => {
2046
+ return;
2047
+ });
2048
+ } catch {}
2049
+ };
2050
+ return { text, snapshot: () => collected, cancel };
2051
+ }
2052
+ function supervise(child, options = {}) {
2053
+ const grace = Math.max(0, options.graceMs ?? EXIT_GRACE_MS);
2054
+ const pollMs = Math.max(1, options.pollMs ?? EXIT_POLL_MS);
2055
+ const alive = options.alive ?? processAlive;
2056
+ const group = options.group ?? false;
2057
+ const { signal, timeoutMs } = options;
2058
+ const out = capture(child.stdout);
2059
+ const err = capture(child.stderr);
2060
+ return new Promise((resolve) => {
2061
+ let ended = null;
2062
+ let exitSeen = false;
2063
+ let settled = false;
2064
+ const gone = goneWatch(grace, pollMs);
2065
+ let deadline;
2066
+ let graceTimer;
2067
+ const settle = (run) => {
2068
+ if (settled)
2069
+ return;
2070
+ settled = true;
2071
+ clearTimeout(deadline);
2072
+ clearTimeout(graceTimer);
2073
+ clearInterval(poller);
2074
+ signal?.removeEventListener("abort", onAbort);
2075
+ resolve(run);
2076
+ };
2077
+ const end = (cause) => {
2078
+ if (ended !== null || settled)
2079
+ return;
2080
+ ended = cause;
2081
+ if (cause !== "lost" || group)
2082
+ killChild(child, group);
2083
+ out.cancel();
2084
+ err.cancel();
2085
+ graceTimer = setTimeout(() => settle({ kind: cause, stdout: out.snapshot(), stderr: err.snapshot() }), grace);
2086
+ if (options.unref)
2087
+ unref(graceTimer);
2088
+ };
2089
+ const onAbort = () => end("aborted");
2090
+ const poller = setInterval(() => {
2091
+ if (exitSeen || ended !== null || settled)
2092
+ return;
2093
+ if (gone(alive(child.pid)))
2094
+ end("lost");
2095
+ }, pollMs);
2096
+ unref(poller);
2097
+ if (timeoutMs !== undefined && timeoutMs > 0 && Number.isFinite(timeoutMs)) {
2098
+ deadline = setTimeout(() => end("timeout"), timeoutMs);
2099
+ if (options.unref)
2100
+ unref(deadline);
2101
+ }
2102
+ signal?.addEventListener("abort", onAbort, { once: true });
2103
+ if (signal?.aborted)
2104
+ onAbort();
2105
+ child.exited.then(() => {
2106
+ exitSeen = true;
2107
+ }, () => {
2108
+ return;
2109
+ });
2110
+ Promise.all([child.exited, out.text, err.text]).then(([exitCode, stdout, stderr]) => {
2111
+ if (ended !== null)
2112
+ settle({ kind: ended, stdout, stderr });
2113
+ else
2114
+ settle({ kind: "exited", exitCode, signalCode: signalName(child.signalCode), stdout, stderr });
2115
+ }, () => end("lost"));
2116
+ });
2117
+ }
2118
+ function signalName(code) {
2119
+ if (code === null || code === undefined)
2120
+ return null;
2121
+ if (typeof code === "string")
2122
+ return code;
2123
+ return Object.entries(constants.signals).find(([, n]) => n === code)?.[0] ?? String(code);
2124
+ }
2125
+
2126
+ // plugins/code-challenge/opencode/src/scan/env.ts
2127
+ var ALLOWED = new Set([
2128
+ "PATH",
2129
+ "HOME",
2130
+ "USER",
2131
+ "LOGNAME",
2132
+ "SHELL",
2133
+ "TERM",
2134
+ "TZ",
2135
+ "LANG",
2136
+ "LANGUAGE",
2137
+ "TMPDIR",
2138
+ "TMP",
2139
+ "TEMP",
2140
+ "CARGO_HOME",
2141
+ "RUSTUP_HOME",
2142
+ "RUSTUP_TOOLCHAIN",
2143
+ "GOPATH",
2144
+ "GOROOT",
2145
+ "GOCACHE",
2146
+ "GOMODCACHE",
2147
+ "GOFLAGS",
2148
+ "GOPROXY",
2149
+ "GONOPROXY",
2150
+ "GONOSUMDB",
2151
+ "GOSUMDB",
2152
+ "GOTOOLCHAIN",
2153
+ "BUN_INSTALL",
2154
+ "BUN_INSTALL_CACHE_DIR",
2155
+ "NPM_CONFIG_CACHE",
2156
+ "npm_config_cache",
2157
+ "XDG_CACHE_HOME",
2158
+ "XDG_CONFIG_HOME",
2159
+ "XDG_DATA_HOME",
2160
+ "HTTP_PROXY",
2161
+ "HTTPS_PROXY",
2162
+ "NO_PROXY",
2163
+ "ALL_PROXY",
2164
+ "http_proxy",
2165
+ "https_proxy",
2166
+ "no_proxy",
2167
+ "all_proxy",
2168
+ "SSL_CERT_FILE",
2169
+ "SSL_CERT_DIR",
2170
+ "NODE_EXTRA_CA_CERTS",
2171
+ "REQUESTS_CA_BUNDLE",
2172
+ "CURL_CA_BUNDLE"
2173
+ ]);
2174
+ var ALLOWED_PREFIXES = ["LC_", "UV_"];
2175
+ var SECRET_NAME = /(TOKEN|SECRET|PASSWORD|PASSWD|KEY|CREDENTIAL|AUTH)/i;
2176
+ var SECRET_PREFIX = /^(AWS_|GH_|GITHUB_)/i;
2177
+ function stripUserinfo(value) {
2178
+ return value.replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@,]*@/gi, "$1");
2179
+ }
2180
+ function childEnv(source = Bun.env, extra = { NO_COLOR: "1", FORCE_COLOR: "0" }) {
2181
+ const env = {};
2182
+ for (const [name, value] of Object.entries(source)) {
2183
+ if (value === undefined)
2184
+ continue;
2185
+ if (SECRET_NAME.test(name) || SECRET_PREFIX.test(name))
2186
+ continue;
2187
+ if (ALLOWED.has(name) || ALLOWED_PREFIXES.some((p) => name.startsWith(p)))
2188
+ env[name] = stripUserinfo(value);
2189
+ }
2190
+ return { ...env, ...extra };
2191
+ }
2192
+
2193
+ // plugins/code-challenge/opencode/src/scan/exec.ts
2194
+ var MAX_STDOUT_BYTES = 16 * 1024 * 1024;
2195
+ var MAX_STDERR_BYTES = 1024 * 1024;
2196
+ function bounded(source, max, onOverflow) {
2197
+ if (!(source instanceof ReadableStream))
2198
+ return source;
2199
+ const reader = source.getReader();
2200
+ let total = 0;
2201
+ return new ReadableStream({
2202
+ async pull(controller) {
2203
+ const chunk = await reader.read().catch(() => ({ done: true, value: undefined }));
2204
+ if (chunk.done)
2205
+ return controller.close();
2206
+ total += chunk.value.byteLength;
2207
+ if (total > max) {
2208
+ onOverflow();
2209
+ reader.cancel().catch(() => {
2210
+ return;
2211
+ });
2212
+ return controller.close();
2213
+ }
2214
+ controller.enqueue(chunk.value);
2215
+ },
2216
+ cancel: () => reader.cancel().catch(() => {
2217
+ return;
2218
+ })
2219
+ });
2220
+ }
2221
+ var spawnTool = async (argv, options) => {
2222
+ const { cwd, timeoutMs, signal } = options;
2223
+ try {
2224
+ const child = Bun.spawn(argv, { cwd, stdin: "ignore", stdout: "pipe", stderr: "pipe", env: childEnv(), detached: true });
2225
+ const state = { overflow: null };
2226
+ const over = (stream) => () => {
2227
+ state.overflow ??= stream;
2228
+ killChild(child, true);
2229
+ };
2230
+ const guarded = {
2231
+ pid: child.pid,
2232
+ exited: child.exited,
2233
+ get signalCode() {
2234
+ return child.signalCode;
2235
+ },
2236
+ kill: (s) => child.kill(s),
2237
+ stdout: bounded(child.stdout, options.maxStdoutBytes ?? MAX_STDOUT_BYTES, over("stdout")),
2238
+ stderr: bounded(child.stderr, options.maxStderrBytes ?? MAX_STDERR_BYTES, over("stderr"))
2239
+ };
2240
+ const run = await supervise(guarded, { timeoutMs, signal, group: true });
2241
+ return state.overflow === null ? run : { kind: "overflow", stream: state.overflow, stdout: "", stderr: "" };
2242
+ } catch (error) {
2243
+ return { kind: "exited", exitCode: 127, signalCode: null, stdout: "", stderr: String(error) };
2244
+ }
2245
+ };
2246
+
2247
+ // plugins/code-challenge/opencode/src/scan/files.ts
2248
+ import { lstatSync as lstatSync3, readdirSync as readdirSync2, realpathSync, statSync as statSync2 } from "fs";
2249
+ import { extname, isAbsolute as isAbsolute2, join as join4, relative, resolve as resolve3, sep } from "path";
2250
+
2251
+ // lib/src/bounded-read.ts
2252
+ import { closeSync, constants as constants2, fstatSync, lstatSync as lstatSync2, openSync, readSync } from "fs";
2253
+ var MAX_LEDGER_FILE_BYTES = 64 * 1024;
2254
+ function readBoundedBytes(path, maxBytes) {
2255
+ let fd;
2256
+ try {
2257
+ if (!lstatSync2(path).isFile())
2258
+ return { kind: "unreadable", reason: "not-regular" };
2259
+ fd = openSync(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
2260
+ const info = fstatSync(fd);
2261
+ if (!info.isFile())
2262
+ return { kind: "unreadable", reason: "not-regular" };
2263
+ if (info.size > maxBytes)
2264
+ return { kind: "unreadable", reason: "too-large" };
2265
+ const buffer = Buffer.alloc(info.size);
2266
+ let offset = 0;
2267
+ while (offset < buffer.length) {
2268
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
2269
+ if (read === 0)
2270
+ break;
2271
+ offset += read;
2272
+ }
2273
+ return { kind: "bytes", bytes: offset === buffer.length ? buffer : buffer.subarray(0, offset) };
2274
+ } catch (error) {
2275
+ const code = error.code;
2276
+ if (code === "ENOENT")
2277
+ return { kind: "absent" };
2278
+ return code === "ELOOP" ? { kind: "unreadable", reason: "not-regular" } : { kind: "unreadable", reason: "io", code };
2279
+ } finally {
2280
+ if (fd !== undefined)
2281
+ closeSync(fd);
2282
+ }
2283
+ }
2284
+
2285
+ // plugins/code-challenge/opencode/src/scan/read.ts
2286
+ function readText(path, maxBytes) {
2287
+ const read = readBoundedBytes(path, maxBytes);
2288
+ if (read.kind === "bytes")
2289
+ return { kind: "text", text: read.bytes.toString("utf8") };
2290
+ return { kind: read.kind };
2291
+ }
2292
+
2293
+ // plugins/code-challenge/opencode/src/scan/types.ts
2294
+ var LANGUAGES = ["ts", "python", "go", "rust"];
2295
+ var DEPTHS2 = ["quick", "standard", "deep"];
2296
+
2297
+ // plugins/code-challenge/opencode/src/scan/files.ts
2298
+ var SKIP_DIRS = new Set([".git", "node_modules", "dist", "target", ".venv", "venv", "__pycache__"]);
2299
+ var EXTENSION_LANGUAGE = {
2300
+ ".ts": "ts",
2301
+ ".tsx": "ts",
2302
+ ".js": "ts",
2303
+ ".jsx": "ts",
2304
+ ".mjs": "ts",
2305
+ ".cjs": "ts",
2306
+ ".mts": "ts",
2307
+ ".cts": "ts",
2308
+ ".py": "python",
2309
+ ".go": "go",
2310
+ ".rs": "rust"
2311
+ };
2312
+ var MARKER_LANGUAGE = [
2313
+ ["package.json", "ts"],
2314
+ ["tsconfig.json", "ts"],
2315
+ ["pyproject.toml", "python"],
2316
+ ["setup.py", "python"],
2317
+ ["requirements.txt", "python"],
2318
+ ["go.mod", "go"],
2319
+ ["Cargo.toml", "rust"]
2320
+ ];
2321
+ function detectLanguages(root, files) {
2322
+ const found = new Set;
2323
+ if (files.length > 0) {
2324
+ for (const file of files) {
2325
+ const language = EXTENSION_LANGUAGE[extname(file)];
2326
+ if (language)
2327
+ found.add(language);
2328
+ }
2329
+ } else {
2330
+ for (const [marker, language] of MARKER_LANGUAGE)
2331
+ if (lstatOrNull(join4(root, marker)) !== null)
2332
+ found.add(language);
2333
+ }
2334
+ return LANGUAGES.filter((l) => found.has(l));
2335
+ }
2336
+ function inside(root, abs) {
2337
+ const rel = relative(root, abs);
2338
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute2(rel);
2339
+ }
2340
+ var outside = (pattern) => new Error(`challenge_scan: path is outside the root: ${pattern}`);
2341
+ function realOrNull(path) {
2342
+ try {
2343
+ return realpathSync(path);
2344
+ } catch {
2345
+ return null;
2346
+ }
2347
+ }
2348
+ function walk(dir, root, out) {
2349
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
2350
+ if (entry.isSymbolicLink())
2351
+ continue;
2352
+ if (entry.isDirectory()) {
2353
+ if (!SKIP_DIRS.has(entry.name))
2354
+ walk(join4(dir, entry.name), root, out);
2355
+ } else
2356
+ out.add(relative(root, join4(dir, entry.name)));
2357
+ }
2358
+ }
2359
+ function expandFiles(root, patterns) {
2360
+ const found = new Set;
2361
+ for (const pattern of patterns) {
2362
+ const isGlob = /[*?[{]/.test(pattern);
2363
+ if (isGlob && (isAbsolute2(pattern) || pattern.split("/").includes("..")))
2364
+ throw outside(pattern);
2365
+ const abs = resolve3(root, pattern);
2366
+ if (!isGlob) {
2367
+ if (!inside(root, abs))
2368
+ throw outside(pattern);
2369
+ const real = realOrNull(abs);
2370
+ if (real === null)
2371
+ continue;
2372
+ if (!inside(root, real))
2373
+ throw outside(pattern);
2374
+ if (statSync2(real).isDirectory())
2375
+ walk(real, root, found);
2376
+ else
2377
+ found.add(relative(root, real));
2378
+ continue;
2379
+ }
2380
+ for (const match of new Bun.Glob(pattern).scanSync({ cwd: root, onlyFiles: true })) {
2381
+ if (match.split("/").some((part) => SKIP_DIRS.has(part)))
2382
+ continue;
2383
+ const real = realOrNull(join4(root, match));
2384
+ if (real !== null && inside(root, real))
2385
+ found.add(relative(root, real));
2386
+ }
2387
+ }
2388
+ return [...found].sort();
2389
+ }
2390
+ function missingMarker(root, markers) {
2391
+ if (!markers)
2392
+ return null;
2393
+ for (const spec of markers) {
2394
+ const [name = "", needle] = spec.split(":");
2395
+ const read = readText(join4(root, name), MAX_MARKER_BYTES);
2396
+ if (read.kind !== "text")
2397
+ continue;
2398
+ if (needle === undefined || read.text.includes(needle))
2399
+ return null;
2400
+ }
2401
+ return `no ${markers.map((m) => m.replace(":", " containing ")).join(" or ")} in the repository`;
2402
+ }
2403
+ var MAX_MARKER_BYTES = 1024 * 1024;
2404
+ function lstatOrNull(path) {
2405
+ return lstatSync3(path, { throwIfNoEntry: false }) ?? null;
2406
+ }
2407
+ function parseListing(stdout) {
2408
+ return stdout.split("\x00").filter((f) => f !== "");
2409
+ }
2410
+ function contained(root, files) {
2411
+ return files.filter((f) => {
2412
+ const abs = join4(root, f);
2413
+ if (!lstatOrNull(abs)?.isFile())
2414
+ return false;
2415
+ const real = realOrNull(abs);
2416
+ return real !== null && inside(root, real);
2417
+ });
2418
+ }
2419
+
2420
+ // plugins/code-challenge/opencode/src/scan/git.ts
2421
+ import { lstatSync as lstatSync4 } from "fs";
2422
+ import { join as join5 } from "path";
2423
+ var GIT_SAFE = ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null"];
2424
+ var LIST_TIMEOUT_MS = 30000;
2425
+ function hasDotGit(root) {
2426
+ return lstatSync4(join5(root, ".git"), { throwIfNoEntry: false }) !== undefined;
2427
+ }
2428
+ async function gitState(root, exec, which, signal) {
2429
+ const git = which("git");
2430
+ if (!git)
2431
+ return hasDotGit(root) ? { kind: "error", reason: "git is not installed" } : { kind: "none" };
2432
+ const run = await exec([git, ...GIT_SAFE, "rev-parse", "--absolute-git-dir"], { cwd: root, timeoutMs: 1e4, signal });
2433
+ if (run.kind !== "exited")
2434
+ return { kind: "error", reason: `git rev-parse ${run.kind === "timeout" ? "timed out" : "did not finish"}` };
2435
+ if (run.exitCode === 0) {
2436
+ const dir = run.stdout.trim();
2437
+ return dir === "" ? { kind: "error", reason: "git rev-parse printed no git directory" } : { kind: "repo", dir };
2438
+ }
2439
+ return run.exitCode === 128 && /not a git repository/i.test(run.stderr) ? { kind: "none" } : { kind: "error", reason: `git rev-parse exited ${run.exitCode}` };
2440
+ }
2441
+ async function list(git, root, exec, args, signal) {
2442
+ const run = await exec([git, ...GIT_SAFE, "ls-files", "-z", ...args], { cwd: root, timeoutMs: LIST_TIMEOUT_MS, signal });
2443
+ if (run.kind !== "exited")
2444
+ return `git ls-files ${run.kind === "timeout" ? "timed out" : run.kind === "overflow" ? "output was too large" : "did not finish"}`;
2445
+ if (run.exitCode !== 0)
2446
+ return `git ls-files exited ${run.exitCode}`;
2447
+ return parseListing(run.stdout);
2448
+ }
2449
+ async function gitListing(root, state, exec, which, signal) {
2450
+ if (state.kind === "none")
2451
+ return { kind: "none" };
2452
+ if (state.kind === "error")
2453
+ return state;
2454
+ const git = which("git");
2455
+ if (!git)
2456
+ return { kind: "error", reason: "git is not installed" };
2457
+ const known = await list(git, root, exec, ["--cached", "--others", "--exclude-standard"], signal);
2458
+ if (typeof known === "string")
2459
+ return { kind: "error", reason: known };
2460
+ const ignored = await list(git, root, exec, ["--cached", "--ignored", "--exclude-standard"], signal);
2461
+ if (typeof ignored === "string")
2462
+ return { kind: "error", reason: ignored };
2463
+ const drop = new Set(ignored);
2464
+ return { kind: "files", files: contained(root, [...new Set(known)].filter((f) => !drop.has(f))) };
2465
+ }
2466
+
2467
+ // plugins/code-challenge/opencode/src/scan/parsers.ts
2468
+ import { lstatSync as lstatSync5 } from "fs";
2469
+ import { isAbsolute as isAbsolute3, join as join6, relative as relative2, resolve as resolve4 } from "path";
2470
+ var obj2 = (v) => typeof v === "object" && v !== null ? v : {};
2471
+ var arr2 = (v) => Array.isArray(v) ? v : [];
2472
+ var str2 = (v, fallback = "") => typeof v === "string" ? v : fallback;
2473
+ var num2 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
2474
+
2475
+ class OutputError extends Error {
2476
+ }
2477
+ function parseJson(text) {
2478
+ const trimmed = text.trim();
2479
+ if (trimmed === "")
2480
+ return null;
2481
+ try {
2482
+ return JSON.parse(trimmed);
2483
+ } catch {
2484
+ const start = trimmed.search(/[[{]/);
2485
+ if (start < 0)
2486
+ return null;
2487
+ try {
2488
+ return JSON.parse(trimmed.slice(start));
2489
+ } catch {
2490
+ return null;
2491
+ }
2492
+ }
2493
+ }
2494
+ function payload(text, kind) {
2495
+ const value = parseJson(text);
2496
+ const ok = kind === "array" ? Array.isArray(value) : typeof value === "object" && value !== null && !Array.isArray(value);
2497
+ if (!ok)
2498
+ throw new OutputError(`expected a JSON ${kind}, got ${text.trim() === "" ? "empty output" : `"${text.trim().slice(0, 60)}"`}`);
2499
+ return value;
2500
+ }
2501
+ function collection(owner, key, where = key, allowNull = false) {
2502
+ const value = obj2(owner)[key];
2503
+ if (Array.isArray(value))
2504
+ return value;
2505
+ if (allowNull && value === null)
2506
+ return [];
2507
+ throw new OutputError(`expected "${where}" to be a list, got ${value === undefined ? "nothing" : typeof value}`);
2508
+ }
2509
+ function relativeTo(root, file, cwd = root) {
2510
+ const abs = isAbsolute3(file) ? file : resolve4(cwd, file);
2511
+ const rel = relative2(root, abs);
2512
+ return rel === "" ? "." : rel;
2513
+ }
2514
+ var MODULE_ROOTS = ["", "src"];
2515
+ function biome(text) {
2516
+ return collection(payload(text, "object"), "diagnostics").flatMap((d) => {
2517
+ const diag = obj2(d);
2518
+ const category = str2(diag.category);
2519
+ if (!category.startsWith("lint/"))
2520
+ return [];
2521
+ const location = obj2(diag.location);
2522
+ const path = typeof location.path === "string" ? location.path : str2(obj2(location.path).file);
2523
+ return [{ rule: category.slice(5), file: path, line: num2(obj2(location.start).line), message: str2(diag.message) }];
2524
+ });
2525
+ }
2526
+ function oxlint(text) {
2527
+ return collection(payload(text, "object"), "diagnostics").map((d) => {
2528
+ const diag = obj2(d);
2529
+ const label = obj2(arr2(diag.labels)[0]);
2530
+ return {
2531
+ rule: str2(diag.code),
2532
+ file: str2(diag.filename),
2533
+ line: num2(obj2(label.span).line),
2534
+ message: str2(diag.message)
2535
+ };
2536
+ });
2537
+ }
2538
+ function eslint(text) {
2539
+ return arr2(payload(text, "array")).flatMap((f) => {
2540
+ const file = obj2(f);
2541
+ return arr2(file.messages).map((m) => {
2542
+ const msg = obj2(m);
2543
+ return { rule: str2(msg.ruleId, "eslint"), file: str2(file.filePath), line: num2(msg.line), message: str2(msg.message) };
2544
+ });
2545
+ });
2546
+ }
2547
+ var KNIP_KEYS = [
2548
+ "files",
2549
+ "dependencies",
2550
+ "devDependencies",
2551
+ "optionalPeerDependencies",
2552
+ "unlisted",
2553
+ "unresolved",
2554
+ "binaries",
2555
+ "exports",
2556
+ "types",
2557
+ "duplicates",
2558
+ "enumMembers",
2559
+ "namespaceMembers"
2560
+ ];
2561
+ function knip(text) {
2562
+ return collection(payload(text, "object"), "issues").flatMap((i) => {
2563
+ const issue = obj2(i);
2564
+ const file = str2(issue.file);
2565
+ return KNIP_KEYS.flatMap((key) => arr2(issue[key]).map((entry) => {
2566
+ const e = obj2(entry);
2567
+ const name = str2(e.name, file);
2568
+ return { rule: `knip/${key}`, file, line: num2(e.line), message: `${key}: ${name}` };
2569
+ }));
2570
+ });
2571
+ }
2572
+ function jscpd(text) {
2573
+ return collection(payload(text, "object"), "duplicates").map((d) => {
2574
+ const dup = obj2(d);
2575
+ const first = obj2(dup.firstFile);
2576
+ const second = obj2(dup.secondFile);
2577
+ const lines = num2(dup.lines) ?? 0;
2578
+ return {
2579
+ rule: "duplication",
2580
+ file: str2(first.name),
2581
+ line: num2(first.start),
2582
+ message: `${lines} duplicated lines also in ${str2(second.name)}:${num2(second.start) ?? "?"}`
2583
+ };
2584
+ });
2585
+ }
2586
+ function depcruise(text) {
2587
+ return collection(obj2(payload(text, "object")).summary, "violations", "summary.violations").map((v) => {
2588
+ const violation = obj2(v);
2589
+ const cycle = arr2(violation.cycle).map((c) => str2(obj2(c).name));
2590
+ const detail = cycle.length > 0 ? `${str2(violation.from)} -> ${cycle.join(" -> ")}` : `${str2(violation.from)} -> ${str2(violation.to)}`;
2591
+ return { rule: str2(obj2(violation.rule).name, "depcruise"), file: str2(violation.from), line: null, message: detail };
2592
+ });
2593
+ }
2594
+ function ruff(text) {
2595
+ return arr2(payload(text, "array")).map((d) => {
2596
+ const diag = obj2(d);
2597
+ return {
2598
+ rule: str2(diag.code),
2599
+ file: str2(diag.filename),
2600
+ line: num2(obj2(diag.location).row),
2601
+ message: str2(diag.message)
2602
+ };
2603
+ });
2604
+ }
2605
+ function vulture(text) {
2606
+ const hits = [];
2607
+ for (const line of text.split(`
2608
+ `)) {
2609
+ const m = /^(.+?):(\d+): (.+) \((\d+)% confidence\)$/.exec(line.trim());
2610
+ if (m)
2611
+ hits.push({ rule: "vulture", file: m[1] ?? "", line: Number(m[2]), message: `${m[3]} (${m[4]}% confidence)` });
2612
+ }
2613
+ return hits;
2614
+ }
2615
+ function moduleFile(root, module) {
2616
+ const path = module.replaceAll(".", "/");
2617
+ for (const base of MODULE_ROOTS) {
2618
+ for (const candidate of [`${path}.py`, `${path}/__init__.py`]) {
2619
+ const rel = base === "" ? candidate : `${base}/${candidate}`;
2620
+ if (lstatSync5(join6(root, rel), { throwIfNoEntry: false })?.isFile())
2621
+ return rel;
2622
+ }
2623
+ }
2624
+ return null;
2625
+ }
2626
+ function importLinter(text, ctx) {
2627
+ const hits = [];
2628
+ const broken = text.split(/^-+\nBroken contracts\n-+\n/m)[1];
2629
+ if (broken === undefined)
2630
+ return hits;
2631
+ let contract = "";
2632
+ let heading = "";
2633
+ for (const raw of broken.split(`
2634
+ `)) {
2635
+ const line = raw.trimEnd();
2636
+ if (/^-+$/.test(line))
2637
+ continue;
2638
+ const next = /^- (\S+) -> (\S+) \(l\.(\d+)\)/.exec(line.trim());
2639
+ if (next) {
2640
+ const module = next[1] ?? "";
2641
+ const file = moduleFile(ctx.root, module);
2642
+ hits.push({
2643
+ rule: contract || "import-linter",
2644
+ file,
2645
+ line: file === null ? null : Number(next[3]),
2646
+ message: `${heading || `${module} imports ${next[2]}`} (${module} -> ${next[2]})`
2647
+ });
2648
+ } else if (/ is not allowed to import /.test(line))
2649
+ heading = line.replace(/:$/, "");
2650
+ else if (line !== "" && !line.startsWith(" ") && !line.startsWith("-") && !line.includes(" -> "))
2651
+ contract = line;
2652
+ }
2653
+ return hits;
2654
+ }
2655
+ function golangci(text) {
2656
+ return collection(payload(text, "object"), "Issues", "Issues", true).map((i) => {
2657
+ const issue = obj2(i);
2658
+ const pos = obj2(issue.Pos);
2659
+ return { rule: str2(issue.FromLinter), file: str2(pos.Filename), line: num2(pos.Line), message: str2(issue.Text) };
2660
+ });
2661
+ }
2662
+ function deadcode(text) {
2663
+ if (text.trim() === "" || text.trim() === "null")
2664
+ return [];
2665
+ return arr2(payload(text, "array")).flatMap((p) => arr2(obj2(p).Funcs).map((f) => {
2666
+ const fn = obj2(f);
2667
+ const pos = obj2(fn.Position);
2668
+ return { rule: "deadcode", file: str2(pos.File), line: num2(pos.Line), message: `unreachable function ${str2(fn.Name)}` };
2669
+ }));
2670
+ }
2671
+ function clippy(text) {
2672
+ const hits = [];
2673
+ for (const line of text.split(`
2674
+ `)) {
2675
+ if (!line.startsWith("{"))
2676
+ continue;
2677
+ const event = obj2(parseJson(line));
2678
+ if (event.reason !== "compiler-message")
2679
+ continue;
2680
+ const message = obj2(event.message);
2681
+ const code = str2(obj2(message.code).code);
2682
+ if (code === "")
2683
+ continue;
2684
+ const span = arr2(message.spans).map(obj2).find((s) => s.is_primary === true);
2685
+ if (!span)
2686
+ continue;
2687
+ hits.push({ rule: code, file: str2(span.file_name), line: num2(span.line_start), message: str2(message.message) });
2688
+ }
2689
+ return hits;
2690
+ }
2691
+ function machete(text) {
2692
+ const hits = [];
2693
+ let manifest = "";
2694
+ for (const line of text.split(`
2695
+ `)) {
2696
+ const header = /^\S.* -- (.+Cargo\.toml):$/.exec(line);
2697
+ if (header)
2698
+ manifest = header[1] ?? "";
2699
+ else if (manifest !== "" && /^\s+\S+$/.test(line)) {
2700
+ hits.push({ rule: "unused-dependency", file: manifest, line: null, message: `unused dependency ${line.trim()}` });
2701
+ }
2702
+ }
2703
+ return hits;
2704
+ }
2705
+ function csvRow(row) {
2706
+ const fields = [];
2707
+ let current = "";
2708
+ let quoted = false;
2709
+ for (const ch of row) {
2710
+ if (ch === '"')
2711
+ quoted = !quoted;
2712
+ else if (ch === "," && !quoted) {
2713
+ fields.push(current);
2714
+ current = "";
2715
+ } else
2716
+ current += ch;
2717
+ }
2718
+ fields.push(current);
2719
+ return fields;
2720
+ }
2721
+ var LIZARD_LIMITS = { ccn: 10, nloc: 50, params: 5 };
2722
+ function lizard(text) {
2723
+ const hits = [];
2724
+ for (const row of text.split(`
2725
+ `)) {
2726
+ const f = csvRow(row.trim());
2727
+ if (f.length < 10)
2728
+ continue;
2729
+ const nloc = Number(f[0]);
2730
+ const ccn = Number(f[1]);
2731
+ const params = Number(f[3]);
2732
+ if (![nloc, ccn, params].every(Number.isFinite))
2733
+ continue;
2734
+ const file = f[6] ?? "";
2735
+ const line = Number(f[9]);
2736
+ const where = { file, line: Number.isFinite(line) ? line : null };
2737
+ const name = f[7] ?? "";
2738
+ if (ccn > LIZARD_LIMITS.ccn)
2739
+ hits.push({ rule: "lizard/ccn", ...where, message: `${name} has cyclomatic complexity ${ccn}` });
2740
+ if (nloc > LIZARD_LIMITS.nloc)
2741
+ hits.push({ rule: "lizard/nloc", ...where, message: `${name} has ${nloc} lines of code` });
2742
+ if (params > LIZARD_LIMITS.params)
2743
+ hits.push({ rule: "lizard/params", ...where, message: `${name} takes ${params} parameters` });
2744
+ }
2745
+ return hits;
2746
+ }
2747
+ var PARSERS = {
2748
+ "biome-json": biome,
2749
+ "oxlint-json": oxlint,
2750
+ "eslint-json": eslint,
2751
+ "knip-json": knip,
2752
+ "jscpd-json": jscpd,
2753
+ "depcruise-json": depcruise,
2754
+ "ruff-json": ruff,
2755
+ "vulture-text": vulture,
2756
+ "import-linter-text": importLinter,
2757
+ "golangci-json": golangci,
2758
+ "deadcode-json": deadcode,
2759
+ "clippy-json": clippy,
2760
+ "machete-text": machete,
2761
+ "lizard-csv": lizard
2762
+ };
2763
+ function parseOutput(parser, text, ctx) {
2764
+ return PARSERS[parser](text, ctx).map((hit) => ({ ...hit, file: hit.file === null ? null : relativeTo(ctx.root, hit.file, ctx.cwd) }));
2765
+ }
2766
+
2767
+ // plugins/code-challenge/opencode/src/scan/pins.ts
2768
+ var PINS = {
2769
+ "@biomejs/biome": "2.6.8",
2770
+ oxlint: "1.94.0",
2771
+ knip: "6.47.0",
2772
+ "dependency-cruiser": "18.8.0",
2773
+ jscpd: "5.4.3",
2774
+ eslint: "10.15.0",
2775
+ "@e18e/eslint-plugin": "0.8.1",
2776
+ ruff: "0.17.6",
2777
+ vulture: "2.16",
2778
+ "import-linter": "2.17",
2779
+ lizard: "1.26.1",
2780
+ "golang.org/x/tools": "v0.53.0"
2781
+ };
2782
+ function pinOf(pkg) {
2783
+ const version = PINS[pkg];
2784
+ if (version === undefined)
2785
+ throw new Error(`challenge_scan: no pinned version for ${pkg}`);
2786
+ return version;
2787
+ }
2788
+
2789
+ // plugins/code-challenge/opencode/src/scan/probes.ts
2790
+ import { dirname as dirname2, join as join7 } from "path";
2791
+ var UNKNOWN = () => null;
2792
+ function nearestRuffConfig(root, file) {
2793
+ let dir = dirname2(join7(root, file));
2794
+ for (;; ) {
2795
+ for (const name of [".ruff.toml", "ruff.toml", "pyproject.toml"]) {
2796
+ const path = join7(dir, name);
2797
+ const read = readText(path, MAX_MARKER_BYTES);
2798
+ if (read.kind !== "text")
2799
+ continue;
2800
+ if (name !== "pyproject.toml" || read.text.includes("[tool.ruff"))
2801
+ return path;
2802
+ }
2803
+ if (dir === root || dirname2(dir) === dir)
2804
+ return "";
2805
+ dir = dirname2(dir);
2806
+ }
2807
+ }
2808
+ async function ruffSettings(env, file) {
2809
+ const run = await env.exec([...env.prefix, "check", "--show-settings", join7(env.root, file)], {
2810
+ cwd: env.root,
2811
+ timeoutMs: env.timeoutMs,
2812
+ signal: env.signal
2813
+ });
2814
+ if (run.kind !== "exited" || run.exitCode !== 0)
2815
+ return null;
2816
+ const start = run.stdout.indexOf("linter.rules.enabled = [");
2817
+ if (start < 0)
2818
+ return null;
2819
+ const end = run.stdout.indexOf(`
2820
+ ]`, start);
2821
+ const block = run.stdout.slice(start, end < 0 ? undefined : end);
2822
+ return new Set([...block.matchAll(/\(([A-Z]+[0-9]+)\)/g)].map((m) => m[1] ?? ""));
2823
+ }
2824
+ async function golangciEnabled(env) {
2825
+ const run = await env.exec([...env.prefix, "linters", "--json"], { cwd: env.root, timeoutMs: env.timeoutMs, signal: env.signal });
2826
+ if (run.kind !== "exited" || run.exitCode !== 0)
2827
+ return null;
2828
+ try {
2829
+ const parsed = JSON.parse(run.stdout);
2830
+ if (!Array.isArray(parsed.Enabled))
2831
+ return null;
2832
+ return new Set(parsed.Enabled.flatMap((l) => l.name ? [l.name] : []));
2833
+ } catch {
2834
+ return null;
2835
+ }
2836
+ }
2837
+ function probeFor(recipe, env) {
2838
+ if (recipe.tool === "ruff") {
2839
+ return async (hits) => {
2840
+ const byConfig = new Map;
2841
+ const keyOf = new Map;
2842
+ for (const hit of hits) {
2843
+ if (hit.file === null)
2844
+ continue;
2845
+ const key = nearestRuffConfig(env.root, hit.file);
2846
+ keyOf.set(hit, key);
2847
+ if (!byConfig.has(key))
2848
+ byConfig.set(key, hit.file);
2849
+ }
2850
+ const settings = new Map;
2851
+ for (const [key, file] of byConfig)
2852
+ settings.set(key, await ruffSettings(env, file));
2853
+ return (hit) => {
2854
+ const key = keyOf.get(hit);
2855
+ const enabled = key === undefined ? null : settings.get(key);
2856
+ return enabled ? enabled.has(hit.rule) : null;
2857
+ };
2858
+ };
2859
+ }
2860
+ if (recipe.tool === "golangci-lint") {
2861
+ return async () => {
2862
+ const enabled = await golangciEnabled(env);
2863
+ return enabled ? (hit) => enabled.has(hit.rule) : UNKNOWN;
2864
+ };
2865
+ }
2866
+ return null;
2867
+ }
2868
+
2869
+ // plugins/code-challenge/opencode/src/scan/recipes.ts
2870
+ var TS_EXT = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
2871
+ var LIZARD_EXT = [
2872
+ ...TS_EXT,
2873
+ ".py",
2874
+ ".go",
2875
+ ".rs",
2876
+ ".java",
2877
+ ".c",
2878
+ ".cc",
2879
+ ".cpp",
2880
+ ".h",
2881
+ ".hpp",
2882
+ ".rb",
2883
+ ".php",
2884
+ ".swift"
2885
+ ];
2886
+ var OXLINT_CONFIG = `{}
2887
+ `;
2888
+ var RECIPES = [
2889
+ {
2890
+ id: "biome:lenses",
2891
+ tool: "biome",
2892
+ language: "ts",
2893
+ lenses: ["simplification", "performance", "stability"],
2894
+ lensRules: [
2895
+ [/^performance\//, "performance"],
2896
+ [/^complexity\//, "simplification"],
2897
+ [/^suspicious\//, "stability"]
2898
+ ],
2899
+ binary: "biome",
2900
+ install: "bunx",
2901
+ package: "@biomejs/biome",
2902
+ args: ["lint", "--config-path={cfg}", "--reporter=json", "--max-diagnostics=1000", "--", "{files}"],
2903
+ configFiles: ({ root, hasGitignore, fromConfigDir }) => ({
2904
+ "biome.json": JSON.stringify({
2905
+ root: true,
2906
+ linter: { enabled: true, rules: { recommended: false, complexity: "on", performance: "on", suspicious: "on" } },
2907
+ ...hasGitignore && !fromConfigDir ? { vcs: { enabled: true, clientKind: "git", useIgnoreFile: true, root } } : {}
2908
+ })
2909
+ }),
2910
+ repoConfigNames: ["biome.json", "biome.jsonc"],
2911
+ needsBuild: false,
2912
+ acceptedExitCodes: [0, 1],
2913
+ parser: "biome-json",
2914
+ scope: "files",
2915
+ extensions: TS_EXT
2916
+ },
2917
+ {
2918
+ id: "oxlint:perf",
2919
+ tool: "oxlint",
2920
+ language: "ts",
2921
+ lenses: ["performance", "stability"],
2922
+ lensRules: [
2923
+ [/no-accumulating-spread|no-array-index-key|no-map-spread/, "performance"],
2924
+ [/^eslint\(|^oxc\(/, "stability"]
2925
+ ],
2926
+ binary: "oxlint",
2927
+ install: "bunx",
2928
+ package: "oxlint",
2929
+ args: ["-c", "{cfg}/oxlintrc.json", "-A", "all", "-D", "perf", "-D", "correctness", "-f", "json", "--", "{files}"],
2930
+ configFiles: () => ({ "oxlintrc.json": OXLINT_CONFIG }),
2931
+ needsBuild: false,
2932
+ acceptedExitCodes: [0, 1],
2933
+ parser: "oxlint-json",
2934
+ scope: "files",
2935
+ extensions: TS_EXT
2936
+ },
2937
+ {
2938
+ id: "eslint:e18e",
2939
+ tool: "eslint",
2940
+ language: "ts",
2941
+ lenses: ["hand-rolled-stdlib", "hand-rolled-library"],
2942
+ lensRules: [
2943
+ [/ban-dependencies/, "hand-rolled-library"],
2944
+ [/^e18e\/prefer-/, "hand-rolled-stdlib"]
2945
+ ],
2946
+ binary: "eslint",
2947
+ install: "tool-dir",
2948
+ package: "eslint",
2949
+ args: ["--no-config-lookup", "-c", "{cfg}/eslint.config.mjs", "-f", "json", "--", "{files}"],
2950
+ configFiles: () => ({
2951
+ "eslint.config.mjs": `import e18e from "@e18e/eslint-plugin"
2952
+ export default [{ ignores: ["**/node_modules/**", "**/dist/**", "**/build/**", "**/coverage/**"] }, e18e.configs.recommended]
2953
+ `
2954
+ }),
2955
+ needsBuild: false,
2956
+ acceptedExitCodes: [0, 1],
2957
+ parser: "eslint-json",
2958
+ scope: "files",
2959
+ extensions: TS_EXT
2960
+ },
2961
+ {
2962
+ id: "knip:unused",
2963
+ tool: "knip",
2964
+ language: "ts",
2965
+ lenses: ["dead-code"],
2966
+ binary: "knip",
2967
+ install: "bunx",
2968
+ package: "knip",
2969
+ args: ["--reporter", "json", "--no-progress", "--include", "files,exports,types,dependencies"],
2970
+ executes: "loads and executes the repository's knip and tool config files (JS/TS) and plugin code",
2971
+ needsBuild: false,
2972
+ acceptedExitCodes: [0, 1],
2973
+ parser: "knip-json",
2974
+ scope: "repo",
2975
+ requiresMarker: ["package.json"]
2976
+ },
2977
+ {
2978
+ id: "depcruise:cycles",
2979
+ tool: "dependency-cruiser",
2980
+ language: "ts",
2981
+ lenses: ["structure"],
2982
+ binary: "depcruise",
2983
+ install: "bunx",
2984
+ package: "dependency-cruiser",
2985
+ args: ["--config", "{cfg}/dc.json", "--output-type", "json", "."],
2986
+ configFiles: () => ({
2987
+ "dc.json": JSON.stringify({
2988
+ forbidden: [
2989
+ { name: "no-circular", severity: "warn", from: {}, to: { circular: true } },
2990
+ { name: "no-orphans", severity: "info", from: { orphan: true, pathNot: "\\.d\\.ts$" }, to: {} }
2991
+ ],
2992
+ options: { doNotFollow: { path: "node_modules" }, tsPreCompilationDeps: true }
2993
+ })
2994
+ }),
2995
+ needsBuild: false,
2996
+ acceptedExitCodes: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
2997
+ parser: "depcruise-json",
2998
+ scope: "repo",
2999
+ requiresMarker: ["package.json"]
3000
+ },
3001
+ {
3002
+ id: "ruff:lenses",
3003
+ tool: "ruff",
3004
+ language: "python",
3005
+ lenses: ["simplification", "performance", "stability", "dead-code", "observability", "hand-rolled-stdlib"],
3006
+ lensRules: [
3007
+ [/^PERF/, "performance"],
3008
+ [/^(F401|F841|ERA)/, "dead-code"],
3009
+ [/^(T20|LOG|G\d)/, "observability"],
3010
+ [/^(BLE|TRY|ASYNC)/, "stability"],
3011
+ [/^(FURB|UP)/, "hand-rolled-stdlib"]
3012
+ ],
3013
+ binary: "ruff",
3014
+ install: "uvx",
3015
+ package: "ruff",
3016
+ args: [
3017
+ "check",
3018
+ "--isolated",
3019
+ "--select",
3020
+ "SIM,PERF,FURB,UP,C4,PIE,RET,TRY,BLE,ASYNC,LOG,G,T20,ERA,F401,F841",
3021
+ "--preview",
3022
+ "--output-format",
3023
+ "json",
3024
+ "--force-exclude",
3025
+ "--",
3026
+ "{files}"
3027
+ ],
3028
+ needsBuild: false,
3029
+ acceptedExitCodes: [0, 1],
3030
+ parser: "ruff-json",
3031
+ scope: "files",
3032
+ extensions: [".py"]
3033
+ },
3034
+ {
3035
+ id: "vulture:dead",
3036
+ tool: "vulture",
3037
+ language: "python",
3038
+ lenses: ["dead-code"],
3039
+ binary: "vulture",
3040
+ install: "uvx",
3041
+ package: "vulture",
3042
+ args: ["--min-confidence", "80", "--", "{files}"],
3043
+ needsBuild: false,
3044
+ acceptedExitCodes: [0, 3],
3045
+ parser: "vulture-text",
3046
+ scope: "files",
3047
+ extensions: [".py"]
3048
+ },
3049
+ {
3050
+ id: "import-linter:contracts",
3051
+ tool: "import-linter",
3052
+ language: "python",
3053
+ lenses: ["structure"],
3054
+ binary: "lint-imports",
3055
+ install: "uvx",
3056
+ package: "import-linter",
3057
+ args: ["--no-cache"],
3058
+ executes: "imports custom contract classes named in the repository's import-linter config",
3059
+ needsBuild: false,
3060
+ acceptedExitCodes: [0, 1],
3061
+ parser: "import-linter-text",
3062
+ scope: "repo",
3063
+ requiresMarker: [".importlinter", "setup.cfg:importlinter", "pyproject.toml:importlinter", "tox.ini:importlinter"]
3064
+ },
3065
+ {
3066
+ id: "golangci:lenses",
3067
+ tool: "golangci-lint",
3068
+ language: "go",
3069
+ lenses: ["simplification", "performance", "stability", "dead-code", "observability", "hand-rolled-stdlib"],
3070
+ lensRules: [
3071
+ [/^(prealloc|perfsprint|bodyclose)$/, "performance"],
3072
+ [/^(unused)$/, "dead-code"],
3073
+ [/^sloglint$/, "observability"],
3074
+ [/^(modernize|usestdlibvars)$/, "hand-rolled-stdlib"],
3075
+ [/^errorlint$/, "stability"]
3076
+ ],
3077
+ binary: "golangci-lint",
3078
+ install: "local",
3079
+ args: [
3080
+ "run",
3081
+ "--no-config",
3082
+ "--default",
3083
+ "none",
3084
+ "--enable",
3085
+ "staticcheck,unused,prealloc,perfsprint,gocritic,bodyclose,errorlint,modernize,usestdlibvars,sloglint",
3086
+ "--output.json.path",
3087
+ "stdout",
3088
+ "--output.text.path",
3089
+ "/dev/null",
3090
+ "--show-stats=false",
3091
+ "./..."
3092
+ ],
3093
+ executes: "compiles the module (cgo may run C compilers), may fetch modules or a Go toolchain; writes the Go build and module caches",
3094
+ needsBuild: true,
3095
+ acceptedExitCodes: [0, 1],
3096
+ parser: "golangci-json",
3097
+ scope: "repo",
3098
+ requiresMarker: ["go.mod"]
3099
+ },
3100
+ {
3101
+ id: "deadcode:go",
3102
+ tool: "deadcode",
3103
+ language: "go",
3104
+ lenses: ["dead-code"],
3105
+ binary: "deadcode",
3106
+ install: "go-run",
3107
+ package: "golang.org/x/tools",
3108
+ subpath: "cmd/deadcode",
3109
+ args: ["-json", "./..."],
3110
+ executes: "compiles the module (cgo may run C compilers), may fetch modules or a Go toolchain; writes the Go build and module caches",
3111
+ needsBuild: true,
3112
+ acceptedExitCodes: [0],
3113
+ parser: "deadcode-json",
3114
+ scope: "repo",
3115
+ requiresMarker: ["go.mod"]
3116
+ },
3117
+ {
3118
+ id: "clippy:lenses",
3119
+ tool: "clippy",
3120
+ language: "rust",
3121
+ lenses: ["performance", "simplification", "dead-code"],
3122
+ lensRules: [
3123
+ [/clippy::(perf|redundant_clone|useless_vec|manual_memcpy)/, "performance"],
3124
+ [/^dead_code$|unused/, "dead-code"],
3125
+ [/^clippy::(manual_|needless_|too_many|cognitive)/, "simplification"]
3126
+ ],
3127
+ binary: "cargo",
3128
+ install: "local",
3129
+ args: [
3130
+ "clippy",
3131
+ "--message-format=json",
3132
+ "--",
3133
+ "-A",
3134
+ "clippy::all",
3135
+ "-W",
3136
+ "clippy::perf",
3137
+ "-W",
3138
+ "clippy::complexity",
3139
+ "-W",
3140
+ "clippy::suspicious",
3141
+ "-W",
3142
+ "clippy::needless_range_loop",
3143
+ "-W",
3144
+ "clippy::manual_map",
3145
+ "-W",
3146
+ "clippy::manual_filter_map",
3147
+ "-W",
3148
+ "clippy::manual_find",
3149
+ "-W",
3150
+ "clippy::manual_flatten",
3151
+ "-W",
3152
+ "clippy::manual_retain",
3153
+ "-W",
3154
+ "clippy::manual_ok_or"
3155
+ ],
3156
+ executes: "builds the crate: runs its build scripts and procedural macros, fetches crates; writes target/ and the cargo caches",
3157
+ needsBuild: true,
3158
+ acceptedExitCodes: [0],
3159
+ parser: "clippy-json",
3160
+ scope: "repo",
3161
+ requiresMarker: ["Cargo.toml"]
3162
+ },
3163
+ {
3164
+ id: "machete:rust",
3165
+ tool: "cargo-machete",
3166
+ language: "rust",
3167
+ lenses: ["dead-code"],
3168
+ binary: "cargo-machete",
3169
+ install: "local",
3170
+ args: ["."],
3171
+ needsBuild: false,
3172
+ acceptedExitCodes: [0, 1],
3173
+ parser: "machete-text",
3174
+ scope: "repo",
3175
+ requiresMarker: ["Cargo.toml"]
3176
+ },
3177
+ {
3178
+ id: "lizard:complexity",
3179
+ tool: "lizard",
3180
+ language: "any",
3181
+ lenses: ["simplification", "over-engineering"],
3182
+ lensRules: [[/lizard\/(params|nloc)/, "over-engineering"]],
3183
+ binary: "lizard",
3184
+ install: "uvx",
3185
+ package: "lizard",
3186
+ args: ["--csv", "-x", "*/node_modules/*", "-x", "*/.git/*", "-x", "*/dist/*", "-x", "*/target/*", "--", "{files}"],
3187
+ needsBuild: false,
3188
+ acceptedExitCodes: [0, 1],
3189
+ parser: "lizard-csv",
3190
+ scope: "files",
3191
+ extensions: LIZARD_EXT
3192
+ },
3193
+ {
3194
+ id: "jscpd:duplication",
3195
+ tool: "jscpd",
3196
+ language: "any",
3197
+ lenses: ["structure"],
3198
+ binary: "jscpd",
3199
+ install: "bunx",
3200
+ package: "jscpd",
3201
+ args: ["--min-lines", "5", "--min-tokens", "50", "--reporters", "json", "--output", "{out}", "--silent", "--", "{files}"],
3202
+ outputFile: "jscpd-report.json",
3203
+ needsBuild: false,
3204
+ acceptedExitCodes: [0, 1],
3205
+ parser: "jscpd-json",
3206
+ scope: "files",
3207
+ extensions: LIZARD_EXT
3208
+ }
3209
+ ];
3210
+
3211
+ // plugins/code-challenge/opencode/src/scan/safe.ts
3212
+ import { closeSync as closeSync2, constants as constants3, lstatSync as lstatSync6, mkdirSync as mkdirSync3, openSync as openSync2, writeSync } from "fs";
3213
+ import { join as join8 } from "path";
3214
+ function ensureDir(base, ...segments) {
3215
+ let current = base;
3216
+ for (const segment of ["", ...segments]) {
3217
+ current = segment === "" ? base : join8(current, segment);
3218
+ try {
3219
+ mkdirSync3(current, { mode: 448 });
3220
+ } catch (error) {
3221
+ if (error.code !== "EEXIST")
3222
+ throw error;
3223
+ }
3224
+ if (!lstatSync6(current).isDirectory())
3225
+ throw new Error(`challenge_scan: refusing to use ${current}: not a real directory`);
3226
+ }
3227
+ return current;
3228
+ }
3229
+ function writeFileNoFollow(path, data) {
3230
+ const fd = openSync2(path, constants3.O_WRONLY | constants3.O_CREAT | constants3.O_TRUNC | constants3.O_NOFOLLOW, 384);
3231
+ try {
3232
+ writeSync(fd, data);
3233
+ } finally {
3234
+ closeSync2(fd);
3235
+ }
3236
+ }
3237
+
3238
+ // plugins/code-challenge/opencode/src/scan/run.ts
3239
+ var DEFAULT_TIMEOUT_SECONDS = 120;
3240
+ var MAX_TIMEOUT_SECONDS = 900;
3241
+ function validRunId(runId) {
3242
+ return /^\w[\w.-]{0,63}$/.test(runId);
3243
+ }
3244
+ function resolveTool(recipe, which, toolsDir) {
3245
+ if (recipe.install === "tool-dir") {
3246
+ if (toolsDir === "")
3247
+ return { gap: `${recipe.tool} needs a tools directory under the git dir, and the root is not a git repository` };
3248
+ const bin = join9(toolsDir, "node_modules", ".bin", recipe.binary);
3249
+ return existsSync(bin) ? { prefix: [bin], oneOff: false } : {
3250
+ gap: `${recipe.tool} is not provisioned; run "bun add eslint@${pinOf("eslint")} @e18e/eslint-plugin@${pinOf("@e18e/eslint-plugin")}" in ${toolsDir}`
3251
+ };
3252
+ }
3253
+ const local = which(recipe.binary);
3254
+ if (local)
3255
+ return { prefix: [local], oneOff: false };
3256
+ const pkg = recipe.package ?? recipe.binary;
3257
+ if (recipe.install === "bunx") {
3258
+ const bunx = which("bunx");
3259
+ if (bunx)
3260
+ return { prefix: [bunx, "-p", `${pkg}@${pinOf(pkg)}`, recipe.binary], oneOff: true };
3261
+ } else if (recipe.install === "uvx") {
3262
+ const uvx = which("uvx");
3263
+ if (uvx)
3264
+ return { prefix: [uvx, "--from", `${pkg}==${pinOf(pkg)}`, recipe.binary], oneOff: true };
3265
+ } else if (recipe.install === "go-run") {
3266
+ const go = which("go");
3267
+ if (go)
3268
+ return { prefix: [go, "run", `${recipe.subpath ? `${pkg}/${recipe.subpath}` : pkg}@${pinOf(pkg)}`], oneOff: true };
3269
+ }
3270
+ const runner = recipe.install === "local" ? "" : ` and no ${recipe.install} runner is on PATH`;
3271
+ return { gap: `${recipe.binary} is not installed${runner}` };
3272
+ }
3273
+ var RUNNER_NAME = { bunx: "bunx", uvx: "uvx", "go-run": "go run" };
3274
+ function risksOf(recipe, resolved) {
3275
+ const risks = [];
3276
+ if (recipe.executes)
3277
+ risks.push(recipe.executes);
3278
+ if (resolved.oneOff && recipe.install !== "local" && recipe.install !== "tool-dir") {
3279
+ const pkg = recipe.package ?? recipe.binary;
3280
+ const spec = recipe.install === "uvx" ? `${pkg}==${pinOf(pkg)}` : `${pkg}@${pinOf(pkg)}`;
3281
+ risks.push(`downloads and runs ${spec} with ${RUNNER_NAME[recipe.install]}; writes the package cache`);
3282
+ }
3283
+ return risks;
3284
+ }
3285
+ function expandArgs(recipe, cfg, out, files, root) {
3286
+ return recipe.args.flatMap((arg) => {
3287
+ if (arg === "{files}")
3288
+ return files.length > 0 ? files.map((f) => join9(root, f)) : ["."];
3289
+ return [arg.replaceAll("{cfg}", cfg).replaceAll("{out}", out)];
3290
+ });
3291
+ }
3292
+ function lensOf(recipe, rule) {
3293
+ for (const [pattern, lens] of recipe.lensRules ?? [])
3294
+ if (pattern.test(rule))
3295
+ return lens;
3296
+ return recipe.lenses[0] ?? "simplification";
3297
+ }
3298
+ var firstLine = (text) => text.trim().split(`
3299
+ `)[0]?.slice(0, 200) ?? "";
3300
+ var slug = (id) => id.replace(/[^\w.-]/g, "_");
3301
+ async function prepare(input, deps, signal) {
3302
+ const root = realpathSync2(resolve5(input.root ?? process.cwd()));
3303
+ if (!statSync3(root).isDirectory())
3304
+ throw new Error(`challenge_scan: root is not a directory: ${root}`);
3305
+ const exec = deps.exec ?? spawnTool;
3306
+ const which = deps.which ?? ((b) => Bun.which(b));
3307
+ if (input.runId !== undefined && !validRunId(input.runId))
3308
+ throw new Error(`challenge_scan: invalid runId "${input.runId}"`);
3309
+ const requested = input.files !== undefined && input.files.length > 0;
3310
+ let files = requested ? expandFiles(root, input.files ?? []) : [];
3311
+ const nothing = requested && files.length === 0;
3312
+ const git = nothing ? { kind: "none" } : await gitState(root, exec, which, signal);
3313
+ let listed;
3314
+ const listing = () => {
3315
+ listed ??= gitListing(root, git, exec, which, signal);
3316
+ return listed;
3317
+ };
3318
+ let ignoreError = null;
3319
+ if (files.length > 0) {
3320
+ const known = await listing();
3321
+ if (known.kind === "files") {
3322
+ const set = new Set(known.files);
3323
+ files = files.filter((f) => set.has(f));
3324
+ } else if (known.kind === "error")
3325
+ ignoreError = known.reason;
3326
+ }
3327
+ return {
3328
+ root,
3329
+ exec,
3330
+ which,
3331
+ now: deps.now ?? Date.now,
3332
+ depth: input.depth ?? "standard",
3333
+ lenses: input.lenses && input.lenses.length > 0 ? input.lenses : LENSES,
3334
+ timeoutMs: Math.min(input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS, MAX_TIMEOUT_SECONDS) * 1000,
3335
+ files,
3336
+ languages: input.languages && input.languages.length > 0 ? input.languages : detectLanguages(root, files),
3337
+ git,
3338
+ toolsDir: deps.toolsDir ?? (git.kind === "repo" ? join9(git.dir, "code-challenge", "tools") : ""),
3339
+ hasGitignore: lstatOrNull(join9(root, ".gitignore"))?.isFile() === true,
3340
+ emptySelection: requested && files.length === 0,
3341
+ listing,
3342
+ ignoreError,
3343
+ signal
3344
+ };
3345
+ }
3346
+ function plan(p) {
3347
+ const items = [];
3348
+ for (const recipe of RECIPES) {
3349
+ if (recipe.language !== "any" && !p.languages.includes(recipe.language))
3350
+ continue;
3351
+ if (recipe.language === "any" && p.languages.length === 0)
3352
+ continue;
3353
+ const skip = (reason) => items.push({ recipe, status: "skipped", reason });
3354
+ if (!recipe.lenses.some((l) => p.lenses.includes(l))) {
3355
+ skip("serves none of the requested lenses");
3356
+ continue;
3357
+ }
3358
+ if (p.depth === "quick" && recipe.needsBuild) {
3359
+ skip("needs a build; skipped at quick depth");
3360
+ continue;
3361
+ }
3362
+ const missing = missingMarker(p.root, recipe.requiresMarker);
3363
+ if (missing) {
3364
+ skip(missing);
3365
+ continue;
3366
+ }
3367
+ let scoped = [];
3368
+ if (recipe.scope === "files" && p.files.length > 0) {
3369
+ if (p.ignoreError) {
3370
+ items.push({ recipe, status: "gap", reason: `the repository's ignore files could not be applied to the named files: ${p.ignoreError}` });
3371
+ continue;
3372
+ }
3373
+ scoped = p.files.filter((f) => !recipe.extensions || recipe.extensions.includes(extname2(f)));
3374
+ if (scoped.length === 0) {
3375
+ skip("no matching files in the file list");
3376
+ continue;
3377
+ }
3378
+ }
3379
+ const resolved = resolveTool(recipe, p.which, p.toolsDir);
3380
+ if ("gap" in resolved) {
3381
+ items.push({ recipe, status: "gap", reason: resolved.gap });
3382
+ continue;
3383
+ }
3384
+ items.push({ recipe, status: "ready", resolved, scoped, risks: risksOf(recipe, resolved) });
3385
+ }
3386
+ return items;
3387
+ }
3388
+ function ensureToolsDir(p) {
3389
+ return p.git.kind === "repo" && p.toolsDir === join9(p.git.dir, "code-challenge", "tools") ? ensureDir(p.git.dir, "code-challenge", "tools") : ensureDir(p.toolsDir);
3390
+ }
3391
+ var MiB = 1024 * 1024;
3392
+ var MAX_ARGV_BYTES = 256 * 1024;
3393
+ function readReport(path, name) {
3394
+ const read = readText(path, MAX_STDOUT_BYTES);
3395
+ if (read.kind === "text")
3396
+ return { text: read.text };
3397
+ return {
3398
+ gap: read.kind === "absent" ? `the report file ${name} was not written` : `the report file ${name} is not a regular file under ${MAX_STDOUT_BYTES / MiB} MiB`
3399
+ };
3400
+ }
3401
+ async function runScan(input, deps = {}, signal) {
3402
+ const p = await prepare(input, deps, signal);
3403
+ const { root, exec, depth } = p;
3404
+ if (p.emptySelection) {
3405
+ const coverage = [
3406
+ { recipe: "*", tool: "-", language: "-", status: "skipped", reason: "the file list matched no files" }
3407
+ ];
3408
+ return { root, languages: [], depth, candidates: [], coverage, timings: [], rawDir: null };
3409
+ }
3410
+ if (input.runId !== undefined && p.git.kind !== "repo") {
3411
+ throw new Error(`challenge_scan: runId needs a git repository for the output directory${p.git.kind === "error" ? ` (${p.git.reason})` : ""}`);
3412
+ }
3413
+ const base = input.runId !== undefined && p.git.kind === "repo" ? ensureDir(p.git.dir, "code-challenge", input.runId, "scan") : mkdtempSync(join9(tmpdir(), "code-challenge-scan-"));
3414
+ const rawDir = input.runId !== undefined && p.git.kind === "repo" ? base : null;
3415
+ const fileSet = new Set(p.files);
3416
+ const coverage = [];
3417
+ const timings = [];
3418
+ const candidates = [];
3419
+ try {
3420
+ for (const item of plan(p)) {
3421
+ const { recipe } = item;
3422
+ const entry = (status, reason) => {
3423
+ coverage.push({ recipe: recipe.id, tool: recipe.tool, language: recipe.language, status, ...reason ? { reason } : {} });
3424
+ };
3425
+ if (item.status !== "ready") {
3426
+ entry(item.status, item.reason);
3427
+ continue;
3428
+ }
3429
+ if (item.risks.length > 0 && input.allowCode !== true) {
3430
+ entry("gap", `not run without allowCode: ${item.risks.join("; ")}; pass allowCode: true to run it`);
3431
+ continue;
3432
+ }
3433
+ if (signal?.aborted) {
3434
+ entry("skipped", "scan aborted");
3435
+ continue;
3436
+ }
3437
+ const name = slug(recipe.id);
3438
+ const fromConfigDir = (recipe.repoConfigNames ?? []).some((n) => lstatOrNull(join9(root, n)) !== null);
3439
+ let files = item.scoped;
3440
+ if (fromConfigDir) {
3441
+ const known = await p.listing();
3442
+ if (known.kind === "error") {
3443
+ entry("gap", `the repository's ignore files could not be applied: ${known.reason}`);
3444
+ continue;
3445
+ }
3446
+ const all = known.kind === "files" ? known.files : expandFiles(root, ["."]);
3447
+ files = p.files.length > 0 ? item.scoped : all.filter((f) => !recipe.extensions || recipe.extensions.includes(extname2(f)));
3448
+ if (files.length === 0) {
3449
+ entry("skipped", "no matching files outside the repo's ignore files");
3450
+ continue;
3451
+ }
3452
+ if (files.reduce((n, f) => n + root.length + f.length + 2, 0) > MAX_ARGV_BYTES) {
3453
+ entry("gap", `too many files to name on one command line in isolated mode (${files.length}); pass a narrower file list`);
3454
+ continue;
3455
+ }
3456
+ }
3457
+ const cfg = recipe.install === "tool-dir" ? ensureToolsDir(p) : ensureDir(base, "cfg", name);
3458
+ const out = ensureDir(base, "out", name);
3459
+ if (recipe.outputFile)
3460
+ rmSync(join9(out, recipe.outputFile), { recursive: true, force: true });
3461
+ for (const [file, content] of Object.entries(recipe.configFiles?.({ root, hasGitignore: p.hasGitignore, toolsDir: p.toolsDir, fromConfigDir }) ?? {})) {
3462
+ writeFileNoFollow(join9(cfg, file), content);
3463
+ }
3464
+ const argv = [...item.resolved.prefix, ...expandArgs(recipe, cfg, out, files, root)];
3465
+ const started = p.now();
3466
+ const run = await exec(argv, { cwd: fromConfigDir ? cfg : root, timeoutMs: p.timeoutMs, signal });
3467
+ timings.push({ recipe: recipe.id, tool: recipe.tool, ms: p.now() - started, exitCode: run.kind === "exited" ? run.exitCode : null });
3468
+ writeFileNoFollow(join9(base, `${name}.stdout`), run.stdout);
3469
+ writeFileNoFollow(join9(base, `${name}.stderr`), run.stderr);
3470
+ if (run.kind === "timeout") {
3471
+ entry("gap", `timed out after ${p.timeoutMs / 1000}s`);
3472
+ continue;
3473
+ }
3474
+ if (run.kind === "aborted") {
3475
+ entry("skipped", "scan aborted");
3476
+ continue;
3477
+ }
3478
+ if (run.kind === "overflow") {
3479
+ const cap = run.stream === "stdout" ? MAX_STDOUT_BYTES : MAX_STDERR_BYTES;
3480
+ entry("gap", `${run.stream} exceeded ${cap / MiB} MiB; the tool was ended`);
3481
+ continue;
3482
+ }
3483
+ if (run.kind === "lost") {
3484
+ entry("gap", "the process vanished without an exit status");
3485
+ continue;
3486
+ }
3487
+ if (!recipe.acceptedExitCodes.includes(run.exitCode)) {
3488
+ entry("gap", `exit ${run.exitCode}: ${firstLine(run.stderr || run.stdout)}`);
3489
+ continue;
3490
+ }
3491
+ let text = run.stdout;
3492
+ if (recipe.outputFile) {
3493
+ const report = readReport(join9(out, recipe.outputFile), recipe.outputFile);
3494
+ if ("gap" in report) {
3495
+ entry("gap", report.gap);
3496
+ continue;
3497
+ }
3498
+ text = report.text;
3499
+ }
3500
+ let hits;
3501
+ try {
3502
+ hits = parseOutput(recipe.parser, text, { root, cwd: root });
3503
+ } catch (error) {
3504
+ if (!(error instanceof OutputError))
3505
+ throw error;
3506
+ entry("gap", `unparseable output: ${error.message}`);
3507
+ continue;
3508
+ }
3509
+ if (fileSet.size > 0 && recipe.scope === "repo")
3510
+ hits = hits.filter((h) => h.file !== null && fileSet.has(h.file));
3511
+ const probe = hits.length > 0 ? probeFor(recipe, { root, prefix: item.resolved.prefix, exec, timeoutMs: p.timeoutMs, signal }) : null;
3512
+ const enabled = probe ? await probe(hits) : null;
3513
+ for (const hit of hits) {
3514
+ const lens = lensOf(recipe, hit.rule);
3515
+ if (!p.lenses.includes(lens))
3516
+ continue;
3517
+ candidates.push({
3518
+ lens,
3519
+ tool: recipe.tool,
3520
+ rule: hit.rule,
3521
+ file: hit.file,
3522
+ line: hit.line,
3523
+ message: hit.message,
3524
+ ruleEnabledInRepo: enabled ? enabled(hit) : null
3525
+ });
3526
+ }
3527
+ entry("ran");
3528
+ }
3529
+ } finally {
3530
+ if (rawDir === null)
3531
+ rmSync(base, { recursive: true, force: true });
3532
+ }
3533
+ const byFile = (a, b) => (a.file ?? "").localeCompare(b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || a.rule.localeCompare(b.rule);
3534
+ candidates.sort(byFile);
3535
+ return { root, languages: p.languages, depth, candidates, coverage, timings, rawDir };
3536
+ }
3537
+
3538
+ // plugins/code-challenge/opencode/src/scan/index.ts
3539
+ var SCAN_TOOL = "challenge_scan";
3540
+ var MAX_INLINE_CANDIDATES = 500;
3541
+ var SCAN_DESCRIPTION = `Run existing static analyzers in a lens profile and return normalised code-challenge candidates.
3542
+ ` + "By default only recipes that execute no repository or downloaded code run; the others are coverage gaps that " + "name what they would run. allowCode=true also runs them: clippy builds the crate (build scripts, proc macros; " + "writes target/), golangci-lint and deadcode compile Go, knip and import-linter load repo config code, and one-off " + "bunx/uvx/go runs download and run pinned packages. Pass allowCode only for a repository the user trusts. " + "Hits carry lens, tool, rule, file, line, message, ruleEnabledInRepo. Quick depth skips build-backed analyzers. " + "With runId, raw output goes to <git-dir>/code-challenge/<runId>/scan/.";
3543
+ var SCAN_INPUT = {
3544
+ type: "object",
3545
+ properties: {
3546
+ root: { type: "string", description: "Target root; defaults to the session directory" },
3547
+ files: { type: "array", items: { type: "string" }, description: "Files, directories or globs to scope the scan" },
3548
+ languages: { type: "array", items: { enum: [...LANGUAGES] }, description: "Languages; auto-detected by default" },
3549
+ lenses: { type: "array", items: { enum: [...LENSES] }, description: "Lenses to keep; all by default" },
3550
+ depth: { enum: [...DEPTHS2], description: "quick skips analyzers that need a build; default standard" },
3551
+ timeoutSeconds: { type: "number", maximum: 900, description: "Per-analyzer timeout in seconds; default 120, at most 900" },
3552
+ runId: { type: "string", description: "Run id; raw outputs go to <git-dir>/code-challenge/<runId>/scan/" },
3553
+ allowCode: { type: "boolean", description: "Also run analyzers that execute repo or downloaded code; only for a trusted repo" }
3554
+ },
3555
+ additionalProperties: false
3556
+ };
3557
+ function pick(name, value, allowed) {
3558
+ if (value === undefined)
3559
+ return;
3560
+ const known = (v) => typeof v === "string" && allowed.includes(v);
3561
+ if (!Array.isArray(value) || !value.every(known))
3562
+ return `${name} must be a list of: ${allowed.join(", ")}`;
3563
+ return value;
3564
+ }
3565
+ function readScanInput(raw, base) {
3566
+ const input = typeof raw === "object" && raw !== null ? raw : {};
3567
+ const root = typeof input.root === "string" && input.root !== "" ? input.root : base;
3568
+ const timeout = input.timeoutSeconds;
3569
+ if (timeout !== undefined && (typeof timeout !== "number" || !(timeout > 0)))
3570
+ return "timeoutSeconds must be a positive number";
3571
+ if (input.runId !== undefined && (typeof input.runId !== "string" || !validRunId(input.runId))) {
3572
+ return "runId must be 1-64 characters of letters, digits, underscore, dot or dash, starting with a letter, digit or underscore";
3573
+ }
3574
+ if (input.depth !== undefined && !DEPTHS2.includes(input.depth))
3575
+ return `depth must be one of ${DEPTHS2.join(", ")}`;
3576
+ if (input.allowCode !== undefined && typeof input.allowCode !== "boolean")
3577
+ return "allowCode must be a boolean";
3578
+ const languages = pick("languages", input.languages, LANGUAGES);
3579
+ if (typeof languages === "string")
3580
+ return languages;
3581
+ const lenses = pick("lenses", input.lenses, LENSES);
3582
+ if (typeof lenses === "string")
3583
+ return lenses;
3584
+ const files = Array.isArray(input.files) ? input.files.filter((f) => typeof f === "string") : undefined;
3585
+ return {
3586
+ root: isAbsolute4(root) ? root : resolve6(base, root),
3587
+ files,
3588
+ languages,
3589
+ lenses,
3590
+ depth: input.depth,
3591
+ timeoutSeconds: timeout,
3592
+ runId: input.runId,
3593
+ allowCode: input.allowCode === true ? true : undefined
3594
+ };
3595
+ }
3596
+ function formatScan(report) {
3597
+ const truncated = report.candidates.length > MAX_INLINE_CANDIDATES;
3598
+ const shown = truncated ? report.candidates.slice(0, MAX_INLINE_CANDIDATES) : report.candidates;
3599
+ return JSON.stringify({ ...report, candidates: shown, candidateCount: report.candidates.length, truncated }, null, 1);
3600
+ }
3601
+ async function runScanTool(raw, call, deps = {}) {
3602
+ const base = await call.directory();
3603
+ const parsed = readScanInput(raw, base);
3604
+ if (typeof parsed === "string")
3605
+ return { content: `${SCAN_TOOL}: ${parsed}`, metadata: { ok: false } };
3606
+ try {
3607
+ const report = await runScan({ ...parsed, root: realpathSync3(parsed.root ?? base) }, deps, call.signal);
3608
+ return { content: formatScan(report), metadata: { ok: true, candidates: report.candidates.length, coverage: report.coverage } };
3609
+ } catch (error) {
3610
+ return { content: `${SCAN_TOOL}: ${error.message}`, metadata: { ok: false } };
3611
+ }
3612
+ }
3613
+
3614
+ // plugins/code-challenge/opencode/src/validate.ts
3615
+ import { execFileSync } from "child_process";
3616
+ import { realpathSync as realpathSync4 } from "fs";
3617
+ import { dirname as dirname3, isAbsolute as isAbsolute5, join as join10, relative as relative3, sep as sep2 } from "path";
3618
+ import { fileURLToPath as fileURLToPath2 } from "url";
3619
+
3620
+ // plugins/code-challenge/opencode/src/json-schema.ts
3621
+ var ANNOTATIONS = new Set(["$schema", "$id", "title", "description", "$defs"]);
3622
+ var KEYWORDS = new Set([
3623
+ "type",
3624
+ "enum",
3625
+ "required",
3626
+ "properties",
3627
+ "additionalProperties",
3628
+ "items",
3629
+ "minItems",
3630
+ "minimum",
3631
+ "minLength",
3632
+ "pattern",
3633
+ "$ref"
3634
+ ]);
3635
+ function validate(schema, value, root = schema, at = "$") {
3636
+ for (const key of Object.keys(schema))
3637
+ if (!KEYWORDS.has(key) && !ANNOTATIONS.has(key))
3638
+ throw new Error(`unsupported schema keyword: ${key}`);
3639
+ if (schema.$ref !== undefined) {
3640
+ const target = schema.$ref.replace(/^#\/\$defs\//, "");
3641
+ const resolved = root.$defs?.[target];
3642
+ if (!resolved)
3643
+ throw new Error(`unresolved reference: ${schema.$ref}`);
3644
+ return validate(resolved, value, root, at);
3645
+ }
3646
+ const errors = [];
3647
+ if (schema.enum && !schema.enum.includes(value))
3648
+ errors.push(`${at}: ${JSON.stringify(value)} is not one of ${JSON.stringify(schema.enum)}`);
3649
+ const kind = Array.isArray(value) ? "array" : value === null ? "null" : typeof value;
3650
+ const matches = (type) => type === "integer" ? Number.isInteger(value) : type === "number" ? kind === "number" : type === kind;
3651
+ if (schema.type && !matches(schema.type))
3652
+ return [...errors, `${at}: expected ${schema.type}, got ${kind}`];
3653
+ if (typeof value === "string") {
3654
+ if (schema.minLength !== undefined && value.length < schema.minLength)
3655
+ errors.push(`${at}: shorter than ${schema.minLength}`);
3656
+ if (schema.pattern !== undefined && !new RegExp(schema.pattern).test(value))
3657
+ errors.push(`${at}: does not match ${schema.pattern}`);
3658
+ }
3659
+ if (typeof value === "number" && schema.minimum !== undefined && value < schema.minimum)
3660
+ errors.push(`${at}: below ${schema.minimum}`);
3661
+ if (Array.isArray(value)) {
3662
+ if (schema.minItems !== undefined && value.length < schema.minItems)
3663
+ errors.push(`${at}: fewer than ${schema.minItems} items`);
3664
+ for (const [index, item] of value.entries())
3665
+ if (schema.items)
3666
+ errors.push(...validate(schema.items, item, root, `${at}[${index}]`));
3667
+ }
3668
+ if (kind === "object") {
3669
+ const record = value;
3670
+ for (const key of schema.required ?? [])
3671
+ if (!(key in record))
3672
+ errors.push(`${at}: missing ${key}`);
3673
+ for (const [key, entry] of Object.entries(record)) {
3674
+ const property = schema.properties?.[key];
3675
+ if (property)
3676
+ errors.push(...validate(property, entry, root, `${at}.${key}`));
3677
+ else if (schema.additionalProperties === false)
3678
+ errors.push(`${at}: unexpected property ${key}`);
3679
+ }
3680
+ }
3681
+ return errors;
3682
+ }
3683
+
3684
+ // plugins/code-challenge/opencode/src/validate.ts
3685
+ var VALIDATE_TOOL = "challenge_validate";
3686
+ var MAX_RUN_FILE_BYTES = 1024 * 1024;
3687
+ var VALIDATE_DESCRIPTION = `Validate a code-challenge run's report.json and decisions.jsonl against the shipped JSON Schemas.
3688
+ ` + "Takes the absolute run directory, which must sit directly under <git-dir>/code-challenge/ of the session's repository. " + "Reads only those two regular files (at most 1 MiB each), lists every error as file, path and message, and " + "reports ok=false when a file is missing, oversized or invalid.";
3689
+ var VALIDATE_INPUT = {
3690
+ type: "object",
3691
+ properties: { run_dir: { type: "string", description: "Absolute path of the run directory" } },
3692
+ required: ["run_dir"],
3693
+ additionalProperties: false
3694
+ };
3695
+ var SCHEMAS = join10(dirname3(fileURLToPath2(import.meta.url)), "..", "skills", "code-challenge", "references");
3696
+ var load = (name) => JSON.parse(readBoundedText(join10(SCHEMAS, name)));
3697
+ function failure(read) {
3698
+ if (read.kind === "absent")
3699
+ return "ENOENT: no such file or directory";
3700
+ if (read.reason === "not-regular")
3701
+ return "not a regular file";
3702
+ if (read.reason === "too-large")
3703
+ return `larger than ${MAX_RUN_FILE_BYTES} bytes`;
3704
+ return `${read.code ?? "EIO"}: cannot be read`;
3705
+ }
3706
+ function readBoundedText(path) {
3707
+ const read = readBoundedBytes(path, MAX_RUN_FILE_BYTES);
3708
+ if (read.kind !== "bytes")
3709
+ throw new Error(`${path}: ${failure(read)}`);
3710
+ return read.bytes.toString("utf8");
3711
+ }
3712
+ var reason = (cause) => cause instanceof Error ? cause.message : String(cause);
3713
+ function validateRun(runDir) {
3714
+ const errors = [];
3715
+ const read = (name) => {
3716
+ const result = readBoundedBytes(join10(runDir, name), MAX_RUN_FILE_BYTES);
3717
+ if (result.kind === "bytes")
3718
+ return result.bytes.toString("utf8");
3719
+ errors.push(`${name}: ${failure(result)}`);
3720
+ return;
3721
+ };
3722
+ const report = read("report.json");
3723
+ if (report !== undefined) {
3724
+ try {
3725
+ for (const error of validate(load("report.schema.json"), JSON.parse(report)))
3726
+ errors.push(`report.json ${error}`);
3727
+ } catch (cause) {
3728
+ errors.push(`report.json: ${reason(cause)}`);
3729
+ }
3730
+ }
3731
+ const decisions = read("decisions.jsonl");
3732
+ if (decisions !== undefined) {
3733
+ const schema = load("decisions.schema.json");
3734
+ const lines = decisions.split(`
3735
+ `);
3736
+ lines.forEach((text, index) => {
3737
+ if (text.trim() === "")
3738
+ return;
3739
+ try {
3740
+ for (const error of validate(schema, JSON.parse(text)))
3741
+ errors.push(`decisions.jsonl:${index + 1} ${error}`);
3742
+ } catch (cause) {
3743
+ errors.push(`decisions.jsonl:${index + 1}: ${reason(cause)}`);
3744
+ }
3745
+ });
3746
+ if (lines.every((text) => text.trim() === ""))
3747
+ errors.push("decisions.jsonl: has no lines");
3748
+ }
3749
+ return errors;
3750
+ }
3751
+ function runRoots(directory) {
3752
+ const out = execFileSync("git", ["rev-parse", "--path-format=absolute", "--git-dir", "--git-common-dir"], {
3753
+ cwd: directory,
3754
+ encoding: "utf8",
3755
+ timeout: 5000,
3756
+ stdio: ["ignore", "pipe", "ignore"]
3757
+ });
3758
+ const roots = new Set;
3759
+ for (const gitDir of out.split(`
3760
+ `).filter(Boolean)) {
3761
+ try {
3762
+ roots.add(join10(realpathSync4(gitDir), "code-challenge"));
3763
+ } catch {}
3764
+ }
3765
+ return [...roots];
3766
+ }
3767
+ function resolveRunDir(directory, runDir) {
3768
+ const inside = `${VALIDATE_TOOL}: run_dir must be inside <git-dir>/code-challenge/ of the session's repository`;
3769
+ if (typeof runDir !== "string" || !isAbsolute5(runDir))
3770
+ return { error: `${VALIDATE_TOOL}: run_dir must be an absolute path` };
3771
+ if (runDir.split(/[\\/]/).includes(".."))
3772
+ return { error: inside };
3773
+ let roots;
3774
+ let real;
3775
+ try {
3776
+ roots = runRoots(directory);
3777
+ real = realpathSync4(runDir);
3778
+ } catch (cause) {
3779
+ return { error: `${VALIDATE_TOOL}: cannot resolve run_dir: ${reason(cause).split(",")[0]}` };
3780
+ }
3781
+ const direct = (root) => {
3782
+ const rel = relative3(root, real);
3783
+ return rel !== "" && !rel.startsWith("..") && !rel.includes(sep2) && !isAbsolute5(rel);
3784
+ };
3785
+ return roots.some(direct) ? { path: real } : { error: inside };
3786
+ }
3787
+ async function runValidate(input, call) {
3788
+ const keys = Object.keys(input ?? {});
3789
+ if (keys.length !== 1 || keys[0] !== "run_dir")
3790
+ return { content: `${VALIDATE_TOOL}: expected exactly { run_dir }`, metadata: { ok: false } };
3791
+ const resolved = resolveRunDir(await call.directory(), input.run_dir);
3792
+ if ("error" in resolved)
3793
+ return { content: resolved.error, metadata: { ok: false } };
3794
+ const errors = validateRun(resolved.path);
3795
+ return {
3796
+ content: errors.length === 0 ? "report.json and decisions.jsonl are valid" : errors.join(`
3797
+ `),
3798
+ metadata: { ok: errors.length === 0, errors }
3799
+ };
3800
+ }
3801
+
3802
+ // plugins/code-challenge/pi-src/index.ts
3803
+ function toToolResult(outcome) {
3804
+ return { content: [{ type: "text", text: outcome.content }], details: outcome.metadata };
3805
+ }
3806
+ function toolCall(ctx, signal) {
3807
+ return { directory: async () => ctx.cwd, signal };
3808
+ }
3809
+ var schema = (input) => input;
3810
+ function challengeTools(deps = {}) {
3811
+ return [
3812
+ {
3813
+ name: SETUP_TOOL,
3814
+ label: "Code challenge: install formulas",
3815
+ description: SETUP_DESCRIPTION,
3816
+ parameters: schema(SETUP_INPUT),
3817
+ approval: "write",
3818
+ execute: async (_id, params, signal, _onUpdate, ctx) => toToolResult(await runSetup(params, toolCall(ctx, signal)))
3819
+ },
3820
+ {
3821
+ name: LIB_FACTS_TOOL,
3822
+ label: "Code challenge: library facts",
3823
+ description: LIB_FACTS_DESCRIPTION,
3824
+ parameters: schema(LIB_FACTS_INPUT),
3825
+ approval: "read",
3826
+ execute: async (_id, params, signal) => toToolResult(await runLibFacts(params, { signal }))
3827
+ },
3828
+ {
3829
+ name: VALIDATE_TOOL,
3830
+ label: "Code challenge: validate run",
3831
+ description: VALIDATE_DESCRIPTION,
3832
+ parameters: schema(VALIDATE_INPUT),
3833
+ approval: "read",
3834
+ execute: async (_id, params, signal, _onUpdate, ctx) => toToolResult(await runValidate(params, toolCall(ctx, signal)))
3835
+ },
3836
+ {
3837
+ name: SCAN_TOOL,
3838
+ label: "Code challenge: scan",
3839
+ description: SCAN_DESCRIPTION,
3840
+ parameters: schema(SCAN_INPUT),
3841
+ approval: "exec",
3842
+ execute: async (_id, params, signal, _onUpdate, ctx) => toToolResult(await runScanTool(params, toolCall(ctx, signal), deps))
3843
+ }
3844
+ ];
3845
+ }
3846
+ function registerCodeChallenge(pi, deps = {}) {
3847
+ for (const tool of challengeTools(deps))
3848
+ pi.registerTool(tool);
3849
+ pi.registerCommand(COMMAND, {
3850
+ description: COMMAND_DESCRIPTION,
3851
+ handler: async (args) => pi.sendUserMessage(challengePrompt(args, "pi"))
3852
+ });
3853
+ }
3854
+ function codeChallenge(pi) {
3855
+ registerCodeChallenge(pi);
3856
+ }
3857
+ export {
3858
+ challengeTools,
3859
+ codeChallenge as default,
3860
+ registerCodeChallenge,
3861
+ toToolResult
3862
+ };