evalctl 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/dist/cli.d.ts +13 -0
- package/dist/cli.js +294 -0
- package/dist/client.d.ts +53 -0
- package/dist/client.js +269 -0
- package/dist/commands/auth.d.ts +6 -0
- package/dist/commands/auth.js +341 -0
- package/dist/commands/common.d.ts +17 -0
- package/dist/commands/common.js +53 -0
- package/dist/commands/export.d.ts +2 -0
- package/dist/commands/export.js +54 -0
- package/dist/commands/index.d.ts +3 -0
- package/dist/commands/index.js +10 -0
- package/dist/commands/info.d.ts +2 -0
- package/dist/commands/info.js +208 -0
- package/dist/commands/runs.d.ts +2 -0
- package/dist/commands/runs.js +325 -0
- package/dist/commands/scenarios.d.ts +2 -0
- package/dist/commands/scenarios.js +585 -0
- package/dist/commands/screens.d.ts +2 -0
- package/dist/commands/screens.js +139 -0
- package/dist/config.d.ts +52 -0
- package/dist/config.js +281 -0
- package/dist/context.d.ts +64 -0
- package/dist/context.js +1 -0
- package/dist/diff.d.ts +7 -0
- package/dist/diff.js +122 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +35 -0
- package/dist/fsutil.d.ts +34 -0
- package/dist/fsutil.js +245 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +18 -0
- package/dist/output.d.ts +38 -0
- package/dist/output.js +156 -0
- package/dist/prompt.d.ts +29 -0
- package/dist/prompt.js +195 -0
- package/dist/sidecar.d.ts +39 -0
- package/dist/sidecar.js +138 -0
- package/dist/state.d.ts +14 -0
- package/dist/state.js +48 -0
- package/dist/util.d.ts +21 -0
- package/dist/util.js +77 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +12 -0
- package/dist/yaml-text.d.ts +15 -0
- package/dist/yaml-text.js +103 -0
- package/package.json +62 -4
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
2
|
+
import { splitLinesKeepEnds, unifiedDiff } from "../diff.js";
|
|
3
|
+
import { CliError, EXIT_CONFLICT, EXIT_OK, EXIT_VALIDATION } from "../errors.js";
|
|
4
|
+
import { checkOutputPath, readUtf8File, resolveOutputPath, writeFileAtomic } from "../fsutil.js";
|
|
5
|
+
import { displayText, emitJson, errOut, formatTable, formatTimestamp, hashImpactChanges, out, outRaw, printHashImpactBanner, printValidationIssues, } from "../output.js";
|
|
6
|
+
import { lookupSidecar, recordScenarioAction, resolveEtagForAction, sidecarPath, SIDECAR_FILENAME, updateSidecar, } from "../sidecar.js";
|
|
7
|
+
import { asArray, asObject, errorMessage, isObject, nonEmptyString, stringList } from "../util.js";
|
|
8
|
+
import { peekScenarioId, renderTemplateYaml } from "../yaml-text.js";
|
|
9
|
+
import { ack, acknowledgedWarnings, authoringBody, confirmAction, isReservedScenarioId, isScenarioId, isScreenName, MAX_SCENARIO_BYTES, originChoices, statusChoices, yes, } from "./common.js";
|
|
10
|
+
const SCENARIOS = "/api/scenarios";
|
|
11
|
+
const allowValidation = [422];
|
|
12
|
+
function requireId(value) {
|
|
13
|
+
if (typeof value === "string" && isReservedScenarioId(value)) {
|
|
14
|
+
throw new CliError(`'${value}' is a reserved name and cannot be a scenario ID.`, { exitCode: EXIT_VALIDATION });
|
|
15
|
+
}
|
|
16
|
+
if (!isScenarioId(value)) {
|
|
17
|
+
throw new CliError("Use a scenario ID of 2–41 lowercase letters, digits or hyphens starting with a letter.", {
|
|
18
|
+
exitCode: EXIT_VALIDATION,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function scenarioPath(id) {
|
|
24
|
+
return SCENARIOS + "/" + encodeURIComponent(id);
|
|
25
|
+
}
|
|
26
|
+
function summaryBody(ctx) {
|
|
27
|
+
const summary = ctx.opt("summary");
|
|
28
|
+
return summary === undefined ? {} : { summary };
|
|
29
|
+
}
|
|
30
|
+
function withResponseEtag(response) {
|
|
31
|
+
const etag = response.headers["etag"];
|
|
32
|
+
return etag !== undefined && !nonEmptyString(response.body["etag"]) ? { ...response.body, etag } : response.body;
|
|
33
|
+
}
|
|
34
|
+
function yamlOf(detail) {
|
|
35
|
+
if (typeof detail["yaml_text"] !== "string") {
|
|
36
|
+
throw new CliError("The server response is missing canonical scenario YAML.");
|
|
37
|
+
}
|
|
38
|
+
return detail["yaml_text"];
|
|
39
|
+
}
|
|
40
|
+
async function list(ctx) {
|
|
41
|
+
const { body } = await ctx.client().request("GET", SCENARIOS, {
|
|
42
|
+
query: {
|
|
43
|
+
origin: ctx.opt("origin"), status: ctx.opt("status"), twin: ctx.opt("twin"),
|
|
44
|
+
family: ctx.opt("family"), tag: ctx.opt("tag"), q: ctx.opt("search"),
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
if (ctx.global.json) {
|
|
48
|
+
emitJson(body);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const rows = asArray(body["scenarios"]).filter(isObject).map((item) => [
|
|
52
|
+
item["id"], item["origin"], item["status"], item["twin"], item["family"], item["current_rev"],
|
|
53
|
+
item["title"], stringList(item["tags"]).join(","),
|
|
54
|
+
]);
|
|
55
|
+
out(rows.length === 0
|
|
56
|
+
? "No scenarios matched."
|
|
57
|
+
: formatTable(["ID", "ORIGIN", "STATUS", "TWIN", "FAMILY", "REV", "TITLE", "TAGS"], rows));
|
|
58
|
+
}
|
|
59
|
+
return EXIT_OK;
|
|
60
|
+
}
|
|
61
|
+
async function show(ctx) {
|
|
62
|
+
const id = requireId(ctx.positionals[0]);
|
|
63
|
+
const { body } = await ctx.client().request("GET", scenarioPath(id));
|
|
64
|
+
if (ctx.global.json) {
|
|
65
|
+
emitJson(body);
|
|
66
|
+
return EXIT_OK;
|
|
67
|
+
}
|
|
68
|
+
const yaml = yamlOf(body);
|
|
69
|
+
if (!ctx.flag("yaml")) {
|
|
70
|
+
out(`ID ${displayText(body["id"])} (${displayText(body["origin"])}, ${displayText(body["status"])})`);
|
|
71
|
+
out(`Title ${displayText(body["title"])}`);
|
|
72
|
+
out(`Twin ${displayText(body["twin"])} Family ${displayText(body["family"])} Lanes ${displayText(stringList(body["lanes"]).join(", "))}`);
|
|
73
|
+
if (typeof body["current_rev"] === "number") {
|
|
74
|
+
out(`Rev ${displayText(body["current_rev"])} ETag ${displayText(body["etag"])}`);
|
|
75
|
+
}
|
|
76
|
+
if (body["base_scenario_id"]) {
|
|
77
|
+
out(`Forked ${displayText(body["base_scenario_id"])} (drifted=${displayText(body["upstream_drifted"])}, deleted=${displayText(body["upstream_deleted"])})`);
|
|
78
|
+
}
|
|
79
|
+
out(`Hashes voice=${displayText(body["voice_hash"])} text=${displayText(body["text_hash"])}`);
|
|
80
|
+
out();
|
|
81
|
+
}
|
|
82
|
+
outRaw(yaml);
|
|
83
|
+
return EXIT_OK;
|
|
84
|
+
}
|
|
85
|
+
async function scaffold(ctx) {
|
|
86
|
+
const id = requireId(ctx.positionals[0]);
|
|
87
|
+
const path = resolveOutputPath(ctx.io.cwd, ctx.opt("out") ?? `${id}.yaml`);
|
|
88
|
+
const force = ctx.flag("force");
|
|
89
|
+
if (checkOutputPath(path, ctx.io.cwd) !== undefined && !force) {
|
|
90
|
+
throw new CliError(`File ${path} already exists. Pass --force to overwrite.`, { exitCode: EXIT_CONFLICT });
|
|
91
|
+
}
|
|
92
|
+
const { body: meta } = await ctx.client().request("GET", `${SCENARIOS}/meta`);
|
|
93
|
+
const templates = asObject(meta["templates"]);
|
|
94
|
+
const names = Object.keys(templates);
|
|
95
|
+
const template = ctx.opt("template") ?? names[0];
|
|
96
|
+
const source = template !== undefined && Object.hasOwn(templates, template) ? templates[template] : undefined;
|
|
97
|
+
if (template === undefined || typeof source !== "string") {
|
|
98
|
+
const message = names.length === 0
|
|
99
|
+
? "The server returned no scenario templates."
|
|
100
|
+
: `Unknown template ${JSON.stringify(template)}. Available templates are ${displayText(names.join(", "))}.`;
|
|
101
|
+
throw new CliError(message, { exitCode: EXIT_VALIDATION });
|
|
102
|
+
}
|
|
103
|
+
const defaultTwin = nonEmptyString(meta["default_twin"]);
|
|
104
|
+
const twin = nonEmptyString(ctx.opt("twin")) ?? defaultTwin;
|
|
105
|
+
if (twin === undefined) {
|
|
106
|
+
throw new CliError("The server did not specify a default twin. Pass --twin TWIN.", { exitCode: EXIT_VALIDATION });
|
|
107
|
+
}
|
|
108
|
+
const yaml = renderTemplateYaml(source, id, { defaultTwin: defaultTwin ?? "", twin, title: ctx.opt("title") });
|
|
109
|
+
if (ctx.global.dryRun) {
|
|
110
|
+
if (ctx.global.json) {
|
|
111
|
+
emitJson({ ok: true, dry_run: true, id, template, path, yaml });
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
out(`Dry run: would write ${path} from template '${displayText(template)}'.`);
|
|
115
|
+
}
|
|
116
|
+
return EXIT_OK;
|
|
117
|
+
}
|
|
118
|
+
checkOutputPath(path, ctx.io.cwd);
|
|
119
|
+
writeFileAtomic(path, yaml, { label: "scenario YAML", fileMode: 0o644, exclusive: !force, refuseSymlink: true });
|
|
120
|
+
if (ctx.global.json) {
|
|
121
|
+
emitJson({ ok: true, id, template, path });
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
out(`Created ${path} from template '${displayText(template)}'.`);
|
|
125
|
+
}
|
|
126
|
+
return EXIT_OK;
|
|
127
|
+
}
|
|
128
|
+
function pullDestination(ctx, id) {
|
|
129
|
+
const dir = resolve(ctx.io.cwd, ctx.opt("dir") ?? ".");
|
|
130
|
+
const path = resolveOutputPath(dir, ctx.opt("out") ?? `${id}.yaml`);
|
|
131
|
+
if (basename(path).toLowerCase() === SIDECAR_FILENAME) {
|
|
132
|
+
throw new CliError(`Choose a YAML file path separate from ${SIDECAR_FILENAME}.`, { exitCode: EXIT_VALIDATION });
|
|
133
|
+
}
|
|
134
|
+
checkOutputPath(path, dir);
|
|
135
|
+
checkOutputPath(sidecarPath(dirname(path)), dir);
|
|
136
|
+
return { dir, path };
|
|
137
|
+
}
|
|
138
|
+
async function pullToDisk(client, id, { dir, path }, dryRun) {
|
|
139
|
+
const detail = withResponseEtag(await client.request("GET", scenarioPath(id)));
|
|
140
|
+
if (!isScenarioId(detail["id"]) || detail["id"] !== id) {
|
|
141
|
+
throw new CliError(`Unexpected scenario ID from server: ${JSON.stringify(detail["id"])}.`);
|
|
142
|
+
}
|
|
143
|
+
const yaml = yamlOf(detail);
|
|
144
|
+
const reference = asObject(asObject(detail["body"])["reference"]);
|
|
145
|
+
const names = new Set();
|
|
146
|
+
for (const name of asArray(reference["screens"])) {
|
|
147
|
+
if (!isScreenName(name)) {
|
|
148
|
+
throw new CliError(`Refusing unsafe screen filename from server: ${JSON.stringify(name)}.`);
|
|
149
|
+
}
|
|
150
|
+
names.add(name);
|
|
151
|
+
}
|
|
152
|
+
const screensDir = join(dirname(path), "screens");
|
|
153
|
+
if (names.size > 0 && basename(path).toLowerCase() === "screens") {
|
|
154
|
+
throw new CliError("Choose a YAML file path separate from the screens directory.", { exitCode: EXIT_VALIDATION });
|
|
155
|
+
}
|
|
156
|
+
const screens = [...names].map((name) => {
|
|
157
|
+
const target = join(screensDir, name);
|
|
158
|
+
checkOutputPath(target, dir);
|
|
159
|
+
return { name, target };
|
|
160
|
+
});
|
|
161
|
+
const result = { scenario: detail, yaml_path: path, screen_paths: screens.map(({ target }) => target) };
|
|
162
|
+
const downloads = [];
|
|
163
|
+
for (const { name, target } of screens) {
|
|
164
|
+
const { body } = await client.request("GET", `/api/screens/${encodeURIComponent(name)}`);
|
|
165
|
+
if (typeof body["content"] !== "string") {
|
|
166
|
+
throw new CliError(`The server response is missing content for screen '${name}'.`);
|
|
167
|
+
}
|
|
168
|
+
downloads.push({ target, content: body["content"] });
|
|
169
|
+
}
|
|
170
|
+
if (dryRun) {
|
|
171
|
+
return { ...result, dry_run: true, sidecar: null };
|
|
172
|
+
}
|
|
173
|
+
// Recheck after downloading. Publish the YAML and its revision state after all screens are present.
|
|
174
|
+
checkOutputPath(path, dir);
|
|
175
|
+
checkOutputPath(sidecarPath(dirname(path)), dir);
|
|
176
|
+
for (const { target } of downloads) {
|
|
177
|
+
checkOutputPath(target, dir);
|
|
178
|
+
}
|
|
179
|
+
for (const { target, content } of downloads) {
|
|
180
|
+
writeFileAtomic(target, content, { label: "screen", fileMode: 0o644, refuseSymlink: true });
|
|
181
|
+
}
|
|
182
|
+
writeFileAtomic(path, yaml, { label: "scenario YAML", fileMode: 0o644, refuseSymlink: true });
|
|
183
|
+
return { ...result, sidecar: updateSidecar(path, detail, client.serverUrl) };
|
|
184
|
+
}
|
|
185
|
+
async function pull(ctx) {
|
|
186
|
+
const id = requireId(ctx.positionals[0]);
|
|
187
|
+
const target = pullDestination(ctx, id);
|
|
188
|
+
const path = target.path;
|
|
189
|
+
const result = await pullToDisk(ctx.client(), id, target, ctx.global.dryRun);
|
|
190
|
+
if (ctx.global.json) {
|
|
191
|
+
emitJson(result);
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
const prefix = ctx.global.dryRun ? "Dry run: would pull" : "Pulled";
|
|
195
|
+
out(`${prefix} ${id} (${displayText(result.scenario["origin"])}) -> ${path}`);
|
|
196
|
+
for (const target of result.screen_paths) {
|
|
197
|
+
out(` screen ${target}`);
|
|
198
|
+
}
|
|
199
|
+
if (!ctx.global.dryRun && result.scenario["origin"] === "server") {
|
|
200
|
+
out(`Rev ${displayText(result.scenario["current_rev"])} ETag ${displayText(result.scenario["etag"])}`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return EXIT_OK;
|
|
204
|
+
}
|
|
205
|
+
function validationPassed(status, payload) {
|
|
206
|
+
return status === 200 && payload["ok"] === true && payload["can_save"] === true;
|
|
207
|
+
}
|
|
208
|
+
async function requestValidation(client, yaml, id, warnings) {
|
|
209
|
+
return client.request("POST", `${SCENARIOS}/validate`, {
|
|
210
|
+
jsonBody: authoringBody({ yaml, ...(id === undefined ? {} : { current_id: id }), ...warnings }),
|
|
211
|
+
allowStatuses: allowValidation,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
function printValidation(body) {
|
|
215
|
+
printValidationIssues(body);
|
|
216
|
+
if (body["message"]) {
|
|
217
|
+
errOut(displayText(body["message"]));
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function validate(ctx) {
|
|
221
|
+
const file = resolve(ctx.io.cwd, ctx.positionals[0] ?? "");
|
|
222
|
+
const yaml = readUtf8File(file, MAX_SCENARIO_BYTES);
|
|
223
|
+
const client = ctx.client();
|
|
224
|
+
const explicit = ctx.opt("id");
|
|
225
|
+
// Bound by --id or by the file name recorded at the last pull, never by the `id:` typed into the file:
|
|
226
|
+
// an edited or copied `id:` must not change which server scenario the file is judged against.
|
|
227
|
+
const saved = lookupSidecar(file, explicit, { serverUrl: client.serverUrl });
|
|
228
|
+
const savedId = saved.entry?.["origin"] === "server" ? saved.id ?? undefined : undefined;
|
|
229
|
+
const id = explicit === undefined ? savedId : requireId(explicit);
|
|
230
|
+
const { status, body } = await requestValidation(client, yaml, id, acknowledgedWarnings(ctx));
|
|
231
|
+
const passed = validationPassed(status, body);
|
|
232
|
+
if (ctx.global.json) {
|
|
233
|
+
emitJson(body);
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
printValidation(body);
|
|
237
|
+
if (body["ok"] === true) {
|
|
238
|
+
const outcome = passed ? "Valid" : "Validation warnings require acknowledgement";
|
|
239
|
+
out(`${outcome} (${displayText(body["twin"])}, lanes=${displayText(stringList(body["lanes"]).join(","))}, ` +
|
|
240
|
+
`voice_hash=${displayText(body["voice_hash"])}, text_hash=${displayText(body["text_hash"])})`);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return passed ? EXIT_OK : EXIT_VALIDATION;
|
|
244
|
+
}
|
|
245
|
+
function impact(previous, response) {
|
|
246
|
+
const { changes, notice } = hashImpactChanges(previous, response);
|
|
247
|
+
const json = Object.fromEntries(Object.entries(changes).map(([key, [from, to]]) => [key, { from, to }]));
|
|
248
|
+
if (notice) {
|
|
249
|
+
json["notice"] = notice;
|
|
250
|
+
}
|
|
251
|
+
return { changes, notice, json };
|
|
252
|
+
}
|
|
253
|
+
function mutationInvalid(ctx, body) {
|
|
254
|
+
if (ctx.global.json) {
|
|
255
|
+
emitJson(body);
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
printValidation(body);
|
|
259
|
+
}
|
|
260
|
+
return EXIT_VALIDATION;
|
|
261
|
+
}
|
|
262
|
+
async function dryPush(ctx, client, yaml, id, updateId, previous, warnings) {
|
|
263
|
+
if (updateId !== undefined) {
|
|
264
|
+
const current = await client.request("GET", scenarioPath(updateId), { allowStatuses: [404] });
|
|
265
|
+
if (current.status === 404) {
|
|
266
|
+
throw new CliError(`Scenario '${updateId}' does not exist on the server. Pass --create to create it.`, { exitCode: EXIT_VALIDATION });
|
|
267
|
+
}
|
|
268
|
+
if (current.body["origin"] === "git") {
|
|
269
|
+
throw gitReadOnly(updateId);
|
|
270
|
+
}
|
|
271
|
+
if (current.body["status"] === "archived") {
|
|
272
|
+
throw new CliError(`Scenario '${updateId}' is archived. Restore it before updating.`, { exitCode: EXIT_CONFLICT });
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const { status, body } = await requestValidation(client, yaml, updateId, warnings);
|
|
276
|
+
const change = impact(previous, body);
|
|
277
|
+
const passed = validationPassed(status, body);
|
|
278
|
+
if (ctx.global.json) {
|
|
279
|
+
emitJson({ dry_run: true, action: updateId === undefined ? "create" : "update", id, validation: body, hash_impact: change.json });
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
printValidation(body);
|
|
283
|
+
printHashImpactBanner(change.changes, change.notice);
|
|
284
|
+
if (passed) {
|
|
285
|
+
out(`Dry run OK: would ${updateId === undefined ? "create" : "update " + updateId}.`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return passed ? EXIT_OK : EXIT_VALIDATION;
|
|
289
|
+
}
|
|
290
|
+
function gitReadOnly(id) {
|
|
291
|
+
const message = `Scenario '${id}' is Git-managed and read-only. Use 'evalctl fork ${id} <new-id>' to create an editable copy.`;
|
|
292
|
+
return new CliError(message, { exitCode: EXIT_CONFLICT, payload: { error: "git_read_only", message } });
|
|
293
|
+
}
|
|
294
|
+
function requirePushEtag(id, value) {
|
|
295
|
+
if (value !== undefined) {
|
|
296
|
+
return value;
|
|
297
|
+
}
|
|
298
|
+
const message = `An If-Match ETag is required to update '${id}'. Pull the scenario first or pass --if-match ETAG.`;
|
|
299
|
+
throw new CliError(message, { exitCode: EXIT_CONFLICT, payload: { error: "precondition_required", message } });
|
|
300
|
+
}
|
|
301
|
+
async function push(ctx) {
|
|
302
|
+
const file = resolve(ctx.io.cwd, ctx.positionals[0] ?? "");
|
|
303
|
+
const yaml = readUtf8File(file, MAX_SCENARIO_BYTES);
|
|
304
|
+
const client = ctx.client();
|
|
305
|
+
const requested = ctx.opt("id") ?? peekScenarioId(yaml);
|
|
306
|
+
const saved = lookupSidecar(file, requested, { serverUrl: client.serverUrl });
|
|
307
|
+
const id = requested ?? saved.id;
|
|
308
|
+
const updateId = ctx.flag("create") ? undefined : requireId(id);
|
|
309
|
+
const warnings = acknowledgedWarnings(ctx);
|
|
310
|
+
if (ctx.global.dryRun) {
|
|
311
|
+
return dryPush(ctx, client, yaml, id, updateId, saved.entry, warnings);
|
|
312
|
+
}
|
|
313
|
+
const jsonBody = authoringBody({ yaml, ...summaryBody(ctx), ...warnings });
|
|
314
|
+
const explicitEtag = nonEmptyString(ctx.opt("if-match"));
|
|
315
|
+
if (updateId !== undefined && explicitEtag === undefined && saved.entry?.["origin"] === "git") {
|
|
316
|
+
throw gitReadOnly(updateId); // pulling again never yields an ETag for a Git scenario: only a fork can be edited
|
|
317
|
+
}
|
|
318
|
+
const etag = updateId === undefined
|
|
319
|
+
? undefined
|
|
320
|
+
: requirePushEtag(updateId, explicitEtag ?? nonEmptyString(saved.entry?.["etag"]));
|
|
321
|
+
checkOutputPath(sidecarPath(dirname(file)), dirname(file));
|
|
322
|
+
const response = await client.request(updateId === undefined ? "POST" : "PUT", updateId === undefined ? SCENARIOS : scenarioPath(updateId), {
|
|
323
|
+
jsonBody, ...(etag === undefined ? {} : { headers: { "If-Match": etag } }), allowStatuses: allowValidation,
|
|
324
|
+
});
|
|
325
|
+
if (response.status === 422) {
|
|
326
|
+
return mutationInvalid(ctx, response.body);
|
|
327
|
+
}
|
|
328
|
+
const body = withResponseEtag(response);
|
|
329
|
+
if (!isScenarioId(body["id"]) || (updateId !== undefined && body["id"] !== updateId)) {
|
|
330
|
+
throw new CliError("The server returned an unexpected scenario ID after saving.");
|
|
331
|
+
}
|
|
332
|
+
const change = impact(saved.entry, body);
|
|
333
|
+
const sidecar = updateSidecar(file, body, client.serverUrl);
|
|
334
|
+
if (ctx.global.json) {
|
|
335
|
+
emitJson({ scenario: body, sidecar, hash_impact: change.json });
|
|
336
|
+
}
|
|
337
|
+
else {
|
|
338
|
+
printValidationIssues(body);
|
|
339
|
+
printHashImpactBanner(change.changes, change.notice);
|
|
340
|
+
out(`Pushed ${displayText(body["id"])} -> rev ${displayText(body["current_rev"])} (etag ${displayText(body["etag"])})`);
|
|
341
|
+
}
|
|
342
|
+
return EXIT_OK;
|
|
343
|
+
}
|
|
344
|
+
async function fork(ctx) {
|
|
345
|
+
const sourceId = requireId(ctx.positionals[0]);
|
|
346
|
+
const newId = requireId(ctx.positionals[1]);
|
|
347
|
+
const file = ctx.opt("file");
|
|
348
|
+
const yaml = file === undefined ? undefined : readUtf8File(resolve(ctx.io.cwd, file), MAX_SCENARIO_BYTES);
|
|
349
|
+
const dry = ctx.global.dryRun;
|
|
350
|
+
const target = ctx.flag("no-pull") ? undefined : pullDestination(ctx, newId);
|
|
351
|
+
const client = ctx.client();
|
|
352
|
+
const { status, body } = await client.request("POST", `${scenarioPath(sourceId)}/fork`, {
|
|
353
|
+
jsonBody: authoringBody({
|
|
354
|
+
new_id: newId, ...(yaml === undefined ? {} : { yaml }), ...summaryBody(ctx), ...acknowledgedWarnings(ctx),
|
|
355
|
+
...(dry ? { dry_run: true } : {}),
|
|
356
|
+
}),
|
|
357
|
+
allowStatuses: allowValidation,
|
|
358
|
+
});
|
|
359
|
+
if (dry) {
|
|
360
|
+
const validation = isObject(body["validation"]) ? body["validation"] : body;
|
|
361
|
+
const passed = validationPassed(status, validation);
|
|
362
|
+
if (ctx.global.json) {
|
|
363
|
+
emitJson(body);
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
printValidation({ ...validation, message: body["message"] ?? validation["message"] });
|
|
367
|
+
if (passed) {
|
|
368
|
+
out(`Dry run OK: would fork '${sourceId}' -> '${newId}'.`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return passed ? EXIT_OK : EXIT_VALIDATION;
|
|
372
|
+
}
|
|
373
|
+
if (status === 422) {
|
|
374
|
+
return mutationInvalid(ctx, body);
|
|
375
|
+
}
|
|
376
|
+
if (body["id"] !== newId) {
|
|
377
|
+
throw new CliError("The server returned an unexpected scenario ID after forking.");
|
|
378
|
+
}
|
|
379
|
+
let pulled = null;
|
|
380
|
+
if (target !== undefined) {
|
|
381
|
+
try {
|
|
382
|
+
pulled = await pullToDisk(client, newId, target, false);
|
|
383
|
+
}
|
|
384
|
+
catch (err) {
|
|
385
|
+
const message = `Forked '${sourceId}' to '${newId}' on the server. Pull failed: ${errorMessage(err)}`;
|
|
386
|
+
throw new CliError(message, {
|
|
387
|
+
exitCode: err instanceof CliError ? err.exitCode : undefined,
|
|
388
|
+
payload: { error: "fork_pull_failed", message, scenario: body },
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (ctx.global.json) {
|
|
393
|
+
emitJson({ scenario: body, pulled });
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
out(`Forked ${sourceId} -> ${newId} (rev ${displayText(body["current_rev"])}, etag ${displayText(body["etag"])})`);
|
|
397
|
+
if (pulled) {
|
|
398
|
+
out(`Pulled to ${pulled.yaml_path}`);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return EXIT_OK;
|
|
402
|
+
}
|
|
403
|
+
async function history(ctx) {
|
|
404
|
+
const id = requireId(ctx.positionals[0]);
|
|
405
|
+
const { body } = await ctx.client().request("GET", `${scenarioPath(id)}/revisions`);
|
|
406
|
+
if (ctx.global.json) {
|
|
407
|
+
emitJson(body);
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
const rows = asArray(body["revisions"]).filter(isObject).map((rev) => [
|
|
411
|
+
rev["rev"], rev["action"], formatTimestamp(rev["changed_at"]), rev["changed_by"], rev["voice_hash"], rev["text_hash"], rev["change_summary"],
|
|
412
|
+
]);
|
|
413
|
+
out(rows.length === 0
|
|
414
|
+
? `No revisions for ${id}.`
|
|
415
|
+
: formatTable(["REV", "ACTION", "CHANGED_AT", "BY", "VOICE_HASH", "TEXT_HASH", "SUMMARY"], rows));
|
|
416
|
+
}
|
|
417
|
+
return EXIT_OK;
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* The server revision a local file is compared with: `--to` or `--from` (one of them), `current` or a positive whole number.
|
|
421
|
+
* Anything else is refused here, since the server would answer a different question than the one that was asked.
|
|
422
|
+
*/
|
|
423
|
+
function localRevision(from, to) {
|
|
424
|
+
if (from !== undefined && to !== undefined) {
|
|
425
|
+
throw new CliError("With --local pass only one of --from and --to: the other side is the local file.", {
|
|
426
|
+
exitCode: EXIT_VALIDATION,
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const selector = to ?? from;
|
|
430
|
+
if (selector === undefined || selector === "current") {
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
if (!/^[1-9]\d*$/.test(selector) || !Number.isSafeInteger(Number(selector))) {
|
|
434
|
+
throw new CliError(`A revision must be 'current' or a positive whole number (got ${JSON.stringify(selector)}).`, {
|
|
435
|
+
exitCode: EXIT_VALIDATION,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
return selector;
|
|
439
|
+
}
|
|
440
|
+
async function diff(ctx) {
|
|
441
|
+
const id = requireId(ctx.positionals[0]);
|
|
442
|
+
const path = scenarioPath(id);
|
|
443
|
+
const local = ctx.opt("local");
|
|
444
|
+
const from = ctx.opt("from");
|
|
445
|
+
const to = ctx.opt("to");
|
|
446
|
+
const rev = local === undefined ? undefined : localRevision(from, to);
|
|
447
|
+
const client = ctx.client();
|
|
448
|
+
if (local !== undefined) {
|
|
449
|
+
const localYaml = readUtf8File(resolve(ctx.io.cwd, local), MAX_SCENARIO_BYTES);
|
|
450
|
+
const { body } = await client.request("GET", rev === undefined ? path : `${path}/revisions/${rev}`);
|
|
451
|
+
const label = rev === undefined ? `${id}@server.yaml` : `${id}@rev-${rev}.yaml`;
|
|
452
|
+
const patch = unifiedDiff(splitLinesKeepEnds(yamlOf(body)), splitLinesKeepEnds(localYaml), label, local);
|
|
453
|
+
if (ctx.global.json) {
|
|
454
|
+
emitJson({ scenario_id: id, changed: patch !== "", diff: patch, local });
|
|
455
|
+
}
|
|
456
|
+
else {
|
|
457
|
+
outRaw(patch || "No differences.\n");
|
|
458
|
+
}
|
|
459
|
+
return EXIT_OK;
|
|
460
|
+
}
|
|
461
|
+
const { body } = await client.request("GET", `${path}/diff`, { query: { from, to } });
|
|
462
|
+
if (ctx.global.json) {
|
|
463
|
+
emitJson(body);
|
|
464
|
+
}
|
|
465
|
+
else if (body["changed"] === true && typeof body["diff"] === "string" && body["diff"] !== "") {
|
|
466
|
+
outRaw(body["diff"]);
|
|
467
|
+
}
|
|
468
|
+
else {
|
|
469
|
+
out("No differences.");
|
|
470
|
+
}
|
|
471
|
+
return EXIT_OK;
|
|
472
|
+
}
|
|
473
|
+
const actionVerbs = { rollback: "Rolled back", archive: "Archived", restore: "Restored" };
|
|
474
|
+
async function changeState(ctx, action) {
|
|
475
|
+
const id = requireId(ctx.positionals[0]);
|
|
476
|
+
const jsonBody = { ...summaryBody(ctx), ...acknowledgedWarnings(ctx) };
|
|
477
|
+
let prompt;
|
|
478
|
+
if (action === "rollback") {
|
|
479
|
+
const input = ctx.positionals[1] ?? "";
|
|
480
|
+
const rev = Number(input);
|
|
481
|
+
if (!/^\d+$/.test(input) || !Number.isSafeInteger(rev) || rev < 1) {
|
|
482
|
+
throw new CliError("Revision number must be a positive integer.", { exitCode: EXIT_VALIDATION });
|
|
483
|
+
}
|
|
484
|
+
jsonBody["rev"] = rev;
|
|
485
|
+
prompt = `Roll back '${id}' to rev ${rev}? [y/N]: `;
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
prompt = `${action === "archive" ? "Archive" : "Restore"} scenario '${id}'? [y/N]: `;
|
|
489
|
+
}
|
|
490
|
+
const client = ctx.client();
|
|
491
|
+
const { etag } = await resolveEtagForAction(client, id, ctx.opt("if-match"), ctx.io.cwd);
|
|
492
|
+
if (ctx.global.dryRun) {
|
|
493
|
+
if (ctx.global.json) {
|
|
494
|
+
emitJson({ dry_run: true, action, id, if_match: etag, ...jsonBody });
|
|
495
|
+
}
|
|
496
|
+
else {
|
|
497
|
+
out(`Dry run: would ${action} '${id}' (If-Match: ${displayText(etag)}).`);
|
|
498
|
+
}
|
|
499
|
+
return EXIT_OK;
|
|
500
|
+
}
|
|
501
|
+
await confirmAction(ctx, prompt, `Aborted ${action} for ${id}.`);
|
|
502
|
+
const result = await client.request("POST", `${scenarioPath(id)}/${action}`, {
|
|
503
|
+
jsonBody: authoringBody(jsonBody), ...(etag === null ? {} : { headers: { "If-Match": etag } }),
|
|
504
|
+
allowStatuses: allowValidation,
|
|
505
|
+
});
|
|
506
|
+
if (result.status === 422) {
|
|
507
|
+
return mutationInvalid(ctx, result.body);
|
|
508
|
+
}
|
|
509
|
+
const detail = withResponseEtag(result);
|
|
510
|
+
const needsPull = recordScenarioAction(ctx.io.cwd, id, detail, client.serverUrl, action === "archive" ? etag ?? undefined : undefined);
|
|
511
|
+
if (ctx.global.json) {
|
|
512
|
+
emitJson(result.body);
|
|
513
|
+
}
|
|
514
|
+
else {
|
|
515
|
+
printValidationIssues(detail);
|
|
516
|
+
out(`${actionVerbs[action]} ${id} -> status=${displayText(detail["status"])}, rev=${displayText(detail["current_rev"])}, etag=${displayText(detail["etag"])}`);
|
|
517
|
+
if (needsPull) {
|
|
518
|
+
out(`Run 'evalctl pull ${id}' to sync local YAML with the server revision.`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
return EXIT_OK;
|
|
522
|
+
}
|
|
523
|
+
const summary = { type: "string", placeholder: "TEXT", description: "Revision change summary" };
|
|
524
|
+
const ifMatch = {
|
|
525
|
+
type: "string",
|
|
526
|
+
placeholder: "ETAG",
|
|
527
|
+
description: "Revision tag (ETag) the change must start from; default: the one saved by pull or push",
|
|
528
|
+
};
|
|
529
|
+
const dir = { type: "string", placeholder: "DIR", description: "Target directory", default: "." };
|
|
530
|
+
const outPath = { type: "string", placeholder: "PATH", description: "Output YAML path" };
|
|
531
|
+
function command(name, summaryText, args, count, handler, options) {
|
|
532
|
+
return { name, summary: summaryText, usage: name + args, positionals: { min: count, max: count }, handler, options };
|
|
533
|
+
}
|
|
534
|
+
export const scenarioCommands = [
|
|
535
|
+
command("list", "List scenarios", " [--origin ORIGIN] [--status STATUS] [--twin TWIN] [--family FAMILY] [--tag TAG] [-q TEXT]", 0, list, {
|
|
536
|
+
origin: { type: "string", placeholder: "ORIGIN", choices: originChoices, description: "Where scenarios are managed: git is read-only, server is editable" },
|
|
537
|
+
status: { type: "string", placeholder: "STATUS", choices: statusChoices, description: "Only scenarios in this state" },
|
|
538
|
+
twin: { type: "string", placeholder: "TWIN", description: "Only scenarios for this twin" },
|
|
539
|
+
family: { type: "string", placeholder: "FAMILY", description: "Only scenarios of this family" },
|
|
540
|
+
tag: { type: "string", placeholder: "TAG", description: "Only scenarios with this tag" },
|
|
541
|
+
search: { type: "string", short: "q", placeholder: "TEXT", description: "Free-text search" },
|
|
542
|
+
}),
|
|
543
|
+
command("show", "Show one scenario", " <id> [--yaml]", 1, show, {
|
|
544
|
+
yaml: { type: "boolean", description: "Print only the canonical YAML" },
|
|
545
|
+
}),
|
|
546
|
+
command("new", "Scaffold a scenario YAML file from a server template", " <id> [--template T] [--twin TWIN] [--title TEXT]", 1, scaffold, {
|
|
547
|
+
template: { type: "string", placeholder: "NAME", description: "Server template name (default: the first template the server offers)" },
|
|
548
|
+
twin: { type: "string", placeholder: "TWIN", description: "Twin the scenario talks to (default: the server's default twin)" },
|
|
549
|
+
title: { type: "string", placeholder: "TEXT", description: "Scenario title" },
|
|
550
|
+
out: { ...outPath, description: "Output file (default: <id>.yaml)" },
|
|
551
|
+
force: { type: "boolean", description: "Overwrite an existing file" },
|
|
552
|
+
}),
|
|
553
|
+
command("pull", "Download a scenario and its screens into a local directory", " <id> [--dir DIR] [--out PATH]", 1, pull, {
|
|
554
|
+
dir, out: outPath,
|
|
555
|
+
}),
|
|
556
|
+
command("validate", "Validate a local scenario file against the server's rules", " <file> [--id ID] [--ack CODE]", 1, validate, {
|
|
557
|
+
id: { type: "string", placeholder: "ID", description: "Existing server scenario being edited" },
|
|
558
|
+
ack,
|
|
559
|
+
}),
|
|
560
|
+
command("push", "Create or update a server scenario from a local file", " <file> [--id ID] [--create] [--ack CODE]", 1, push, {
|
|
561
|
+
id: { type: "string", placeholder: "ID", description: "Target scenario ID" },
|
|
562
|
+
create: { type: "boolean", description: "Create a new server scenario" },
|
|
563
|
+
ack, summary, "if-match": ifMatch,
|
|
564
|
+
}),
|
|
565
|
+
command("fork", "Fork a Git-managed scenario into an editable server copy", " <git-id> <new-id> [--file PATH]", 2, fork, {
|
|
566
|
+
file: { type: "string", placeholder: "PATH", description: "YAML file overriding the source" },
|
|
567
|
+
summary, ack, dir, out: outPath,
|
|
568
|
+
"no-pull": { type: "boolean", description: "Skip downloading the fork" },
|
|
569
|
+
}),
|
|
570
|
+
command("history", "Show a scenario's revision history", " <id>", 1, history),
|
|
571
|
+
command("diff", "Diff two revisions, or a revision against a local file", " <id> [--from REV] [--to REV] [--local FILE]", 1, diff, {
|
|
572
|
+
from: { type: "string", placeholder: "REV", description: "Older revision: a number or 'current'; with --local, the revision to compare (instead of --to)" },
|
|
573
|
+
to: { type: "string", placeholder: "REV", description: "Newer revision: a number or 'current'; with --local, the revision to compare (instead of --from)" },
|
|
574
|
+
local: { type: "string", placeholder: "FILE", description: "Compare a local YAML file with one server revision (default: the current one)" },
|
|
575
|
+
}),
|
|
576
|
+
command("rollback", "Roll a server scenario back to an earlier revision", " <id> <rev>", 2, (ctx) => changeState(ctx, "rollback"), {
|
|
577
|
+
summary, ack, "if-match": ifMatch, yes,
|
|
578
|
+
}),
|
|
579
|
+
command("archive", "Archive a server scenario", " <id>", 1, (ctx) => changeState(ctx, "archive"), {
|
|
580
|
+
summary, "if-match": ifMatch, yes,
|
|
581
|
+
}),
|
|
582
|
+
command("restore", "Restore an archived server scenario", " <id>", 1, (ctx) => changeState(ctx, "restore"), {
|
|
583
|
+
summary, ack, "if-match": ifMatch, yes,
|
|
584
|
+
}),
|
|
585
|
+
];
|