@jacebenson/jsn 5.4.0 → 5.5.0-dev.155.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.
@@ -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
 
@@ -339,6 +341,117 @@ function newestFirst(a, b) {
339
341
  return b.created_on.localeCompare(a.created_on) || a.sys_id.localeCompare(b.sys_id);
340
342
  }
341
343
 
344
+ // Only dictionary-typed durations are offsets; an epoch-shaped date is still a date.
345
+ function durationDisplay(value) {
346
+ if (!/^1970-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value)) return value;
347
+ const milliseconds = Date.parse(`${value.replace(' ', 'T')}Z`);
348
+ if (!Number.isFinite(milliseconds) || milliseconds < 0
349
+ || new Date(milliseconds).toISOString().slice(0, 19) !== value.replace(' ', 'T')) return value;
350
+ let seconds = milliseconds / 1000;
351
+ const parts = [];
352
+ for (const [unit, size] of [['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]]) {
353
+ const count = Math.floor(seconds / size);
354
+ seconds %= size;
355
+ if (count) parts.push(`${count} ${unit}${count === 1 ? '' : 's'}`);
356
+ }
357
+ return parts.join(' ') || '0 seconds';
358
+ }
359
+
360
+ // Resolve the declared target table's display column, including inherited columns.
361
+ // Cache metadata (and failures) per table for this inspection, never per activity.
362
+ async function configurationValues(sdk, rows) {
363
+ const metadata = new Map();
364
+ const targets = new Map();
365
+ const identifier = value => /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value);
366
+ async function lookup(table, options) {
367
+ // These reads only enrich values. A failed enrichment must not hide the
368
+ // original ID or make an otherwise readable workflow unavailable.
369
+ try {
370
+ return await readComponent(sdk, table, options);
371
+ } catch {
372
+ return { state: 'unavailable', rows: [] };
373
+ }
374
+ }
375
+ async function displayField(table, seen = new Set()) {
376
+ if (!identifier(table) || seen.has(table) || seen.size >= 16) return '';
377
+ if (metadata.has(table)) return metadata.get(table);
378
+ seen.add(table);
379
+ const dictionary = await lookup('sys_dictionary', {
380
+ query: `name=${table}^display=true`, fields: 'element', limit: 2,
381
+ });
382
+ let field = dictionary.rows?.length === 1 ? raw(dictionary.rows[0].element) : '';
383
+ if (!field && dictionary.state === 'ok' && !dictionary.rows.length) {
384
+ const parent = await lookup('sys_db_object', {
385
+ query: `name=${table}`, fields: 'super_class.name', limit: 2,
386
+ });
387
+ if (parent.rows?.length === 1) field = await displayField(raw(parent.rows[0]['super_class.name']), seen);
388
+ }
389
+ if (!field && dictionary.state === 'ok') {
390
+ // ServiceNow can use its conventional name/number column without an
391
+ // explicit display=true dictionary entry (e.g. sys_user_group).
392
+ const defaults = await lookup('sys_dictionary', {
393
+ query: `name=${table}^elementINname,number`, fields: 'element', limit: 2,
394
+ });
395
+ const elements = new Set((defaults.rows || []).map(row => raw(row.element)));
396
+ field = ['name', 'number'].find(element => elements.has(element)) || '';
397
+ }
398
+ field = identifier(field) ? field : '';
399
+ metadata.set(table, field);
400
+ return field;
401
+ }
402
+ const values = rows.map(row => {
403
+ const type = raw(row['variable.internal_type']);
404
+ const value = raw(row.value);
405
+ const table = raw(row['variable.reference']);
406
+ const info = { raw_value: value, display_value: text(row.value), type, reference_table: table };
407
+ if (type === 'glide_duration') info.display_value = durationDisplay(value);
408
+ if (['reference', 'glide_list'].includes(type) && value.trim()) {
409
+ const ids = value.split(',').map(id => id.trim());
410
+ info.resolution = 'unresolved';
411
+ if (info.display_value.trim() && info.display_value !== value
412
+ && !info.display_value.split(',').every(id => isSysId(id.trim()))) {
413
+ info.resolution = 'resolved';
414
+ } else if (identifier(table) && ids.every(isSysId)) {
415
+ if (!targets.has(table)) targets.set(table, new Set());
416
+ for (const id of ids) targets.get(table).add(id);
417
+ }
418
+ }
419
+ return info;
420
+ });
421
+ const names = new Map();
422
+ for (const [table, ids] of targets) {
423
+ const field = await displayField(table);
424
+ if (!field) continue;
425
+ for (const chunk of chunks([...ids])) {
426
+ const records = await lookup(table, {
427
+ query: `sys_idIN${chunk.join(',')}`, fields: `sys_id,${field}`, limit: CHUNK,
428
+ });
429
+ for (const record of records.rows || []) {
430
+ const name = text(record[field]).trim();
431
+ if (name && name !== raw(record.sys_id)) names.set(`${table}:${raw(record.sys_id)}`, name);
432
+ }
433
+ }
434
+ }
435
+ for (const info of values) {
436
+ if (info.resolution !== 'unresolved') continue;
437
+ let resolved = true;
438
+ info.display_value = info.raw_value.split(',').map(value => {
439
+ const id = value.trim();
440
+ // A reference field may legitimately hold a template expression, a script
441
+ // variable or plain text (for example "${opened_by}"). Only a 32-hex sys_id
442
+ // can be a reference, so anything else is passed through untouched and must
443
+ // not be reported as an unresolved reference.
444
+ if (!/^[0-9a-f]{32}$/i.test(id)) return value;
445
+ const name = names.get(`${info.reference_table}:${id}`);
446
+ if (name) return name;
447
+ resolved = false;
448
+ return `${id} (unresolved reference)`;
449
+ }).join(', ');
450
+ info.resolution = resolved ? 'resolved' : 'unresolved';
451
+ }
452
+ return values;
453
+ }
454
+
342
455
  function isScriptField(element) {
343
456
  return element === 'script' || element.startsWith('script_') || element.endsWith('_script');
344
457
  }
@@ -438,6 +551,7 @@ export async function inspectWorkflow(sdk, {
438
551
  let activities = [];
439
552
  let conditions = [];
440
553
  let transitions = [];
554
+ let transitionsTruncated = false;
441
555
  let stages = [];
442
556
  let activitySample = { limit, returned: 0, truncated: false };
443
557
  let definitions = new Map();
@@ -506,6 +620,9 @@ export async function inspectWorkflow(sdk, {
506
620
  limit: MAX_LIMIT,
507
621
  }));
508
622
  }
623
+ // Hitting a per-query bound is conservatively incomplete; do not add a
624
+ // count query or fetch more rows just for graph analysis.
625
+ transitionsTruncated = transitionReads.some(read => read.state === 'ok' && read.rows.length >= MAX_LIMIT);
509
626
  const transitionState = worstState(transitionReads);
510
627
  components.transitions = activityIds.length === 0 ? 'not_applicable' : transitionState;
511
628
  if (transitionState !== 'ok' && transitionState !== 'not_applicable') {
@@ -535,7 +652,7 @@ export async function inspectWorkflow(sdk, {
535
652
  for (const chunk of chunks(activityIds)) {
536
653
  configurationReads.push(await readComponent(sdk, VARIABLE_VALUE, {
537
654
  query: `document=wf_activity^document_keyIN${chunk.join(',')}^ORDERBYorder`,
538
- fields: 'document_key,variable.element,value',
655
+ fields: 'document_key,variable.element,variable.internal_type,variable.reference,value',
539
656
  limit: MAX_LIMIT,
540
657
  }));
541
658
  }
@@ -546,15 +663,23 @@ export async function inspectWorkflow(sdk, {
546
663
  inaccessible.push({ component: 'configuration', state: failed.state, http_status: failed.http_status ?? null, code: failed.code ?? null });
547
664
  }
548
665
  const byActivity = new Map();
549
- for (const row of configurationReads.flatMap(read => read.rows || [])) {
666
+ const detailsByActivity = new Map();
667
+ const configurationRows = configurationReads.flatMap(read => read.rows || []);
668
+ const values = await configurationValues(sdk, configurationRows);
669
+ for (const [index, row] of configurationRows.entries()) {
550
670
  const activityId = raw(row.document_key);
551
671
  const element = raw(row['variable.element']);
552
672
  if (!activityId || !element) continue;
553
673
  if (!byActivity.has(activityId)) byActivity.set(activityId, {});
554
- byActivity.get(activityId)[element] = text(row.value);
674
+ byActivity.get(activityId)[element] = values[index].type ? raw(row.value) : text(row.value);
675
+ if (values[index].type) {
676
+ if (!detailsByActivity.has(activityId)) detailsByActivity.set(activityId, {});
677
+ detailsByActivity.get(activityId)[element] = values[index];
678
+ }
555
679
  }
556
680
  for (const activity of activities) {
557
681
  activity.configuration = byActivity.get(activity.sys_id) || {};
682
+ if (detailsByActivity.has(activity.sys_id)) activity.configuration_values = detailsByActivity.get(activity.sys_id);
558
683
  activity.configuration_omissions = [];
559
684
  for (const [element, value] of Object.entries(activity.configuration)) {
560
685
  if (isScriptField(element) && isCommentOnlyScript(value)) {
@@ -634,6 +759,12 @@ export async function inspectWorkflow(sdk, {
634
759
  integrity = buildIntegrity({ activities, transitions, conditions, inaccessible, activitySample, version: null, definitions });
635
760
  }
636
761
 
762
+ const numbering = numberWorkflowSteps(activities, transitions, version?.start_activity_id, components);
763
+ const graph = analyzeWorkflowGraph(activities, transitions);
764
+ const loopDetectionComplete = Boolean(version) && components.activities === 'ok'
765
+ && ['ok', 'not_applicable'].includes(components.transitions)
766
+ && !activitySample.truncated && !transitionsTruncated
767
+ && transitions.every(edge => graph.activity_ids.has(edge.from_id) && graph.activity_ids.has(edge.to_id));
637
768
  const componentsComplete = Object.entries(components).every(([, state]) => ['ok', 'not_applicable', 'skipped'].includes(state));
638
769
  const data = {
639
770
  engine: 'legacy_workflow_editor',
@@ -648,11 +779,17 @@ export async function inspectWorkflow(sdk, {
648
779
  },
649
780
  version: version ? versionSummary(version) : null,
650
781
  activities,
782
+ ...numbering,
651
783
  transitions,
784
+ transitions_by_activity: graph.groups,
785
+ loops: graph.loops,
652
786
  stages,
653
787
  integrity,
654
788
  coverage: {
655
- complete: componentsComplete && !activitySample.truncated && !versionsTruncated
789
+ loops_found: graph.loops.length,
790
+ loop_detection_complete: loopDetectionComplete,
791
+ transitions_truncated: transitionsTruncated,
792
+ complete: componentsComplete && !activitySample.truncated && !versionsTruncated && !transitionsTruncated
656
793
  && inaccessible.length === 0,
657
794
  components,
658
795
  activity_sample: activitySample,
@@ -733,27 +870,55 @@ function describeSelection(reason) {
733
870
  }
734
871
  }
735
872
 
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)`;
873
+ function describeTransition(transition, stepById) {
874
+ const target = stepById.get(transition.to_id);
875
+ const to = target ? `step ${target.number} ${target.name || '(unnamed activity)'}` : '(activity not in the readable steps)';
876
+ const condition = transition.condition_status === 'missing' ? 'unreadable condition'
877
+ : transition.condition_name || 'unconditional';
878
+ const issue = transition.status === 'dangling' ? ' ⚠ missing activity'
879
+ : transition.status === 'outside_sample' ? ' (outside the activity sample)' : '';
880
+ return `${to} [${condition}]${issue}`;
740
881
  }
741
882
 
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 = '') {
883
+ // Bound previews only; a selected step retains every line and character.
884
+ function formatStepContent(activity, full = false) {
885
+ const lines = [];
886
+ const entries = Object.entries(activity.configuration || {})
887
+ .filter(([, value]) => value != null && String(value).trim())
888
+ .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
889
+ const width = Math.max(0, ...entries.map(([field]) => field.length + 1));
890
+ for (const [field, value] of entries) {
891
+ const display = activity.configuration_values?.[field]?.display_value ?? value;
892
+ const valueLines = (full ? String(display) : String(display).trim()).split(/\r?\n/);
893
+ const prefix = ` ${`${field}:`.padEnd(width)} `;
894
+ const continuation = ' '.repeat(prefix.length);
895
+ const visible = full ? valueLines : valueLines.slice(0, 3);
896
+ visible.forEach((line, index) => {
897
+ const preview = !full && line.length > 160
898
+ ? `${line.slice(0, 160)}… (${line.length - 160} more characters, use --json for the full value)`
899
+ : line;
900
+ lines.push(`${index === 0 ? prefix : continuation}${preview}`);
901
+ });
902
+ if (!full && valueLines.length > 3) {
903
+ lines.push(`${continuation}… (${valueLines.length - 3} more lines, use --json for the full value)`);
904
+ }
905
+ }
906
+ for (const omission of [...(activity.configuration_omissions || [])].sort((a, b) => a.field < b.field ? -1 : a.field > b.field ? 1 : 0)) {
907
+ lines.push(` omitted ${omission.field}: comment-only script (no executable code)`);
908
+ }
909
+ if (activity.configuration_status && !['ok', 'skipped'].includes(activity.configuration_status)) {
910
+ lines.push(` configuration: ${activity.configuration_status}`);
911
+ }
912
+ return lines;
913
+ }
914
+
915
+ /** Human-readable outline. Record identifiers and full detail stay in JSON. */
916
+ export function formatWorkflowOutline(data, { includeConfiguration = false, step: selectedStep } = {}) {
748
917
  const lines = [];
749
918
  const workflow = data.workflow;
750
919
  lines.push('');
751
920
  lines.push(`Legacy workflow: ${workflow.name} (table: ${workflow.table || 'unset'})`);
752
921
  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
922
  if (workflow.description) lines.push(` Description: ${workflow.description}`);
758
923
  if (data.coverage.components.versions === 'ok') {
759
924
  lines.push(` Versions: ${data.versions.length}${data.versions_truncated ? '+' : ''} (${describeSelection(data.selection.reason)})`);
@@ -765,7 +930,6 @@ export function formatWorkflowOutline(data, instanceURL = '') {
765
930
  if (version) {
766
931
  const flags = [version.published ? 'published' : 'not published', version.active ? 'active' : 'inactive'];
767
932
  lines.push(` Selected version: ${version.name} — ${flags.join(', ')}`);
768
- lines.push(` Version sys_id: ${version.sys_id}`);
769
933
  if (version.condition) lines.push(` Condition: ${version.condition}`);
770
934
  if (version.checked_out_by_id) {
771
935
  lines.push(` Checked out by: ${version.checked_out_by_name || version.checked_out_by_id} on ${version.checked_out || 'unknown date'}`);
@@ -783,59 +947,58 @@ export function formatWorkflowOutline(data, instanceURL = '') {
783
947
  if (item.checked_out_by_id) flags.push(`checked out by ${item.checked_out_by_name || item.checked_out_by_id}`);
784
948
  const marker = item.sys_id === version?.sys_id ? '*' : ' ';
785
949
  lines.push(` ${marker} ${index + 1}. ${item.name} [${flags.join(', ')}] ${item.created_on}`);
786
- lines.push(` ${item.sys_id}`);
787
950
  });
788
951
  }
789
952
 
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) {
953
+ const stepById = new Map(data.steps.map(step => [step.sys_id, step]));
954
+ const groups = new Map(data.transitions_by_activity.map(group => [group.sys_id, group.transitions]));
955
+ const loopEdges = new Set(data.loops.flatMap(loop => loop.edges.map(edge => edge.sys_id)));
956
+ const closesLoop = edge => loopEdges.has(edge.sys_id)
957
+ && stepById.get(edge.to_id)?.number <= stepById.get(edge.from_id)?.number;
958
+ lines.push('', '▶ STEPS', '─'.repeat(50));
959
+ if (data.step_order.fallback_reason) {
960
+ lines.push(` Order fallback: ${data.step_order.fallback_reason}; stable name/sys_id order, not a flow sequence.`);
961
+ } else if (!data.coverage.loop_detection_complete) {
962
+ lines.push(' Order follows observed transitions only; activity/transition coverage is incomplete.');
963
+ }
964
+ if (data.steps.length === 0) {
794
965
  lines.push(` (${data.coverage.components.activities === 'ok' ? 'no activities found' : `activities ${data.coverage.components.activities}`})`);
795
966
  }
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}`);
967
+ const activityById = new Map(data.activities.map(activity => [activity.sys_id, activity]));
968
+ for (const step of data.steps.filter(step => selectedStep === undefined || step.number === selectedStep)) {
969
+ const activity = activityById.get(step.sys_id);
970
+ const showContent = includeConfiguration || selectedStep !== undefined;
971
+ const outgoing = groups.get(step.sys_id) || [];
972
+ const flags = [];
973
+ if (!step.reached_from_start) flags.push(data.step_order.fallback_reason
974
+ ? 'not reached from start; order fallback' : 'not reached from start');
975
+ if (outgoing.length === 0) {
976
+ if (!data.coverage.loop_detection_complete) flags.push('no outgoing transitions observed; detection incomplete');
977
+ else if (!/(end|finish|done|stop)$/i.test(step.name.trim())) flags.push('end');
811
978
  }
812
- for (const omission of activity.configuration_omissions || []) {
813
- lines.push(` omitted ${omission.field}: comment-only script (no executable code)`);
979
+ lines.push(` ${step.number}. ${step.name || '(unnamed activity)'}${showContent && activity?.definition_name ? ` (${activity.definition_name})` : ''}${flags.length ? ` (${flags.join('; ')})` : ''}`);
980
+ if (showContent && activity) lines.push(...formatStepContent(activity, selectedStep !== undefined));
981
+ if (selectedStep !== undefined) {
982
+ data.loops.forEach((loop, index) => {
983
+ if (!loop.members.some(member => member.sys_id === step.sys_id)) return;
984
+ const backTo = [...new Set(loop.edges.filter(closesLoop).map(edge => stepById.get(edge.to_id).number))].sort((a, b) => a - b);
985
+ const shown = backTo.slice(0, 6);
986
+ const extra = backTo.length - shown.length;
987
+ 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)'}`);
988
+ });
814
989
  }
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}`);
990
+ for (const edge of outgoing.filter(edge => selectedStep !== undefined || !edge.is_sequential)) {
991
+ lines.push(` ${closesLoop(edge) ? '↺ ' : ''}→ ${describeTransition(edge, stepById)}`);
819
992
  }
820
- });
993
+ }
994
+ // Preserve malformed source links without inventing an activity or a step.
995
+ for (const group of data.transitions_by_activity.filter(group => selectedStep === undefined && !stepById.has(group.sys_id))) {
996
+ lines.push(' (source activity not in the readable steps)');
997
+ for (const edge of group.transitions) lines.push(` → ${describeTransition(edge, stepById)}`);
998
+ }
821
999
 
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}`);
1000
+ if (!data.coverage.loop_detection_complete) {
1001
+ lines.push('', ' ⚠ Loop detection is incomplete: activities or transitions unreadable, truncated, or endpoints outside the sample.');
839
1002
  }
840
1003
 
841
1004
  if (data.stages.length > 0) {
@@ -853,7 +1016,7 @@ export function formatWorkflowOutline(data, instanceURL = '') {
853
1016
  warnings.push(`${item.component}: ${item.state}${item.http_status ? ` (HTTP ${item.http_status})` : ''}`);
854
1017
  }
855
1018
  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})`);
1019
+ warnings.push(`activity definition missing for ${item.activity_name || 'unnamed activity'}; see --json for IDs`);
857
1020
  }
858
1021
  for (const item of data.integrity.dangling_transitions) {
859
1022
  warnings.push(`transition ${item.transition_id} references missing activity ${item.missing_endpoints.join(', ')}`);
@@ -877,6 +1040,11 @@ export function formatWorkflowOutline(data, instanceURL = '') {
877
1040
  lines.push('');
878
1041
  lines.push(`Note: ${DESIGN_TIME_SCOPE}`);
879
1042
  lines.push('');
1043
+ // No blanket id redaction. Scripts, encoded conditions and free text legitimately
1044
+ // contain 32-hex record and workflow ids — for a workflow inspector those values
1045
+ // ARE the data, and rewriting them inside a script body produces code that looks
1046
+ // corrupted. Identifiers printed structurally use step numbers instead of sys_ids,
1047
+ // so there is nothing left here that needs hiding.
880
1048
  return `${lines.join('\n')}\n`;
881
1049
  }
882
1050
 
@@ -0,0 +1,69 @@
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
+ // Keep the observed traversal ahead of the stable detached appendix.
50
+ // Only reached terminal activities move behind other reached activities.
51
+ if (!fallback_reason) {
52
+ steps.sort((a, b) => Number(b.reached_from_start) - Number(a.reached_from_start)
53
+ || (a.reached_from_start ? Number(outgoing.get(a.sys_id).length === 0)
54
+ - Number(outgoing.get(b.sys_id).length === 0) : 0));
55
+ steps.forEach((step, index) => { step.number = index + 1; });
56
+ }
57
+ const byId = new Map(steps.map(step => [step.sys_id, step]));
58
+ // Exactly one preferred edge may be implicit. Parallel conditions remain visible.
59
+ for (const edge of transitions) edge.is_sequential = false;
60
+ for (const step of steps) {
61
+ if (!step.reached_from_start) continue;
62
+ const edges = outgoing.get(step.sys_id);
63
+ const next = edges[0];
64
+ const target = byId.get(next?.to_id);
65
+ if (next && (!exception(next) || edges.length === 1)
66
+ && target?.reached_from_start && target.number === step.number + 1) next.is_sequential = true;
67
+ }
68
+ return { steps, step_order: { method: fallback_reason ? 'stable_fallback' : 'start_traversal', fallback_reason } };
69
+ }