-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrecipe-run.ts
More file actions
1767 lines (1641 loc) · 85.1 KB
/
Copy pathrecipe-run.ts
File metadata and controls
1767 lines (1641 loc) · 85.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash } from "node:crypto"
import { readFileSync } from "node:fs"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import { createRequire } from "node:module"
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
import { DEFAULT_WORDPRESS_VERSION, createRuntime, normalizeRecipeRunSummary, normalizeRuntimeEnvRecord, parseCommandOptions, validateRuntimePolicy, type ArtifactBundle, type ArtifactPackageIdentity, type ArtifactPackageProvenance, type Runtime, type RuntimeAssetSpec, type RuntimePolicy, type RuntimePreviewSpec, type RuntimeRunRegistry, type WorkspaceRecipe, type WorkspaceRecipeComponentManifest, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeFixtureDatabase, type WorkspaceRecipeFuzzCasePhase } from "@automattic/wp-codebox-core"
import { stripUndefined } from "@automattic/wp-codebox-core/internals"
import { recipeExecutionSpec, sandboxWorkspaceContract } from "../agent-sandbox.js"
import { captureStdout, printRecipeHumanOutput, printRecipeValidateHumanOutput, serializeError } from "../output.js"
import { parsePreviewBind, parsePreviewHoldSeconds, parsePreviewLease, parsePreviewPort, parsePreviewPublicUrl } from "../preview-options.js"
import { dryRunRecipe, planWorkspaceRecipe, recipeDryRunSiteSeeds } from "../recipe-dry-run.js"
import { appendRecipeRuntimeEvidence, collectAndFinalizeFailedRecipeArtifacts, collectRecipeRuntimeArtifacts, finalizeAgentSandboxEvidence, finalizeRecipeArtifactEvidence, recipeAgentResultFailure, recipeArtifactEvidenceFailure, recipeReplayStatusOutput, recipeVerifyStepFailure } from "../recipe-evidence.js"
import { recipeExternalServiceBoundarySummaries } from "../recipe-external-services.js"
import { mergeRecipeSecretEnvSummary, resolveRecipeSecretEnv } from "../recipe-secret-env.js"
import type { PreparedRuntimeBackendPackage } from "../recipe-backend-package.js"
import { cleanupRecipePreparedSources, recipeBlueprintWithBootActivePlugins, recipeExtraPlugins, type PreparedDependencyOverlay, type PreparedExtraPlugin, type PreparedRuntimeOverlay, type PreparedStagedFile, type PreparedWorkspaceMount } from "../recipe-sources.js"
import { loadWorkspaceRecipe, recipePolicy, recipeWorkflowSteps, validateRecipeRuntimePolicy, validateWorkspaceRecipe, type RecipeWorkflowPhase } from "../recipe-validation.js"
import { resolveCliRuntimeBackend } from "../runtime-backends.js"
import { previewSpec, releaseRuntime, runtimeMetadata, type RunOutput } from "../runtime-command-wrappers.js"
import { artifactManifestFilesByPath, parseBenchResults, writeBenchmarkArtifactEvidence } from "./recipe-run-benchmark-artifacts.js"
import { createRecipeRunContext } from "./recipe-run-context.js"
import { collectRecipeDeclaredArtifacts, materializeTypedRecipeDeclaredArtifacts, recipeDeclaredArtifactFailure, recipeProbeFailure, recipeRuntimeEvidenceFiles } from "./recipe-declared-artifacts.js"
import { completedRecipeOutputFields, finalizeCompletedRecipeRun, finalizeRecipeValidationFailure, finalizeRecoveredRecipeFailure, runRecipeCleanup, RunResourceCleanupError, type RunResourceCleanupEvidence } from "./recipe-run-finalizer.js"
import { RecipeRunPhaseExecutor } from "./recipe-run-phase-executor.js"
import { RecipeArtifactsMountConflictError, recipeArtifactsMountConflict } from "./recipe-run-artifacts-mount-guard.js"
import { createRecipeInterruptionController, interruptedRecipeOutput, markRecipeArtifactsFinalized, recipeInterruptionSerializedError } from "./recipe-run-interruption.js"
import { bestEffortTimeout, exitAfterPlaygroundCliBootFailure, exitAfterRecipeRunTimeout, exitAfterTerminalRecipePhaseFailure, printJsonFailureDiagnostic, RecipeRunTimeoutError, RecipeRuntimeCreateError, serializeRecipeRunError, writeRecipeJsonOutput, writeRecipeSummaryHumanOutput } from "./recipe-run-output.js"
import { RecipePhaseError } from "./recipe-run-phases.js"
import { markPreviewLeaseAvailable, markPreviewLeaseFailed, markPreviewLeaseReleased, startPreviewLeaseRecipeRun } from "./preview-lease.js"
import { importRecipeSiteSeeds } from "./recipe-site-seeds.js"
import { applyRecipeRuntimeSetup, cleanupInputMountBaselines, prepareRecipeRuntimeSetup, recipeRunDependencyOverlay, recipeRunExtraPlugin, recipeRunStagedFile, rewriteInputMountPathArgs } from "./recipe-runtime-setup.js"
import { provisionRuntimeServices, provisionRuntimeServicesForRecipe, runtimeServiceEvidenceFromError, type RuntimeServiceEvidence } from "../runtime-services.js"
import { distributionStartupProbeFailure, executeRecipeCollectWorkloadResult, executeRecipeWorkflowStep, recipeAdvisoryFailure, recipeBrowserEvidence, recipeStepFailure, recipeWorkflowArgsEvidence, recipeWorkflowStepIsAdvisory, runDistributionSetupArtifacts, runDistributionStartupProbes, runRecipeProbes, withRecipeExecutionPhase } from "./recipe-run-workflow-evidence.js"
import { recipeAdversarialCampaignFailure, runRecipeAdversarialCampaigns, writeRecipeAdversarialEvidence, type RecipeAdversarialCampaignOutput } from "../adversarial-recipe.js"
import type { RecipeAdvisoryFailure, RecipeBrowserEvidence, RecipeDiagnosticArtifactRef, RecipeEffectiveRecipeArtifact, RecipeExecutionResult, RecipeFuzzCaseCommandRef, RecipeFuzzCaseResult, RecipeFuzzCaseStatus, RecipeFuzzRunResult, RecipeInterruptionController, RecipePhaseEvidence, RecipePhaseName, RecipePhpWasmRuntimeDiagnostic, RecipeRunCommandOutput, RecipeRunComponentContract, RecipeRunDeclaredArtifact, RecipeRunDistributionSetupArtifact, RecipeRunDistributionStartupProbe, RecipeRunFixtureDatabase, RecipeRunOptions, RecipeRunOutput, RecipeRunProbe, RecipeRunProvenance, RecipeRunStagedFile, RecipeRuntimeDiagnostic, RecipeStepFailure, RecipeValidateOptions, RecipeValidateOutput } from "./recipe-run-types.js"
const DEFAULT_RECIPE_RUN_TIMEOUT_MS = 25 * 60 * 1000
const SUCCESSFUL_RECIPE_RUNTIME_SNAPSHOT_TIMEOUT_MS = 120 * 1000
const packageRequire = createRequire(import.meta.url)
export async function runRecipeRunCommand(args: string[]): Promise<number> {
const options = parseRecipeRunOptions(args)
if (options.previewLeaseRequested && !options.previewLeaseChild) {
return startPreviewLeaseRecipeRun({ args, json: options.json, recipePath: options.recipePath, artifactsDirectory: options.artifactsDirectory, runRegistryDirectory: options.runRegistryDirectory, previewHoldSeconds: options.previewHoldSeconds })
}
const interruption = options.dryRun ? undefined : createRecipeInterruptionController()
interruption?.install()
const execute = (): Promise<RecipeRunCommandOutput> => options.dryRun ? dryRunRecipe(options, { defaultWordPressVersion: DEFAULT_WORDPRESS_VERSION, resolveExecutionSpec: recipeExecutionSpec }) : runRecipe(options, interruption)
try {
if (options.summary) {
const { result } = await captureStdout(execute)
const output = interruptedRecipeOutput(result, interruption)
const summary = normalizeRecipeRunSummary(output)
if (options.json) await writeRecipeJsonOutput(summary)
else await writeRecipeSummaryHumanOutput(summary)
interruption?.propagateIfInterrupted()
exitAfterRecipeRunTimeout(output)
exitAfterPlaygroundCliBootFailure(output)
exitAfterTerminalRecipePhaseFailure(output)
return output.success ? 0 : 1
}
if (!options.json) {
const output = interruptedRecipeOutput(await execute(), interruption)
printRecipeHumanOutput(output)
interruption?.propagateIfInterrupted()
exitAfterRecipeRunTimeout(output)
exitAfterPlaygroundCliBootFailure(output)
exitAfterTerminalRecipePhaseFailure(output)
return output.success ? 0 : 1
}
const { result, logs } = await captureStdout(execute)
const interruptedResult = interruptedRecipeOutput(result, interruption)
const output = logs.length > 0 ? { ...interruptedResult, logs } : interruptedResult
await writeRecipeJsonOutput(output)
printJsonFailureDiagnostic(output)
interruption?.propagateIfInterrupted()
exitAfterRecipeRunTimeout(output)
exitAfterPlaygroundCliBootFailure(output)
exitAfterTerminalRecipePhaseFailure(output)
return output.success ? 0 : 1
} finally {
interruption?.dispose()
}
}
export async function runRecipeValidateCommand(args: string[]): Promise<number> {
const options = parseRecipeValidateOptions(args)
const output = await validateRecipe(options)
if (!options.json) {
printRecipeValidateHumanOutput(output)
return output.success ? 0 : 1
}
await writeRecipeJsonOutput(output)
return output.success ? 0 : 1
}
export async function runRecipe(options: RecipeRunOptions, interruption?: RecipeInterruptionController): Promise<RecipeRunOutput> {
const mountConflictFailure = await recipeArtifactsMountConflictFailure(options)
if (mountConflictFailure) {
return mountConflictFailure
}
const context = await createRecipeRunContext(options)
const { recipePath, recipeDirectory, recipe, configuredArtifactsDirectory, runRegistry, artifactPointer, startedAtMs } = context
let { runRecord } = context
runRecord = await runRegistry.update(runRecord.runId, { metadata: { provenance: recipeRunProvenance(recipe, recipePath) } })
await artifactPointer.update({ commandStatus: "queued" })
const issues = [
...await validateWorkspaceRecipe(recipe, recipePath),
...validateRecipeRuntimePolicy(recipe, options.policy ?? recipePolicy(recipe, recipeDirectory), recipeDirectory),
]
if (issues.length > 0) {
const failure = {
name: "RecipeValidationError",
message: `Recipe validation failed with ${issues.length} issue${issues.length === 1 ? "" : "s"}.`,
issues,
}
return await finalizeRecipeValidationFailure({
recipePath,
runRegistry,
runRecord,
artifactPointer,
startedAtMs,
failure,
componentContracts: componentContractResults(recipe, [], [], [], failure),
validation: { issues },
provenance: recipeRunProvenance(recipe, recipePath),
})
}
const plan = await planWorkspaceRecipe(recipe, recipeDirectory, { recipePath, artifactsDirectory: configuredArtifactsDirectory }, { defaultWordPressVersion: DEFAULT_WORDPRESS_VERSION, resolveExecutionSpec: recipeExecutionSpec })
const { valid: _policyValid, issues: _policyIssues, ...plannedPolicy } = plan.policy
const policy = options.policy ?? plannedPolicy
const runtimeEnv = {
...distributionRuntimeEnv(recipe),
...normalizeRuntimeEnv(recipe.inputs?.runtimeEnv ?? {}),
}
const secretEnvResolution = resolveRecipeSecretEnv(recipe.inputs?.secretEnv ?? [], { field: "--secret-env name" })
const secretEnv = secretEnvResolution.values
let secretEnvSummary = secretEnvResolution.summary
let effectivePolicy = Object.keys(secretEnv).length > 0 ? { ...policy, secrets: "connector-scoped" as const } : policy
let workspaceMounts: PreparedWorkspaceMount[] = []
let extraPlugins: PreparedExtraPlugin[] = []
let dependencyOverlays: PreparedDependencyOverlay[] = []
let stagedFiles: PreparedStagedFile[] = []
let overlays: PreparedRuntimeOverlay[] = []
let inputMountBaselinePaths: string[] = []
let inputMountPathMap: NonNullable<Awaited<ReturnType<typeof prepareRecipeRuntimeSetup>>["inputMountPathMap"]> = []
let backendPackage: PreparedRuntimeBackendPackage | undefined
let runtime: Awaited<ReturnType<typeof createRuntime>> | undefined
const executions: RecipeExecutionResult[] = []
let fixtureDatabases: RecipeRunFixtureDatabase[] = []
let distributionSetupArtifacts: RecipeRunDistributionSetupArtifact[] = []
let distributionStartupProbes: RecipeRunDistributionStartupProbe[] = []
let probes: RecipeRunProbe[] = []
let declaredArtifacts: RecipeRunDeclaredArtifact[] = []
let adversarialCampaigns: RecipeAdversarialCampaignOutput[] = []
let stepFailures: RecipeStepFailure[] = []
let advisoryFailures: RecipeAdvisoryFailure[] = []
let browserEvidence: RecipeBrowserEvidence[] = []
let artifacts: ArtifactBundle | undefined
let startupDurationMs: number | undefined
let cleanupEvidence: RunResourceCleanupEvidence | undefined
let managedServices: Awaited<ReturnType<typeof provisionRuntimeServices>> | undefined
let managedServicesReleased = false
let serviceEvidence: RuntimeServiceEvidence[] = []
const releaseManagedServices = async (): Promise<void> => {
if (!managedServices || managedServicesReleased) return
await managedServices.release()
managedServicesReleased = true
}
let runtimeDestroyed = false
const destroyActiveRuntime = async (): Promise<void> => {
if (!runtime || runtimeDestroyed) {
return
}
runtimeDestroyed = true
await bestEffortTimeout(runtime.destroy(), 2_000)
}
const phaseExecutor = new RecipeRunPhaseExecutor({ context, timeoutMs: options.timeoutMs, interruption, destroyActiveRuntime })
const phaseTracker = phaseExecutor.tracker
const awaitRecipe = <T>(operation: string, promiseOrFactory: Promise<T> | (() => Promise<T>), timeoutMs?: number): Promise<T> => phaseExecutor.operation(operation, promiseOrFactory, timeoutMs)
const cancellationWatcher = interruption ? watchRunCancellationRequests(runRegistry, runRecord.runId, interruption) : undefined
try {
const preparedRuntimeSetup = await prepareRecipeRuntimeSetup(recipe, recipeDirectory, plan.runtime.backend)
;({ workspaceMounts, extraPlugins, dependencyOverlays, stagedFiles, overlays, inputMountBaselinePaths, inputMountPathMap, backendPackage } = preparedRuntimeSetup)
interruption?.throwIfInterrupted()
runRecord = await runRegistry.update(runRecord.runId, { status: "booting" })
managedServices = await phaseTracker.run("provision_runtime_services", { services: recipe.inputs?.services?.map(({ id, kind }) => ({ id, kind })) ?? [] }, async () => await provisionRuntimeServicesForRecipe(
recipe.inputs?.services ?? [],
async (provisioning) => await awaitRecipe("runtime-services.provision", provisioning),
{
signal: interruption?.signal,
policy,
externalServices: recipe.inputs?.externalServices ?? [],
externalServiceWritesApproved: options.externalServiceWritesApproved,
reservedEnvNames: [...Object.keys(runtimeEnv), ...(recipe.inputs?.secretEnv ?? [])],
onEvidence: (evidence) => { serviceEvidence = evidence },
},
))
serviceEvidence = managedServices.evidence
Object.assign(runtimeEnv, managedServices.env)
for (const [name, value] of Object.entries(managedServices.secretEnv)) {
delete runtimeEnv[name]
secretEnv[name] = value
}
secretEnvSummary = mergeRecipeSecretEnvSummary(secretEnvSummary, Object.keys(managedServices.secretEnv))
if (Object.keys(managedServices.secretEnv).length > 0) effectivePolicy = { ...policy, secrets: "connector-scoped" }
const runtimeEnvironment = {
kind: "wordpress" as const,
name: plan.runtime.name,
version: plan.runtime.wp,
phpVersion: plan.runtime.phpVersion,
workers: plan.runtime.workers,
wordpressInstallMode: plan.runtime.wordpressInstallMode,
databaseSetup: recipe.inputs?.services?.some(({ kind }) => kind === "mysql") ? "external" as const : undefined,
blueprint: plan.runtime.blueprint,
assets: resolveRecipeRuntimeAssets(recipe, recipeDirectory),
extensions: resolveRecipeRuntimeExtensionManifests(recipe, recipeDirectory),
}
const effectivePreview = effectiveRecipePreview(recipe.runtime?.preview, options)
const runtimeCreateSpec = {
backend: plan.runtime.backend,
environment: runtimeEnvironment,
policy: effectivePolicy,
runtimeEnv,
secretEnv,
secretEnvTargets: managedServices.secretEnvTargets,
artifactsDirectory: configuredArtifactsDirectory,
metadata: {
...runtimeMetadata(configuredArtifactsDirectory, plan.runtime.wp),
run: { runId: runRecord.runId, registryDirectory: runRegistry.directory },
...(serviceEvidence.length > 0 ? { managedRuntimeServices: serviceEvidence } : {}),
...recipeRunMetadata(recipe, recipePath, workspaceMounts, extraPlugins, dependencyOverlays, stagedFiles, overlays, backendPackage, effectivePreview),
},
preview: previewSpec(effectivePreview.publicUrl, effectivePreview.port, effectivePreview.bind, effectivePreview.siteUrl, effectivePreview.lease),
}
try {
const startupStartedAtMs = Date.now()
runtime = await phaseTracker.run("runtime_startup", {
operation: "runtime.create",
backend: runtimeCreateSpec.backend,
...(backendPackage ? { backendPackage: backendPackage.provenance } : {}),
runtime: runtimeEnvironment,
}, async () => await awaitRecipe("runtime.create", () => createRuntime(
runtimeCreateSpec,
resolveCliRuntimeBackend(runtimeCreateSpec.backend, backendPackage?.runtimeBackendContext),
)))
startupDurationMs = Date.now() - startupStartedAtMs
} catch (error) {
const blueprintSteps = recipeBlueprintSteps(runtimeEnvironment.blueprint)
if (blueprintSteps.length > 0) {
phaseTracker.fail("run_blueprint_steps", error, {
stepCount: blueprintSteps.length,
appliedDuring: "runtime.create",
})
}
throw new RecipeRuntimeCreateError("Runtime creation failed before recipe workflow execution.", {
operation: "runtime.create",
backend: runtimeCreateSpec.backend,
environment: runtimeEnvironment,
extraPlugins: extraPlugins.map(recipeRunExtraPlugin),
dependencyOverlays: dependencyOverlays.map(recipeRunDependencyOverlay),
workspaces: workspaceMounts.map((workspace) => ({
source: workspace.source,
target: workspace.target,
mode: workspace.mode,
metadata: workspace.metadata,
})),
stagedFiles: stagedFiles.map(recipeRunStagedFile),
overlays: overlays.map((overlay) => ({
source: overlay.source,
target: overlay.target,
type: overlay.type,
mode: overlay.mode,
metadata: overlay.metadata,
})),
...(backendPackage ? { backendPackage: backendPackage.provenance } : {}),
}, error)
}
if (!runtime) {
throw new Error("Runtime creation did not return a runtime")
}
runRecord = await runRegistry.update(runRecord.runId, { status: "running", runtime: await runtime.info() })
await artifactPointer.update({ runtime: await runtime.info(), phases: phaseTracker.list() })
const blueprintSteps = recipeBlueprintSteps(runtimeEnvironment.blueprint)
phaseTracker.complete("run_blueprint_steps", {
stepCount: blueprintSteps.length,
appliedDuring: "runtime.create",
})
interruption?.throwIfInterrupted()
executions.push(...(await applyRecipeRuntimeSetup({ recipe, recipeDirectory, runtime, runtimeSpec: runtimeCreateSpec, prepared: preparedRuntimeSetup, phaseExecutor, interruption })).executions)
fixtureDatabases = await phaseTracker.run("import_fixture_databases", phaseFixtureDatabaseData(recipe), async () => await awaitRecipe("fixture-databases.import", importRecipeFixtureDatabases(recipe, recipeDirectory, runtime!, executions)))
const siteSeeds = await awaitRecipe("site-seeds.import", importRecipeSiteSeeds(recipe, recipeDirectory, runtime!, executions))
distributionSetupArtifacts = await phaseTracker.run("run_distribution_setup_artifacts", phaseDistributionSetupArtifactData(recipe), async () => await awaitRecipe("distribution.setup-artifacts.run", runDistributionSetupArtifacts(recipe, recipeDirectory, runtime!, executions)))
interruption?.throwIfInterrupted()
const sandboxWorkspace = sandboxWorkspaceContract(workspaceMounts, recipe.inputs?.mounts ?? [])
const workflowSteps = recipeWorkflowSteps(recipe)
distributionStartupProbes = await phaseTracker.run("run_distribution_startup_probes", phaseDistributionStartupProbeData(recipe), async () => await awaitRecipe("distribution.startup-probes.run", runDistributionStartupProbes(recipe, runtime!, executions)))
const startupProbeFailure = distributionStartupProbeFailure(distributionStartupProbes)
if (startupProbeFailure) {
throw startupProbeFailure
}
await phaseTracker.run("run_workloads", phaseWorkflowData(workflowSteps), async () => {
for (const workflowStep of workflowSteps) {
const operation = `workflow.${workflowStep.phase}[${workflowStep.index}]:${workflowStep.step.command}`
const stepStartedAtMs = Date.now()
try {
const execution = await awaitRecipe(operation, async () => workflowStep.step.command === "wordpress.collect-workload-result"
? withRecipeExecutionPhase(executeRecipeCollectWorkloadResult(workflowStep.step, executions, new Date().toISOString()), workflowStep.phase, workflowStep.index, workflowStep.step.command, recipeWorkflowArgsEvidence(workflowStep.step.args, workflowStep.step.args), workflowStep.step.metadata)
: executeRecipeWorkflowStep(runtime!, workflowStep, recipeDirectory, sandboxWorkspace, configuredArtifactsDirectory, options, inputMountPathMap))
executions.push({ ...execution, ...(recipeWorkflowStepIsAdvisory(workflowStep.step) ? { recipeAdvisory: true } : {}) })
interruption?.throwIfInterrupted()
} catch (error) {
const failure = recipeStepFailure(workflowStep, error, stepStartedAtMs)
stepFailures.push(failure)
await artifactPointer.update({ command: operation, commandStatus: "failed", failure: failure.error, phases: phaseTracker.list(), stepFailures })
if (!recipeWorkflowStepIsAdvisory(workflowStep.step)) {
throw error
}
advisoryFailures.push(recipeAdvisoryFailure(workflowStep, error))
interruption?.clear()
}
}
})
adversarialCampaigns = await phaseTracker.run("run_adversarial_campaigns", { campaigns: recipe.adversarialCampaigns?.map(({ id, seed }) => ({ id, seed })) ?? [] }, async () => runRecipeAdversarialCampaigns({
recipe,
recipePath,
recipeDirectory,
runtime: runtime!,
sandboxWorkspace,
artifactRoot: configuredArtifactsDirectory,
runOptions: options,
inputMountPathMap,
signal: interruption?.signal,
executions,
provenance: recipeRunProvenance(recipe, recipePath) as unknown as Record<string, unknown>,
}))
interruption?.throwIfInterrupted()
probes = await phaseTracker.run("run_probes", phaseProbeData(recipe), async () => await awaitRecipe("recipe-probes.run", runRecipeProbes(recipe, recipeDirectory, runtime!, executions)))
const probeFailure = recipeProbeFailure(probes)
if (probeFailure) {
throw probeFailure
}
let evidence = await phaseTracker.run("collect_artifacts", { includeLogs: true, includeObservations: true }, async () => {
declaredArtifacts = await awaitRecipe("recipe-artifacts.collect", collectRecipeDeclaredArtifacts(recipe, runtime!))
const declaredArtifactFailure = recipeDeclaredArtifactFailure(declaredArtifacts)
await awaitRecipe("runtime.observe:runtime-info", runtime!.observe({ type: "runtime-info" }))
await awaitRecipe("runtime.observe:mounts", runtime!.observe({ type: "mounts" }))
runRecord = await runRegistry.update(runRecord.runId, { status: "collecting_artifacts", runtime: await runtime!.info() })
artifacts = await awaitRecipe("runtime.collect-artifacts", collectRecipeRuntimeArtifacts(runtime!, { includeLogs: true, includeObservations: true }, { snapshotTimeoutMs: SUCCESSFUL_RECIPE_RUNTIME_SNAPSHOT_TIMEOUT_MS, activeExecution: executions.at(-1) }))
await writeRecipeAdversarialEvidence(artifacts, adversarialCampaigns, Object.values(secretEnv))
browserEvidence = await recipeBrowserEvidence(artifacts, executions, recipe)
await artifactPointer.update({ runtime: await runtime!.info(), artifacts, phases: phaseTracker.list(), browserEvidence })
await materializeTypedRecipeDeclaredArtifacts(artifacts, declaredArtifacts)
await appendRecipeRuntimeEvidence(artifacts, recipeRuntimeEvidenceFiles(fixtureDatabases, distributionSetupArtifacts, distributionStartupProbes, probes, declaredArtifacts))
if (declaredArtifactFailure) {
throw declaredArtifactFailure
}
const recipeEvidence = await finalizeRecipeArtifactEvidence(artifacts, recipe, workspaceMounts, stagedFiles, effectivePolicy, secretEnvSummary)
const agentEvidence = await finalizeAgentSandboxEvidence(artifacts, executions)
Object.assign(recipeEvidence, agentEvidence)
markRecipeArtifactsFinalized(interruption, true)
return recipeEvidence
})
if (!artifacts) {
throw new Error("Recipe artifact collection did not return an artifact bundle")
}
const strictFailure = recipeArtifactEvidenceFailure(evidence)
const agentFailure = recipeAgentResultFailure(evidence.agentResult)
const verifyFailure = recipeVerifyStepFailure(executions)
const recipeFailure = strictFailure ?? agentFailure ?? recipeAdversarialCampaignFailure(adversarialCampaigns) ?? verifyFailure
const successfulRecipe = !recipeFailure
if (successfulRecipe && options.previewHoldSeconds) {
artifacts = await awaitRecipe("runtime.collect-artifacts.preview-hold", collectRecipeRuntimeArtifacts(runtime, { includeLogs: true, includeObservations: true, previewHoldSeconds: options.previewHoldSeconds }, { snapshotTimeoutMs: SUCCESSFUL_RECIPE_RUNTIME_SNAPSHOT_TIMEOUT_MS, activeExecution: executions.at(-1) }))
browserEvidence = await recipeBrowserEvidence(artifacts, executions, recipe)
await artifactPointer.update({ runtime: await runtime.info(), artifacts, phases: phaseTracker.list(), browserEvidence })
declaredArtifacts = await collectRecipeDeclaredArtifacts(recipe, runtime)
await materializeTypedRecipeDeclaredArtifacts(artifacts, declaredArtifacts)
await appendRecipeRuntimeEvidence(artifacts, recipeRuntimeEvidenceFiles(fixtureDatabases, distributionSetupArtifacts, distributionStartupProbes, probes, declaredArtifacts))
evidence = await finalizeRecipeArtifactEvidence(artifacts, recipe, workspaceMounts, stagedFiles, effectivePolicy, secretEnvSummary)
const previewAgentEvidence = await finalizeAgentSandboxEvidence(artifacts, executions)
Object.assign(evidence, previewAgentEvidence)
}
const runtimeInfo = successfulRecipe && options.previewHoldSeconds ? await runtime.info() : undefined
if (successfulRecipe && options.previewLeaseChild && options.previewLeaseFile) {
await markPreviewLeaseAvailable(options.previewLeaseFile, { runId: runRecord.runId, preview: artifacts.preview, holdSeconds: options.previewHoldSeconds })
}
const activeRuntime = runtime
cleanupEvidence = await runManagedServiceCleanup(runRegistry, runRecord, serviceEvidence, false, async () => {
await awaitRecipe("runtime.release", async () => {
try {
await releaseRuntime(activeRuntime, successfulRecipe && options.previewHoldBlocking ? options.previewHoldSeconds : 0, async () => {
await markPreviewLeaseReleased(options.previewLeaseFile)
}, interruption)
} catch (error) {
if (!options.previewLeaseChild || interruption?.metadata?.reason !== "run-cancellation-request") {
throw error
}
await markPreviewLeaseReleased(options.previewLeaseFile)
interruption.clear()
}
})
await releaseManagedServices()
await cleanupRecipePreparedSources(workspaceMounts, extraPlugins, stagedFiles, overlays, dependencyOverlays)
await cleanupInputMountBaselines(inputMountBaselinePaths)
})
runRecord = await runRegistry.read(runRecord.runId)
interruption?.throwIfInterrupted()
const benchmarkManifestFiles = await artifactManifestFilesByPath(artifacts)
const benchResultsList = executions
.filter((execution) => execution.command === "wordpress.bench" && execution.exitCode === 0)
.map((execution) => parseBenchResults(execution.stdout, benchmarkManifestFiles))
if (benchResultsList.length > 0) {
await writeBenchmarkArtifactEvidence(artifacts, benchResultsList)
}
const fuzzRunResult = recipeFuzzRunResult(recipe, executions)
if (recipeFailure) {
const finalRuntimeInfo = runtimeInfo ?? await runtime.info()
return await finalizeCompletedRecipeRun({
success: false,
recipePath,
runRegistry,
runRecord,
artifactPointer,
startedAtMs,
runtime: finalRuntimeInfo,
artifacts,
startupDurationMs,
cleanup: cleanupEvidence,
phaseEvidence: phaseTracker.list(),
browserEvidence,
replayStatus: evidence.replayStatus ? recipeReplayStatusOutput(evidence.replayStatus) : undefined,
failure: recipeFailure,
output: { ...completedRecipeOutputFields({ executions, componentContracts: componentContractResults(recipe, extraPlugins, phaseTracker.list(), executions), stagedFiles: stagedFiles.map(recipeRunStagedFile), fixtureDatabases, siteSeeds, distributionSetupArtifacts, distributionStartupProbes, probes, declaredArtifacts, stepFailures, phaseEvidence: phaseTracker.list(), advisoryFailures, browserEvidence, benchResultsList, fuzzRun: fuzzRunResult, evidence }), ...(adversarialCampaigns.length > 0 ? { adversarialCampaigns } : {}), provenance: recipeRunProvenance(recipe, recipePath), managedRuntimeServices: serviceEvidence },
})
}
const finalRuntimeInfo = runtimeInfo ?? await runtime.info()
return await finalizeCompletedRecipeRun({
success: true,
recipePath,
runRegistry,
runRecord,
artifactPointer,
startedAtMs,
runtime: finalRuntimeInfo,
artifacts,
startupDurationMs,
cleanup: cleanupEvidence,
phaseEvidence: phaseTracker.list(),
browserEvidence,
replayStatus: evidence.replayStatus ? recipeReplayStatusOutput(evidence.replayStatus) : undefined,
output: { ...completedRecipeOutputFields({ executions, componentContracts: componentContractResults(recipe, extraPlugins, phaseTracker.list(), executions), stagedFiles: stagedFiles.map(recipeRunStagedFile), fixtureDatabases, siteSeeds, distributionSetupArtifacts, distributionStartupProbes, probes, declaredArtifacts, stepFailures, phaseEvidence: phaseTracker.list(), advisoryFailures, browserEvidence, benchResultsList, fuzzRun: fuzzRunResult, evidence }), ...(adversarialCampaigns.length > 0 ? { adversarialCampaigns } : {}), provenance: recipeRunProvenance(recipe, recipePath), managedRuntimeServices: serviceEvidence },
})
} catch (error) {
const failedServiceEvidence = runtimeServiceEvidenceFromError(error)
if (failedServiceEvidence) {
serviceEvidence = failedServiceEvidence
await runRegistry.update(runRecord.runId, { metadata: { managedRuntimeServices: serviceEvidence } })
}
await markPreviewLeaseFailed(options.previewLeaseFile, error)
const serializedError = interruption?.metadata ? recipeInterruptionSerializedError(interruption.metadata) : serializeRecipeRunError(error)
const failureDiagnostics = recipeFailureRuntimeEvidenceFile({
recipe,
recipePath,
inputMountPathMap,
extraPlugins,
dependencyOverlays,
workspaceMounts,
stagedFiles,
overlays,
executions,
fixtureDatabases,
distributionSetupArtifacts,
distributionStartupProbes,
probes,
declaredArtifacts,
stepFailures,
phaseEvidence: phaseTracker.list(),
diagnostics: recipeRuntimeDiagnostics(recipe, executions, error) ?? [],
error: serializedError,
})
let diagnosticArtifacts: RecipeDiagnosticArtifactRef[] = []
if (runtime) {
const activeRuntime = runtime
artifacts = await phaseTracker.run("collect_artifacts", { failureRecovery: true, includeLogs: true, includeObservations: true }, async () => await collectAndFinalizeFailedRecipeArtifacts({
runtime: activeRuntime,
existingArtifacts: artifacts,
recipe,
workspaceMounts,
stagedFiles,
policy: effectivePolicy,
secretEnv: secretEnvSummary,
executions,
interruption,
}))
if (artifacts) {
const collectedArtifacts = artifacts
await writeRecipeAdversarialEvidence(artifacts, adversarialCampaigns, Object.values(secretEnv)).catch(() => undefined)
browserEvidence = await recipeBrowserEvidence(artifacts, executions, recipe)
await artifactPointer.update({ runtime: await activeRuntime.info(), artifacts, phases: phaseTracker.list(), browserEvidence })
try {
if (declaredArtifacts.length === 0) {
declaredArtifacts = await collectRecipeDeclaredArtifacts(recipe, activeRuntime)
}
await materializeTypedRecipeDeclaredArtifacts(artifacts, declaredArtifacts)
const evidenceFiles = await appendRecipeRuntimeEvidence(artifacts, [
...recipeRuntimeEvidenceFiles(fixtureDatabases, distributionSetupArtifacts, distributionStartupProbes, probes, declaredArtifacts),
recipeEffectiveRecipeEvidenceFile(recipe, recipePath, inputMountPathMap),
failureDiagnostics,
])
diagnosticArtifacts = evidenceFiles
.filter((file) => file.kind === failureDiagnostics.kind || file.kind === "recipe-run-effective-recipe")
.map((file) => ({ path: join(basename(collectedArtifacts.directory), file.path), kind: file.kind, contentType: file.contentType, sha256: file.sha256 }))
} catch {
// Preserve the original recipe failure; failure recovery already kept the base artifact bundle.
}
}
if (error instanceof RecipeRunTimeoutError) {
await destroyActiveRuntime()
} else {
await runRecipeCleanup(runRegistry, runRecord, async () => {
try {
await destroyActiveRuntime()
} catch {
// Preserve the original failure as the CLI result.
}
})
runRecord = await runRegistry.read(runRecord.runId)
}
}
if (diagnosticArtifacts.length === 0) {
diagnosticArtifacts = await writeRecipeFailureDiagnosticArtifacts(configuredArtifactsDirectory, [
recipeEffectiveRecipeEvidenceFile(recipe, recipePath, inputMountPathMap),
failureDiagnostics,
])
}
cleanupEvidence = await runManagedServiceCleanup(runRegistry, runRecord, serviceEvidence, true, async () => {
await releaseManagedServices()
await cleanupRecipePreparedSources(workspaceMounts, extraPlugins, stagedFiles, overlays, dependencyOverlays)
await cleanupInputMountBaselines(inputMountBaselinePaths)
})
runRecord = await runRegistry.read(runRecord.runId)
const fuzzRunResult = recipeFuzzRunResult(recipe, executions)
return await finalizeRecoveredRecipeFailure({
recipePath,
runRegistry,
runRecord,
artifactPointer,
startedAtMs,
originalError: error,
serializedError,
...(runtime ? { runtime: await runtime.info() } : {}),
...(artifacts ? { artifacts } : {}),
startupDurationMs,
cleanup: cleanupEvidence,
phaseEvidence: phaseTracker.list(),
browserEvidence,
diagnosticArtifacts,
interruption,
output: {
executions,
componentContracts: componentContractResults(recipe, extraPlugins, phaseTracker.list(), executions, error),
stagedFiles: stagedFiles.map(recipeRunStagedFile),
fixtureDatabases,
distributionSetupArtifacts,
distributionStartupProbes,
probes,
declaredArtifacts,
...(stepFailures.length > 0 ? { stepFailures } : {}),
phaseEvidence: phaseTracker.list(),
...(advisoryFailures.length > 0 ? { advisoryFailures } : {}),
...(browserEvidence.length > 0 ? { browserEvidence } : {}),
...(fuzzRunResult ? { fuzzRun: fuzzRunResult } : {}),
...(adversarialCampaigns.length > 0 ? { adversarialCampaigns } : {}),
diagnostics: recipeRuntimeDiagnostics(recipe, executions, error),
provenance: recipeRunProvenance(recipe, recipePath, diagnosticArtifacts),
managedRuntimeServices: serviceEvidence,
},
})
} finally {
if (managedServices && !managedServicesReleased) {
await managedServices.release().catch(() => undefined)
await runRegistry.update(runRecord.runId, { metadata: { managedRuntimeServices: managedServices.evidence } }).catch(() => undefined)
}
cancellationWatcher?.dispose()
}
}
export async function runManagedServiceCleanup(
runRegistry: RuntimeRunRegistry,
runRecord: Awaited<ReturnType<RuntimeRunRegistry["read"]>>,
serviceEvidence: RuntimeServiceEvidence[],
preservePrimaryFailure: boolean,
cleanup: () => Promise<void>,
): Promise<RunResourceCleanupEvidence> {
try {
return await runRecipeCleanup(runRegistry, runRecord, cleanup, () => ({ managedRuntimeServices: serviceEvidence }))
} catch (error) {
if (preservePrimaryFailure && error instanceof RunResourceCleanupError) {
return error.evidence
}
throw error
}
}
async function recipeArtifactsMountConflictFailure(options: RecipeRunOptions): Promise<RecipeRunOutput | undefined> {
const recipePath = resolve(options.recipePath)
const recipeDirectory = dirname(recipePath)
const recipe = await loadWorkspaceRecipe(recipePath)
const configuredArtifactsDirectory = options.artifactsDirectory ?? recipe.artifacts?.directory
const conflict = recipeArtifactsMountConflict(recipe, recipeDirectory, configuredArtifactsDirectory)
if (!conflict) {
return undefined
}
return {
success: false,
schema: "wp-codebox/recipe-run/v1",
recipePath,
executions: [],
error: serializeError(new RecipeArtifactsMountConflictError(conflict)),
}
}
function watchRunCancellationRequests(runRegistry: RuntimeRunRegistry, runId: string, interruption: RecipeInterruptionController): { dispose(): void } {
let disposed = false
let checking = false
const check = async (): Promise<void> => {
if (disposed || checking || interruption.metadata) {
return
}
checking = true
try {
const record = await runRegistry.read(runId)
if (record.lifecycle.cancelRequested && !record.lifecycle.terminal) {
interruption.requestCancellation()
}
} catch {
// Cancellation polling must not replace the primary recipe-run failure.
} finally {
checking = false
}
}
const timer = setInterval(() => {
void check()
}, 1_000)
timer.unref()
void check()
return {
dispose() {
disposed = true
clearInterval(timer)
},
}
}
function withRecipeExecutionArgs(execution: RecipeExecutionResult, argsEvidence: RecipeExecutionResult["recipeArgs"]): RecipeExecutionResult {
return argsEvidence ? { ...execution, recipeArgs: argsEvidence } : execution
}
function resolveRecipeRuntimeAssets(recipe: WorkspaceRecipe, recipeDirectory: string): RuntimeAssetSpec | undefined {
const assets = recipe.runtime?.assets
if (!assets?.wordpressDirectory && !assets?.wordpressZip) {
return undefined
}
return {
...assets,
...(assets.wordpressDirectory ? { wordpressDirectory: resolve(recipeDirectory, assets.wordpressDirectory) } : {}),
...(assets.wordpressZip ? { wordpressZip: isUrl(assets.wordpressZip) ? assets.wordpressZip : resolve(recipeDirectory, assets.wordpressZip) } : {}),
}
}
export function resolveRecipeRuntimeExtensionManifests(recipe: WorkspaceRecipe, recipeDirectory: string): Array<{ manifest: string }> | undefined {
const extensions = recipe.runtime?.extensions
if (!extensions || extensions.length === 0) {
return undefined
}
const root = resolve(recipeDirectory)
return extensions.map((extension, index) => {
const manifest = extension.manifest.trim()
if (!manifest || manifest.includes("\0")) {
throw new Error(`Recipe runtime extension ${index} requires a non-empty manifest path or HTTPS URL`)
}
if (/^https:\/\//i.test(manifest)) {
return { manifest }
}
if (isAbsolute(manifest)) {
throw new Error(`Recipe runtime extension ${index} manifest must be an HTTPS URL or a recipe-local path`)
}
const resolved = resolve(root, manifest)
const pathFromRoot = relative(root, resolved)
if (!pathFromRoot || pathFromRoot.startsWith("..") || isAbsolute(pathFromRoot)) {
throw new Error(`Recipe runtime extension ${index} manifest resolves outside the recipe directory`)
}
return { manifest: resolved }
})
}
function isUrl(value: string): boolean {
return /^https?:\/\//i.test(value)
}
async function validateRecipe(options: RecipeValidateOptions): Promise<RecipeValidateOutput> {
const recipePath = resolve(options.recipePath)
try {
const recipe = await loadWorkspaceRecipe(recipePath)
const issues = [
...await validateWorkspaceRecipe(recipe, recipePath),
...validateRecipeRuntimePolicy(recipe, options.policy ?? recipePolicy(recipe, dirname(recipePath)), dirname(recipePath)),
]
return {
success: issues.length === 0,
schema: "wp-codebox/recipe-validation/v1",
recipePath,
valid: issues.length === 0,
issues,
summary: {
steps: recipeWorkflowSteps(recipe).length,
mounts: recipe.inputs?.mounts?.length ?? 0,
workspaces: recipe.inputs?.workspaces?.length ?? 0,
extraPlugins: recipeExtraPlugins(recipe).length,
stagedFiles: recipe.inputs?.stagedFiles?.length ?? 0,
},
}
} catch (error) {
return {
success: false,
schema: "wp-codebox/recipe-validation/v1",
recipePath,
valid: false,
issues: [
{
code: "invalid-recipe",
path: "$",
message: error instanceof SyntaxError ? `Recipe JSON is invalid: ${error.message}` : error instanceof Error ? error.message : String(error),
},
],
error: serializeError(error),
}
}
}
function normalizeRuntimeEnv(values: Record<string, unknown>): Record<string, string> {
return normalizeRuntimeEnvRecord(values, { field: "inputs.runtimeEnv", invalid: "omit" })
}
function distributionRuntimeEnv(recipe: WorkspaceRecipe): Record<string, string> {
const values: Record<string, string> = {}
for (const [name, value] of Object.entries(recipe.distribution?.env ?? {})) {
if (value === null || ["string", "number", "boolean"].includes(typeof value)) {
values[name] = value === null ? "" : String(value)
}
}
return normalizeRuntimeEnvRecord(values, { field: "distribution.env", invalid: "omit" })
}
function parseRecipeRunOptions(args: string[]): RecipeRunOptions {
const parsed = parseCommandOptions(args, new Set(["--json", "--summary", "--summary-only", "--dry-run", "--preview-hold-blocking", "--preview-lease", "--preview-lease-child", "--approve-external-service-writes"]))
if (parsed.positionals.length > 0) {
throw new Error(`Invalid argument: ${parsed.positionals[0]}`)
}
const options: Partial<RecipeRunOptions> = {
json: parsed.options.get("--json") === true,
summary: parsed.options.get("--summary") === true || parsed.options.get("--summary-only") === true,
dryRun: parsed.options.get("--dry-run") === true,
previewHoldBlocking: parsed.options.get("--preview-hold-blocking") === true,
previewLeaseRequested: parsed.options.get("--preview-lease") === true,
previewLeaseChild: parsed.options.get("--preview-lease-child") === true,
externalServiceWritesApproved: parsed.options.get("--approve-external-service-writes") === true,
timeoutMs: DEFAULT_RECIPE_RUN_TIMEOUT_MS,
}
for (const [name, value] of parsed.options) {
if (value === true) {
continue
}
switch (name) {
case "--recipe":
options.recipePath = value
break
case "--artifacts":
options.artifactsDirectory = value
break
case "--run-registry":
options.runRegistryDirectory = value
break
case "--preview-hold-seconds":
options.previewHoldSeconds = parsePreviewHoldSeconds(value)
break
case "--preview-public-url":
options.previewPublicUrl = parsePreviewPublicUrl(value)
break
case "--preview-lease-json":
options.previewLease = parsePreviewLease(value)
break
case "--preview-port":
options.previewPort = parsePreviewPort(value)
break
case "--preview-bind":
options.previewBind = parsePreviewBind(value)
break
case "--preview-lease-id":
options.previewLeaseId = value
break
case "--preview-lease-file":
options.previewLeaseFile = value
break
case "--timeout":
options.timeoutMs = parseRecipeRunTimeoutMs(value)
break
case "--policy":
options.policy = parseRecipePolicy(value)
break
case "--adversarial-replay":
options.adversarialReplayPath = value
break
default:
throw new Error(`Unknown option: ${name}`)
}
}
if (!options.recipePath) {
throw new Error("Missing required option: --recipe")
}
return options as RecipeRunOptions
}
function parseRecipeRunTimeoutMs(value: unknown): number {
const raw = String(value).trim()
const match = raw.match(/^(\d+)(ms|s|m)?$/)
if (!match) {
throw new Error("--timeout must be a positive duration such as 5000ms, 30s, or 25m")
}
const amount = Number.parseInt(match[1], 10)
const unit = match[2] ?? "ms"
const multiplier = unit === "m" ? 60_000 : unit === "s" ? 1000 : 1
const timeoutMs = amount * multiplier
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
throw new Error("--timeout must be a positive duration")
}
return timeoutMs
}
function parseRecipePolicy(value: string): RuntimePolicy {
const raw = value.trim().startsWith("{") ? value : readFileSync(resolve(value), "utf8")
const policy = JSON.parse(raw) as unknown
const result = validateRuntimePolicy(policy)
if (!result.valid) {
throw new Error(`Runtime policy is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`)
}
return policy as RuntimePolicy
}
function parseRecipeValidateOptions(args: string[]): RecipeValidateOptions {
const parsed = parseCommandOptions(args, new Set(["--json"]))
if (parsed.positionals.length > 0) {
throw new Error(`Invalid argument: ${parsed.positionals[0]}`)
}
const options: Partial<RecipeValidateOptions> = { json: parsed.options.get("--json") === true }
for (const [name, value] of parsed.options) {
if (value === true) {
continue
}
switch (name) {
case "--recipe":
options.recipePath = value
break
case "--policy":
options.policy = parseRecipePolicy(value)
break
default:
throw new Error(`Unknown option: ${name}`)
}
}
if (!options.recipePath) {
throw new Error("Missing required option: --recipe")
}
return options as RecipeValidateOptions
}
async function importRecipeFixtureDatabases(recipe: WorkspaceRecipe, recipeDirectory: string, runtime: Runtime, executions: RecipeExecutionResult[]): Promise<RecipeRunFixtureDatabase[]> {
const results: RecipeRunFixtureDatabase[] = []
for (const [index, fixture] of (recipe.inputs?.fixtureDatabases ?? []).entries()) {
const source = resolve(recipeDirectory, fixture.source)
const sql = await readFile(source, "utf8")
const reset = {
strategy: fixture.reset?.strategy ?? "truncate-tables" as const,
tables: fixture.reset?.tables ?? [],
}
const execution = await runtime.execute({
command: "wordpress.run-php",
args: [`code=${fixtureDatabaseImportCode(fixture, sql, reset)}`],
})
executions.push(withRecipeExecutionPhase(execution, "setup", index, `fixture-database.import:${fixture.name}`))
const imported = parseFixtureDatabaseImportResult(execution.stdout)
results.push({
schema: "wp-codebox/fixture-database-result/v1",
index,
name: fixture.name,
version: fixture.version,
source,
format: fixture.format ?? "sql",
action: "imported",
reset,
identity: {
name: fixture.name,
version: fixture.version,
sourceSha256: createHash("sha256").update(sql).digest("hex"),
},
counts: imported.counts,
...(fixture.metadata ? { metadata: fixture.metadata } : {}),
})
}
return results
}
function recipeFailureRuntimeEvidenceFile(args: {
recipe: WorkspaceRecipe
recipePath: string
inputMountPathMap: NonNullable<Awaited<ReturnType<typeof prepareRecipeRuntimeSetup>>["inputMountPathMap"]>
extraPlugins: PreparedExtraPlugin[]
dependencyOverlays: PreparedDependencyOverlay[]
workspaceMounts: PreparedWorkspaceMount[]
stagedFiles: PreparedStagedFile[]
overlays: PreparedRuntimeOverlay[]
executions: RecipeExecutionResult[]
fixtureDatabases: RecipeRunFixtureDatabase[]
distributionSetupArtifacts: RecipeRunDistributionSetupArtifact[]
distributionStartupProbes: RecipeRunDistributionStartupProbe[]
probes: RecipeRunProbe[]
declaredArtifacts: RecipeRunDeclaredArtifact[]
stepFailures: RecipeStepFailure[]
phaseEvidence: RecipePhaseEvidence[]
diagnostics: RecipeRuntimeDiagnostic[]
error: RunOutput["error"]
}): { filename: string; kind: string; value: unknown } {
return {
filename: "recipe-run-failure-diagnostics.json",
kind: "recipe-run-failure-diagnostics",
value: stripUndefined({
schema: "wp-codebox/recipe-run-failure-diagnostics/v1",
createdAt: new Date().toISOString(),
provenance: recipeRunProvenance(args.recipe, args.recipePath),
recipe: {
path: args.recipePath,
schema: args.recipe.schema,
sourceSha256: recipeDigest(args.recipe),
effectiveSha256: recipeDigest(effectiveRecipeForReplay(args.recipe, args.inputMountPathMap)),
effectiveJson: effectiveRecipeForReplay(args.recipe, args.inputMountPathMap),
runtime: args.recipe.runtime ?? {},
workflow: effectiveRecipeWorkflowMetadata(args.recipe, args.inputMountPathMap),
inputs: {
extra_plugins: args.extraPlugins.map(recipeRunExtraPlugin),
dependency_overlays: args.dependencyOverlays.map(recipeRunDependencyOverlay),
workspaces: args.workspaceMounts.map((workspace) => ({ target: workspace.target, mode: workspace.mode, metadata: workspace.metadata })),
stagedFiles: args.stagedFiles.map(recipeRunStagedFile),
secretEnv: args.recipe.inputs?.secretEnv ?? [],
externalServices: recipeExternalServiceBoundarySummaries(args.recipe),
},
artifacts: args.recipe.artifacts ?? {},
},
preparedRuntimeOverlays: args.overlays.map((overlay) => ({ target: overlay.target, type: overlay.type, mode: overlay.mode, metadata: overlay.metadata })),
executions: args.executions,
fixtureDatabases: args.fixtureDatabases,
distributionSetupArtifacts: args.distributionSetupArtifacts,
distributionStartupProbes: args.distributionStartupProbes,
probes: args.probes,
declaredArtifacts: args.declaredArtifacts,
stepFailures: args.stepFailures,
phaseEvidence: args.phaseEvidence,
diagnostics: args.diagnostics,
error: args.error,