@jacebenson/jsn 5.3.0 → 5.4.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.
@@ -0,0 +1,933 @@
1
+ import { assertSafeExactMatch } from './helpers.js';
2
+ import { errAmbiguous, errNotFound, errUsage } from './errors.js';
3
+
4
+ /**
5
+ * Read-only inspection of legacy Workflow Editor automation (the `wf_*`
6
+ * tables). This is deliberately a reader: it never checks a workflow out,
7
+ * publishes, edits or converts anything, so it works against published and
8
+ * checked-out workflows alike and never needs a draft.
9
+ *
10
+ * Flow Designer (`sys_hub_flow`) inspection lives in `flow-inspection.js`;
11
+ * these are different engines with different records and must not be
12
+ * conflated in output.
13
+ *
14
+ * Table layout supported here (legacy Workflow Editor):
15
+ *
16
+ * wf_workflow name, table, description
17
+ * wf_workflow_version workflow, name, table, published, active, checked_out,
18
+ * checked_out_by, condition, condition_type, start,
19
+ * full_sequences
20
+ * wf_activity workflow_version, activity_definition, name, parent,
21
+ * stage, x/y/width/height, input
22
+ * wf_condition activity, name, condition, order, else_flag, error, event
23
+ * wf_transition from, to, condition
24
+ * wf_stage workflow_version, name, value, order
25
+ * sys_variable_value document=wf_activity, document_key=<activity sys_id>,
26
+ * variable.element (script, table, field, ...), value
27
+ * wf_element_definition activity type name/description
28
+ *
29
+ * Required permissions: read on the tables above. Reading a workflow does not
30
+ * require checking it out. Tables or columns outside the reader's ACL are
31
+ * reported as `inaccessible`/`unavailable` in `coverage` and
32
+ * `integrity.inaccessible` rather than being rendered as empty data.
33
+ */
34
+
35
+ const WORKFLOW = 'wf_workflow';
36
+ const VERSION = 'wf_workflow_version';
37
+ const ACTIVITY = 'wf_activity';
38
+ const TRANSITION = 'wf_transition';
39
+ const CONDITION = 'wf_condition';
40
+ const STAGE = 'wf_stage';
41
+ const DEFINITION = 'wf_element_definition';
42
+ const VARIABLE_VALUE = 'sys_variable_value';
43
+
44
+ const WORKFLOW_FIELDS = 'sys_id,name,table,description';
45
+ const VERSION_FIELDS = [
46
+ 'sys_id', 'workflow', 'name', 'table', 'description', 'published', 'active',
47
+ 'checked_out', 'checked_out_by', 'checked_out_by.name', 'condition',
48
+ 'condition_type', 'start', 'full_sequences', 'sys_created_on', 'sys_updated_on',
49
+ ].join(',');
50
+ const ACTIVITY_FIELDS = [
51
+ 'sys_id', 'name', 'activity_definition', 'activity_definition.name',
52
+ 'parent', 'stage', 'x', 'y', 'width', 'height', 'input',
53
+ ].join(',');
54
+ const CONDITION_FIELDS = [
55
+ 'sys_id', 'activity', 'name', 'condition', 'order', 'else_flag', 'error',
56
+ 'event', 'event_name', 'short_description', 'skip_during_generate',
57
+ ].join(',');
58
+ const TRANSITION_FIELDS = 'sys_id,from,to,condition';
59
+ const STAGE_FIELDS = 'sys_id,name,value,order';
60
+ const DEFINITION_FIELDS = 'sys_id,name,description,sys_class_name';
61
+
62
+ const CHUNK = 100;
63
+ const VERSIONS_LIMIT = 200;
64
+ const MAX_LIMIT = 1000;
65
+
66
+ const DESIGN_TIME_SCOPE = 'Design-time configuration of the selected workflow version. '
67
+ + 'This is not evidence that this version executed, and runtime history is not inspected here.';
68
+
69
+ export function isSysId(value) {
70
+ return /^[0-9a-f]{32}$/i.test(String(value ?? ''));
71
+ }
72
+
73
+ function raw(value) {
74
+ if (value && typeof value === 'object') {
75
+ if (value.value != null) return String(value.value);
76
+ if (value.display_value != null) return String(value.display_value);
77
+ return '';
78
+ }
79
+ return value == null ? '' : String(value);
80
+ }
81
+
82
+ function text(value) {
83
+ if (value && typeof value === 'object') {
84
+ if (value.display_value != null) return String(value.display_value);
85
+ if (value.value != null) return String(value.value);
86
+ return '';
87
+ }
88
+ return value == null ? '' : String(value);
89
+ }
90
+
91
+ function truthy(value) {
92
+ return raw(value) === 'true';
93
+ }
94
+
95
+ function integer(value, fallback) {
96
+ const n = Number(value);
97
+ return Number.isInteger(n) ? n : fallback;
98
+ }
99
+
100
+ function chunks(items, size = CHUNK) {
101
+ const out = [];
102
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
103
+ return out;
104
+ }
105
+
106
+ function tableParams({ query, fields, limit, offset }) {
107
+ const params = new URLSearchParams();
108
+ params.set('sysparm_query', query);
109
+ params.set('sysparm_fields', fields);
110
+ params.set('sysparm_limit', String(limit));
111
+ if (offset != null) params.set('sysparm_offset', String(offset));
112
+ params.set('sysparm_display_value', 'all');
113
+ return params;
114
+ }
115
+
116
+ function assertRows(rows, table) {
117
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row !== 'object' || Array.isArray(row))) {
118
+ throw Object.assign(new Error(`Malformed table response for ${table}: expected a list of records`), { code: 'malformed_response' });
119
+ }
120
+ return rows;
121
+ }
122
+
123
+ /**
124
+ * Read one component as an explicit status. Only authentication/authorization,
125
+ * missing-table and malformed-body outcomes become statuses; network and
126
+ * unexpected failures still abort so a broken read is never mistaken for an
127
+ * empty component.
128
+ */
129
+ async function readComponent(sdk, table, { query, fields, limit }) {
130
+ try {
131
+ const rows = assertRows(await sdk.listStrict(table, tableParams({ query, fields, limit })), table);
132
+ return { state: 'ok', rows };
133
+ } catch (error) {
134
+ const status = Number(error?.status) || 0;
135
+ const code = error?.code || 'api_error';
136
+ if (status === 401 || status === 403) {
137
+ return { state: 'inaccessible', http_status: status, code };
138
+ }
139
+ if (status === 400 || status === 404) {
140
+ // A wf_* table can be missing on a platform that never enabled the
141
+ // legacy editor; that is a layout difference, not an empty workflow.
142
+ return { state: 'unavailable', http_status: status, code };
143
+ }
144
+ if (code === 'malformed_response') return { state: 'malformed', code };
145
+ throw error;
146
+ }
147
+ }
148
+
149
+ function normalizeWorkflow(row) {
150
+ return {
151
+ sys_id: raw(row.sys_id),
152
+ name: text(row.name),
153
+ table: text(row.table),
154
+ description: text(row.description),
155
+ };
156
+ }
157
+
158
+ function normalizeVersion(row) {
159
+ return {
160
+ sys_id: raw(row.sys_id),
161
+ workflow_id: raw(row.workflow),
162
+ name: text(row.name),
163
+ table: text(row.table),
164
+ description: text(row.description),
165
+ published: truthy(row.published),
166
+ active: truthy(row.active),
167
+ checked_out: text(row.checked_out),
168
+ checked_out_by_id: raw(row.checked_out_by),
169
+ checked_out_by_name: text(row['checked_out_by.name']),
170
+ condition: text(row.condition),
171
+ condition_type: text(row.condition_type),
172
+ start_activity_id: raw(row.start),
173
+ full_sequences: text(row.full_sequences).split(',').map(item => item.trim()).filter(Boolean),
174
+ created_on: text(row.sys_created_on),
175
+ updated_on: text(row.sys_updated_on),
176
+ };
177
+ }
178
+
179
+ function normalizeCondition(row) {
180
+ return {
181
+ sys_id: raw(row.sys_id),
182
+ activity_id: raw(row.activity),
183
+ name: text(row.name),
184
+ condition: text(row.condition),
185
+ order: integer(raw(row.order), 0),
186
+ else_flag: truthy(row.else_flag),
187
+ error: truthy(row.error),
188
+ event: text(row.event),
189
+ event_name: text(row.event_name),
190
+ short_description: text(row.short_description),
191
+ skip_during_generate: truthy(row.skip_during_generate),
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Summarize published and checked-out versions for a page of workflows.
197
+ * Two exact reads keep the `published=true` and `checked_outISNOTEMPTY`
198
+ * filters scoped; the reference implementation's single OR query can let
199
+ * another workflow's rows through.
200
+ */
201
+ async function versionsForWorkflows(sdk, workflowIds) {
202
+ if (workflowIds.length === 0) return { state: 'ok', rows: [] };
203
+ const scope = `workflowIN${workflowIds.join(',')}`;
204
+ const published = await readComponent(sdk, VERSION, {
205
+ query: `${scope}^published=true`, fields: VERSION_FIELDS, limit: CHUNK,
206
+ });
207
+ const drafts = await readComponent(sdk, VERSION, {
208
+ query: `${scope}^checked_outISNOTEMPTY`, fields: VERSION_FIELDS, limit: CHUNK,
209
+ });
210
+ const states = [published, drafts].filter(read => read.state !== 'ok');
211
+ return {
212
+ state: states.length === 0 ? 'ok' : states[0].state,
213
+ http_status: states[0]?.http_status,
214
+ rows: [...(published.rows || []), ...(drafts.rows || [])],
215
+ truncated: (published.rows || []).length >= CHUNK || (drafts.rows || []).length >= CHUNK,
216
+ };
217
+ }
218
+
219
+ export function validateListBounds({ limit, offset }) {
220
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw errUsage('--limit must be from 1 to 100.');
221
+ if (!Number.isInteger(offset) || offset < 0) throw errUsage('--offset must be a nonnegative integer.');
222
+ }
223
+
224
+ /**
225
+ * List legacy workflows with the state of their published and checked-out
226
+ * versions. One-row lookahead gives bounded pagination without pretending an
227
+ * unreadable version set is empty.
228
+ */
229
+ export async function listWorkflows(sdk, { name = '', table = '', query = '', limit = 20, offset = 0 } = {}) {
230
+ validateListBounds({ limit, offset });
231
+ if (table && !/^[a-z][a-z0-9_]*$/.test(table)) throw errUsage('--table must be an exact table name.');
232
+ const parts = [];
233
+ if (name) {
234
+ assertSafeExactMatch(name);
235
+ parts.push(`nameLIKE${name}`);
236
+ }
237
+ if (table) parts.push(`table=${table}`);
238
+ if (query) parts.push(query);
239
+ parts.push('ORDERBYname', 'ORDERBYsys_id');
240
+
241
+ const rows = assertRows(await sdk.listStrict(WORKFLOW, tableParams({
242
+ query: parts.join('^'), fields: WORKFLOW_FIELDS, limit: limit + 1, offset,
243
+ })), WORKFLOW);
244
+ const hasMore = rows.length > limit;
245
+ const page = rows.slice(0, limit);
246
+ const workflows = page.map(normalizeWorkflow);
247
+ const versionRead = await versionsForWorkflows(sdk, workflows.map(w => w.sys_id).filter(isSysId));
248
+
249
+ const versions = (versionRead.rows || []).map(normalizeVersion);
250
+ const records = workflows.map(workflow => {
251
+ const own = versions.filter(version => version.workflow_id === workflow.sys_id);
252
+ const published = own.filter(version => version.published)
253
+ .sort((a, b) => Number(b.active) - Number(a.active) || newestFirst(a, b))[0] || null;
254
+ const draft = own.find(version => !version.published && version.checked_out_by_id) || null;
255
+ const record = {
256
+ ...workflow,
257
+ published_version: published && compactVersion(published),
258
+ checked_out_version: draft && {
259
+ ...compactVersion(draft),
260
+ checked_out_by_id: draft.checked_out_by_id,
261
+ checked_out_by_name: draft.checked_out_by_name,
262
+ checked_out_on: draft.checked_out,
263
+ },
264
+ version_state: versionRead.state,
265
+ };
266
+ if (versionRead.http_status) record.version_http_status = versionRead.http_status;
267
+ return record;
268
+ });
269
+
270
+ return {
271
+ engine: 'legacy_workflow_editor',
272
+ table: WORKFLOW,
273
+ count: records.length,
274
+ records,
275
+ pagination: { limit, offset, has_more: hasMore },
276
+ versions_truncated: versionRead.truncated === true,
277
+ coverage: {
278
+ complete: versionRead.state === 'ok' && versionRead.truncated !== true,
279
+ components: { workflows: 'ok', versions: versionRead.state },
280
+ },
281
+ definition_scope: DESIGN_TIME_SCOPE,
282
+ };
283
+ }
284
+
285
+ function compactVersion(version) {
286
+ return {
287
+ sys_id: version.sys_id,
288
+ name: version.name,
289
+ table: version.table,
290
+ active: version.active,
291
+ condition: version.condition,
292
+ created_on: version.created_on,
293
+ };
294
+ }
295
+
296
+ async function resolveWorkflow(sdk, identifier) {
297
+ const matches = [];
298
+ let matchedBy = 'sys_id';
299
+
300
+ if (isSysId(identifier)) {
301
+ const rows = assertRows(await sdk.listStrict(WORKFLOW, tableParams({
302
+ query: `sys_id=${identifier}`, fields: WORKFLOW_FIELDS, limit: 1,
303
+ })), WORKFLOW);
304
+ matches.push(...rows);
305
+ if (rows.length === 0) {
306
+ // A version sys_id is a legitimate handle even when the caller does not
307
+ // know which workflow owns it.
308
+ const versions = assertRows(await sdk.listStrict(VERSION, tableParams({
309
+ query: `sys_id=${identifier}`, fields: 'sys_id,workflow', limit: 1,
310
+ })), VERSION);
311
+ const workflowId = raw(versions[0]?.workflow);
312
+ if (workflowId) {
313
+ const owners = assertRows(await sdk.listStrict(WORKFLOW, tableParams({
314
+ query: `sys_id=${workflowId}`, fields: WORKFLOW_FIELDS, limit: 1,
315
+ })), WORKFLOW);
316
+ matches.push(...owners);
317
+ matchedBy = 'version_sys_id';
318
+ }
319
+ }
320
+ } else {
321
+ assertSafeExactMatch(identifier);
322
+ matchedBy = 'name';
323
+ const rows = assertRows(await sdk.listStrict(WORKFLOW, tableParams({
324
+ query: `name=${identifier}`, fields: WORKFLOW_FIELDS, limit: 10,
325
+ })), WORKFLOW);
326
+ matches.push(...rows);
327
+ }
328
+
329
+ if (matches.length === 0) {
330
+ throw errNotFound('Legacy workflow', identifier);
331
+ }
332
+ if (matches.length > 1) {
333
+ throw errAmbiguous('legacy workflows', matches.map(row => `${raw(row.sys_id)} (${text(row.table)})`));
334
+ }
335
+ return { workflow: normalizeWorkflow(matches[0]), matched_by: matchedBy };
336
+ }
337
+
338
+ function newestFirst(a, b) {
339
+ return b.created_on.localeCompare(a.created_on) || a.sys_id.localeCompare(b.sys_id);
340
+ }
341
+
342
+ function isScriptField(element) {
343
+ return element === 'script' || element.startsWith('script_') || element.endsWith('_script');
344
+ }
345
+
346
+ // Recognize only whitespace and complete JavaScript comments. Anything else
347
+ // (including a shebang or an unterminated block) is conservatively retained.
348
+ function isCommentOnlyScript(value) {
349
+ let rest = value;
350
+ let sawComment = false;
351
+ while (rest.trimStart()) {
352
+ rest = rest.trimStart();
353
+ if (rest.startsWith('//')) {
354
+ sawComment = true;
355
+ const end = rest.search(/[\r\n\u2028\u2029]/);
356
+ rest = end < 0 ? '' : rest.slice(end);
357
+ } else if (rest.startsWith('/*')) {
358
+ const end = rest.indexOf('*/', 2);
359
+ if (end < 0) return false;
360
+ sawComment = true;
361
+ rest = rest.slice(end + 2);
362
+ } else {
363
+ return false;
364
+ }
365
+ }
366
+ return sawComment;
367
+ }
368
+
369
+ export function selectVersion(versions, versionId = '') {
370
+ if (versionId) {
371
+ if (!isSysId(versionId)) throw errUsage('--version must be a wf_workflow_version sys_id (32 hexadecimal characters).');
372
+ const requested = versions.find(version => version.sys_id === versionId);
373
+ if (!requested) throw errUsage(`Version ${versionId} is not one of this workflow's versions.`);
374
+ return { version: requested, reason: 'requested' };
375
+ }
376
+ const published = versions.filter(version => version.published)
377
+ .sort((a, b) => Number(b.active) - Number(a.active) || newestFirst(a, b));
378
+ if (published.length > 0) return { version: published[0], reason: 'latest_published' };
379
+ if (versions.length > 0) return { version: [...versions].sort(newestFirst)[0], reason: 'newest' };
380
+ return { version: null, reason: 'none' };
381
+ }
382
+
383
+ /**
384
+ * Read one workflow version's design-time definition: activities, conditions,
385
+ * transitions, stages, activity configuration and the activity-type records
386
+ * they reference. Every link keeps its sys_id.
387
+ */
388
+ export async function inspectWorkflow(sdk, {
389
+ identifier, versionId = '', includeConfiguration = true, limit = 200,
390
+ } = {}) {
391
+ if (typeof identifier !== 'string' || !identifier.trim()) {
392
+ throw errUsage('Provide a legacy workflow name or sys_id.');
393
+ }
394
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
395
+ throw errUsage(`--limit must be from 1 to ${MAX_LIMIT}.`);
396
+ }
397
+
398
+ const { workflow, matched_by } = await resolveWorkflow(sdk, identifier.trim());
399
+ const versionRead = await readComponent(sdk, VERSION, {
400
+ query: `workflow=${workflow.sys_id}^ORDERBYDESCsys_created_on`,
401
+ fields: VERSION_FIELDS,
402
+ limit: VERSIONS_LIMIT,
403
+ });
404
+ const versions = (versionRead.rows || []).map(normalizeVersion).sort(newestFirst);
405
+ const versionsTruncated = versionRead.state === 'ok' && versions.length === VERSIONS_LIMIT;
406
+
407
+ let selection = { version: null, reason: 'unavailable' };
408
+ if (versionRead.state === 'ok') {
409
+ selection = selectVersion(versions, versionId);
410
+ } else if (versionId) {
411
+ if (!isSysId(versionId)) throw errUsage('--version must be a wf_workflow_version sys_id (32 hexadecimal characters).');
412
+ const direct = await readComponent(sdk, VERSION, {
413
+ query: `sys_id=${versionId}`, fields: VERSION_FIELDS, limit: 1,
414
+ });
415
+ const version = (direct.rows || []).map(normalizeVersion)[0] || null;
416
+ if (!version) throw errNotFound('Workflow version', versionId);
417
+ if (version.workflow_id !== workflow.sys_id) {
418
+ throw errUsage(`Version ${versionId} belongs to workflow ${version.workflow_id}, not ${workflow.sys_id}.`);
419
+ }
420
+ selection = { version, reason: 'requested' };
421
+ }
422
+
423
+ const version = selection.version;
424
+ const components = {
425
+ versions: versionRead.state,
426
+ activities: 'not_requested',
427
+ conditions: 'not_requested',
428
+ transitions: 'not_requested',
429
+ stages: 'not_requested',
430
+ configuration: includeConfiguration ? 'not_requested' : 'skipped',
431
+ definitions: 'not_requested',
432
+ };
433
+ const inaccessible = [];
434
+ if (versionRead.state !== 'ok') {
435
+ inaccessible.push({ component: 'versions', state: versionRead.state, http_status: versionRead.http_status ?? null, code: versionRead.code ?? null });
436
+ }
437
+
438
+ let activities = [];
439
+ let conditions = [];
440
+ let transitions = [];
441
+ let stages = [];
442
+ let activitySample = { limit, returned: 0, truncated: false };
443
+ let definitions = new Map();
444
+ let integrity;
445
+
446
+ if (version) {
447
+ const activityRead = await readComponent(sdk, ACTIVITY, {
448
+ query: `workflow_version=${version.sys_id}^ORDERBYsys_created_on`,
449
+ fields: ACTIVITY_FIELDS,
450
+ limit: limit + 1,
451
+ });
452
+ components.activities = activityRead.state;
453
+ if (activityRead.state !== 'ok') {
454
+ inaccessible.push({ component: 'activities', state: activityRead.state, http_status: activityRead.http_status ?? null, code: activityRead.code ?? null });
455
+ } else {
456
+ activitySample = {
457
+ limit,
458
+ returned: Math.min(activityRead.rows.length, limit),
459
+ truncated: activityRead.rows.length > limit,
460
+ };
461
+ activities = activityRead.rows.slice(0, limit).map(row => ({
462
+ sys_id: raw(row.sys_id),
463
+ name: text(row.name),
464
+ definition_id: raw(row.activity_definition),
465
+ definition_name: text(row['activity_definition.name']),
466
+ definition_status: 'unknown',
467
+ parent_id: raw(row.parent),
468
+ stage_id: raw(row.stage),
469
+ position: {
470
+ x: integer(raw(row.x), null),
471
+ y: integer(raw(row.y), null),
472
+ width: integer(raw(row.width), null),
473
+ height: integer(raw(row.height), null),
474
+ },
475
+ input: text(row.input),
476
+ conditions: [],
477
+ configuration: {},
478
+ configuration_status: includeConfiguration ? 'not_requested' : 'skipped',
479
+ }));
480
+ }
481
+
482
+ const activityIds = activities.map(activity => activity.sys_id).filter(isSysId);
483
+
484
+ const conditionReads = [];
485
+ for (const chunk of chunks(activityIds)) {
486
+ conditionReads.push(await readComponent(sdk, CONDITION, {
487
+ query: `activityIN${chunk.join(',')}^ORDERBYorder`,
488
+ fields: CONDITION_FIELDS,
489
+ limit: MAX_LIMIT,
490
+ }));
491
+ }
492
+ const conditionState = worstState(conditionReads);
493
+ components.conditions = activityIds.length === 0 ? 'not_applicable' : conditionState;
494
+ if (conditionState !== 'ok' && conditionState !== 'not_applicable') {
495
+ const failed = conditionReads.find(read => read.state !== 'ok');
496
+ inaccessible.push({ component: 'conditions', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
497
+ }
498
+ conditions = conditionReads.flatMap(read => read.rows || []).map(normalizeCondition)
499
+ .sort((a, b) => a.activity_id.localeCompare(b.activity_id) || a.order - b.order);
500
+
501
+ const transitionReads = [];
502
+ for (const chunk of chunks(activityIds)) {
503
+ transitionReads.push(await readComponent(sdk, TRANSITION, {
504
+ query: `fromIN${chunk.join(',')}`,
505
+ fields: TRANSITION_FIELDS,
506
+ limit: MAX_LIMIT,
507
+ }));
508
+ }
509
+ const transitionState = worstState(transitionReads);
510
+ components.transitions = activityIds.length === 0 ? 'not_applicable' : transitionState;
511
+ if (transitionState !== 'ok' && transitionState !== 'not_applicable') {
512
+ const failed = transitionReads.find(read => read.state !== 'ok');
513
+ inaccessible.push({ component: 'transitions', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
514
+ }
515
+
516
+ const stageRead = await readComponent(sdk, STAGE, {
517
+ query: `workflow_version=${version.sys_id}^ORDERBYorder`,
518
+ fields: STAGE_FIELDS,
519
+ limit: 500,
520
+ });
521
+ components.stages = stageRead.state;
522
+ if (stageRead.state !== 'ok' && stageRead.state !== 'unavailable') {
523
+ inaccessible.push({ component: 'stages', state: stageRead.state, http_status: stageRead.http_status ?? null, code: stageRead.code ?? null });
524
+ }
525
+ stages = (stageRead.rows || []).map(row => ({
526
+ sys_id: raw(row.sys_id),
527
+ name: text(row.name),
528
+ value: text(row.value),
529
+ order: integer(raw(row.order), 0),
530
+ })).sort((a, b) => a.order - b.order);
531
+
532
+ if (includeConfiguration && activityIds.length === 0) components.configuration = 'not_applicable';
533
+ if (includeConfiguration && activityIds.length > 0) {
534
+ const configurationReads = [];
535
+ for (const chunk of chunks(activityIds)) {
536
+ configurationReads.push(await readComponent(sdk, VARIABLE_VALUE, {
537
+ query: `document=wf_activity^document_keyIN${chunk.join(',')}^ORDERBYorder`,
538
+ fields: 'document_key,variable.element,value',
539
+ limit: MAX_LIMIT,
540
+ }));
541
+ }
542
+ const configurationState = worstState(configurationReads);
543
+ components.configuration = configurationState;
544
+ if (configurationState !== 'ok') {
545
+ const failed = configurationReads.find(read => read.state !== 'ok');
546
+ inaccessible.push({ component: 'configuration', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
547
+ }
548
+ const byActivity = new Map();
549
+ for (const row of configurationReads.flatMap(read => read.rows || [])) {
550
+ const activityId = raw(row.document_key);
551
+ const element = raw(row['variable.element']);
552
+ if (!activityId || !element) continue;
553
+ if (!byActivity.has(activityId)) byActivity.set(activityId, {});
554
+ byActivity.get(activityId)[element] = text(row.value);
555
+ }
556
+ for (const activity of activities) {
557
+ activity.configuration = byActivity.get(activity.sys_id) || {};
558
+ activity.configuration_omissions = [];
559
+ for (const [element, value] of Object.entries(activity.configuration)) {
560
+ if (isScriptField(element) && isCommentOnlyScript(value)) {
561
+ delete activity.configuration[element];
562
+ activity.configuration_omissions.push({ field: element, reason: 'comment_only_script' });
563
+ }
564
+ }
565
+ activity.configuration_status = configurationState === 'ok' ? 'ok' : configurationState;
566
+ }
567
+ }
568
+
569
+ const definitionIds = [...new Set(activities.map(activity => activity.definition_id).filter(isSysId))];
570
+ const definitionReads = [];
571
+ for (const chunk of chunks(definitionIds)) {
572
+ definitionReads.push(await readComponent(sdk, DEFINITION, {
573
+ query: `sys_idIN${chunk.join(',')}`,
574
+ fields: DEFINITION_FIELDS,
575
+ limit: CHUNK,
576
+ }));
577
+ }
578
+ const definitionState = worstState(definitionReads, definitionIds.length === 0 ? 'not_applicable' : 'ok');
579
+ components.definitions = definitionState;
580
+ if (definitionState !== 'ok' && definitionState !== 'not_applicable') {
581
+ const failed = definitionReads.find(read => read.state !== 'ok');
582
+ inaccessible.push({ component: 'activity_definitions', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
583
+ }
584
+ definitions = new Map();
585
+ for (const row of definitionReads.flatMap(read => read.rows || [])) {
586
+ definitions.set(raw(row.sys_id), {
587
+ sys_id: raw(row.sys_id),
588
+ name: text(row.name),
589
+ description: text(row.description),
590
+ sys_class_name: text(row.sys_class_name),
591
+ });
592
+ }
593
+ for (const activity of activities) {
594
+ const definition = definitions.get(activity.definition_id);
595
+ if (definition) {
596
+ activity.definition_name = activity.definition_name || definition.name;
597
+ activity.definition_status = 'ok';
598
+ } else if (definitionState === 'ok') {
599
+ activity.definition_status = activity.definition_id ? 'missing' : 'unset';
600
+ } else {
601
+ activity.definition_status = definitionState;
602
+ }
603
+ }
604
+
605
+ const activityById = new Map(activities.map(activity => [activity.sys_id, activity]));
606
+ for (const condition of conditions) {
607
+ activityById.get(condition.activity_id)?.conditions.push(condition);
608
+ }
609
+
610
+ const conditionById = new Map(conditions.map(condition => [condition.sys_id, condition]));
611
+ transitions = transitionReads.flatMap(read => read.rows || []).map(row => {
612
+ const fromId = raw(row.from);
613
+ const toId = raw(row.to);
614
+ const conditionId = raw(row.condition);
615
+ const missing = [fromId, toId].filter(id => id && !activityById.has(id));
616
+ let status = 'ok';
617
+ if (missing.length > 0) status = activitySample.truncated ? 'outside_sample' : 'dangling';
618
+ return {
619
+ sys_id: raw(row.sys_id),
620
+ from_id: fromId,
621
+ to_id: toId,
622
+ from_name: activityById.get(fromId)?.name || '',
623
+ to_name: activityById.get(toId)?.name || '',
624
+ condition_id: conditionId,
625
+ condition_name: conditionById.get(conditionId)?.name || '',
626
+ condition_status: !conditionId ? 'none' : (conditionById.has(conditionId) ? 'ok' : 'missing'),
627
+ status,
628
+ missing_endpoints: missing,
629
+ };
630
+ }).sort((a, b) => a.from_name.localeCompare(b.from_name) || a.to_name.localeCompare(b.to_name));
631
+
632
+ integrity = buildIntegrity({ activities, transitions, conditions, inaccessible, activitySample, version, definitions });
633
+ } else {
634
+ integrity = buildIntegrity({ activities, transitions, conditions, inaccessible, activitySample, version: null, definitions });
635
+ }
636
+
637
+ const componentsComplete = Object.entries(components).every(([, state]) => ['ok', 'not_applicable', 'skipped'].includes(state));
638
+ const data = {
639
+ engine: 'legacy_workflow_editor',
640
+ workflow,
641
+ matched_by,
642
+ versions: versions.map(versionSummary),
643
+ versions_truncated: versionsTruncated,
644
+ selection: {
645
+ requested_version_id: versionId || null,
646
+ selected_version_id: version?.sys_id || null,
647
+ reason: selection.reason,
648
+ },
649
+ version: version ? versionSummary(version) : null,
650
+ activities,
651
+ transitions,
652
+ stages,
653
+ integrity,
654
+ coverage: {
655
+ complete: componentsComplete && !activitySample.truncated && !versionsTruncated
656
+ && inaccessible.length === 0,
657
+ components,
658
+ activity_sample: activitySample,
659
+ comment_only_scripts_omitted: activities.reduce((count, activity) => count + (activity.configuration_omissions?.length || 0), 0),
660
+ versions_truncated: versionsTruncated,
661
+ },
662
+ definition_scope: DESIGN_TIME_SCOPE,
663
+ };
664
+ return data;
665
+ }
666
+
667
+ function versionSummary(version) {
668
+ return {
669
+ sys_id: version.sys_id,
670
+ workflow_id: version.workflow_id,
671
+ name: version.name,
672
+ table: version.table,
673
+ published: version.published,
674
+ active: version.active,
675
+ checked_out: version.checked_out,
676
+ checked_out_by_id: version.checked_out_by_id,
677
+ checked_out_by_name: version.checked_out_by_name,
678
+ condition: version.condition,
679
+ start_activity_id: version.start_activity_id,
680
+ created_on: version.created_on,
681
+ updated_on: version.updated_on,
682
+ };
683
+ }
684
+
685
+ function worstState(reads, empty = 'not_applicable') {
686
+ if (reads.length === 0) return empty;
687
+ const failed = reads.find(read => read.state !== 'ok');
688
+ return failed ? failed.state : 'ok';
689
+ }
690
+
691
+ function buildIntegrity({ activities, transitions, conditions, inaccessible, activitySample, version, definitions }) {
692
+ const activityIds = new Set(activities.map(activity => activity.sys_id));
693
+ const expectedDefinitions = activities.filter(activity => activity.definition_id && !definitions.has(activity.definition_id));
694
+ return {
695
+ missing_activity_definitions: expectedDefinitions.map(activity => ({
696
+ activity_id: activity.sys_id,
697
+ activity_name: activity.name,
698
+ definition_id: activity.definition_id,
699
+ })),
700
+ unset_activity_definitions: activities.filter(activity => !activity.definition_id).map(activity => ({
701
+ activity_id: activity.sys_id,
702
+ activity_name: activity.name,
703
+ })),
704
+ dangling_transitions: transitions.filter(transition => transition.status === 'dangling').map(transition => ({
705
+ transition_id: transition.sys_id,
706
+ from_id: transition.from_id,
707
+ to_id: transition.to_id,
708
+ missing_endpoints: transition.missing_endpoints,
709
+ })),
710
+ unresolved_transition_conditions: transitions.filter(transition => transition.condition_status === 'missing').map(transition => ({
711
+ transition_id: transition.sys_id,
712
+ condition_id: transition.condition_id,
713
+ })),
714
+ dangling_start_activity: version?.start_activity_id && !activityIds.has(version.start_activity_id)
715
+ ? version.start_activity_id
716
+ : null,
717
+ inaccessible,
718
+ transitions_outside_sample: transitions.filter(transition => transition.status === 'outside_sample').length,
719
+ activity_sample_truncated: activitySample.truncated,
720
+ // A transition condition that was not read (ACL, deleted record) is
721
+ // listed in unresolved_transition_conditions rather than rendered empty.
722
+ condition_count: conditions.length,
723
+ };
724
+ }
725
+
726
+ function describeSelection(reason) {
727
+ switch (reason) {
728
+ case 'requested': return 'requested version';
729
+ case 'latest_published': return 'latest published version (active preferred)';
730
+ case 'newest': return 'newest version (no published version)';
731
+ case 'unavailable': return 'versions not readable';
732
+ default: return 'no version';
733
+ }
734
+ }
735
+
736
+ function truncateLines(value, max = 12) {
737
+ const lines = String(value).split('\n');
738
+ if (lines.length <= max) return lines.join('\n');
739
+ return `${lines.slice(0, max).join('\n')}\n… (${lines.length - max} more lines; use --json for the full value)`;
740
+ }
741
+
742
+ /**
743
+ * Human-readable outline. IDs stay visible so an agent or operator can follow
744
+ * up with a focused read; the structured JSON returned by inspectWorkflow
745
+ * remains the source of every detail.
746
+ */
747
+ export function formatWorkflowOutline(data, instanceURL = '') {
748
+ const lines = [];
749
+ const workflow = data.workflow;
750
+ lines.push('');
751
+ lines.push(`Legacy workflow: ${workflow.name} (table: ${workflow.table || 'unset'})`);
752
+ lines.push('');
753
+ lines.push(` Workflow sys_id: ${workflow.sys_id}`);
754
+ if (instanceURL) {
755
+ lines.push(` Link: ${instanceURL}/nav_to.do?uri=wf_workflow.do?sys_id=${workflow.sys_id}`);
756
+ }
757
+ if (workflow.description) lines.push(` Description: ${workflow.description}`);
758
+ if (data.coverage.components.versions === 'ok') {
759
+ lines.push(` Versions: ${data.versions.length}${data.versions_truncated ? '+' : ''} (${describeSelection(data.selection.reason)})`);
760
+ } else {
761
+ lines.push(` Versions: not readable (${data.coverage.components.versions})`);
762
+ }
763
+
764
+ const version = data.version;
765
+ if (version) {
766
+ const flags = [version.published ? 'published' : 'not published', version.active ? 'active' : 'inactive'];
767
+ lines.push(` Selected version: ${version.name} — ${flags.join(', ')}`);
768
+ lines.push(` Version sys_id: ${version.sys_id}`);
769
+ if (version.condition) lines.push(` Condition: ${version.condition}`);
770
+ if (version.checked_out_by_id) {
771
+ lines.push(` Checked out by: ${version.checked_out_by_name || version.checked_out_by_id} on ${version.checked_out || 'unknown date'}`);
772
+ }
773
+ } else {
774
+ lines.push(' Selected version: none');
775
+ }
776
+
777
+ if (data.versions.length > 0) {
778
+ lines.push('');
779
+ lines.push('▶ VERSIONS (newest first)');
780
+ lines.push('─'.repeat(50));
781
+ data.versions.forEach((item, index) => {
782
+ const flags = [item.published ? 'published' : 'draft', item.active ? 'active' : 'inactive'];
783
+ if (item.checked_out_by_id) flags.push(`checked out by ${item.checked_out_by_name || item.checked_out_by_id}`);
784
+ const marker = item.sys_id === version?.sys_id ? '*' : ' ';
785
+ lines.push(` ${marker} ${index + 1}. ${item.name} [${flags.join(', ')}] ${item.created_on}`);
786
+ lines.push(` ${item.sys_id}`);
787
+ });
788
+ }
789
+
790
+ lines.push('');
791
+ lines.push(`⚡ ACTIVITIES (${data.activities.length}${data.coverage.activity_sample.truncated ? '+' : ''})`);
792
+ lines.push('─'.repeat(50));
793
+ if (data.activities.length === 0) {
794
+ lines.push(` (${data.coverage.components.activities === 'ok' ? 'no activities found' : `activities ${data.coverage.components.activities}`})`);
795
+ }
796
+ data.activities.forEach((activity, index) => {
797
+ const definition = activity.definition_name || activity.definition_id || 'unset definition';
798
+ const details = [];
799
+ if (activity.parent_id) details.push(`parent ${activity.parent_id}`);
800
+ if (activity.stage_id) details.push(`stage ${activity.stage_id}`);
801
+ lines.push(` ${index + 1}. ${activity.name} [${definition}]`);
802
+ lines.push(` activity ${activity.sys_id}`);
803
+ if (details.length) lines.push(` ${details.join(' | ')}`);
804
+ for (const condition of activity.conditions) {
805
+ const flags = [condition.else_flag ? 'else' : '', condition.error ? 'error' : ''].filter(Boolean).join(', ');
806
+ lines.push(` condition: ${condition.name || condition.condition || condition.sys_id}${flags ? ` (${flags})` : ''} [${condition.sys_id}]`);
807
+ if (condition.condition && condition.name) lines.push(` ${condition.condition}`);
808
+ }
809
+ if (activity.configuration_status !== 'ok' && activity.configuration_status !== 'skipped') {
810
+ lines.push(` configuration: ${activity.configuration_status}`);
811
+ }
812
+ for (const omission of activity.configuration_omissions || []) {
813
+ lines.push(` omitted ${omission.field}: comment-only script (no executable code)`);
814
+ }
815
+ const script = activity.configuration?.script;
816
+ if (script) {
817
+ lines.push(' script:');
818
+ for (const line of truncateLines(script).split('\n')) lines.push(` ${line}`);
819
+ }
820
+ });
821
+
822
+ lines.push('');
823
+ lines.push('▶ TRANSITIONS');
824
+ lines.push('─'.repeat(50));
825
+ if (data.transitions.length === 0) {
826
+ lines.push(' (none found)');
827
+ }
828
+ for (const transition of data.transitions) {
829
+ const from = transition.from_name || transition.from_id || '(unknown)';
830
+ const to = transition.to_name || transition.to_id || '(unknown)';
831
+ const condition = transition.condition_id
832
+ ? ` [${transition.condition_name || transition.condition_id}${transition.condition_status === 'missing' ? ' — unreadable' : ''}]`
833
+ : '';
834
+ const issue = transition.status === 'dangling'
835
+ ? ` ⚠ missing ${transition.missing_endpoints.join(', ')}`
836
+ : transition.status === 'outside_sample' ? ' (outside the activity sample)' : '';
837
+ lines.push(` ${from} → ${to}${condition}${issue}`);
838
+ lines.push(` ${transition.sys_id}`);
839
+ }
840
+
841
+ if (data.stages.length > 0) {
842
+ lines.push('');
843
+ lines.push('▶ STAGES');
844
+ lines.push('─'.repeat(50));
845
+ for (const stage of data.stages) lines.push(` • ${stage.name} = ${stage.value} (order ${stage.order})`);
846
+ }
847
+
848
+ const warnings = [];
849
+ if (data.coverage.comment_only_scripts_omitted) {
850
+ warnings.push(`${data.coverage.comment_only_scripts_omitted} comment-only script fields omitted; see per-activity notes`);
851
+ }
852
+ for (const item of data.integrity.inaccessible) {
853
+ warnings.push(`${item.component}: ${item.state}${item.http_status ? ` (HTTP ${item.http_status})` : ''}`);
854
+ }
855
+ for (const item of data.integrity.missing_activity_definitions) {
856
+ warnings.push(`activity definition missing for ${item.activity_name || item.activity_id} (${item.definition_id})`);
857
+ }
858
+ for (const item of data.integrity.dangling_transitions) {
859
+ warnings.push(`transition ${item.transition_id} references missing activity ${item.missing_endpoints.join(', ')}`);
860
+ }
861
+ for (const item of data.integrity.unresolved_transition_conditions) {
862
+ warnings.push(`transition ${item.transition_id} references unreadable condition ${item.condition_id}`);
863
+ }
864
+ if (data.integrity.dangling_start_activity) {
865
+ warnings.push(`start activity ${data.integrity.dangling_start_activity} is not among this version's activities`);
866
+ }
867
+ if (data.integrity.activity_sample_truncated) {
868
+ warnings.push(`activities truncated at ${data.coverage.activity_sample.limit}; links outside the sample are reported as outside_sample`);
869
+ }
870
+ if (warnings.length > 0) {
871
+ lines.push('');
872
+ lines.push('⚠ INTEGRITY / COVERAGE');
873
+ lines.push('─'.repeat(50));
874
+ for (const warning of warnings) lines.push(` - ${warning}`);
875
+ }
876
+
877
+ lines.push('');
878
+ lines.push(`Note: ${DESIGN_TIME_SCOPE}`);
879
+ lines.push('');
880
+ return `${lines.join('\n')}\n`;
881
+ }
882
+
883
+ export function formatWorkflowList(data) {
884
+ const lines = ['', 'Legacy workflows (wf_workflow) — read-only inspection', ''];
885
+ lines.push('NAME | TABLE | PUBLISHED | CHECKED OUT | SYS_ID');
886
+ lines.push('--- | --- | --- | --- | ---');
887
+ for (const record of data.records) {
888
+ const published = record.published_version
889
+ ? `${record.published_version.name}${record.published_version.active ? '' : ' (inactive)'}`
890
+ : '—';
891
+ const checkout = record.checked_out_version
892
+ ? `${record.checked_out_version.checked_out_by_name || record.checked_out_version.checked_out_by_id}`
893
+ : '—';
894
+ lines.push(`${record.name} | ${record.table || '—'} | ${published} | ${checkout} | ${record.sys_id}`);
895
+ }
896
+ if (data.records.length === 0) lines.push('(no workflows on this page)');
897
+ lines.push('');
898
+ lines.push(`Page: limit ${data.pagination.limit}, offset ${data.pagination.offset}, more: ${data.pagination.has_more ? 'yes' : 'no'}`);
899
+ if (data.coverage.components.versions !== 'ok') {
900
+ lines.push(`⚠ Version state not readable: ${data.coverage.components.versions}`);
901
+ }
902
+ if (data.versions_truncated) {
903
+ lines.push('⚠ Version state is a bounded sample (100 rows per state); narrow the list with --name, --table or --query.');
904
+ }
905
+ lines.push('');
906
+ return `${lines.join('\n')}\n`;
907
+ }
908
+
909
+ /**
910
+ * Published workflow versions configured for one table. Intended for reuse by
911
+ * table-behavior discovery (#398). This reports only workflows whose version
912
+ * names the table; it does not discover script-started or condition-started
913
+ * workflows and does not claim to.
914
+ */
915
+ export async function listPublishedWorkflowVersionsForTable(sdk, table, { limit = 50 } = {}) {
916
+ if (!/^[a-z][a-z0-9_]*$/.test(String(table || ''))) throw errUsage('A table name is required.');
917
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw errUsage('limit must be from 1 to 200.');
918
+ const read = await readComponent(sdk, VERSION, {
919
+ query: `table=${table}^published=true^ORDERBYname`,
920
+ fields: VERSION_FIELDS,
921
+ limit,
922
+ });
923
+ return {
924
+ table,
925
+ state: read.state,
926
+ http_status: read.http_status ?? null,
927
+ versions: (read.rows || []).map(normalizeVersion).map(versionSummary),
928
+ coverage: {
929
+ complete: read.state === 'ok',
930
+ note: 'Association by wf_workflow_version.table only. Script- and condition-started workflows are not discovered.',
931
+ },
932
+ };
933
+ }