@jacebenson/jsn 5.3.0-dev.136.1 → 5.3.0-dev.139.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.3.0-dev.136.1",
3
+ "version": "5.3.0-dev.139.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -65,6 +65,7 @@ import {
65
65
  } from './commands/_simple.js';
66
66
  import { decisiontablesCmd } from './commands/decisiontables.js';
67
67
  import { flowsCmd } from './commands/flows.js';
68
+ import { workflowsCmd } from './commands/workflows.js';
68
69
  import { formsCmd } from './commands/forms.js';
69
70
  import { listsCmd } from './commands/lists.js';
70
71
  import { updateSetsCmd } from './commands/updatesets.js';
@@ -359,6 +360,7 @@ export function buildCLI() {
359
360
  .command(casesCmd(wrap))
360
361
  // AUTOMATION — Async
361
362
  .command(flowsCmd(wrap))
363
+ .command(workflowsCmd(wrap))
362
364
  .command(actionsCmd(wrap))
363
365
  .command(scriptactionsCmd(wrap))
364
366
  .command(scheduledjobsCmd(wrap))
@@ -6,6 +6,7 @@ import { inspectFlow } from '../flow-inspection.js';
6
6
  import { publishFlows, publishFlowLifecycle, publishDoctor, flowStatus } from '../flow-publish.js';
7
7
  import { resolveRecord, unwrapSysId } from '../resolve-record.js';
8
8
  import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet } from '../flow-create.js';
9
+ import { alignUpdateSetCapture } from '../context.js';
9
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
10
11
  import { testFlow } from '../flow-test.js';
11
12
  import { errUsage } from '../errors.js';
@@ -331,6 +332,7 @@ export function flowsCmd(wrap) {
331
332
  }
332
333
  const result = await createFlowFromManifest(app.sdk, app.getEffectiveInstance(), manifest, {
333
334
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
335
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
334
336
  });
335
337
  app.ok({ ...result, trigger_guidance: triggerGuidance(result.trigger) }, {
336
338
  summary: `Created draft flow "${result.flow.name}" (${result.flow.id}) with trigger ${result.trigger?.type ?? 'unknown'} (${result.trigger?.id ?? 'no trigger id'}) without activation`,
@@ -368,6 +370,7 @@ export function flowsCmd(wrap) {
368
370
  const result = await updateFlowFromManifest(app.sdk, app.getEffectiveInstance(), argv.identifier, manifest, {
369
371
  preview: argv.preview,
370
372
  readUpdateSet: () => readCurrentUpdateSet(app.sdk),
373
+ ensureCapture: intended => alignUpdateSetCapture(app.sdk, intended),
371
374
  });
372
375
  const diff = result.changes.map(change => `${change.component}${change.order ? ` ${change.order}` : ''}.${change.input}: ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}`).join('\n');
373
376
  const state = `${result.flow.status}${result.flow.active ? ', active' : ''}`;
@@ -0,0 +1,97 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { errUsage } from '../errors.js';
3
+ import {
4
+ inspectWorkflow,
5
+ listWorkflows,
6
+ formatWorkflowList,
7
+ formatWorkflowOutline,
8
+ } from '../workflow-inspection.js';
9
+
10
+ // Legacy Workflow Editor inspection is read-only by construction: every
11
+ // request in workflow-inspection.js is a Table API GET. Declaring no mutation
12
+ // subcommands keeps the mutation guard and read-only profiles aligned with
13
+ // what the command can actually do.
14
+ declareCapabilities('workflows', { mutationSubcommands: [] });
15
+
16
+ // A curated human view belongs to the command; keeping it non-enumerable
17
+ // leaves the JSON envelope free of presentation text.
18
+ function defineFormatted(data, formatted) {
19
+ Object.defineProperty(data, '_formatted', { value: formatted, enumerable: false, configurable: true });
20
+ }
21
+
22
+ export function workflowsCmd(wrap) {
23
+ return {
24
+ command: 'workflows [subcommand]',
25
+ aliases: ['workflow'],
26
+ describe: 'Inspect legacy Workflow Editor workflows (read-only)',
27
+ builder: (yargs) => yargs
28
+ .command({
29
+ command: 'list',
30
+ aliases: ['ls'],
31
+ describe: 'List legacy workflows with published and checked-out versions',
32
+ builder: (y) => y
33
+ .option('name', { type: 'string', describe: 'Workflow name contains this text' })
34
+ .option('table', { type: 'string', describe: 'Exact target table name (e.g. incident)' })
35
+ .option('query', { type: 'string', describe: 'Additional encoded query (e.g. "nameLIKEapproval")' })
36
+ .option('limit', { alias: 'l', type: 'number', default: 20, describe: 'Page size (1–100)' })
37
+ .option('offset', { type: 'number', default: 0, describe: 'Starting result offset' }),
38
+ handler: wrap(async (argv, app) => {
39
+ app.requireInstance();
40
+ const data = await listWorkflows(app.sdk, {
41
+ name: argv.name || '',
42
+ table: argv.table || '',
43
+ query: argv.query || '',
44
+ limit: argv.limit,
45
+ offset: argv.offset,
46
+ });
47
+ const next = data.pagination.has_more
48
+ ? `jsn workflows list --limit ${data.pagination.limit} --offset ${data.pagination.offset + data.pagination.limit}`
49
+ : '';
50
+ const breadcrumbs = data.records.slice(0, 5).map(record => ({
51
+ action: 'show',
52
+ cmd: `jsn workflows show ${record.sys_id}`,
53
+ description: `Inspect ${record.name}`,
54
+ }));
55
+ if (next) breadcrumbs.push({ action: 'next', cmd: next, description: 'Next page of legacy workflows' });
56
+ defineFormatted(data, formatWorkflowList(data));
57
+ app.ok(data, {
58
+ summary: `${data.count} legacy workflow(s)${data.pagination.has_more ? ', more available' : ''}`,
59
+ breadcrumbs,
60
+ });
61
+ }),
62
+ })
63
+ .command({
64
+ command: 'show <identifier>',
65
+ aliases: ['get'],
66
+ describe: 'Inspect one legacy workflow: versions, activities, transitions, conditions and configuration',
67
+ builder: (y) => y
68
+ .positional('identifier', { type: 'string', describe: 'Workflow name, workflow sys_id, or version sys_id' })
69
+ .option('version', { type: 'string', describe: 'Specific wf_workflow_version sys_id (default: published, else newest)' })
70
+ .option('config', { type: 'boolean', default: true, describe: 'Read activity configuration and scripts' })
71
+ .option('limit', { alias: 'l', type: 'number', default: 200, describe: 'Maximum activities to read (1–1000)' }),
72
+ handler: wrap(async (argv, app) => {
73
+ app.requireInstance();
74
+ if (typeof argv.identifier !== 'string' || !argv.identifier.trim()) {
75
+ throw errUsage('Provide a legacy workflow name or sys_id.');
76
+ }
77
+ const data = await inspectWorkflow(app.sdk, {
78
+ identifier: argv.identifier,
79
+ versionId: argv.version || '',
80
+ includeConfiguration: argv.config !== false,
81
+ limit: argv.limit,
82
+ });
83
+ defineFormatted(data, formatWorkflowOutline(data, app.getEffectiveInstance()));
84
+ const versionLabel = data.version
85
+ ? `${data.version.name} (${data.selection.reason})`
86
+ : 'no readable version';
87
+ app.ok(data, {
88
+ summary: `Legacy workflow: ${data.workflow.name} — ${versionLabel}, ${data.activities.length} activity(ies)${data.coverage.complete ? '' : ', partial coverage'}`,
89
+ breadcrumbs: [
90
+ { action: 'list', cmd: 'jsn workflows list', description: 'Back to legacy workflows' },
91
+ ...(data.version ? [{ action: 'json', cmd: `jsn workflows show ${data.workflow.sys_id} --json`, description: 'Structured definition with IDs' }] : []),
92
+ ],
93
+ });
94
+ }),
95
+ }),
96
+ };
97
+ }
package/src/context.js CHANGED
@@ -98,3 +98,86 @@ export async function setCurrentApplication(sdk, _userSysID, scopeSysID) {
98
98
  export async function setCurrentUpdateSet(sdk, _userSysID, updateSetSysID) {
99
99
  await selectContext(sdk, 'updateset', { sysId: updateSetSysID }, updateSetSysID);
100
100
  }
101
+
102
+ /**
103
+ * Read the update set this authenticated session will actually capture into.
104
+ *
105
+ * `sys_user_preference:user=<user>^name=sys_update_set` is the persisted
106
+ * choice; this endpoint reports the session's effective picker selection. They
107
+ * are different sources and can disagree in a freshly-warmed session, so the
108
+ * preference alone must not be treated as the provider's capture context.
109
+ */
110
+ export async function readEffectiveUpdateSet(sdk) {
111
+ const endpoint = `${sdk.baseURL}/api/now/ui/concoursepicker/updateset`;
112
+ const response = await sdk.request(endpoint, { method: 'GET', readOnly: true });
113
+ const current = response?.result?.current;
114
+ if (!current || typeof current !== 'object') {
115
+ throw new Error('Invalid update-set picker response: expected result.current.');
116
+ }
117
+ const sysId = typeof current.sysId === 'string' ? current.sysId : '';
118
+ return {
119
+ sys_id: sysId,
120
+ name: typeof current.name === 'string' ? current.name : '',
121
+ label: current.displayValue || current.name || sysId,
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Make the warmed session's effective capture set match the persisted choice
127
+ * before content writes, and verify the result.
128
+ *
129
+ * A fresh CLI invocation is a fresh authenticated session; the persisted
130
+ * preference is the user's intentional choice, but nothing guarantees the new
131
+ * session inherited it (`jsn updatesets create`/`set` may have selected the set
132
+ * in a session that has since ended). When the two disagree, re-apply the
133
+ * persisted selection through the same picker contract and verify it.
134
+ *
135
+ * Returns a report instead of throwing when the effective selection cannot be
136
+ * read at all (for example an auth mode that cannot keep a UI session). A
137
+ * readable-but-unalignable mismatch throws, so a content write never proceeds
138
+ * into a set the CLI would then wrongly report.
139
+ */
140
+ export async function alignUpdateSetCapture(sdk, intended) {
141
+ const intendedId = intended?.sys_id || '';
142
+ let effective;
143
+ try {
144
+ effective = await readEffectiveUpdateSet(sdk);
145
+ } catch (error) {
146
+ return {
147
+ intended: intended || null,
148
+ effective: null,
149
+ aligned: null,
150
+ action: 'unverified',
151
+ reason: `effective session selection could not be read: ${error.message}`,
152
+ };
153
+ }
154
+ const report = { intended: intended || null, effective, aligned: null, action: 'none' };
155
+ if (!intendedId) {
156
+ report.reason = 'no persisted update-set selection (Default or unreadable preference)';
157
+ return report;
158
+ }
159
+ if (effective.sys_id === intendedId) {
160
+ report.aligned = true;
161
+ return report;
162
+ }
163
+ try {
164
+ await setCurrentUpdateSet(sdk, null, intendedId);
165
+ } catch (error) {
166
+ const message = `Session capture context could not be aligned with the selected update set before any content write. `
167
+ + `This session resolves to ${effective.sys_id || 'an empty selection'} (${effective.name || 'unknown'}), `
168
+ + `but the persisted selection is ${intended?.name || intendedId} (${intendedId}). ${error.message} `
169
+ + 'No content was written. Re-select explicitly with `jsn updatesets set` in an interactive session, '
170
+ + 'or use an auth profile that keeps a UI session, then retry.';
171
+ const failure = new Error(message, { cause: error });
172
+ failure.capture_context = { ...report, aligned: false, action: 'select_failed' };
173
+ throw failure;
174
+ }
175
+ report.previous_effective = effective;
176
+ report.effective = await readEffectiveUpdateSet(sdk);
177
+ report.action = 'selected';
178
+ report.aligned = report.effective.sys_id === intendedId;
179
+ if (!report.aligned) {
180
+ report.reason = 'session still resolves to a different set after re-selection';
181
+ }
182
+ return report;
183
+ }
@@ -794,13 +794,23 @@ function unavailableCapture(reason) {
794
794
  return { available: false, status: 'unavailable', reason };
795
795
  }
796
796
 
797
+ // Reporting reads the persisted preference, but the provider captures into the
798
+ // session's effective selection. Reconcile the two before the first content
799
+ // write and carry the result into the payload so a save can never claim a set
800
+ // it did not use.
801
+ async function resolveCaptureContext(options, readUpdateSet) {
802
+ if (!options.ensureCapture) return undefined;
803
+ const intended = await readUpdateSet();
804
+ return options.ensureCapture(intended);
805
+ }
806
+
797
807
  async function addPostMutationCapture(snapshot, sdk, readUpdateSet, flowId) {
798
808
  const updateSet = await readUpdateSet();
799
809
  snapshot.after = updateSet;
800
810
  snapshot.capture_after = await readUpdateSetCapture(sdk, updateSet, flowId);
801
811
  }
802
812
 
803
- export async function readUpdateSetCapture(sdk, updateSet, flowId) {
813
+ export async function readUpdateSetCapture(sdk, updateSet, flowId, { locateElsewhere = false } = {}) {
804
814
  const updateSetId = idValue(updateSet?.sys_id || updateSet?.sysId);
805
815
  if (!updateSetId) return unavailableCapture('current update set has no selected sys_id (likely Default)');
806
816
  const rows = await sdk.list('sys_update_xml', new URLSearchParams({
@@ -810,13 +820,67 @@ export async function readUpdateSetCapture(sdk, updateSet, flowId) {
810
820
  sysparm_fields: 'sys_id,name,type,action,target_name,update_set,payload,xml',
811
821
  }));
812
822
  const matches = rows.filter(row => JSON.stringify(row).includes(flowId));
813
- return {
823
+ const capture = {
814
824
  available: true,
815
825
  status: matches.length ? 'captured' : 'missing',
816
826
  update_set: updateSet,
817
827
  count: matches.length,
818
828
  records: matches,
819
829
  };
830
+ if (!matches.length && locateElsewhere) {
831
+ capture.elsewhere = await findCaptureElsewhere(sdk, flowId, updateSetId);
832
+ const destinations = capture.elsewhere.update_sets || [];
833
+ capture.diagnosis = destinations.length
834
+ ? `Content was saved, but no update XML for this flow is in ${updateSet?.name || updateSetId}. `
835
+ + `${destinations.reduce((sum, set) => sum + set.count, 0)} matching record(s) are in `
836
+ + `${destinations.map(set => `${set.name || set.sys_id} (${set.sys_id})`).join(', ')}. `
837
+ + 'These may be historical captures and do not prove this save was routed elsewhere. '
838
+ + 'Capture can be asynchronous; re-check the intended set before completing or exporting it.'
839
+ : `Content was saved, but no update XML naming this flow was found in ${updateSet?.name || updateSetId} `
840
+ + `or by nameLIKE${flowId}. Capture may be absent or recorded under a different name; `
841
+ + 'inspect sys_update_xml for the flow sys_id before completing the set.';
842
+ }
843
+ return capture;
844
+ }
845
+
846
+ // The flow's own update XML is named `<table>_<sys_id>`, so the flow sys_id is
847
+ // searchable across every set. This locates candidate captures without moving
848
+ // records; a historical match alone cannot establish where this save landed.
849
+ async function findCaptureElsewhere(sdk, flowId, intendedSetId) {
850
+ const id = idValue(flowId);
851
+ // Only a single opaque token may reach the encoded query; never allow query
852
+ // operators such as ^ or = to be injected through a caller-supplied id.
853
+ if (!/^[0-9a-zA-Z_-]{1,64}$/.test(id)) {
854
+ return { checked: false, reason: 'flow identifier is not a safe exact token', update_sets: [] };
855
+ }
856
+ const params = new URLSearchParams({
857
+ sysparm_query: `nameLIKE${id}`,
858
+ sysparm_limit: '50',
859
+ sysparm_display_value: 'all',
860
+ sysparm_fields: 'sys_id,name,type,action,target_name,update_set,sys_created_on',
861
+ });
862
+ let rows;
863
+ try {
864
+ rows = await sdk.list('sys_update_xml', params);
865
+ } catch (error) {
866
+ return { checked: true, available: false, reason: error.message, update_sets: [] };
867
+ }
868
+ const bySet = new Map();
869
+ for (const row of rows) {
870
+ const raw = row.update_set;
871
+ const setId = idValue(raw);
872
+ if (!setId || setId === intendedSetId) continue;
873
+ const entry = bySet.get(setId) || { sys_id: setId, name: raw?.display_value || '', count: 0, records: [] };
874
+ entry.count += 1;
875
+ entry.records.push({
876
+ sys_id: idValue(row.sys_id),
877
+ name: row.name?.display_value || row.name || '',
878
+ action: row.action?.display_value || row.action || '',
879
+ sys_created_on: row.sys_created_on?.display_value || row.sys_created_on || '',
880
+ });
881
+ bySet.set(setId, entry);
882
+ }
883
+ return { checked: true, available: true, query: `nameLIKE${id}`, update_sets: [...bySet.values()] };
820
884
  }
821
885
 
822
886
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
@@ -825,6 +889,12 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
825
889
  const idFactory = options.idFactory || (() => randomUUID());
826
890
  const readUpdateSet = options.readUpdateSet || (async () => null);
827
891
  const snapshots = [];
892
+ let captureContext;
893
+ try {
894
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
895
+ } catch (error) {
896
+ throw new Error(`Flow creation refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
897
+ }
828
898
 
829
899
  let parentResponse;
830
900
  try {
@@ -885,7 +955,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
885
955
  instance, flowId, scope, type: 'Autosave', annotation: 'JSN flow create',
886
956
  }), updateSet => readUpdateSetCapture(sdk, updateSet, flowId));
887
957
  const selectedUpdateSet = await readUpdateSet();
888
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
958
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
889
959
 
890
960
  const triggerReadback = findArray(processflow, 'triggerInstances')[0] || {};
891
961
  return {
@@ -895,6 +965,7 @@ export async function createFlowFromManifest(sdk, instance, inputManifest, optio
895
965
  processflow,
896
966
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
897
967
  version,
968
+ ...(captureContext ? { capture_context: captureContext } : {}),
898
969
  update_set_capture: updateSetCapture,
899
970
  update_set_mutations: snapshots,
900
971
  lifecycle: { published: false, supported: ['draft', 'autosave'], deferred: ['publish/activation', 'Flow Logic', 'subflows', 'flow variables', 'error handling'] },
@@ -984,6 +1055,12 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
984
1055
  deferred: DEFERRED_LIFECYCLE,
985
1056
  },
986
1057
  };
1058
+ let captureContext;
1059
+ try {
1060
+ captureContext = await resolveCaptureContext(options, readUpdateSet);
1061
+ } catch (error) {
1062
+ throw new Error(`Flow ${flowId} update refused before any content write: capture context could not be established. ${error.message}`, { cause: error });
1063
+ }
987
1064
  // Baseline the published runtime after the definition read (a legacy read can
988
1065
  // materialize a version row) and before the edit session exists.
989
1066
  const runtimeBefore = published ? await readFlowRuntime(sdk, instance, flowId, { scope, snapshotId }) : null;
@@ -1082,7 +1159,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1082
1159
  completedStage = 'runtime_verified';
1083
1160
  }
1084
1161
  const selectedUpdateSet = await readUpdateSet();
1085
- const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId);
1162
+ const updateSetCapture = await readUpdateSetCapture(sdk, selectedUpdateSet, flowId, { locateElsewhere: true });
1086
1163
  // Report what the record says after the save, not the pre-edit label: a
1087
1164
  // published flow that now has a draft working copy must not look published
1088
1165
  // in the result. `active` and the snapshot pointers are the runtime gates.
@@ -1099,6 +1176,7 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
1099
1176
  definition_readback: { available: true, status: 'read_back', flow_id: flowId },
1100
1177
  version,
1101
1178
  ...(runtime ? { runtime_preservation: runtime } : {}),
1179
+ ...(captureContext ? { capture_context: captureContext } : {}),
1102
1180
  update_set_capture: updateSetCapture,
1103
1181
  update_set_mutations: snapshots,
1104
1182
  lifecycle: {
@@ -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
+ }