@jacebenson/jsn 5.4.0-dev.140.1 → 5.4.0-dev.142.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.4.0-dev.140.1",
3
+ "version": "5.4.0-dev.142.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": {
@@ -9,6 +9,7 @@ import { createFlowFromManifest, updateFlowFromManifest, readCurrentUpdateSet }
9
9
  import { alignUpdateSetCapture } from '../context.js';
10
10
  import { EXCLUDED_TRIGGER_TYPES, SUPPORTED_TRIGGER_TYPES, readTriggerCatalog, readTriggerInputDefinitions } from '../flow-triggers.js';
11
11
  import { testFlow } from '../flow-test.js';
12
+ import { releaseOwnFlowSafeEdit } from '../flow-safe-edit.js';
12
13
  import { errUsage } from '../errors.js';
13
14
  import { cancelled, pickDesignerRecord, guidedFlowCreate, guidedFlowEdit, guidedFlowTestRecord, hasDefinitionData, confirmDesignerMutation } from '../flow-designer-interactive.js';
14
15
 
@@ -24,6 +25,7 @@ const FLOW_COMMANDS = [
24
25
  { name: 'create', description: 'Create a draft flow: guided in a terminal, JSON manifest in scripts' },
25
26
  { name: 'update [identifier]', description: 'Update a draft, or a published flow whose definition reports write access (alias: edit)' },
26
27
  { name: 'doctor', description: 'Check whether this instance can publish flows at all' },
28
+ { name: 'unlock [identifier]', description: 'Release this user\'s stale safe-edit session (orphaned lease) after a failed update' },
27
29
  { name: 'delete [identifier]', description: 'Delete a flow (not implemented: use the Flow Designer UI)' },
28
30
  ];
29
31
 
@@ -46,7 +48,7 @@ function triggerGuidance(trigger) {
46
48
  };
47
49
  }
48
50
 
49
- declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test'] });
51
+ declareCapabilities('flows', { mutationSubcommands: ['create', 'update', 'edit', 'delete', 'publish', 'test', 'unlock'] });
50
52
 
51
53
  function renderChecks(checks) {
52
54
  return checks.map((c) => {
@@ -383,6 +385,31 @@ export function flowsCmd(wrap) {
383
385
  });
384
386
  }),
385
387
  })
388
+ .command({
389
+ command: 'unlock [identifier]',
390
+ describe: 'Release this user\'s stale Flow Designer safe-edit session on a flow. Recovery for an orphaned lease left by a failed update: the provider only releases the calling user\'s own session, the before/after canUserEdit and currentEditor values are printed, and an unconfirmed release fails instead of reporting success. Does not edit content, publish, or touch another user\'s session.',
391
+ builder: (y) => y
392
+ .option('force', { type: 'boolean', default: false, describe: 'Skip confirmation' }),
393
+ handler: wrap(async (argv, app) => {
394
+ app.requireInstance();
395
+ const identifier = await pickFlow(argv, app);
396
+ if (identifier === undefined) return;
397
+ const sysID = unwrapSysId(await resolveRecord(app.sdk, {
398
+ table: 'sys_hub_flow', identifier, matchField: 'name', resource: 'Flow',
399
+ }));
400
+ await confirmDesignerMutation(argv, app, `Release your Flow Designer safe-edit session on flow ${identifier}? If this flow is open in Flow Designer, that editor's next save will fail.`);
401
+ const result = await releaseOwnFlowSafeEdit(app.sdk, app.getEffectiveInstance(), sysID);
402
+ const state = status => `canUserEdit=${status.canUserEdit}, currentEditor=${JSON.stringify(status.currentEditor ?? null)}`;
403
+ return app.ok({ ...result, flow: { id: sysID, name: identifier } }, {
404
+ summary: result.released
405
+ ? `Released this user's safe edit session on flow ${identifier} (${sysID}): ${state(result.before)} -> ${state(result.after)}`
406
+ : `No safe edit session to release on flow ${identifier} (${sysID}): ${state(result.before)}`,
407
+ breadcrumbs: result.released
408
+ ? [{ action: 'update', cmd: `jsn flows update ${sysID}`, description: 'Retry the edit' }]
409
+ : [{ action: 'show', cmd: `jsn flows show ${sysID}`, description: 'Inspect the flow' }],
410
+ });
411
+ }),
412
+ })
386
413
  .command({
387
414
  command: 'delete [identifier]',
388
415
  describe: 'Delete a flow (not yet implemented)',
@@ -19,6 +19,27 @@ function defineFormatted(data, formatted) {
19
19
  Object.defineProperty(data, '_formatted', { value: formatted, enumerable: false, configurable: true });
20
20
  }
21
21
 
22
+ export function parseWorkflowStep(value) {
23
+ if (value === undefined) return undefined;
24
+ if (!/^[1-9]\d*$/.test(String(value)) || !Number.isSafeInteger(Number(value))) {
25
+ throw errUsage('--step must be a positive integer.');
26
+ }
27
+ return Number(value);
28
+ }
29
+
30
+ export function selectWorkflowStep(data, number) {
31
+ if (number === undefined) return data;
32
+ const step = data.steps.find(step => step.number === number);
33
+ if (!step) throw errUsage(`Step ${number} is out of range: ${data.steps.length} steps; valid range ${data.steps.length ? `1–${data.steps.length}` : 'none (0 steps)'}.`);
34
+ return {
35
+ ...data,
36
+ activities: data.activities.filter(activity => activity.sys_id === step.sys_id),
37
+ steps: [step],
38
+ transitions: data.transitions.filter(edge => edge.from_id === step.sys_id),
39
+ transitions_by_activity: data.transitions_by_activity.filter(group => group.sys_id === step.sys_id),
40
+ };
41
+ }
42
+
22
43
  export function workflowsCmd(wrap) {
23
44
  return {
24
45
  command: 'workflows [subcommand]',
@@ -67,28 +88,33 @@ export function workflowsCmd(wrap) {
67
88
  builder: (y) => y
68
89
  .positional('identifier', { type: 'string', describe: 'Workflow name, workflow sys_id, or version sys_id' })
69
90
  .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' })
91
+ .option('config', { type: 'boolean', describe: 'Show activity configuration and scripts under each step' })
92
+ .option('step', { type: 'string', describe: 'Inspect one positive step number with full configuration' })
71
93
  .option('limit', { alias: 'l', type: 'number', default: 200, describe: 'Maximum activities to read (1–1000)' }),
72
94
  handler: wrap(async (argv, app) => {
73
95
  app.requireInstance();
74
96
  if (typeof argv.identifier !== 'string' || !argv.identifier.trim()) {
75
97
  throw errUsage('Provide a legacy workflow name or sys_id.');
76
98
  }
99
+ const step = parseWorkflowStep(argv.step);
77
100
  const data = await inspectWorkflow(app.sdk, {
78
101
  identifier: argv.identifier,
79
102
  versionId: argv.version || '',
80
- includeConfiguration: argv.config !== false,
103
+ // Keep the existing JSON/read contract; --config controls presentation.
104
+ includeConfiguration: step !== undefined || argv.config !== false,
81
105
  limit: argv.limit,
82
106
  });
83
- defineFormatted(data, formatWorkflowOutline(data, app.getEffectiveInstance()));
107
+ const selected = selectWorkflowStep(data, step);
108
+ const formatted = formatWorkflowOutline(data, { includeConfiguration: argv.config === true, step });
109
+ defineFormatted(selected, formatted);
84
110
  const versionLabel = data.version
85
111
  ? `${data.version.name} (${data.selection.reason})`
86
112
  : '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'}`,
113
+ app.ok(selected, {
114
+ summary: `Legacy workflow: ${data.workflow.name} — ${versionLabel}, ${selected.activities.length} activity(ies)${data.coverage.complete ? '' : ', partial coverage'}`,
89
115
  breadcrumbs: [
90
116
  { 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' }] : []),
117
+ ...(data.version ? [{ action: 'json', cmd: `jsn workflows show ${JSON.stringify(data.workflow.name)} --json`, description: 'Structured definition with IDs' }] : []),
92
118
  ],
93
119
  });
94
120
  }),
@@ -13,15 +13,36 @@ export async function flowSafeEditRequest(sdk, instance, flowId, operation, last
13
13
  return result;
14
14
  }
15
15
 
16
+ export async function readFlowSafeEditStatus(sdk, instance, flowId) {
17
+ const { status } = await flowSafeEditRequest(sdk, instance, flowId, 'read');
18
+ if (!status || typeof status.canUserEdit !== 'boolean' || !(status.currentEditor == null || typeof status.currentEditor === 'string')) throw new Error('Unreadable safe edit status');
19
+ return status;
20
+ }
21
+
22
+ // The provider's `delete` only ever releases the calling user's own session, so
23
+ // recovery needs no ownership guess. It stays explicit anyway: releasing a lease
24
+ // that a live Flow Designer tab owns makes that editor's next save fail.
25
+ export async function releaseOwnFlowSafeEdit(sdk, instance, flowId) {
26
+ const before = await readFlowSafeEditStatus(sdk, instance, flowId);
27
+ const describe = status => `canUserEdit=${status.canUserEdit}, currentEditor=${JSON.stringify(status.currentEditor ?? null)}`;
28
+ if (!before.canUserEdit && !before.currentEditor) return { released: false, before, after: before };
29
+ const { deleteResult } = await flowSafeEditRequest(sdk, instance, flowId, 'delete');
30
+ if (deleteResult?.deleteSuccess !== true || deleteResult.id !== flowId) {
31
+ throw new Error(`Flow ${flowId} safe edit release was not confirmed by the provider (deleteSuccess=${JSON.stringify(deleteResult?.deleteSuccess ?? null)}, id=${JSON.stringify(deleteResult?.id ?? null)}); no retry attempted. Status before release: ${describe(before)}.`);
32
+ }
33
+ const after = await readFlowSafeEditStatus(sdk, instance, flowId);
34
+ if (after.canUserEdit || after.currentEditor) throw new Error(`Flow ${flowId} release was acknowledged, but readback still reports an edit session (${describe(after)}). Inspect the exact flow and Flow Designer session before retrying.`);
35
+ return { released: true, before, after };
36
+ }
37
+
16
38
  export async function withFlowSafeEdit(sdk, instance, flowId, lastUpdated, operation) {
17
39
  if (typeof lastUpdated !== 'string' || !lastUpdated) throw new Error(`Flow ${flowId} has no authoritative updated timestamp; safe edit refused`);
18
- const read = async () => {
19
- const { status } = await flowSafeEditRequest(sdk, instance, flowId, 'read');
20
- if (!status || typeof status.canUserEdit !== 'boolean' || !(status.currentEditor == null || typeof status.currentEditor === 'string')) throw new Error('Unreadable safe edit status');
21
- return status;
22
- };
40
+ const read = () => readFlowSafeEditStatus(sdk, instance, flowId);
23
41
  const before = await read();
24
- if (before.canUserEdit || before.currentEditor) throw new Error(`Flow ${flowId} already has an existing edit session/editor; close it in Flow Designer before retrying. No lock changed.`);
42
+ // Refuse any reported session, including one this same user holds: releasing
43
+ // it would close a Flow Designer tab this CLI never opened, so recovery stays
44
+ // an explicit command (`jsn flows unlock`) rather than an implicit takeover.
45
+ if (before.canUserEdit || before.currentEditor) throw new Error(`Flow ${flowId} already has an existing edit session/editor (canUserEdit=${before.canUserEdit}, currentEditor=${JSON.stringify(before.currentEditor ?? null)}); close it in Flow Designer before retrying, or release your own stale session with \`jsn flows unlock ${flowId}\`. No lock changed.`);
25
46
  let status;
26
47
  try {
27
48
  ({ status } = await flowSafeEditRequest(sdk, instance, flowId, 'upsert', lastUpdated));
@@ -0,0 +1,88 @@
1
+ // Compare explicit keys without depending on the host locale.
2
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
3
+ const byNameId = (a, b) => compare(a.name, b.name) || compare(a.sys_id, b.sys_id);
4
+ const byEdge = (a, b) => compare(a.to_name, b.to_name) || compare(a.sys_id, b.sys_id);
5
+
6
+ /** Pure analysis of already-loaded rows. Iterative Kosaraju avoids stack limits. */
7
+ export function analyzeWorkflowGraph(activities, transitions) {
8
+ const members = activities.map(({ sys_id, name }) => ({ sys_id, name })).sort(byNameId);
9
+ const activity_ids = new Set(members.map(member => member.sys_id));
10
+ const outgoing = new Map(members.map(member => [member.sys_id, []]));
11
+ const reverse = new Map(members.map(member => [member.sys_id, []]));
12
+ const groups = new Map(members.map(member => [member.sys_id, { ...member, transitions: [] }]));
13
+ for (const edge of transitions) {
14
+ // Retain malformed source links in the grouped view too, without treating
15
+ // the missing source as an activity in the sampled graph.
16
+ if (!groups.has(edge.from_id)) groups.set(edge.from_id, {
17
+ sys_id: edge.from_id, name: edge.from_name, transitions: [],
18
+ });
19
+ groups.get(edge.from_id).transitions.push(edge);
20
+ if (activity_ids.has(edge.from_id) && activity_ids.has(edge.to_id)) {
21
+ outgoing.get(edge.from_id).push(edge.to_id);
22
+ reverse.get(edge.to_id).push(edge.from_id);
23
+ }
24
+ }
25
+ const visited = new Set();
26
+ const finished = [];
27
+ for (const { sys_id } of members) {
28
+ if (visited.has(sys_id)) continue;
29
+ visited.add(sys_id);
30
+ const stack = [[sys_id, 0]];
31
+ while (stack.length) {
32
+ const frame = stack[stack.length - 1];
33
+ const neighbors = outgoing.get(frame[0]);
34
+ if (frame[1] === neighbors.length) {
35
+ finished.push(frame[0]);
36
+ stack.pop();
37
+ } else {
38
+ const next = neighbors[frame[1]++];
39
+ if (!visited.has(next)) {
40
+ visited.add(next);
41
+ stack.push([next, 0]);
42
+ }
43
+ }
44
+ }
45
+ }
46
+ const componentOf = new Map();
47
+ const components = [];
48
+ for (const id of finished.reverse()) {
49
+ if (componentOf.has(id)) continue;
50
+ const index = components.length;
51
+ const component = [];
52
+ const stack = [id];
53
+ componentOf.set(id, index);
54
+ while (stack.length) {
55
+ const current = stack.pop();
56
+ component.push(current);
57
+ for (const next of reverse.get(current)) {
58
+ if (!componentOf.has(next)) {
59
+ componentOf.set(next, index);
60
+ stack.push(next);
61
+ }
62
+ }
63
+ }
64
+ components.push({ ids: component, edges: [], entries: new Set() });
65
+ }
66
+ for (const edge of transitions) {
67
+ const target = componentOf.get(edge.to_id);
68
+ if (target === undefined) continue;
69
+ if (componentOf.get(edge.from_id) === target) components[target].edges.push(edge);
70
+ else components[target].entries.add(edge.to_id);
71
+ }
72
+ const memberById = new Map(members.map(member => [member.sys_id, member]));
73
+ const loops = components.filter(component => component.ids.length > 1
74
+ || component.edges.some(edge => edge.from_id === edge.to_id)).map(component => ({
75
+ members: component.ids.map(id => memberById.get(id)).sort(byNameId),
76
+ // Every internal SCC edge participates in a cycle, not just a DFS back-edge.
77
+ edges: component.edges.sort((a, b) => compare(a.from_name, b.from_name)
78
+ || compare(a.from_id, b.from_id) || byEdge(a, b)),
79
+ entry_points: [...component.entries].map(id => memberById.get(id)).sort(byNameId),
80
+ })).sort((a, b) => byNameId(a.members[0], b.members[0]));
81
+ return {
82
+ activity_ids,
83
+ groups: [...groups.values()].sort(byNameId).map(group => ({
84
+ ...group, transitions: group.transitions.sort(byEdge),
85
+ })),
86
+ loops,
87
+ };
88
+ }
@@ -1,3 +1,5 @@
1
+ import { analyzeWorkflowGraph } from './workflow-graph.js';
2
+ import { numberWorkflowSteps } from './workflow-steps.js';
1
3
  import { assertSafeExactMatch } from './helpers.js';
2
4
  import { errAmbiguous, errNotFound, errUsage } from './errors.js';
3
5
 
@@ -438,6 +440,7 @@ export async function inspectWorkflow(sdk, {
438
440
  let activities = [];
439
441
  let conditions = [];
440
442
  let transitions = [];
443
+ let transitionsTruncated = false;
441
444
  let stages = [];
442
445
  let activitySample = { limit, returned: 0, truncated: false };
443
446
  let definitions = new Map();
@@ -506,6 +509,9 @@ export async function inspectWorkflow(sdk, {
506
509
  limit: MAX_LIMIT,
507
510
  }));
508
511
  }
512
+ // Hitting a per-query bound is conservatively incomplete; do not add a
513
+ // count query or fetch more rows just for graph analysis.
514
+ transitionsTruncated = transitionReads.some(read => read.state === 'ok' && read.rows.length >= MAX_LIMIT);
509
515
  const transitionState = worstState(transitionReads);
510
516
  components.transitions = activityIds.length === 0 ? 'not_applicable' : transitionState;
511
517
  if (transitionState !== 'ok' && transitionState !== 'not_applicable') {
@@ -634,6 +640,12 @@ export async function inspectWorkflow(sdk, {
634
640
  integrity = buildIntegrity({ activities, transitions, conditions, inaccessible, activitySample, version: null, definitions });
635
641
  }
636
642
 
643
+ const numbering = numberWorkflowSteps(activities, transitions, version?.start_activity_id, components);
644
+ const graph = analyzeWorkflowGraph(activities, transitions);
645
+ const loopDetectionComplete = Boolean(version) && components.activities === 'ok'
646
+ && ['ok', 'not_applicable'].includes(components.transitions)
647
+ && !activitySample.truncated && !transitionsTruncated
648
+ && transitions.every(edge => graph.activity_ids.has(edge.from_id) && graph.activity_ids.has(edge.to_id));
637
649
  const componentsComplete = Object.entries(components).every(([, state]) => ['ok', 'not_applicable', 'skipped'].includes(state));
638
650
  const data = {
639
651
  engine: 'legacy_workflow_editor',
@@ -648,11 +660,17 @@ export async function inspectWorkflow(sdk, {
648
660
  },
649
661
  version: version ? versionSummary(version) : null,
650
662
  activities,
663
+ ...numbering,
651
664
  transitions,
665
+ transitions_by_activity: graph.groups,
666
+ loops: graph.loops,
652
667
  stages,
653
668
  integrity,
654
669
  coverage: {
655
- complete: componentsComplete && !activitySample.truncated && !versionsTruncated
670
+ loops_found: graph.loops.length,
671
+ loop_detection_complete: loopDetectionComplete,
672
+ transitions_truncated: transitionsTruncated,
673
+ complete: componentsComplete && !activitySample.truncated && !versionsTruncated && !transitionsTruncated
656
674
  && inaccessible.length === 0,
657
675
  components,
658
676
  activity_sample: activitySample,
@@ -733,27 +751,54 @@ function describeSelection(reason) {
733
751
  }
734
752
  }
735
753
 
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)`;
754
+ function describeTransition(transition, stepById) {
755
+ const target = stepById.get(transition.to_id);
756
+ const to = target ? `step ${target.number} ${target.name || '(unnamed activity)'}` : '(activity not in the readable steps)';
757
+ const condition = transition.condition_status === 'missing' ? 'unreadable condition'
758
+ : transition.condition_name || 'unconditional';
759
+ const issue = transition.status === 'dangling' ? ' ⚠ missing activity'
760
+ : transition.status === 'outside_sample' ? ' (outside the activity sample)' : '';
761
+ return `${to} [${condition}]${issue}`;
740
762
  }
741
763
 
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 = '') {
764
+ // Bound previews only; a selected step retains every line and character.
765
+ function formatStepContent(activity, full = false) {
766
+ const lines = [];
767
+ const entries = Object.entries(activity.configuration || {})
768
+ .filter(([, value]) => value != null && String(value).trim())
769
+ .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
770
+ const width = Math.max(0, ...entries.map(([field]) => field.length + 1));
771
+ for (const [field, value] of entries) {
772
+ const valueLines = (full ? String(value) : String(value).trim()).split(/\r?\n/);
773
+ const prefix = ` ${`${field}:`.padEnd(width)} `;
774
+ const continuation = ' '.repeat(prefix.length);
775
+ const visible = full ? valueLines : valueLines.slice(0, 3);
776
+ visible.forEach((line, index) => {
777
+ const preview = !full && line.length > 160
778
+ ? `${line.slice(0, 160)}… (${line.length - 160} more characters, use --json for the full value)`
779
+ : line;
780
+ lines.push(`${index === 0 ? prefix : continuation}${preview}`);
781
+ });
782
+ if (!full && valueLines.length > 3) {
783
+ lines.push(`${continuation}… (${valueLines.length - 3} more lines, use --json for the full value)`);
784
+ }
785
+ }
786
+ for (const omission of [...(activity.configuration_omissions || [])].sort((a, b) => a.field < b.field ? -1 : a.field > b.field ? 1 : 0)) {
787
+ lines.push(` omitted ${omission.field}: comment-only script (no executable code)`);
788
+ }
789
+ if (activity.configuration_status && !['ok', 'skipped'].includes(activity.configuration_status)) {
790
+ lines.push(` configuration: ${activity.configuration_status}`);
791
+ }
792
+ return lines;
793
+ }
794
+
795
+ /** Human-readable outline. Record identifiers and full detail stay in JSON. */
796
+ export function formatWorkflowOutline(data, { includeConfiguration = false, step: selectedStep } = {}) {
748
797
  const lines = [];
749
798
  const workflow = data.workflow;
750
799
  lines.push('');
751
800
  lines.push(`Legacy workflow: ${workflow.name} (table: ${workflow.table || 'unset'})`);
752
801
  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
802
  if (workflow.description) lines.push(` Description: ${workflow.description}`);
758
803
  if (data.coverage.components.versions === 'ok') {
759
804
  lines.push(` Versions: ${data.versions.length}${data.versions_truncated ? '+' : ''} (${describeSelection(data.selection.reason)})`);
@@ -765,7 +810,6 @@ export function formatWorkflowOutline(data, instanceURL = '') {
765
810
  if (version) {
766
811
  const flags = [version.published ? 'published' : 'not published', version.active ? 'active' : 'inactive'];
767
812
  lines.push(` Selected version: ${version.name} — ${flags.join(', ')}`);
768
- lines.push(` Version sys_id: ${version.sys_id}`);
769
813
  if (version.condition) lines.push(` Condition: ${version.condition}`);
770
814
  if (version.checked_out_by_id) {
771
815
  lines.push(` Checked out by: ${version.checked_out_by_name || version.checked_out_by_id} on ${version.checked_out || 'unknown date'}`);
@@ -783,59 +827,58 @@ export function formatWorkflowOutline(data, instanceURL = '') {
783
827
  if (item.checked_out_by_id) flags.push(`checked out by ${item.checked_out_by_name || item.checked_out_by_id}`);
784
828
  const marker = item.sys_id === version?.sys_id ? '*' : ' ';
785
829
  lines.push(` ${marker} ${index + 1}. ${item.name} [${flags.join(', ')}] ${item.created_on}`);
786
- lines.push(` ${item.sys_id}`);
787
830
  });
788
831
  }
789
832
 
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) {
833
+ const stepById = new Map(data.steps.map(step => [step.sys_id, step]));
834
+ const groups = new Map(data.transitions_by_activity.map(group => [group.sys_id, group.transitions]));
835
+ const loopEdges = new Set(data.loops.flatMap(loop => loop.edges.map(edge => edge.sys_id)));
836
+ const closesLoop = edge => loopEdges.has(edge.sys_id)
837
+ && stepById.get(edge.to_id)?.number <= stepById.get(edge.from_id)?.number;
838
+ lines.push('', '▶ STEPS', '─'.repeat(50));
839
+ if (data.step_order.fallback_reason) {
840
+ lines.push(` Order fallback: ${data.step_order.fallback_reason}; stable name/sys_id order, not a flow sequence.`);
841
+ } else if (!data.coverage.loop_detection_complete) {
842
+ lines.push(' Order follows observed transitions only; activity/transition coverage is incomplete.');
843
+ }
844
+ if (data.steps.length === 0) {
794
845
  lines.push(` (${data.coverage.components.activities === 'ok' ? 'no activities found' : `activities ${data.coverage.components.activities}`})`);
795
846
  }
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}`);
847
+ const activityById = new Map(data.activities.map(activity => [activity.sys_id, activity]));
848
+ for (const step of data.steps.filter(step => selectedStep === undefined || step.number === selectedStep)) {
849
+ const activity = activityById.get(step.sys_id);
850
+ const showContent = includeConfiguration || selectedStep !== undefined;
851
+ const outgoing = groups.get(step.sys_id) || [];
852
+ const flags = [];
853
+ if (!step.reached_from_start) flags.push(data.step_order.fallback_reason
854
+ ? 'not reached from start; order fallback' : 'not reached from start');
855
+ if (outgoing.length === 0) {
856
+ if (!data.coverage.loop_detection_complete) flags.push('no outgoing transitions observed; detection incomplete');
857
+ else if (!/(end|finish|done|stop)$/i.test(step.name.trim())) flags.push('end');
808
858
  }
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)`);
859
+ lines.push(` ${step.number}. ${step.name || '(unnamed activity)'}${showContent && activity?.definition_name ? ` (${activity.definition_name})` : ''}${flags.length ? ` (${flags.join('; ')})` : ''}`);
860
+ if (showContent && activity) lines.push(...formatStepContent(activity, selectedStep !== undefined));
861
+ if (selectedStep !== undefined) {
862
+ data.loops.forEach((loop, index) => {
863
+ if (!loop.members.some(member => member.sys_id === step.sys_id)) return;
864
+ const backTo = [...new Set(loop.edges.filter(closesLoop).map(edge => stepById.get(edge.to_id).number))].sort((a, b) => a - b);
865
+ const shown = backTo.slice(0, 6);
866
+ const extra = backTo.length - shown.length;
867
+ lines.push(` Loop ${index + 1}: back to step${shown.length === 1 ? '' : 's'} ${shown.join(', ')}${extra > 0 ? ` …and ${extra} more` : ''}${data.coverage.loop_detection_complete ? '' : ' (observed; detection incomplete)'}`);
868
+ });
814
869
  }
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}`);
870
+ for (const edge of outgoing.filter(edge => selectedStep !== undefined || !edge.is_sequential)) {
871
+ lines.push(` ${closesLoop(edge) ? '↺ ' : ''}→ ${describeTransition(edge, stepById)}`);
819
872
  }
820
- });
873
+ }
874
+ // Preserve malformed source links without inventing an activity or a step.
875
+ for (const group of data.transitions_by_activity.filter(group => selectedStep === undefined && !stepById.has(group.sys_id))) {
876
+ lines.push(' (source activity not in the readable steps)');
877
+ for (const edge of group.transitions) lines.push(` → ${describeTransition(edge, stepById)}`);
878
+ }
821
879
 
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}`);
880
+ if (!data.coverage.loop_detection_complete) {
881
+ lines.push('', ' ⚠ Loop detection is incomplete: activities or transitions unreadable, truncated, or endpoints outside the sample.');
839
882
  }
840
883
 
841
884
  if (data.stages.length > 0) {
@@ -853,7 +896,7 @@ export function formatWorkflowOutline(data, instanceURL = '') {
853
896
  warnings.push(`${item.component}: ${item.state}${item.http_status ? ` (HTTP ${item.http_status})` : ''}`);
854
897
  }
855
898
  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})`);
899
+ warnings.push(`activity definition missing for ${item.activity_name || 'unnamed activity'}; see --json for IDs`);
857
900
  }
858
901
  for (const item of data.integrity.dangling_transitions) {
859
902
  warnings.push(`transition ${item.transition_id} references missing activity ${item.missing_endpoints.join(', ')}`);
@@ -877,6 +920,11 @@ export function formatWorkflowOutline(data, instanceURL = '') {
877
920
  lines.push('');
878
921
  lines.push(`Note: ${DESIGN_TIME_SCOPE}`);
879
922
  lines.push('');
923
+ // No blanket id redaction. Scripts, encoded conditions and free text legitimately
924
+ // contain 32-hex record and workflow ids — for a workflow inspector those values
925
+ // ARE the data, and rewriting them inside a script body produces code that looks
926
+ // corrupted. Identifiers printed structurally use step numbers instead of sys_ids,
927
+ // so there is nothing left here that needs hiding.
880
928
  return `${lines.join('\n')}\n`;
881
929
  }
882
930
 
@@ -0,0 +1,67 @@
1
+ // Number only already-loaded rows; this module performs no instance reads.
2
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
3
+ const byNameId = (a, b) => compare(a.name, b.name) || compare(a.sys_id, b.sys_id);
4
+ const unconditional = edge => edge.condition_status === 'none'
5
+ || (edge.condition_status === 'ok' && /^always$/i.test(edge.condition_name.trim()));
6
+ const exception = edge => edge.condition_status === 'ok'
7
+ && /^(rejected|reject|failure|failed|error|skipped|cancelled|canceled|timeout|expired)$/i.test(edge.condition_name.trim());
8
+ const preference = edge => unconditional(edge) ? 0
9
+ : edge.condition_status === 'ok'
10
+ && /^(approved|approve|success|ok|true|yes|completed)$/i.test(edge.condition_name.trim()) ? 1
11
+ : exception(edge) ? 3 : 2;
12
+ const byEdge = (a, b) => preference(a) - preference(b)
13
+ || compare(a.to_name, b.to_name) || compare(a.to_id, b.to_id)
14
+ || compare(a.condition_name, b.condition_name) || compare(a.condition_id, b.condition_id)
15
+ || compare(a.sys_id, b.sys_id);
16
+
17
+ /** Deterministic iterative DFS preorder, starting only at the version's start. */
18
+ export function numberWorkflowSteps(activities, transitions, startId, components) {
19
+ const stable = [...activities].sort(byNameId);
20
+ const activityById = new Map(stable.map(activity => [activity.sys_id, activity]));
21
+ const outgoing = new Map(stable.map(activity => [activity.sys_id, []]));
22
+ for (const edge of transitions) outgoing.get(edge.from_id)?.push(edge);
23
+ for (const edges of outgoing.values()) edges.sort(byEdge);
24
+ let fallback_reason = null;
25
+ if (!startId) fallback_reason = 'no start activity';
26
+ else if (!activityById.has(startId)) fallback_reason = 'start activity not in the readable activities';
27
+ else if (components.activities !== 'ok' || !['ok', 'not_applicable'].includes(components.transitions)) {
28
+ fallback_reason = 'activities or transitions not readable';
29
+ }
30
+ const steps = [];
31
+ const visited = new Set();
32
+ const add = (activity, reached_from_start) => {
33
+ visited.add(activity.sys_id);
34
+ steps.push({ number: steps.length + 1, sys_id: activity.sys_id, name: activity.name, reached_from_start });
35
+ };
36
+ if (!fallback_reason) {
37
+ const stack = [startId];
38
+ while (stack.length) {
39
+ const id = stack.pop();
40
+ if (visited.has(id)) continue;
41
+ add(activityById.get(id), true);
42
+ // Reverse push preserves preferred-edge order without recursive stack limits.
43
+ for (const edge of [...outgoing.get(id)].reverse()) {
44
+ if (activityById.has(edge.to_id) && !visited.has(edge.to_id)) stack.push(edge.to_id);
45
+ }
46
+ }
47
+ }
48
+ for (const activity of stable) if (!visited.has(activity.sys_id)) add(activity, false);
49
+ // Stable partition after traversal; fallback retains its disclosed name/ID order.
50
+ if (!fallback_reason) {
51
+ steps.sort((a, b) => Number(outgoing.get(a.sys_id).length === 0)
52
+ - Number(outgoing.get(b.sys_id).length === 0));
53
+ steps.forEach((step, index) => { step.number = index + 1; });
54
+ }
55
+ const byId = new Map(steps.map(step => [step.sys_id, step]));
56
+ // Exactly one preferred edge may be implicit. Parallel conditions remain visible.
57
+ for (const edge of transitions) edge.is_sequential = false;
58
+ for (const step of steps) {
59
+ if (!step.reached_from_start) continue;
60
+ const edges = outgoing.get(step.sys_id);
61
+ const next = edges[0];
62
+ const target = byId.get(next?.to_id);
63
+ if (next && (!exception(next) || edges.length === 1)
64
+ && target?.reached_from_start && target.number === step.number + 1) next.is_sequential = true;
65
+ }
66
+ return { steps, step_order: { method: fallback_reason ? 'stable_fallback' : 'start_traversal', fallback_reason } };
67
+ }