-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoutput.ts
More file actions
352 lines (317 loc) · 15.2 KB
/
output.ts
File metadata and controls
352 lines (317 loc) · 15.2 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
import type { ArtifactBundle, ArtifactBundleVerificationResult, ExecutionResult, RuntimeInfo } from "@automattic/wp-codebox-core"
interface CliError {
name: string
message: string
code?: string
[key: string]: unknown
}
interface RunOutputLike {
success: boolean
runtime?: RuntimeInfo
execution?: ExecutionResult
artifacts?: ArtifactBundle
error?: CliError
}
interface RecipeRunOutputLike extends RunOutputLike {
executions?: ExecutionResult[]
dryRun?: boolean
plan?: {
workflow?: { steps?: unknown[] }
mounts?: unknown[]
workspaces?: unknown[]
extra_plugins?: unknown[]
siteSeeds?: unknown[]
stagedFiles?: unknown[]
}
validation?: {
issues?: Array<{ code: string; path: string; message: string }>
}
}
interface RecipeValidateOutputLike {
recipePath?: string
valid: boolean
issues: Array<{ code: string; path: string; message: string }>
summary?: {
steps: number
mounts: number
workspaces: number
extraPlugins: number
stagedFiles?: number
}
}
interface BlueprintValidateOutputLike extends RunOutputLike {
blueprintPath?: string
}
interface BatchOutputLike {
concurrency: number
total: number
completed: number
runs: Array<RunOutputLike & { index: number; task: string }>
}
interface CommandCatalogOutputLike {
commands: Array<{
id: string
description: string
acceptedArgs: Array<{ name: string; required?: boolean }>
outputShape: string
policyRequirement: string
}>
}
interface RecipeSchemaOutputLike {
id: string
jsonSchema: Record<string, unknown>
}
export async function captureStdout<T>(callback: () => Promise<T>): Promise<{ result: T; logs: string[] }> {
const logs: string[] = []
const write = process.stdout.write.bind(process.stdout)
process.stdout.write = ((chunk: string | Uint8Array, encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void), callback?: (error?: Error | null) => void) => {
logs.push(typeof chunk === "string" ? chunk : chunk.toString())
if (typeof encodingOrCallback === "function") {
encodingOrCallback()
} else if (callback) {
callback()
}
return true
}) as typeof process.stdout.write
try {
return { result: await callback(), logs: logs.map((log) => log.trim()).filter(Boolean) }
} finally {
process.stdout.write = write
}
}
export function serializeError(error: unknown): CliError {
if (error instanceof Error) {
const extras = Object.fromEntries(
Object.entries(error).filter(([key]) => !["name", "message", "stack"].includes(key)),
)
const cause = "cause" in error && error.cause !== undefined ? serializeError(error.cause) : undefined
return {
name: error.name,
message: error.message,
...("code" in error && typeof error.code === "string" ? { code: error.code } : {}),
...extras,
...(cause ? { cause } : {}),
}
}
return { name: "Error", message: String(error) }
}
export function printHumanOutput(output: RunOutputLike): void {
if (!output.success) {
console.error(output.error?.message ?? "WP Codebox failed")
return
}
console.log("WP Codebox run")
console.log(`Runtime: ${output.runtime?.backend ?? "unknown"}`)
console.log(`Executed: ${output.execution?.command ?? "unknown"}`)
console.log(`Artifacts: ${output.artifacts?.directory ?? "none"}`)
if (output.artifacts?.preview?.url) {
console.log(`Preview: ${output.artifacts.preview.url} (${output.artifacts.preview.status})`)
}
}
export function printBootHumanOutput(output: RunOutputLike): void {
if (!output.success) {
console.error(output.error?.message ?? "WP Codebox boot failed")
return
}
console.log("WP Codebox boot")
console.log(`Runtime: ${output.runtime?.backend ?? "unknown"}`)
console.log(`Artifacts: ${output.artifacts?.directory ?? "none"}`)
if (output.artifacts?.preview?.url) {
console.log(`Preview: ${output.artifacts.preview.url} (${output.artifacts.preview.status})`)
}
}
export function printBlueprintValidateHumanOutput(output: BlueprintValidateOutputLike): void {
if (!output.success) {
console.error(output.error?.message ?? "WP Codebox blueprint validation failed")
return
}
console.log("WP Codebox blueprint validation")
console.log(`Blueprint: ${output.blueprintPath ?? "inline"}`)
console.log(`Runtime: ${output.runtime?.backend ?? "unknown"}`)
console.log(`Artifacts: ${output.artifacts?.directory ?? "none"}`)
if (output.artifacts?.preview?.url) {
console.log(`Preview: ${output.artifacts.preview.url} (${output.artifacts.preview.status})`)
}
}
export function printRecipeHumanOutput(output: RecipeRunOutputLike): void {
if (!output.success) {
console.error(output.error?.message ?? "WP Codebox recipe failed")
for (const issue of output.validation?.issues ?? []) {
console.error(`- ${issue.code} ${issue.path}: ${issue.message}`)
}
return
}
if (output.dryRun) {
console.log("WP Codebox recipe dry-run")
console.log(`Steps: ${output.plan?.workflow?.steps?.length ?? 0}`)
console.log(`Mounts: ${output.plan?.mounts?.length ?? 0}`)
console.log(`Workspaces: ${output.plan?.workspaces?.length ?? 0}`)
console.log(`Extra plugins: ${output.plan?.extra_plugins?.length ?? 0}`)
console.log(`Site seeds: ${output.plan?.siteSeeds?.length ?? 0}`)
console.log(`Staged files: ${output.plan?.stagedFiles?.length ?? 0}`)
return
}
console.log("WP Codebox recipe")
console.log(`Runtime: ${output.runtime?.backend ?? "unknown"}`)
console.log(`Steps: ${output.executions?.length ?? 0}`)
console.log(`Artifacts: ${output.artifacts?.directory ?? "none"}`)
if (output.artifacts?.preview?.url) {
console.log(`Preview: ${output.artifacts.preview.url} (${output.artifacts.preview.status})`)
}
}
export function printRecipeValidateHumanOutput(output: RecipeValidateOutputLike): void {
console.log("WP Codebox recipe validation")
console.log(`Recipe: ${output.recipePath ?? "unknown"}`)
console.log(`Valid: ${output.valid ? "yes" : "no"}`)
if (output.summary) {
console.log(`Steps: ${output.summary.steps}`)
console.log(`Mounts: ${output.summary.mounts}`)
console.log(`Workspaces: ${output.summary.workspaces}`)
console.log(`Extra plugins: ${output.summary.extraPlugins}`)
if (output.summary.stagedFiles !== undefined) {
console.log(`Staged files: ${output.summary.stagedFiles}`)
}
}
for (const issue of output.issues) {
console.log(`- ${issue.code} ${issue.path}: ${issue.message}`)
}
}
export function printArtifactVerifyHumanOutput(output: ArtifactBundleVerificationResult): void {
console.log("WP Codebox artifact bundle verification")
console.log(`Bundle: ${output.bundleDirectory}`)
console.log(`Valid: ${output.valid ? "yes" : "no"}`)
for (const violation of output.violations) {
console.log(`- ${violation.code} ${violation.path}: ${violation.message}`)
}
}
export function printBatchHumanOutput(output: BatchOutputLike): void {
console.log("WP Codebox batch")
console.log(`Runs: ${output.completed}/${output.total} completed`)
console.log(`Concurrency: ${output.concurrency}`)
for (const run of output.runs) {
console.log(`${run.success ? "ok" : "fail"} #${run.index + 1}: ${run.task}`)
if (run.artifacts?.directory) {
console.log(` Artifacts: ${run.artifacts.directory}`)
}
}
}
export function printCommandCatalogHumanOutput(output: CommandCatalogOutputLike): void {
console.log("WP Codebox commands")
for (const command of output.commands) {
const requiredArgs = command.acceptedArgs.filter((arg) => arg.required).map((arg) => arg.name)
console.log(`${command.id}: ${command.description}`)
if (requiredArgs.length > 0) {
console.log(` Required args: ${requiredArgs.join(", ")}`)
}
console.log(` Output: ${command.outputShape}`)
console.log(` Policy: ${command.policyRequirement}`)
}
}
export function printRecipeSchemaHumanOutput(output: RecipeSchemaOutputLike): void {
const properties = output.jsonSchema.properties && typeof output.jsonSchema.properties === "object" ? Object.keys(output.jsonSchema.properties) : []
console.log("WP Codebox recipe schema")
console.log(`Schema: ${output.id}`)
console.log(`Top-level fields: ${properties.join(", ")}`)
}
export function printHelp(): void {
console.log(`Usage:
wp-codebox commands [--json]
wp-codebox schema recipe [--json]
wp-codebox doctor [--json] [--fix] [--archive-root <dir>] [--stale-after-seconds <n>]
wp-codebox cleanup [--json] [--archive-root <dir>] [--stale-after-seconds <n>]
wp-codebox workspace-policy check --workspace-root <path> --writable-root <path> [options]
wp-codebox recipe build phpunit --options <path> [--output <path>]
wp-codebox recipe validate --recipe <path> [--json]
wp-codebox bench matrix --matrix <path> [--recipe <path>] [--artifacts <dir>] [--json]
wp-codebox bench summarize (--input <recipe-run.json>|--bundle <dir>) [--json]
wp-codebox bench compare --baseline-input <recipe-run.json> --candidate-input <recipe-run.json> [--json]
wp-codebox artifacts verify --bundle <dir> [--json]
wp-codebox artifacts apply-preflight --bundle <dir> --approved-file <path> [--json]
wp-codebox artifacts browser-metrics --bundle <dir> [--json]
wp-codebox artifacts transfer-verify --bundle <dir> [--json]
wp-codebox artifacts transfer-probes --bundle <dir> [--json]
wp-codebox artifacts benchmark --bundle <dir> [--scenario-id <id>] [--extract-to <dir>] [--json]
wp-codebox artifacts bench-results --bundle <dir> [--json]
wp-codebox artifacts bench-compare --baseline-bundle <dir> --candidate-bundle <dir> [--json]
wp-codebox runs status --registry <dir> --run-id <id> [--json]
wp-codebox runs artifacts --registry <dir> --run-id <id> [--json]
wp-codebox agent-task-run --input-file <path> [--json] [--preview-hold-seconds <n>] [--preview-public-url <url>]
wp-codebox validate-blueprint --blueprint <json|file> [options]
wp-codebox recipe-run --recipe <path> [options]
wp-codebox boot [--mount <host>:<vfs>] [options]
wp-codebox run --mount <host>:<vfs> --command <id> [options]
Options:
--recipe <path> Workspace recipe JSON file for recipe-run or recipe validate.
--options <path> Recipe builder options JSON file for recipe build.
--output <path> Optional output JSON path for recipe build; defaults to stdout.
--input-file <path> Agent task input JSON for agent-task-run.
--preview-hold-seconds <n>
Keep preview runtimes alive after agent-task-run/recipe-run.
--preview-public-url <url>
Public preview URL passed through to agent-task-run/recipe-run.
--bundle <dir> Artifact bundle directory for artifact verification/probe commands.
--approved-file <path>
Changed file approved for artifacts apply-preflight. Repeatable.
--approved-files <paths>
Comma-separated changed files approved for artifacts apply-preflight.
--scenario-id <id> Filter benchmark artifact refs to one scenario.
--extract-to <dir> Copy listed benchmark artifact refs to a directory.
--input <path> Saved recipe-run JSON output for benchmark summarization.
--matrix <path> Benchmark recipe matrix JSON file for bench matrix.
--baseline-input <path>
Saved baseline recipe-run JSON for benchmark comparison.
--candidate-input <path>
Saved candidate recipe-run JSON for benchmark comparison.
--baseline-bundle <dir>
Baseline artifact bundle directory for benchmark comparison.
--candidate-bundle <dir>
Candidate artifact bundle directory for benchmark comparison.
--baseline-index <n>
Benchmark envelope index to compare when a source has multiple results.
--candidate-index <n>
Benchmark envelope index to compare when a source has multiple results.
--artifacts <dir> Artifact root directory. Also accepted by artifacts verify.
--run-registry <dir>
Durable run registry directory for recipe-run.
--registry <dir> Durable run registry directory for runs lookup commands.
--run-id <id> Run ID for runs lookup commands.
--mount <host:vfs> Mount a host path into the runtime. Repeatable.
--command <id> Command/action id to execute.
--arg <key=value> Command argument. Repeatable. Recipe commands include wordpress.run-php, wordpress.phpunit, wordpress.core-phpunit, wordpress.plugin-check, wordpress.wp-cli, wordpress.ability, wordpress.bench, and wordpress.browser-probe.
--wp <version> WordPress version for Playground. Defaults to 7.0; accepts latest, trunk, nightly, or numeric versions.
--blueprint <json|file>
WordPress Playground blueprint JSON or path for boot or validate-blueprint.
--artifacts <dir> Artifact root directory.
--hold <n> Keep a booted Playground preview available before teardown. Accepts the same values as --preview-hold.
--preview-hold <n> Keep the live Playground preview available after a successful run. Accepts seconds or minutes, e.g. 30s or 15m; max 3600s.
--preview-port <n> Start Playground on a fixed local port. Defaults to a random available port.
--preview-bind <host>
Host/IP for the fixed-port WP Codebox preview proxy. Requires --preview-port.
Defaults to 127.0.0.1; use 0.0.0.0 only behind trusted network controls.
--preview-public-url <url>
Public tunnel/proxy URL to report in preview artifacts and pass to Playground as site-url.
Upstream Playground remains loopback-bound; this only changes the WP Codebox proxy bind.
--timeout <duration> Maximum live recipe-run duration before emitting a structured timeout failure. Defaults to 25m.
--policy <json|file> Runtime policy JSON or path to a JSON file.
--dry-run Validate recipe-run and emit a resolved JSON plan without booting Playground or writing temp workspaces.
--json Emit machine-readable JSON.
Doctor and cleanup:
doctor Report binary/source fingerprint, Node/npm availability, stale recipe-run processes, and corrupt archives.
cleanup Run doctor checks and remove safe stale/corrupt runtime state.
--fix Allow mutating cleanup when command is doctor.
--stale-after-seconds <n>
Age threshold for stale recipe-run processes. Defaults to 3600.
--archive-root <dir> Additional archive/cache root to scan for invalid .zip files. Repeatable.
Workspace policy:
--workspace-root <dir>
Workspace root to inspect. Defaults to the current directory.
--writable-root <path>
Relative path that may be changed. Repeatable.
--hidden-path <path> Relative path that must not be changed or exposed. Repeatable.
--git Use git status metadata, including ignored and unmerged entries.
Discovery:
commands Print supported runtime and recipe command metadata.
schema recipe Print the wp-codebox/workspace-recipe/v1 JSON Schema.
Example:
wp-codebox run --mount ./examples/simple-plugin:/wordpress/wp-content/plugins/simple-plugin --command wordpress.run-php --arg code-file=./examples/simple-plugin/probe.php --artifacts ./artifacts --json`)
}