@zalosai/zalos-cli 0.2.19 → 0.2.21

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/PUBLISHING.md CHANGED
@@ -59,6 +59,18 @@ Do not publish with uncommitted package changes or reuse an existing version.
59
59
 
60
60
  ## Central developer access release
61
61
 
62
+ Version 0.2.21 adds `workflow view --published` and `workflow export --published`
63
+ for reading client-facing workflow definitions through the existing API. These
64
+ reads omit draft update checksums and reject protected workflows that resolve to
65
+ an unpublished version. Team-scoped `export --all --published` is supported;
66
+ cross-team `--all-teams --published` is not.
67
+
68
+ Version 0.2.20 adds `zl workflow eval` for evaluation suites, cases, results,
69
+ incidents, evidence, captured-execution scoring, case launches and thread
70
+ consolidation. Writes preview by default and require `--apply`. Deploy the
71
+ workflow-evaluation API stack before publishing this version; consolidation
72
+ also requires its API and a configured model.
73
+
62
74
  Version 0.2.19 adds Custom Page sidebar group management with
63
75
  `zl custom-page navigation get --manage` and `zl custom-page navigation set --file`.
64
76
  Groups support named views and optional child icons. Changes preview by default
package/README.md CHANGED
@@ -144,12 +144,72 @@ Workflow import/update/publish require `--apply`; without it they validate and p
144
144
  from the signed-in human's team membership, role, and token scopes. Credential reads
145
145
  return metadata only. No product command loads database credentials.
146
146
 
147
+ ### Workflow evaluations
148
+
149
+ Evaluation commands use the selected environment and profile's team. They require
150
+ an API with workflow evaluations enabled; thread consolidation additionally requires
151
+ the consolidation API and a configured model. No command falls back to the database.
152
+
153
+ ```bash
154
+ zl --environment staging workflow eval summary <workflow-id>
155
+ zl --environment staging workflow eval suite get <workflow-id> --output /tmp/eval-suite.json
156
+ # Edit the suite's cases, fixtures, expectations or monitoringEnabled; retain revision.
157
+ zl --environment staging workflow eval suite set <workflow-id> --input /tmp/eval-suite.json
158
+ zl --environment staging workflow eval suite set <workflow-id> --input /tmp/eval-suite.json --apply
159
+ zl --environment staging workflow eval case list <workflow-id>
160
+ zl --environment staging workflow eval case view <workflow-id> <case-id>
161
+ zl --environment staging workflow eval evaluate <workflow-id> --execution-id <execution-id> --case-id <case-id> --apply
162
+ zl --environment staging workflow eval launch <workflow-id> --case-id <case-id> --request-id <stable-request-id> --apply
163
+ zl --environment staging workflow eval result list <workflow-id> --fields id,status,executionId
164
+ zl --environment staging workflow eval result view <workflow-id> <run-id>
165
+ zl --environment staging workflow eval evidence <workflow-id> <run-id> --output /tmp/eval-evidence.json
166
+ zl --environment staging workflow eval consolidate <workflow-id> --execution-id <execution-id> --output /tmp/proposal.json --apply
167
+ zl --environment staging workflow eval incident list <workflow-id> --status open
168
+ zl --environment staging workflow eval incident view <workflow-id> <incident-id>
169
+ zl --environment staging workflow eval incident resolve <workflow-id> <incident-id> --apply
170
+ ```
171
+
172
+ Every evaluation write previews by default, including evaluation, launch, model
173
+ consolidation and incident resolution. `--dry-run` takes precedence over `--apply`.
174
+ Evaluation scores an existing execution and persists its result; launch executes
175
+ the saved case against the workflow draft using frozen fixtures. Reuse the same
176
+ `--request-id` after a lost launch response; changing it starts a separate execution.
177
+ Consolidation proposes turns only and never saves a suite or case automatically.
178
+
179
+ Suite exports always contain the full suite and revision, even with global `--fields`.
180
+ For a new suite, supply a definition and `--expected-revision 0`. Updates require the
181
+ exported revision (or an explicit matching `--expected-revision`); conflicts are
182
+ returned without fetching a newer revision or retrying the write. Export again and
183
+ reconcile your edits before retrying.
184
+
185
+ Result list/view cover the API's **recent 50 results**, and incident list/view its
186
+ **recent 100 incidents**. `--limit`, `--offset`, `--status` and `--fields` operate
187
+ inside those windows. Evidence downloads can address an older known run ID directly.
188
+ JSON files are written with mode 0600 and never overwrite an existing file. Evidence
189
+ requires `executions:read`, launches require `executions:write`, and suite/evaluation/
190
+ incident writes require `workflows:write`. Provision both workflow-write and
191
+ execution-read access for transcript consolidation.
192
+
147
193
  For protected workflows, `workflow update --apply` saves a draft. Its response reports
148
194
  whether runs use that version and names the live version when they do not. Use
149
195
  `workflow publish <workflow-id> --apply` to promote the current draft. `workflow export`
150
196
  keeps stdout as reusable workflow JSON and writes a structured stderr warning when the
151
197
  exported draft differs from the version used by runs.
152
198
 
199
+ Use `workflow view <id> --published` or `workflow export <id> --published` to read
200
+ the definition clients run, without publishing or changing the draft:
201
+
202
+ ```bash
203
+ zl --environment us-prod workflow export <workflow-id> --published --pretty --output /tmp/published.json
204
+ zl --environment us-prod workflow export --all --published --output /tmp/team-live-workflows.json
205
+ ```
206
+
207
+ Protected workflows return their published content; unprotected workflows return
208
+ their current definition. A protected workflow that falls back to a draft is
209
+ rejected. Published reads omit update checksums: export the current draft before
210
+ editing it. `--published` cannot be combined with `--all-teams`; select the owning
211
+ team and use an ID or `--all`.
212
+
153
213
  `workflow list --all-teams` and `workflow export --all-teams` read every workflow in
154
214
  the selected regional database. They require an internal Zalos human CLI token with
155
215
  `workflows:read`; external users and automation tokens are rejected. `workflow export --all`
@@ -0,0 +1,233 @@
1
+ import { open, readFile, unlink } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { client } from '../client.js';
4
+ import { ApiError, NotFoundError, ValidationError } from '../utils/errors.js';
5
+ import { filterSingle, printJson } from '../utils/output.js';
6
+ import { action, fields, isRow, printPage, resourceId } from '../utils/product-api.js';
7
+ const CONSOLIDATION_TIMEOUT_MS = 240_000;
8
+ function validateOutput(options, required = false) {
9
+ if (options.output === undefined && !required)
10
+ return;
11
+ if (typeof options.output !== 'string' || !options.output.trim())
12
+ throw new ValidationError('output', 'Provide a non-empty output file path');
13
+ }
14
+ function path(workflowId) {
15
+ return `/workflows/${resourceId(workflowId)}/evaluations`;
16
+ }
17
+ function caseId(value) {
18
+ if (!value || value.length > 128)
19
+ throw new ValidationError('caseId', 'Case IDs must be 1–128 characters');
20
+ return value;
21
+ }
22
+ function row(value) {
23
+ // Evaluation routes return bare JSON, unlike the product API's data envelope.
24
+ if (!isRow(value))
25
+ throw new ApiError(502, 'Expected an evaluation object');
26
+ return value;
27
+ }
28
+ function rows(value) {
29
+ if (!Array.isArray(value) || !value.every(isRow))
30
+ throw new ApiError(502, 'Expected evaluation rows');
31
+ return value;
32
+ }
33
+ async function output(produce, options) {
34
+ if (options.output === undefined) {
35
+ printJson(await produce());
36
+ return;
37
+ }
38
+ const destination = resolve(options.output);
39
+ const handle = await open(destination, 'wx', 0o600);
40
+ try {
41
+ await handle.writeFile(JSON.stringify(await produce(), null, 2) + '\n');
42
+ }
43
+ catch (error) {
44
+ await handle.close();
45
+ await unlink(destination);
46
+ throw error;
47
+ }
48
+ await handle.close();
49
+ printJson({ output: destination });
50
+ }
51
+ async function summary(workflowId) {
52
+ return row(await client.get(path(workflowId)));
53
+ }
54
+ function suite(value) {
55
+ if (!isRow(value.suite))
56
+ throw new NotFoundError('evaluation suite', 'not configured');
57
+ return value.suite;
58
+ }
59
+ export async function evalSummaryAction(workflowId, options) {
60
+ validateOutput(options);
61
+ await output(async () => filterSingle(await summary(workflowId), options.fields), options);
62
+ }
63
+ export async function evalSuiteGetAction(workflowId, options) {
64
+ validateOutput(options);
65
+ await output(async () => suite(await summary(workflowId)), options);
66
+ }
67
+ export async function evalSuiteSetAction(workflowId, options) {
68
+ const endpoint = `${path(workflowId)}/suite`;
69
+ let input;
70
+ try {
71
+ input = JSON.parse(await readFile(options.input, 'utf8'));
72
+ }
73
+ catch {
74
+ throw new ValidationError('input', 'Unable to read suite JSON');
75
+ }
76
+ if (!isRow(input) ||
77
+ typeof input.name !== 'string' ||
78
+ !['northwind_cash', 'ah_bill_reports'].includes(String(input.profile)) ||
79
+ !Array.isArray(input.cases) ||
80
+ typeof input.monitoringEnabled !== 'boolean')
81
+ throw new ValidationError('input', 'Expected a suite with name, profile, cases and monitoringEnabled');
82
+ if (input.workflowId !== undefined && input.workflowId !== workflowId)
83
+ throw new ValidationError('workflowId', 'Exported suite belongs to another workflow');
84
+ const exported = input.expectedRevision ?? input.revision;
85
+ const explicit = options.expectedRevision;
86
+ if (explicit !== undefined && !/^\d+$/.test(explicit))
87
+ throw new ValidationError('expectedRevision', 'Expected a nonnegative integer revision');
88
+ const revision = explicit === undefined ? exported : Number(explicit);
89
+ if (typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 0)
90
+ throw new ValidationError('expectedRevision', 'Keep the exported revision, or use --expected-revision 0 to create a suite');
91
+ if ((input.expectedRevision !== undefined &&
92
+ input.revision !== undefined &&
93
+ input.expectedRevision !== input.revision) ||
94
+ (explicit !== undefined && exported !== undefined && revision !== exported))
95
+ throw new ValidationError('expectedRevision', 'Revision options conflict with the exported revision');
96
+ const payload = {
97
+ name: input.name,
98
+ profile: input.profile,
99
+ cases: input.cases,
100
+ monitoringEnabled: input.monitoringEnabled,
101
+ expectedRevision: revision,
102
+ };
103
+ if (!options.apply || options.dryRun) {
104
+ printJson({ dryRun: true, method: 'PUT', path: endpoint, payload });
105
+ return;
106
+ }
107
+ printJson(row(await client.put(endpoint, payload)));
108
+ }
109
+ export async function evalListAction(workflowId, collection, options) {
110
+ const value = await summary(workflowId);
111
+ let items = rows(collection === 'cases' ? suite(value).cases : value[collection]);
112
+ if (options.status)
113
+ items = items.filter((item) => item.status === options.status);
114
+ printPage(items, options);
115
+ }
116
+ export async function evalViewAction(workflowId, collection, id, options) {
117
+ if (collection === 'cases')
118
+ caseId(id);
119
+ else
120
+ resourceId(id);
121
+ const value = await summary(workflowId);
122
+ const found = rows(collection === 'cases' ? suite(value).cases : value[collection]).find((item) => item.id === id);
123
+ if (!found)
124
+ throw new NotFoundError(collection === 'runs'
125
+ ? 'result in recent 50 runs (use evidence for older run IDs)'
126
+ : collection === 'incidents'
127
+ ? 'incident in recent 100 incidents'
128
+ : 'evaluation case', id);
129
+ printJson(filterSingle(found, options.fields));
130
+ }
131
+ export async function evalEvidenceAction(workflowId, runId, options) {
132
+ validateOutput(options, true);
133
+ const endpoint = `${path(workflowId)}/runs/${resourceId(runId)}/evidence`;
134
+ await output(async () => row(await client.get(endpoint)), options);
135
+ }
136
+ export async function evalOperationAction(workflowId, operation, options) {
137
+ validateOutput(options);
138
+ const root = path(workflowId);
139
+ let endpoint;
140
+ let payload;
141
+ if (operation === 'launch') {
142
+ const selectedCaseId = encodeURIComponent(caseId(options.caseId ?? ''));
143
+ if (!options.requestId || !/^[A-Za-z0-9_-]{8,100}$/.test(options.requestId))
144
+ throw new ValidationError('requestId', 'Use a stable request ID of 8–100 letters, digits, underscores or hyphens; reuse it for retries');
145
+ endpoint = `${root}/cases/${selectedCaseId}/launch`;
146
+ payload = { requestId: options.requestId };
147
+ }
148
+ else if (operation === 'resolve') {
149
+ endpoint = `${root}/incidents/${resourceId(options.incidentId ?? '')}/resolve`;
150
+ payload = {};
151
+ }
152
+ else {
153
+ endpoint = `${root}/${operation === 'consolidate' ? 'consolidations' : 'runs'}`;
154
+ payload = { executionId: resourceId(options.executionId ?? '') };
155
+ if (operation === 'evaluate' && options.caseId)
156
+ payload.caseId = caseId(options.caseId);
157
+ }
158
+ if (!options.apply || options.dryRun) {
159
+ printJson({ dryRun: true, method: 'POST', path: endpoint, payload });
160
+ return;
161
+ }
162
+ await output(async () => {
163
+ const result = operation === 'consolidate' || operation === 'evaluate'
164
+ ? await client.post(endpoint, payload, { timeoutMs: CONSOLIDATION_TIMEOUT_MS })
165
+ : await client.post(endpoint, payload);
166
+ return row(result);
167
+ }, options);
168
+ }
169
+ export function registerWorkflowEvalCommand(workflow, program) {
170
+ const cmd = workflow
171
+ .command('eval')
172
+ .description('Workflow evaluations (selected environment and team)');
173
+ cmd
174
+ .command('summary <workflow-id>')
175
+ .option('--output <file>', 'Write private JSON without overwriting')
176
+ .action(async (id, o) => action(() => evalSummaryAction(id, { ...o, ...fields(program) })));
177
+ const suites = cmd.command('suite').description('Export and replace the revisioned suite');
178
+ suites
179
+ .command('get <workflow-id>')
180
+ .option('--output <file>', 'Write full suite JSON including its revision')
181
+ .action(async (id, o) => action(() => evalSuiteGetAction(id, o)));
182
+ suites
183
+ .command('set <workflow-id>')
184
+ .requiredOption('--input <file>', 'Exported suite or suite definition JSON')
185
+ .option('--expected-revision <n>', 'Revision precondition; 0 creates a new suite')
186
+ .option('--apply', 'Save the proposed suite')
187
+ .option('--dry-run', 'Preview only, even with --apply')
188
+ .action(async (id, o) => action(() => evalSuiteSetAction(id, o)));
189
+ for (const [name, collection, description] of [
190
+ ['case', 'cases', 'Saved cases'],
191
+ ['result', 'runs', 'Recent 50 evaluation results (server summary window)'],
192
+ ['incident', 'incidents', 'Recent 100 live-monitor incidents (server summary window)'],
193
+ ]) {
194
+ const group = cmd.command(name).description(description);
195
+ group
196
+ .command('list <workflow-id>')
197
+ .option('--limit <n>', 'Maximum results from the summary window', '100')
198
+ .option('--offset <n>', 'Offset within the summary window', '0')
199
+ .option('--status <status>', 'Filter by status')
200
+ .action(async (id, o) => action(() => evalListAction(id, collection, { ...o, ...fields(program) })));
201
+ group
202
+ .command('view <workflow-id> <id>')
203
+ .action(async (workflowId, id) => action(() => evalViewAction(workflowId, collection, id, fields(program))));
204
+ if (collection === 'incidents')
205
+ group
206
+ .command('resolve <workflow-id> <incident-id>')
207
+ .option('--apply', 'Resolve the live incident')
208
+ .option('--dry-run', 'Preview resolution')
209
+ .action(async (id, incidentId, o) => action(() => evalOperationAction(id, 'resolve', { ...o, incidentId })));
210
+ }
211
+ cmd
212
+ .command('evidence <workflow-id> <run-id>')
213
+ .requiredOption('--output <file>', 'Private evidence JSON file (must not exist)')
214
+ .action(async (id, runId, o) => action(() => evalEvidenceAction(id, runId, o)));
215
+ for (const operation of ['evaluate', 'launch', 'consolidate']) {
216
+ const command = cmd
217
+ .command(`${operation} <workflow-id>`)
218
+ .option('--apply', 'Perform this operation; otherwise print a preview')
219
+ .option('--dry-run', 'Preview only, even with --apply');
220
+ if (operation === 'launch')
221
+ command
222
+ .requiredOption('--case-id <id>', 'Saved case ID')
223
+ .requiredOption('--request-id <id>', 'Stable idempotency key; reuse after a lost response');
224
+ else
225
+ command.requiredOption('--execution-id <id>', 'Captured execution ID');
226
+ if (operation === 'evaluate')
227
+ command.option('--case-id <id>', 'Saved case ID');
228
+ if (operation === 'consolidate')
229
+ command.option('--output <file>', 'Write proposal JSON without overwriting (does not save a case)');
230
+ command.action(async (id, o) => action(() => evalOperationAction(id, operation, o)));
231
+ }
232
+ }
233
+ //# sourceMappingURL=workflow-eval.js.map
@@ -2,10 +2,23 @@ import { writeFile, stat } from 'node:fs/promises';
2
2
  import { resolve, join } from 'node:path';
3
3
  import { client } from '../client.js';
4
4
  import { readWorkflowFile, serializeWorkflow } from '../workflow-file.js';
5
- import { ValidationError } from '../utils/errors.js';
5
+ import { ApiError, ValidationError } from '../utils/errors.js';
6
6
  import { filterSingle, printJson } from '../utils/output.js';
7
7
  import { action, dataRow, dataRows, fields, isRow, printPage, resourceId, } from '../utils/product-api.js';
8
8
  import { parseJson } from '../utils/validate.js';
9
+ import { registerWorkflowEvalCommand } from './workflow-eval.js';
10
+ async function readWorkflow(id, options) {
11
+ const workflow = dataRow(await client.get(`/workflows/${resourceId(id)}${options.published ? '?resolvePublished=true' : ''}`));
12
+ if (!options.published)
13
+ return workflow;
14
+ if (workflow.publishedVersionId && workflow.versionId !== workflow.publishedVersionId) {
15
+ throw new ApiError(502, 'The API did not resolve the published workflow version; refusing to export a draft');
16
+ }
17
+ // The client-facing API retains the current draft's checksum when resolving
18
+ // published content. Never let that token authorize an update with old content.
19
+ const { checksum: _checksum, expectedChecksum: _expectedChecksum, ...snapshot } = workflow;
20
+ return snapshot;
21
+ }
9
22
  function publicationStatus(workflow, publishedNow = false) {
10
23
  const draftVersionId = typeof workflow.versionId === 'string' ? workflow.versionId : undefined;
11
24
  const publishedVersionId = typeof workflow.publishedVersionId === 'string' ? workflow.publishedVersionId : undefined;
@@ -47,12 +60,14 @@ export async function listWorkflowsAction(options) {
47
60
  printPage(dataRows(await client.get(path)), options);
48
61
  }
49
62
  export async function viewWorkflowAction(id, options) {
50
- printJson(filterSingle(dataRow(await client.get(`/workflows/${resourceId(id)}`)), options.fields));
63
+ printJson(filterSingle(await readWorkflow(id, options), options.fields));
51
64
  }
52
65
  export async function exportWorkflowAction(id, options) {
53
66
  const selections = [Boolean(id), Boolean(options.all), Boolean(options.allTeams)].filter(Boolean).length;
54
67
  if (selections !== 1)
55
68
  throw new ValidationError('id', 'Choose a workflow ID, --all, or --all-teams');
69
+ if (options.published && options.allTeams)
70
+ throw new ValidationError('published', '--published cannot be combined with --all-teams; select the owning team and use an ID or --all');
56
71
  if (id)
57
72
  resourceId(id);
58
73
  const output = options.output ? resolve(options.output) : undefined;
@@ -79,7 +94,7 @@ export async function exportWorkflowAction(id, options) {
79
94
  });
80
95
  rows = [];
81
96
  for (const workflowId of ids)
82
- rows.push(filterSingle(dataRow(await client.get(`/workflows/${workflowId}`)), options.fields));
97
+ rows.push(filterSingle(await readWorkflow(workflowId, options), options.fields));
83
98
  }
84
99
  rows.forEach(warnIfWorkflowDraftIsUnpublished);
85
100
  if (options.separate && output) {
@@ -190,6 +205,7 @@ export async function runWorkflowAction(id, options) {
190
205
  }
191
206
  export function registerWorkflowCommand(program) {
192
207
  const cmd = program.command('workflow').description('Manage workflows through the regional API');
208
+ registerWorkflowEvalCommand(cmd, program);
193
209
  cmd
194
210
  .command('list')
195
211
  .option('--all-teams', 'List workflows across every team in the selected region')
@@ -198,11 +214,13 @@ export function registerWorkflowCommand(program) {
198
214
  .action(async (o) => action(() => listWorkflowsAction({ ...o, ...fields(program) })));
199
215
  cmd
200
216
  .command('view <id>')
201
- .action(async (id) => action(() => viewWorkflowAction(id, fields(program))));
217
+ .option('--published', 'Read the definition clients run (current when unprotected)')
218
+ .action(async (id, o) => action(() => viewWorkflowAction(id, { ...o, ...fields(program) })));
202
219
  cmd
203
220
  .command('export [id]')
204
221
  .option('--all', 'Export every accessible workflow')
205
222
  .option('--all-teams', 'Export workflows across every team in the selected region')
223
+ .option('--published', 'Export the definition clients run (current when unprotected); omits update checksum')
206
224
  .option('--output <path>', 'Output file (must not exist)')
207
225
  .option('--pretty', 'Indent JSON')
208
226
  .option('--separate', 'Write ID-named JSON in output directory')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.19",
3
+ "version": "0.2.21",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",