@zalosai/zalos-cli 0.2.36 → 0.2.37

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.
@@ -1,6 +1,7 @@
1
- import { writeFile, stat } from 'node:fs/promises';
1
+ import { readFile, writeFile, stat } from 'node:fs/promises';
2
2
  import { resolve, join } from 'node:path';
3
3
  import { client } from '../client.js';
4
+ import { auditWorkflowPayload, projectWorkflowPayload } from '../workflow-payload.js';
4
5
  import { parseWorkflowFile, readWorkflowFile, serializeWorkflow } from '../workflow-file.js';
5
6
  import { ApiError, NotFoundError, ValidationError } from '../utils/errors.js';
6
7
  import { filterSingle, printJson } from '../utils/output.js';
@@ -129,12 +130,31 @@ export async function exportWorkflowAction(id, options) {
129
130
  else
130
131
  process.stdout.write(serialized);
131
132
  }
132
- export async function validateWorkflowAction(path) {
133
- const value = await readWorkflowFile(path);
133
+ async function readJsonFile(path, field) {
134
+ try {
135
+ return JSON.parse(await readFile(path, 'utf8'));
136
+ }
137
+ catch {
138
+ throw new ValidationError(field, 'Cannot read a valid JSON file');
139
+ }
140
+ }
141
+ export async function validateWorkflowAction(path, options = {}) {
142
+ let value = await readWorkflowFile(path);
143
+ if (options.fix || options.output) {
144
+ if (!options.fix || !options.output)
145
+ throw new ValidationError('fix', 'Use --fix <field-maps.json> with --output <new-workflow.json>');
146
+ value = projectWorkflowPayload(value, await readJsonFile(options.fix, 'fix'));
147
+ await writeFile(resolve(options.output), serializeWorkflow(value, true), {
148
+ flag: 'wx',
149
+ mode: 0o600,
150
+ });
151
+ }
134
152
  printJson({
135
153
  valid: true,
136
154
  id: value.id,
137
155
  nodeCount: value.nodes.length,
156
+ payloadAudit: auditWorkflowPayload(value),
157
+ ...(options.output ? { output: resolve(options.output) } : {}),
138
158
  });
139
159
  }
140
160
  export async function importWorkflowAction(path, options) {
@@ -181,16 +201,67 @@ async function saveWorkflowDraft(id, draft, options) {
181
201
  return;
182
202
  }
183
203
  const saved = await putWorkflowDraft(id, draft);
184
- printJson({ workflow: saved, publication: publicationStatus(saved) });
204
+ const payloadAudit = auditWorkflowPayload(saved);
205
+ printJson({
206
+ workflow: saved,
207
+ publication: publicationStatus(saved),
208
+ ...(payloadAudit.requiredNodes.length ? { payloadAudit } : {}),
209
+ });
210
+ }
211
+ function rehearsalRequest(draft, fixture) {
212
+ if (typeof draft.checksum !== 'string' || !/^sha256:[a-f0-9]{64}$/.test(draft.checksum))
213
+ throw new ValidationError('checksum', 'The API must return a draft checksum to rehearse this workflow');
214
+ return {
215
+ expectedChecksum: draft.checksum,
216
+ fixture,
217
+ requiredNodes: auditWorkflowPayload(draft).requiredNodes,
218
+ };
219
+ }
220
+ export async function rehearseWorkflowAction(id, options) {
221
+ const draft = await readWorkflow(id, {});
222
+ const fixture = await readJsonFile(options.fixture, 'fixture');
223
+ const report = dataRow(await client.post(`/workflows/${id}/rehearse`, rehearsalRequest(draft, fixture), {
224
+ timeoutMs: 30_000,
225
+ }));
226
+ printJson(report);
227
+ if (report.passed !== true)
228
+ process.exitCode = 1;
185
229
  }
186
230
  export async function publishWorkflowAction(id, options) {
187
- const path = `/workflows/${resourceId(id)}/publish`;
231
+ const path = `/workflows/${resourceId(id)}/${options.fixture ? 'rehearse-and-publish' : 'publish'}`;
232
+ const draft = await readWorkflow(id, {});
233
+ const payloadAudit = auditWorkflowPayload(draft);
234
+ const requiresRehearsal = payloadAudit.requiredNodes.length > 0 &&
235
+ (draft.versionId === undefined || draft.versionId !== draft.publishedVersionId);
236
+ const body = options.fixture
237
+ ? rehearsalRequest(draft, await readJsonFile(options.fixture, 'fixture'))
238
+ : undefined;
239
+ if (!options.apply || options.dryRun) {
240
+ printJson({ dryRun: true, method: 'POST', path, payloadAudit, requiresRehearsal });
241
+ return;
242
+ }
243
+ if (requiresRehearsal && !body)
244
+ throw new ValidationError('fixture', 'This draft needs a simulated rehearsal. Run workflow publish with --fixture <cases.json> --apply');
245
+ const response = body
246
+ ? await client.post(path, body, { timeoutMs: 30_000 })
247
+ : await client.post(path);
248
+ const published = dataRow(response);
249
+ if (body && (!isRow(response.rehearsal) || response.rehearsal.passed !== true))
250
+ throw new ApiError(502, 'The API did not return a passing rehearsal result');
251
+ printJson({
252
+ workflow: published,
253
+ publication: publicationStatus(published, true),
254
+ ...(response.rehearsal ? { rehearsal: response.rehearsal } : {}),
255
+ });
256
+ }
257
+ export async function protectWorkflowAction(id, options) {
258
+ const path = `/workflows/${resourceId(id)}/protect`;
188
259
  if (!options.apply || options.dryRun) {
189
260
  printJson({ dryRun: true, method: 'POST', path });
190
261
  return;
191
262
  }
192
- const published = dataRow(await client.post(path));
193
- printJson({ workflow: published, publication: publicationStatus(published, true) });
263
+ const workflow = dataRow(await client.post(path));
264
+ printJson({ workflow, publication: publicationStatus(workflow) });
194
265
  }
195
266
  export async function activateWorkflowAction(id, options) {
196
267
  const path = `/workflows/${resourceId(id)}/activate`;
@@ -479,7 +550,9 @@ export function registerWorkflowCommand(program) {
479
550
  .action(async (id, o) => action(() => exportWorkflowAction(id, { ...o, ...fields(program) })));
480
551
  cmd
481
552
  .command('validate <file>')
482
- .action(async (file) => action(() => validateWorkflowAction(file)));
553
+ .option('--fix <file>', 'Project explicit Set output fields from a JSON field map')
554
+ .option('--output <file>', 'Write repaired workflow to a new file')
555
+ .action(async (file, o) => action(() => validateWorkflowAction(file, o)));
483
556
  cmd
484
557
  .command('import <file>')
485
558
  .option('--apply', 'Create workflow')
@@ -491,10 +564,21 @@ export function registerWorkflowCommand(program) {
491
564
  .option('--apply', 'Apply update')
492
565
  .option('--dry-run', 'Preview update')
493
566
  .action(async (id, o) => action(() => updateWorkflowAction(id, o)));
567
+ cmd
568
+ .command('rehearse <id>')
569
+ .requiredOption('--fixture <file>', 'Simulated inputs, node outputs, and coverage assertions')
570
+ .action(async (id, o) => action(() => rehearseWorkflowAction(id, o)));
571
+ cmd
572
+ .command('protect <id>')
573
+ .description('Keep runs on the published version while editing drafts')
574
+ .option('--apply', 'Protect the current workflow version')
575
+ .option('--dry-run', 'Preview protection')
576
+ .action(async (id, o) => action(() => protectWorkflowAction(id, o)));
494
577
  cmd
495
578
  .command('publish <id>')
496
579
  .option('--apply', 'Publish workflow')
497
580
  .option('--dry-run', 'Preview publish')
581
+ .option('--fixture <file>', 'Run a simulated rehearsal of the draft before publishing')
498
582
  .action(async (id, o) => action(() => publishWorkflowAction(id, o)));
499
583
  cmd
500
584
  .command('activate <id>')
@@ -0,0 +1,167 @@
1
+ import { ValidationError } from './utils/errors.js';
2
+ import { isRow } from './utils/product-api.js';
3
+ const bulkField = /\b(?:rows|values|items|currentSheetValues|currentTransactionValues|queryReadback|transactionReadback|runtimeProvider|originalJournalRequests)\b/;
4
+ const wholeNode = /\$\(\s*(['"])(.*?)\1\s*\)\s*\.\s*(?:first\(\)|last\(\)|item)\s*\.\s*json(?!\w|\s*(?:\.|\?\.|\[))/g;
5
+ const wholeInput = /\$json(?!\w|\s*(?:\.|\?\.|\[))|\$input\s*\.\s*all\(|\*\*\s*(?:item|state)\b|\.\.\.\s*(?:item|state|\$json)\b/;
6
+ function kind(node, type) {
7
+ return node.type === `mesh-nodes-base.${type}`;
8
+ }
9
+ function bulkRead(node) {
10
+ return ((kind(node, 'googleSheets') && node.parameters.operation === 'getValues') ||
11
+ node.parameters.returnAll === true ||
12
+ kind(node, 'financialAgent') ||
13
+ kind(node, 'computerUse'));
14
+ }
15
+ function graphNodes(workflow) {
16
+ return (Array.isArray(workflow.nodes) ? workflow.nodes : []).flatMap((node) => isRow(node) && typeof node.name === 'string' && typeof node.type === 'string'
17
+ ? [
18
+ {
19
+ name: node.name,
20
+ type: node.type,
21
+ parameters: isRow(node.parameters) ? node.parameters : {},
22
+ },
23
+ ]
24
+ : []);
25
+ }
26
+ export function auditWorkflowPayload(workflow) {
27
+ const nodes = graphNodes(workflow);
28
+ const names = new Set(nodes.map((node) => node.name));
29
+ const edges = new Map();
30
+ const incoming = new Map();
31
+ for (const [name, outputs] of Object.entries(isRow(workflow.connections) ? workflow.connections : {})) {
32
+ if (!isRow(outputs) || !Array.isArray(outputs.main))
33
+ continue;
34
+ const targets = outputs.main
35
+ .flat()
36
+ .flatMap((edge) => isRow(edge) && typeof edge.node === 'string' && names.has(edge.node) ? [edge.node] : []);
37
+ edges.set(name, targets);
38
+ for (const target of targets)
39
+ incoming.set(target, [...(incoming.get(target) ?? []), name]);
40
+ }
41
+ function reachable(starts) {
42
+ const seen = new Set();
43
+ for (const queue = [...starts]; queue.length;) {
44
+ const name = queue.pop();
45
+ if (seen.has(name))
46
+ continue;
47
+ seen.add(name);
48
+ queue.push(...(edges.get(name) ?? []));
49
+ }
50
+ return seen;
51
+ }
52
+ const sources = nodes.filter(bulkRead);
53
+ const inlineFields = new Set([
54
+ 'rows',
55
+ 'values',
56
+ 'items',
57
+ 'runtimeProvider',
58
+ 'originalJournalRequests',
59
+ ]);
60
+ for (const node of sources) {
61
+ if (node.parameters.outputMode === 'file')
62
+ continue;
63
+ if (typeof node.parameters.outputFieldName === 'string')
64
+ inlineFields.add(node.parameters.outputFieldName);
65
+ }
66
+ const downstream = reachable(sources.map((node) => node.name));
67
+ const carriesBulk = new Set(sources
68
+ .filter((node) => node.parameters.outputMode !== 'file')
69
+ .map((node) => node.name));
70
+ const payloads = nodes.map((node) => {
71
+ const params = Object.values(node.parameters)
72
+ .map((value) => (typeof value === 'string' ? value : (JSON.stringify(value) ?? '')))
73
+ .join('\n');
74
+ const copiesInput = wholeInput.test(params);
75
+ const referencedNodes = [...params.matchAll(wholeNode)].map((match) => match[2]);
76
+ const mappedFields = [...params.matchAll(/\.([a-zA-Z_$][\w$]*)\s*\}\}/g)];
77
+ const selectsBulkField = mappedFields.some((match) => inlineFields.has(match[1]) || bulkField.test(match[1]));
78
+ const inheritsInput = (kind(node, 'set') && (node.parameters.includeInputFields !== false || selectsBulkField)) ||
79
+ (kind(node, 'googleSheets') &&
80
+ ['getValues', 'batchUpdate', 'listSheets'].includes(String(node.parameters.operation))) ||
81
+ ['if', 'wait', 'merge', 'splitInBatches'].some((type) => kind(node, type));
82
+ const returnsInput = inheritsInput || ((kind(node, 'set') || kind(node, 'pythonCode')) && copiesInput);
83
+ return { node, params, copiesInput, referencedNodes, returnsInput };
84
+ });
85
+ const receivesBulk = (name) => (incoming.get(name) ?? []).some((parent) => carriesBulk.has(parent));
86
+ const referencesBulk = (refs) => refs.some((ref) => carriesBulk.has(ref));
87
+ let previousSize = -1;
88
+ while (previousSize !== carriesBulk.size) {
89
+ previousSize = carriesBulk.size;
90
+ for (const { node, returnsInput, referencedNodes } of payloads) {
91
+ if ((returnsInput && receivesBulk(node.name)) ||
92
+ (kind(node, 'set') && referencesBulk(referencedNodes)))
93
+ carriesBulk.add(node.name);
94
+ }
95
+ }
96
+ const findings = [];
97
+ const required = new Set();
98
+ for (const { node, params, copiesInput, referencedNodes } of payloads) {
99
+ const { name, type, parameters } = node;
100
+ const wholeProducer = referencesBulk(referencedNodes);
101
+ if (wholeProducer || (receivesBulk(name) && copiesInput)) {
102
+ findings.push({
103
+ code: 'WHOLE_BULK_OUTPUT',
104
+ node: name,
105
+ message: 'Select individual fields or pass a run-scoped artifact reference.',
106
+ });
107
+ required.add(name);
108
+ }
109
+ if (receivesBulk(name) && kind(node, 'set') && parameters.includeInputFields !== false) {
110
+ findings.push({
111
+ code: 'BULK_PASSTHROUGH',
112
+ node: name,
113
+ message: 'Project the required fields with includeInputFields disabled.',
114
+ });
115
+ required.add(name);
116
+ }
117
+ const successors = reachable(edges.get(name) ?? []);
118
+ const loopEntry = successors.has(name) &&
119
+ (incoming.get(name) ?? []).some((parent) => !successors.has(parent));
120
+ const boundary = /\.(?:wait|executeWorkflow|splitInBatches)$/.test(type) || loopEntry;
121
+ if (boundary && downstream.has(name))
122
+ required.add(name);
123
+ if (boundary && (carriesBulk.has(name) || wholeProducer)) {
124
+ findings.push({
125
+ code: 'INLINE_BULK_BOUNDARY',
126
+ node: name,
127
+ message: 'Persist bulk data before the loop, wait, or sub-workflow and load it at the consumer.',
128
+ });
129
+ required.add(name);
130
+ }
131
+ else if (boundary && bulkField.test(params) && wholeInput.test(params)) {
132
+ findings.push({
133
+ code: 'INLINE_BULK_BOUNDARY',
134
+ node: name,
135
+ message: 'Pass a compact manifest with counts, hashes, or artifact references at this boundary.',
136
+ });
137
+ required.add(name);
138
+ }
139
+ }
140
+ return { findings, requiredNodes: [...required].sort() };
141
+ }
142
+ export function projectWorkflowPayload(workflow, projections) {
143
+ if (!isRow(projections) || !Object.keys(projections).length)
144
+ throw new ValidationError('fix', 'Provide an object mapping Set node names to their complete output field maps');
145
+ const nodes = Array.isArray(workflow.nodes) ? workflow.nodes : [];
146
+ for (const [name, values] of Object.entries(projections)) {
147
+ const matches = nodes.filter((node) => isRow(node) && node.name === name);
148
+ if (matches.length !== 1 || matches[0].type !== 'mesh-nodes-base.set' || !isRow(values))
149
+ throw new ValidationError('fix', `Projection for "${name}" needs a unique Set node and an explicit field map`);
150
+ }
151
+ return {
152
+ ...workflow,
153
+ nodes: nodes.map((node) => {
154
+ if (!isRow(node) || typeof node.name !== 'string' || !Object.hasOwn(projections, node.name))
155
+ return node;
156
+ return {
157
+ ...node,
158
+ parameters: {
159
+ ...(isRow(node.parameters) ? node.parameters : {}),
160
+ includeInputFields: false,
161
+ values: JSON.stringify(projections[node.name]),
162
+ },
163
+ };
164
+ }),
165
+ };
166
+ }
167
+ //# sourceMappingURL=workflow-payload.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zalosai/zalos-cli",
3
- "version": "0.2.36",
3
+ "version": "0.2.37",
4
4
  "description": "API-only product command-line interface for Zalos",
5
5
  "repository": {
6
6
  "type": "git",
@@ -71,11 +71,10 @@ command with `--apply` only when the intended team, object, and paths are confir
71
71
  ```bash
72
72
  zl --environment <us-prod|eu-prod> workflow update <workflow-id> --input /tmp/workflow.json --dry-run
73
73
  zl --environment <us-prod|eu-prod> workflow update <workflow-id> --input /tmp/workflow.json --apply
74
- zl --environment <us-prod|eu-prod> workflow publish <workflow-id> --apply
74
+ zl --environment <us-prod|eu-prod> workflow publish <workflow-id> --fixture ./cases.json --apply
75
75
  ```
76
76
 
77
- A workflow update saves a draft. Publish the workflow after reviewing its draft and
78
- live-version response; executions continue using the published version until then.
77
+ For an unprotected workflow that needs guarded publishing, use `zl --environment <us-prod|eu-prod> workflow protect <workflow-id> --apply` before editing. On a protected workflow, an update saves a draft and executions continue using the published version. Review the draft and rehearsal result before publishing.
79
78
 
80
79
  For Team Files seeding, preview first, then use exactly the checksum returned by that
81
80
  preview:
@@ -96,6 +95,48 @@ When authoring or reviewing a workflow that reads worksheets, loops over rows, o
96
95
 
97
96
  For a workbook verification → journal-source planning handoff, pass the readback artifact reference, worksheet ID, row count, and verification result. The planning node can read the artifact when it needs the rows.
98
97
 
98
+ Use the payload audit when building or changing a workflow that handles bulk inputs:
99
+
100
+ ```bash
101
+ zl --environment <us-prod|eu-prod> workflow validate ./draft.json
102
+ zl --environment <us-prod|eu-prod> workflow validate ./draft.json --fix ./fields.json --output ./projected.json
103
+ zl --environment <us-prod|eu-prod> workflow rehearse <workflow-id> --fixture ./cases.json
104
+ zl --environment <us-prod|eu-prod> workflow publish <workflow-id> --fixture ./cases.json --apply
105
+ ```
106
+
107
+ Each entry in `fields.json` maps a Set node name to its complete output field map. Include every field its consumers need. A map such as
108
+ `{"Prepare Review":{"period":"{{ $json.period }}","fileRef":"{{ $json.rowsFile.fileRef }}"}}`
109
+ sets `includeInputFields` to false and writes a separate workflow file. Review the diff and apply it as a draft update before rehearsing. Use Sheets file output and update downstream file inputs when a consumer needs the full rows.
110
+
111
+ Rehearsal runs in isolation in the workflow’s region. The rehearsal file has a `cases` array. Each case names a trigger in `start`, supplies trigger JSON items in `input`, and maps node names to `mocks`. Each mock has an `outputs` array of ports, each containing an array of JSON items. Set `mergeInput: true` when the real connector includes its incoming fields. Set, If, Merge, and Split In Batches run as defined. Supply a mock for every other node the case reaches, including connectors, waits, sub-workflows, and custom code. For a Wait, a mock can return synthetic approval data on the port leading to the resume path.
112
+
113
+ ```json
114
+ {
115
+ "cases": [
116
+ {
117
+ "name": "Month-end approval",
118
+ "start": "Form",
119
+ "input": [{ "period": "October" }],
120
+ "mocks": {
121
+ "Read Rows": {
122
+ "mergeInput": true,
123
+ "outputs": [[{ "rows": [[1, "sample"]], "rowsFile": { "fileRef": "synthetic-rows" } }]]
124
+ },
125
+ "Approve": { "mergeInput": true, "outputs": [[{ "approved": true }]] },
126
+ "Write": { "outputs": [[{ "status": "verified" }]] }
127
+ },
128
+ "expect": {
129
+ "Read Rows": { "minBytes": 500000 },
130
+ "Prepare Review": { "maxBytes": 8192 },
131
+ "Write": { "minAttempts": 1 }
132
+ }
133
+ }
134
+ ]
135
+ }
136
+ ```
137
+
138
+ Replace the sample row with representative synthetic month-end data before running this case. For a file-output connector, simulate the actual reference and metadata shape. Set the size minimum on a node that handles inline rows. Adjust assertions to the workflow's expected payloads and iteration counts. The report shows the mocked nodes, attempts, maximum bytes per attempt, and cumulative bytes for each node. Check both approval outcomes in separate cases when both affect control flow. The guarded publish command reruns the fixture on the current protected draft and rejects failed coverage, exceeded budgets, and edits that change the draft checksum before publish.
139
+
99
140
  ## Pages and Motion work
100
141
 
101
142
  Pages use Markdown files with a revision marker. Export before editing, then preview