@jacebenson/jsn 5.1.1-dev.127.1 → 5.1.1-dev.128.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.1.1-dev.127.1",
3
+ "version": "5.1.1-dev.128.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": {
@@ -311,6 +311,9 @@ export function buildDevCmd(name, table, aliases, defaultColumns, wrap, opts = {
311
311
  console.log(' update Update a record');
312
312
  console.log(' delete Delete a record');
313
313
  }
314
+ for (const sub of opts.extraSubcommands || []) {
315
+ console.log(` ${sub.name.padEnd(12)}${sub.description}`);
316
+ }
314
317
  console.log(`\nRun "jsn ${name} <command> --help" for details.`);
315
318
  },
316
319
  };
@@ -1,5 +1,6 @@
1
1
  import { buildProfileCommand } from '../record-profiles.js';
2
2
  import { getStringField } from '../helpers.js';
3
+ import { withTableBehavior } from './table-behavior.js';
3
4
  // Simple table-based commands — singular names passed for grammar
4
5
  // Default columns and aliases match the Go version exactly
5
6
 
@@ -62,7 +63,7 @@ export const uiActionsCmd = (wrap) => buildProfileCommand('uiactions', wrap);
62
63
  // this module's uiPoliciesCmd before uipoliciesCmd — so the factory version
63
64
  // was dead code shadowing nothing. Deleted; the re-export is the behavior.
64
65
 
65
- export const tablesCmd = (wrap) => buildProfileCommand('tables', wrap, {
66
+ export const tablesCmd = (wrap) => withTableBehavior(buildProfileCommand('tables', wrap, {
66
67
  async onShow(record, app) {
67
68
  const tableName = getStringField(record, 'name');
68
69
  const [count, extChain] = await Promise.all([
@@ -72,7 +73,8 @@ export const tablesCmd = (wrap) => buildProfileCommand('tables', wrap, {
72
73
  record._column_count = count;
73
74
  record._extension_info = { chain: extChain };
74
75
  },
75
- });
76
+ extraSubcommands: [{ name: 'behavior', description: 'Read-only behavior inventory (dictionary, ACLs, rules, scripts, actions, policies, notifications, styles, views, flow triggers)' }],
77
+ }), wrap);
76
78
 
77
79
  export { columnsCmd } from './columns.js';
78
80
 
@@ -0,0 +1,79 @@
1
+ // `tables behavior` — extends the existing tables command surface with a
2
+ // read-only configuration inventory. See docs/DECISIONS.md.
3
+
4
+ import { discoverTableBehavior, formatTableBehavior } from '../table-behavior.js';
5
+ import { errUsage } from '../errors.js';
6
+ import { FormatAuto, FormatStyled } from '../output.js';
7
+
8
+ function decodeCursorTokens(tokens = []) {
9
+ const cursors = {};
10
+ for (const token of tokens) {
11
+ let parsed;
12
+ try {
13
+ parsed = JSON.parse(Buffer.from(String(token), 'base64url').toString('utf8'));
14
+ } catch {
15
+ throw errUsage('Invalid cursor token.');
16
+ }
17
+ if (!parsed || typeof parsed.c !== 'string') throw errUsage('Invalid cursor token.');
18
+ cursors[parsed.c] = token;
19
+ }
20
+ return cursors;
21
+ }
22
+
23
+ export function withTableBehavior(command, wrap) {
24
+ const originalBuilder = command.builder;
25
+ command.builder = (yargs) => originalBuilder(yargs).command({
26
+ command: 'behavior <table>',
27
+ aliases: ['behaviour'],
28
+ describe: 'Read-only inventory of tables behavior: rules, scripts, actions, policies, dictionary, notifications, ACLs, styles, views and flow triggers (inherited included)',
29
+ builder: (y) => y
30
+ .positional('table', { type: 'string', describe: 'Table name (e.g. incident)' })
31
+ .option('category', {
32
+ alias: ['categories'], type: 'string', array: true,
33
+ describe: 'Limit categories (comma-separated or repeatable): business_rules, client_scripts, ui_actions, ui_policies, data_policies, dictionary_entries (dictionary), dictionary_overrides, notifications, access_controls (acls), styles, view_rules, flows',
34
+ })
35
+ .option('direct-only', { type: 'boolean', default: false, describe: 'Only configuration associated with this exact table; no ancestors or global actions' })
36
+ .option('include-inactive', { type: 'boolean', default: false, describe: 'Include inactive configuration (active-only by default)' })
37
+ .option('name', { type: 'string', describe: 'Filter artifact names with a LIKE match (no encoded-query characters)' })
38
+ .option('limit', { alias: 'l', type: 'number', default: 200, describe: 'Maximum items per category (1-500)' })
39
+ .option('max-bytes', { type: 'number', default: 524288, describe: 'Response size budget in bytes (4096-1048576); oversized pages are omitted whole' })
40
+ .option('cursor', { type: 'string', array: true, describe: 'Continuation token from a category next_cursor; repeatable' })
41
+ .epilogue([
42
+ 'Read-only: this inventories configuration with GET requests and never executes scripts, flows, notifications or evaluates conditions.',
43
+ 'Client requirements (client scripts, UI actions, UI policies, styles) are reported separately from server enforcement (business rules, data policies, ACLs, notifications, flow record triggers).',
44
+ 'Empty categories describe accessible configuration only; unavailable/unsupported categories are reported separately.',
45
+ 'Flow template and other non-record trigger types are explicitly unsupported; no text joins are guessed.',
46
+ 'Known artifacts stay directly retrievable: jsn records get --table <source_table> --sys-id <reference.sys_id> --json',
47
+ ].join('\n')),
48
+ handler: wrap(async (argv, app) => {
49
+ app.requireInstance();
50
+ const data = await discoverTableBehavior(app.sdk, argv.table, {
51
+ categories: argv.category,
52
+ directOnly: argv.directOnly === true,
53
+ includeInactive: argv.includeInactive === true,
54
+ name: argv.name,
55
+ limit: argv.limit,
56
+ maxBytes: argv.maxBytes,
57
+ cursors: decodeCursorTokens(argv.cursor),
58
+ });
59
+ const breadcrumbs = [
60
+ ...data.categories
61
+ .flatMap(section => section.items.slice(0, 1).map(item => ({
62
+ action: 'show',
63
+ cmd: `jsn records get --table ${item.reference.source_table} --sys-id ${item.reference.sys_id} --json`,
64
+ description: `Retrieve ${item.reference.kind} record for ${item.name}`,
65
+ }))),
66
+ { action: 'list', cmd: `jsn tables show ${data.table}`, description: `Show table ${data.table}` },
67
+ ];
68
+ const human = [FormatAuto, FormatStyled].includes(app.output.getFormat());
69
+ app.ok(human ? { ...data, _formatted: formatTableBehavior(data) } : data, {
70
+ summary: `Table behavior: ${data.table} \u2014 ${data.totals.returned} item(s), ${data.totals.direct} direct, ${data.totals.inherited} inherited`,
71
+ breadcrumbs,
72
+ });
73
+ }),
74
+ });
75
+ if (Array.isArray(command.discovery?.benefits)) {
76
+ command.discovery.benefits.push('Table behavior inventory: jsn tables behavior <table> [--direct-only] [--include-inactive]');
77
+ }
78
+ return command;
79
+ }
@@ -0,0 +1,1053 @@
1
+ // Read-only table behavior discovery.
2
+ //
3
+ // Inventories accessible configuration associated with a table and its
4
+ // ancestors. It does NOT execute scripts, evaluate conditions, or predict
5
+ // which artifact runs for a record. See docs/decisions and GLOSSARY.md.
6
+ //
7
+ // Design informed by now-sdk-ext-core's TableBehaviorDiscovery (MIT,
8
+ // Copyright (c) 2026 SoniSoft Inc). This implementation is written for jsn's
9
+ // authenticated readers and output envelope; no source is copied verbatim.
10
+
11
+ import { createHash } from 'node:crypto';
12
+ import { getStringField } from './helpers.js';
13
+ import { errUsage } from './errors.js';
14
+
15
+ export const BEHAVIOR_CATEGORIES = [
16
+ 'business_rules',
17
+ 'client_scripts',
18
+ 'ui_actions',
19
+ 'ui_policies',
20
+ 'data_policies',
21
+ 'dictionary_entries',
22
+ 'dictionary_overrides',
23
+ 'notifications',
24
+ 'access_controls',
25
+ 'styles',
26
+ 'view_rules',
27
+ 'flows',
28
+ ];
29
+
30
+ const DEFAULT_LIMIT = 200;
31
+ const MAX_LIMIT = 500;
32
+ const DEFAULT_MAX_BYTES = 524288;
33
+ const MIN_MAX_BYTES = 4096;
34
+ const MAX_MAX_BYTES = 1048576;
35
+ const TABLE_NAME = /^[a-zA-Z][a-zA-Z0-9_]*$/;
36
+ // ServiceNow sys_ids are normally 32 hex characters, but some platform records
37
+ // (for example sysverb_query/sysverb_post_update) use bounded word ids. Allow
38
+ // only characters that cannot change encoded-query structure.
39
+ const SAFE_SYS_ID = /^[A-Za-z0-9_]{1,64}$/;
40
+ const CATEGORY_ALIASES = new Map([
41
+ ['business_rules', 'business_rules'], ['business-rules', 'business_rules'], ['businessrules', 'business_rules'], ['rules', 'business_rules'],
42
+ ['client_scripts', 'client_scripts'], ['client-scripts', 'client_scripts'], ['clientscripts', 'client_scripts'],
43
+ ['ui_actions', 'ui_actions'], ['ui-actions', 'ui_actions'], ['uiactions', 'ui_actions'], ['actions', 'ui_actions'],
44
+ ['ui_policies', 'ui_policies'], ['ui-policies', 'ui_policies'], ['uipolicies', 'ui_policies'],
45
+ ['data_policies', 'data_policies'], ['data-policies', 'data_policies'], ['datapolicies', 'data_policies'],
46
+ ['dictionary_entries', 'dictionary_entries'], ['dictionary-entries', 'dictionary_entries'], ['dictionaryentries', 'dictionary_entries'], ['dictionary', 'dictionary_entries'], ['columns', 'dictionary_entries'],
47
+ ['dictionary_overrides', 'dictionary_overrides'], ['dictionary-overrides', 'dictionary_overrides'], ['dictionaryoverrides', 'dictionary_overrides'], ['dictionary_overide', 'dictionary_overrides'], ['overrides', 'dictionary_overrides'],
48
+ ['notifications', 'notifications'], ['notification', 'notifications'], ['email_notifications', 'notifications'], ['email-notifications', 'notifications'],
49
+ ['access_controls', 'access_controls'], ['access-controls', 'access_controls'], ['accesscontrols', 'access_controls'], ['acls', 'access_controls'], ['acl', 'access_controls'],
50
+ ['styles', 'styles'], ['style', 'styles'],
51
+ ['view_rules', 'view_rules'], ['view-rules', 'view_rules'], ['viewrules', 'view_rules'], ['viewrule', 'view_rules'],
52
+ ['flows', 'flows'], ['flow', 'flows'], ['record_triggers', 'flows'], ['record-triggers', 'flows'],
53
+ ]);
54
+
55
+ const COMMON_FIELDS = ['sys_id', 'sys_class_name', 'name', 'short_description', 'description', 'active', 'sys_scope', 'sys_updated_on', 'order', 'sys_overrides'];
56
+
57
+ /**
58
+ * Category sources. `target` is the field holding the associated table.
59
+ * `inherit` is the artifact's opt-in inheritance flag for ancestor records;
60
+ * categories without one inherit to descendants through the platform.
61
+ */
62
+ const SOURCES = {
63
+ business_rules: {
64
+ label: 'Business rules', layer: 'server', enforcement: 'server',
65
+ summary: 'Server-side rules. Client-side requirements are not proof of server enforcement.',
66
+ sources: [{
67
+ table: 'sys_script', target: 'collection', inherit: null, includeGlobal: true,
68
+ sortPhases: [
69
+ { query: 'when=before', order: ['order', 'name'] },
70
+ { query: 'when=after', order: ['order', 'name'] },
71
+ { query: 'when=async', order: ['order', 'name'] },
72
+ { query: 'when=display', order: ['order', 'name'] },
73
+ { query: 'whenNOT INbefore,after,async,display^whenISNOTEMPTY', order: ['when', 'order', 'name'] },
74
+ { query: 'whenISEMPTY', order: ['order', 'name'] },
75
+ ],
76
+ fields: ['when', 'action_insert', 'action_update', 'action_delete', 'action_query', 'filter_condition', 'condition', 'advanced', 'abort_action', 'add_message', 'message', 'change_fields', 'role_conditions'],
77
+ scripts: ['script'],
78
+ }],
79
+ },
80
+ client_scripts: {
81
+ label: 'Client scripts', layer: 'client', enforcement: 'client',
82
+ summary: 'Browser-side scripts. They shape the form but do not enforce server data.',
83
+ sources: [{
84
+ table: 'sys_script_client', target: 'table', inherit: 'applies_extended', sort: ['name', 'order'],
85
+ fields: ['type', 'field', 'ui_type', 'view', 'global', 'applies_extended', 'isolate_script', 'condition'],
86
+ scripts: ['script'],
87
+ }],
88
+ },
89
+ ui_actions: {
90
+ label: 'UI actions', layer: 'client', enforcement: 'client',
91
+ summary: 'Form/list actions. Button visibility and conditions are client-side configuration.',
92
+ sources: [{
93
+ table: 'sys_ui_action', target: 'table', inherit: null, includeGlobal: true, sort: ['order', 'name'],
94
+ fields: ['action_name', 'condition', 'client', 'roles', 'form_button', 'form_link', 'form_context_menu', 'list_button', 'list_link', 'list_context_menu', 'list_banner_button', 'list_choice', 'show_insert', 'show_update', 'sys_overrides', 'ui_type', 'form_button_v2', 'form_menu_button_v2', 'format_for_configurable_workspace'],
95
+ scripts: ['script', 'onclick', 'client_script_v2'],
96
+ }],
97
+ },
98
+ ui_policies: {
99
+ label: 'UI policies', layer: 'client', enforcement: 'client',
100
+ summary: 'Client-side field behavior. Mandatory/read-only actions here are not server enforcement.',
101
+ sources: [{
102
+ table: 'sys_ui_policy', target: 'table', inherit: 'inherit', sort: ['order', 'name'],
103
+ fields: ['conditions', 'on_load', 'reverse_if_false', 'inherit', 'global', 'view', 'run_scripts', 'ui_type'],
104
+ scripts: ['script_true', 'script_false'],
105
+ related: {
106
+ table: 'sys_ui_policy_action', foreignKey: 'ui_policy',
107
+ fields: ['field', 'mandatory', 'disabled', 'visible', 'cleared', 'value_action', 'value', 'field_message_type', 'field_message'],
108
+ },
109
+ }],
110
+ },
111
+ data_policies: {
112
+ label: 'Server data policies', layer: 'server', enforcement: 'server',
113
+ summary: 'Server-side field requirements (mandatory/read-only) from data policies.',
114
+ sources: [{
115
+ table: 'sys_data_policy2', target: 'model_table', inherit: 'inherit', sort: ['order', 'name'],
116
+ fields: ['conditions', 'reverse_if_false', 'inherit', 'apply_import_set', 'apply_soap', 'enforce_ui'],
117
+ related: {
118
+ table: 'sys_data_policy_rule', foreignKey: 'sys_data_policy',
119
+ fields: ['field', 'mandatory', 'disabled'],
120
+ },
121
+ }],
122
+ },
123
+ dictionary_entries: {
124
+ label: 'Dictionary entries', layer: 'schema', enforcement: 'schema',
125
+ summary: 'Column and table dictionary rows. Table-level rows have no element and are labelled explicitly; field labels and types are metadata, not effective UI behavior.',
126
+ sources: [{
127
+ table: 'sys_dictionary', target: 'name', inherit: null, includeGlobal: false, sort: ['element'], filterField: 'element',
128
+ fields: ['element', 'column_label', 'internal_type', 'max_length', 'mandatory', 'reference', 'default_value', 'active', 'sys_scope', 'sys_overrides'],
129
+ }],
130
+ },
131
+ dictionary_overrides: {
132
+ label: 'Dictionary overrides', layer: 'schema', enforcement: 'schema',
133
+ summary: 'Raw sys_dictionary_override rows for this table and its ancestors. Override fields are preserved as stored; effective dictionary resolution is not computed.',
134
+ sources: [{
135
+ table: 'sys_dictionary_override', target: 'name', inherit: null, includeGlobal: false, sort: ['element'], filterField: 'element', activeField: 'active',
136
+ fields: ['element', 'base_table', 'mandatory', 'mandatory_override', 'read_only', 'read_only_override', 'read_only_option', 'default_value', 'default_value_override', 'reference_qual', 'reference_qual_override', 'calculation', 'calculation_override', 'attributes', 'attributes_override', 'dependent', 'display_override'],
137
+ }],
138
+ },
139
+ notifications: {
140
+ label: 'Email notifications', layer: 'server', enforcement: 'server',
141
+ summary: 'Email notification actions. Message bodies are measured only; they are never returned inline.',
142
+ sources: [{
143
+ table: 'sysevent_email_action', target: 'collection', inherit: null, includeGlobal: false, sort: ['name'],
144
+ fields: ['event_name', 'type', 'condition', 'advanced_condition', 'subject', 'weight', 'recipient_fields', 'event_parm_1', 'event_parm_2', 'template', 'item', 'item_table', 'category', 'importance', 'digestable'],
145
+ scripts: ['message', 'message_html', 'message_text'],
146
+ }],
147
+ },
148
+ access_controls: {
149
+ label: 'Access controls', layer: 'server', enforcement: 'server',
150
+ summary: 'ACL rows matching global, table and field clauses. Rows are configuration evidence, not proof of effective access.',
151
+ sources: [{
152
+ table: 'sys_security_acl', target: 'name', inherit: null, includeGlobal: false, sort: ['name', 'operation'],
153
+ associationQuery: ({ table, ancestors, directOnly }) => {
154
+ const clauses = [];
155
+ if (!directOnly) clauses.push('name=*', 'nameSTARTSWITH*.');
156
+ clauses.push(`name=${table}`, `nameSTARTSWITH${table}.`);
157
+ if (!directOnly) {
158
+ for (const ancestor of ancestors) clauses.push(`name=${ancestor}`, `nameSTARTSWITH${ancestor}.`);
159
+ }
160
+ return clauses.join('^OR');
161
+ },
162
+ fields: ['operation', 'type', 'admin_overrides', 'decision_type', 'condition', 'applies_to', 'description'],
163
+ scripts: ['script'],
164
+ }],
165
+ },
166
+ styles: {
167
+ label: 'UI styles', layer: 'client', enforcement: 'client',
168
+ summary: 'Field style definitions for this table and its ancestors. Style values are shipped to the browser, not server enforcement.',
169
+ sources: [{
170
+ table: 'sys_ui_style', target: 'name', inherit: null, includeGlobal: false, sort: ['name', 'element'], activeField: 'active',
171
+ fields: ['element', 'value', 'style', 'alt', 'themed_style'],
172
+ }],
173
+ },
174
+ view_rules: {
175
+ label: 'View rules', layer: 'client', enforcement: 'client',
176
+ summary: 'List view rules. An empty result is a real accessible-empty inventory; inaccessible or malformed reads are reported separately.',
177
+ sources: [{
178
+ table: 'sysrule_view', target: 'table', inherit: null, includeGlobal: false, sort: ['view'], filterField: 'view',
179
+ fields: ['view', 'advanced', 'condition', 'script', 'match_conditions', 'device_type', 'overrides_user_preference'],
180
+ }],
181
+ },
182
+ flows: {
183
+ label: 'Flow record triggers', layer: 'server', enforcement: 'server',
184
+ summary: 'Record-triggered flows. Only sys_flow_record_trigger rows are inventoried; template and other trigger types are unsupported and are never guessed by text joins.',
185
+ triggerSupport: {
186
+ supported: ['record'],
187
+ unsupported: [
188
+ { type: 'template', table: 'sys_hub_trigger_template', reason: 'Template triggers attach to trigger templates, not a table field; no text join is guessed.' },
189
+ { type: 'catalog', table: 'sys_flow_catalog_trigger', reason: 'Catalog triggers are request/catalog scoped, not record triggers.' },
190
+ { type: 'email', table: 'sys_flow_email_trigger', reason: 'Email triggers are inbound-event scoped, not table-field scoped.' },
191
+ { type: 'knowledge', table: 'sys_flow_knowledge_trigger', reason: 'Knowledge triggers are article-event scoped, not table-field scoped.' },
192
+ { type: 'rest', table: 'sys_flow_rest_trigger', reason: 'REST triggers are endpoint scoped, not table-field scoped.' },
193
+ { type: 'timer', table: 'sys_flow_timer_trigger', reason: 'Timer triggers are schedule scoped, not table-field scoped.' },
194
+ { type: 'enhanced_timer', table: 'sys_flow_enhanced_timer_trigger', reason: 'Enhanced timer triggers are schedule scoped, not table-field scoped.' },
195
+ ],
196
+ },
197
+ sources: [{
198
+ table: 'sys_flow_record_trigger', target: 'table', inherit: null, includeGlobal: false, sort: ['name'], activeField: 'active',
199
+ fields: ['on_insert', 'on_update', 'on_delete', 'condition', 'run_flow_in', 'run_on_extended', 'run_when_user_list', 'run_when_setting'],
200
+ }],
201
+ },
202
+ };
203
+
204
+ function rawValue(record, field) {
205
+ if (!record || typeof record !== 'object') return undefined;
206
+ const value = record[field];
207
+ if (value && typeof value === 'object') return value.value ?? value.display_value;
208
+ return value;
209
+ }
210
+
211
+ function text(record, field) {
212
+ return getStringField(record, field);
213
+ }
214
+
215
+ function bool(record, field) {
216
+ const value = rawValue(record, field);
217
+ if (value === undefined || value === null || value === '') return undefined;
218
+ if (typeof value === 'boolean') return value;
219
+ const normalized = String(value).toLowerCase();
220
+ if (['true', '1', 'yes'].includes(normalized)) return true;
221
+ if (['false', '0', 'no'].includes(normalized)) return false;
222
+ return undefined;
223
+ }
224
+
225
+ function integer(record, field) {
226
+ const value = text(record, field);
227
+ if (!value) return undefined;
228
+ const parsed = parseInt(value.replace(/,/g, ''), 10);
229
+ return Number.isFinite(parsed) ? parsed : undefined;
230
+ }
231
+
232
+ function byteLength(value) {
233
+ return Buffer.byteLength(JSON.stringify(value), 'utf8');
234
+ }
235
+
236
+ function tableName(value) {
237
+ const name = String(value || '');
238
+ if (!name) return name;
239
+ if (name.length > 160 || !TABLE_NAME.test(name)) {
240
+ throw errUsage(`Invalid table name: ${name}`, 'Use a table name such as incident or x_custom_table.');
241
+ }
242
+ return name;
243
+ }
244
+
245
+ export function normalizeCategories(input) {
246
+ const requested = input === undefined || input === null || input === ''
247
+ ? [...BEHAVIOR_CATEGORIES]
248
+ : (Array.isArray(input) ? input : [input])
249
+ .flatMap(value => String(value).split(','))
250
+ .map(value => value.trim())
251
+ .filter(Boolean);
252
+ const categories = [];
253
+ for (const value of requested) {
254
+ const category = CATEGORY_ALIASES.get(value.toLowerCase());
255
+ if (!category) {
256
+ throw errUsage(`Unknown behavior category: ${value}`, `Use one of: ${BEHAVIOR_CATEGORIES.join(', ')}`);
257
+ }
258
+ if (!categories.includes(category)) categories.push(category);
259
+ }
260
+ if (!categories.length) throw errUsage('Select at least one behavior category.');
261
+ return categories;
262
+ }
263
+
264
+ async function loadHierarchy(sdk, requested) {
265
+ const nodes = [];
266
+ const seen = new Set();
267
+ let query = `name=${requested}`;
268
+ for (let depth = 0; depth < 32; depth++) {
269
+ const rows = await sdk.listStrict('sys_db_object', new URLSearchParams({
270
+ sysparm_query: query,
271
+ sysparm_limit: '1',
272
+ sysparm_fields: 'sys_id,name,label,super_class,sys_scope',
273
+ sysparm_display_value: 'all',
274
+ }));
275
+ if (!rows.length) {
276
+ throw errUsage(`Table hierarchy not found or not accessible: ${requested}`,
277
+ 'Check the table name and the account\'s access to sys_db_object.');
278
+ }
279
+ const row = rows[0];
280
+ const name = text(row, 'name');
281
+ if (!TABLE_NAME.test(name) || seen.has(name)) {
282
+ throw new Error(`Invalid or cyclic table hierarchy while resolving ${requested}.`);
283
+ }
284
+ seen.add(name);
285
+ nodes.push({ name, sys_id: text(row, 'sys_id'), label: text(row, 'label') || undefined });
286
+ const parent = rawValue(row, 'super_class');
287
+ if (!parent) return nodes;
288
+ if (!SAFE_SYS_ID.test(String(parent))) throw new Error(`Invalid parent table reference while resolving ${requested}.`);
289
+ query = `sys_id=${parent}`;
290
+ }
291
+ throw new Error(`Table hierarchy exceeds 32 levels: ${requested}`);
292
+ }
293
+
294
+ function categorySignature(table, category, options, ancestors) {
295
+ return createHash('sha256').update(JSON.stringify({
296
+ table, category, directOnly: options.directOnly, includeInactive: options.includeInactive,
297
+ name: options.name || null, limit: options.limit, ancestors,
298
+ })).digest('hex').slice(0, 16);
299
+ }
300
+
301
+ function decodeCursor(token, category, signature) {
302
+ if (!token) return { phase: 0, offset: 0 };
303
+ if (typeof token !== 'string' || token.length > 512) throw errUsage('Invalid cursor token.');
304
+ let parsed;
305
+ try {
306
+ parsed = JSON.parse(Buffer.from(token, 'base64url').toString('utf8'));
307
+ } catch {
308
+ throw errUsage('Invalid cursor token.');
309
+ }
310
+ const version = parsed?.v;
311
+ const phase = version === 1 ? 0 : parsed?.p;
312
+ if (!parsed || ![1, 2].includes(version) || parsed.c !== category || parsed.s !== signature
313
+ || !Number.isInteger(parsed.o) || parsed.o < 0 || parsed.o > 1000000
314
+ || !Number.isInteger(phase) || phase < 0 || phase > 16) {
315
+ throw errUsage('Cursor does not match this table, category, or filter set.',
316
+ 'Restart discovery without a cursor or keep the original filters.');
317
+ }
318
+ return { phase, offset: parsed.o };
319
+ }
320
+
321
+ function encodeCursor(category, phase, offset, signature) {
322
+ return Buffer.from(JSON.stringify({ v: 2, c: category, p: phase, o: offset, s: signature }), 'utf8').toString('base64url');
323
+ }
324
+
325
+ function sourceError(error, sourceTable) {
326
+ const status = error?.status;
327
+ if (status === 403 || status === 401) {
328
+ return { code: 'permission_denied', message: `Read access denied while reading ${sourceTable}; results are not evidence of absence.`, source_table: sourceTable };
329
+ }
330
+ if (status === 404) {
331
+ return { code: 'not_found', message: `${sourceTable} is not installed or not visible to this account.`, source_table: sourceTable };
332
+ }
333
+ if (error?.code === 'malformed_response') {
334
+ return { code: 'malformed_response', message: `Malformed response while reading ${sourceTable}.`, source_table: sourceTable };
335
+ }
336
+ return { code: 'request_failed', message: `Read failed for ${sourceTable}. Check connection and metadata access.`, source_table: sourceTable };
337
+ }
338
+
339
+ async function dictionaryFields(sdk, table) {
340
+ const params = new URLSearchParams({
341
+ sysparm_query: `nameIN${table}^elementISNOTEMPTY`,
342
+ sysparm_limit: '2001',
343
+ sysparm_fields: 'element',
344
+ });
345
+ const rows = await sdk.listStrict('sys_dictionary', params);
346
+ if (rows.length > 2000) throw errUsage(`Field inventory for ${table} exceeds the supported bound.`);
347
+ const fields = new Set(rows.map(row => text(row, 'element')).filter(Boolean));
348
+ fields.add('sys_id');
349
+ return fields;
350
+ }
351
+
352
+ function quoteList(values) {
353
+ return values.join(',');
354
+ }
355
+
356
+ function associationFor(source, rowTable, requested, ancestors) {
357
+ if (rowTable === requested) return { association: 'direct', detail: 'exact_table', inherited: false };
358
+ if (source.includeGlobal && rowTable === 'global') {
359
+ return { association: 'inherited', detail: 'global_actions', inherited: true };
360
+ }
361
+ if (ancestors.includes(rowTable)) {
362
+ if (source.inherit === 'applies_extended') return { association: 'inherited', detail: 'ancestor_applies_extended', inherited: true };
363
+ if (source.inherit === 'inherit') return { association: 'inherited', detail: 'ancestor_inherit_flag', inherited: true };
364
+ return { association: 'inherited', detail: 'ancestor_table', inherited: true };
365
+ }
366
+ return { association: 'inherited', detail: 'unrecognized_association', inherited: true };
367
+ }
368
+
369
+ /**
370
+ * ACL clauses are names such as `incident`, `incident.*`, `incident.field`,
371
+ * `*.field` or `*`. Keep the global/table/field distinction explicit instead
372
+ * of reducing every row to a generic inherited association.
373
+ */
374
+ function aclAssociation(name, requested, ancestors) {
375
+ if (!name) return { association: 'inherited', detail: 'unrecognized_association', inherited: true };
376
+ if (name === '*') return { association: 'global', detail: 'global_all', inherited: true };
377
+ if (name.startsWith('*.')) return { association: 'global', detail: 'global_field', inherited: true };
378
+ for (const [index, table] of [requested, ...ancestors].entries()) {
379
+ const prefix = index === 0 ? 'direct' : 'ancestor';
380
+ const association = index === 0 ? 'direct' : 'inherited';
381
+ if (name === table) return { association, detail: `${prefix}_table`, inherited: index !== 0 };
382
+ if (name === `${table}.*`) return { association, detail: `${prefix}_table_wildcard`, inherited: index !== 0 };
383
+ if (name.startsWith(`${table}.`)) return { association, detail: `${prefix}_field`, inherited: index !== 0 };
384
+ }
385
+ return { association: 'inherited', detail: 'unrecognized_association', inherited: true };
386
+ }
387
+
388
+ function overrideEvidence(row, fields) {
389
+ if (!fields.has('sys_overrides')) return undefined;
390
+ const override = text(row, 'sys_overrides');
391
+ if (!override) return undefined;
392
+ return {
393
+ sys_overrides: rawValue(row, 'sys_overrides') || override,
394
+ note: 'Override link preserved as evidence; effective resolution is not simulated.',
395
+ };
396
+ }
397
+
398
+ /**
399
+ * Ordering is expressed in the instance query, not applied to a returned page.
400
+ * ServiceNow sorts empty values first for ORDERBY, so a primary sort key gets
401
+ * an ISEMPTY phase after its ISNOTEMPTY phase to keep missing keys last.
402
+ */
403
+ function sortPhases(source) {
404
+ if (source.sortPhases?.length) return source.sortPhases;
405
+ const sort = source.sort || [];
406
+ if (!sort.length) return [{ query: '', order: [] }];
407
+ const [primary, ...rest] = sort;
408
+ return [
409
+ { query: `${primary}ISNOTEMPTY`, order: sort },
410
+ { query: `${primary}ISEMPTY`, order: rest },
411
+ ];
412
+ }
413
+
414
+ function associationParts(source, requested, ancestors, directOnly) {
415
+ if (source.associationQuery) {
416
+ return [source.associationQuery({ table: requested, ancestors, directOnly })];
417
+ }
418
+ if (directOnly) return [`${source.target}=${requested}`];
419
+ if (source.inherit) {
420
+ const parts = [`${source.target}=${requested}`];
421
+ if (ancestors.length) parts.push(`${source.target}IN${quoteList(ancestors)}^${source.inherit}=true`);
422
+ if (source.includeGlobal) parts.push(`${source.target}=global`);
423
+ return parts;
424
+ }
425
+ const associated = source.includeGlobal ? [...ancestors, 'global'] : ancestors;
426
+ return [`${source.target}IN${quoteList([requested, ...associated])}`];
427
+ }
428
+
429
+ function phaseQuery(parts, filters, phase) {
430
+ const order = [...new Set([...(phase.order || []), 'sys_id'])].map(field => `ORDERBY${field}`);
431
+ return parts
432
+ .map(part => [part, ...filters, phase.query, ...order].filter(Boolean).join('^'))
433
+ .join('^NQ');
434
+ }
435
+
436
+ function requiredField(source, fields, field) {
437
+ return fields.has(field) || field === source.target || field === source.activeField
438
+ || (source.sort || []).includes(field)
439
+ || (source.sortPhases || []).some(phase => (phase.order || []).includes(field))
440
+ || field === 'sys_id';
441
+ }
442
+
443
+ async function readOrderedRows(sdk, source, context) {
444
+ const { requested, ancestors, directOnly, includeInactive, name, fields, limit, cursor } = context;
445
+ const phases = sortPhases(source);
446
+ const parts = associationParts(source, requested, ancestors, directOnly);
447
+ const filters = [];
448
+ const activeField = source.activeField || (fields.has('active') ? 'active' : null);
449
+ if (!includeInactive) {
450
+ if (activeField) filters.push(`${activeField}=true`);
451
+ }
452
+ if (name) {
453
+ const nameField = source.filterField
454
+ || (fields.has('name') ? 'name' : fields.has('short_description') ? 'short_description' : null);
455
+ if (nameField) filters.push(`${nameField}LIKE${name}`);
456
+ }
457
+
458
+ const collected = [];
459
+ // A row can satisfy more than one ordering phase on a live instance (an empty
460
+ // value still matches ISNOTEMPTY for some field types), so keep the first
461
+ // occurrence and drop repeats. Ordering is preserved.
462
+ const seenIds = new Set();
463
+ for (let phaseIndex = cursor.phase; phaseIndex < phases.length && collected.length <= limit; phaseIndex++) {
464
+ const phase = phases[phaseIndex];
465
+ const offset = phaseIndex === cursor.phase ? cursor.offset : 0;
466
+ const remaining = limit + 1 - collected.length;
467
+ if (remaining <= 0) break;
468
+ const query = phaseQuery(parts, filters, phase);
469
+ const rows = await sdk.listStrict(source.table, new URLSearchParams({
470
+ sysparm_query: query,
471
+ sysparm_fields: context.wanted.join(','),
472
+ sysparm_limit: String(remaining),
473
+ sysparm_offset: String(offset),
474
+ sysparm_display_value: 'all',
475
+ sysparm_exclude_reference_link: 'true',
476
+ sysparm_no_count: 'true',
477
+ }));
478
+ for (let index = 0; index < rows.length; index++) {
479
+ const rowId = text(rows[index], 'sys_id');
480
+ if (rowId) {
481
+ if (seenIds.has(rowId)) continue;
482
+ seenIds.add(rowId);
483
+ }
484
+ collected.push({ row: rows[index], phase: phaseIndex, index: offset + index });
485
+ }
486
+ if (rows.length < remaining) continue;
487
+ break;
488
+ }
489
+
490
+ const hasMore = collected.length > limit;
491
+ const extra = hasMore ? collected[limit] : null;
492
+ return {
493
+ page: collected.slice(0, limit),
494
+ hasMore,
495
+ next: extra ? { phase: extra.phase, offset: extra.index } : null,
496
+ };
497
+ }
498
+
499
+ function scriptSummary(row, source, fields) {
500
+ const available = (source.scripts || []).filter(field => fields.has(field));
501
+ let present = false;
502
+ let bytesTotal = 0;
503
+ for (const field of available) {
504
+ const value = text(row, field);
505
+ if (value) present = true;
506
+ bytesTotal += Buffer.byteLength(value || '', 'utf8');
507
+ }
508
+ return { has_script: present, script_bytes: bytesTotal, script_fields: available };
509
+ }
510
+
511
+ function summarize(category, source, row, fields, context) {
512
+ const { requested, ancestors } = context;
513
+ const rowTable = source.target ? text(row, source.target) : '';
514
+ const sysId = text(row, 'sys_id');
515
+ if (!SAFE_SYS_ID.test(sysId)) throw new Error(`Metadata record in ${source.table} lacks a valid sys_id.`);
516
+ const rowName = text(row, 'name');
517
+ const association = category === 'access_controls'
518
+ ? aclAssociation(rowName, requested, ancestors)
519
+ : associationFor(source, rowTable, requested, ancestors);
520
+ const item = {
521
+ reference: { kind: category, source_table: source.table, sys_id: sysId },
522
+ source_table: source.table,
523
+ name: rowName || text(row, 'short_description') || sysId,
524
+ table: rowTable || undefined,
525
+ association: association.association,
526
+ association_detail: association.detail,
527
+ inherited: association.inherited,
528
+ active: bool(row, 'active'),
529
+ scope: text(row, 'sys_scope') || undefined,
530
+ order: integer(row, 'order'),
531
+ updated_on: text(row, 'sys_updated_on') || undefined,
532
+ override_evidence: overrideEvidence(row, fields),
533
+ };
534
+ const has = field => fields.has(field);
535
+
536
+ if (category === 'business_rules') {
537
+ item.when = text(row, 'when') || undefined;
538
+ item.operations = ['action_insert', 'action_update', 'action_delete', 'action_query']
539
+ .filter(field => has(field) && bool(row, field) === true)
540
+ .map(field => field.replace('action_', ''));
541
+ item.condition = text(row, 'filter_condition') || text(row, 'condition') || undefined;
542
+ item.advanced = bool(row, 'advanced');
543
+ item.abort_action = bool(row, 'abort_action');
544
+ item.message = has('add_message') && bool(row, 'add_message') === true ? (text(row, 'message') || undefined) : undefined;
545
+ Object.assign(item, scriptSummary(row, source, fields));
546
+ } else if (category === 'client_scripts') {
547
+ item.type = text(row, 'type') || undefined;
548
+ item.field = text(row, 'field') || undefined;
549
+ item.ui_type = text(row, 'ui_type') || undefined;
550
+ item.view = text(row, 'view') || undefined;
551
+ item.applies_extended = bool(row, 'applies_extended');
552
+ item.isolate_script = bool(row, 'isolate_script');
553
+ item.condition = text(row, 'condition') || undefined;
554
+ Object.assign(item, scriptSummary(row, source, fields));
555
+ } else if (category === 'ui_actions') {
556
+ item.action_name = text(row, 'action_name') || undefined;
557
+ item.client = bool(row, 'client');
558
+ item.ui_type = text(row, 'ui_type') || undefined;
559
+ item.condition = text(row, 'condition') || undefined;
560
+ item.roles = text(row, 'roles') || undefined;
561
+ item.show_insert = bool(row, 'show_insert');
562
+ item.show_update = bool(row, 'show_update');
563
+ item.placements = ['form_button', 'form_link', 'form_context_menu', 'list_button', 'list_link', 'list_context_menu', 'list_banner_button', 'list_choice']
564
+ .filter(field => has(field) && bool(row, field) === true);
565
+ Object.assign(item, scriptSummary(row, source, fields));
566
+ } else if (category === 'ui_policies') {
567
+ item.conditions = text(row, 'conditions') || undefined;
568
+ item.on_load = bool(row, 'on_load');
569
+ item.reverse_if_false = bool(row, 'reverse_if_false');
570
+ item.inherit = bool(row, 'inherit');
571
+ item.global = bool(row, 'global');
572
+ item.view = text(row, 'view') || undefined;
573
+ item.run_scripts = bool(row, 'run_scripts');
574
+ item.ui_type = text(row, 'ui_type') || undefined;
575
+ item.field_actions = (context.related.get(sysId) || []).map(action => ({
576
+ field: text(action, 'field') || undefined,
577
+ mandatory: text(action, 'mandatory') || undefined,
578
+ disabled: text(action, 'disabled') || undefined,
579
+ visible: text(action, 'visible') || undefined,
580
+ cleared: text(action, 'cleared') || undefined,
581
+ value_action: text(action, 'value_action') || undefined,
582
+ value: text(action, 'value') || undefined,
583
+ field_message_type: text(action, 'field_message_type') || undefined,
584
+ field_message: text(action, 'field_message') || undefined,
585
+ reference: SAFE_SYS_ID.test(text(action, 'sys_id')) ? { kind: category, source_table: 'sys_ui_policy_action', sys_id: text(action, 'sys_id') } : undefined,
586
+ }));
587
+ } else if (category === 'data_policies') {
588
+ item.conditions = text(row, 'conditions') || undefined;
589
+ item.reverse_if_false = bool(row, 'reverse_if_false');
590
+ item.inherit = bool(row, 'inherit');
591
+ item.apply_import_set = bool(row, 'apply_import_set');
592
+ item.apply_soap = bool(row, 'apply_soap');
593
+ item.enforce_ui = bool(row, 'enforce_ui');
594
+ item.field_actions = (context.related.get(sysId) || []).map(action => ({
595
+ field: text(action, 'field') || undefined,
596
+ mandatory: text(action, 'mandatory') || undefined,
597
+ disabled: text(action, 'disabled') || undefined,
598
+ reference: SAFE_SYS_ID.test(text(action, 'sys_id')) ? { kind: category, source_table: 'sys_data_policy_rule', sys_id: text(action, 'sys_id') } : undefined,
599
+ }));
600
+ } else if (category === 'dictionary_entries') {
601
+ const element = text(row, 'element');
602
+ item.level = element ? 'column' : 'table';
603
+ item.element = element || undefined;
604
+ item.column_label = text(row, 'column_label') || undefined;
605
+ item.internal_type = text(row, 'internal_type') || undefined;
606
+ item.max_length = integer(row, 'max_length');
607
+ item.mandatory = bool(row, 'mandatory');
608
+ item.reference_table = text(row, 'reference') || undefined;
609
+ item.default_value = text(row, 'default_value') || undefined;
610
+ item.active = bool(row, 'active');
611
+ item.scope = text(row, 'sys_scope') || undefined;
612
+ item.sys_overrides = text(row, 'sys_overrides') || undefined;
613
+ if (!element) {
614
+ item.name = `${rowTable || 'unknown'} (table-level)`;
615
+ item.table_level = true;
616
+ } else {
617
+ item.name = text(row, 'column_label') ? `${element} (${text(row, 'column_label')})` : element;
618
+ }
619
+ } else if (category === 'dictionary_overrides') {
620
+ const element = text(row, 'element');
621
+ item.level = element ? 'column' : 'table';
622
+ for (const field of source.fields) item[field] = rawValue(row, field);
623
+ item.table_level = !element;
624
+ item.name = element || `${rowTable || 'unknown'} (table-level override)`;
625
+ item.interpretation = 'Raw override values; no effective dictionary resolution is computed.';
626
+ } else if (category === 'notifications') {
627
+ item.event_name = text(row, 'event_name') || undefined;
628
+ item.type = text(row, 'type') || undefined;
629
+ item.condition = text(row, 'condition') || undefined;
630
+ item.advanced_condition = text(row, 'advanced_condition') || undefined;
631
+ item.subject = text(row, 'subject') || undefined;
632
+ item.weight = integer(row, 'weight');
633
+ item.recipient_fields = text(row, 'recipient_fields') || undefined;
634
+ item.event_parm_1 = text(row, 'event_parm_1') || undefined;
635
+ item.event_parm_2 = text(row, 'event_parm_2') || undefined;
636
+ item.template = text(row, 'template') || undefined;
637
+ item.item = text(row, 'item') || undefined;
638
+ item.item_table = text(row, 'item_table') || undefined;
639
+ item.category = text(row, 'category') || undefined;
640
+ item.importance = text(row, 'importance') || undefined;
641
+ item.digestable = bool(row, 'digestable');
642
+ Object.assign(item, scriptSummary(row, source, fields));
643
+ } else if (category === 'access_controls') {
644
+ item.name = rowName || sysId;
645
+ item.operation = text(row, 'operation') || undefined;
646
+ item.type = text(row, 'type') || undefined;
647
+ item.active = bool(row, 'active');
648
+ item.admin_overrides = bool(row, 'admin_overrides');
649
+ item.decision_type = text(row, 'decision_type') || undefined;
650
+ item.condition = text(row, 'condition') || undefined;
651
+ item.applies_to = text(row, 'applies_to') || undefined;
652
+ item.description = text(row, 'description') || undefined;
653
+ Object.assign(item, scriptSummary(row, source, fields));
654
+ } else if (category === 'styles') {
655
+ item.element = text(row, 'element') || undefined;
656
+ item.value = text(row, 'value') || undefined;
657
+ item.style = text(row, 'style') || undefined;
658
+ item.alt = text(row, 'alt') || undefined;
659
+ item.themed_style = text(row, 'themed_style') || undefined;
660
+ } else if (category === 'view_rules') {
661
+ const view = text(row, 'view');
662
+ item.view = view || undefined;
663
+ item.view_empty = has('view') && 'view' in row && !view;
664
+ item.advanced = bool(row, 'advanced');
665
+ item.condition = text(row, 'condition') || undefined;
666
+ item.match_conditions = text(row, 'match_conditions') || undefined;
667
+ item.device_type = text(row, 'device_type') || undefined;
668
+ item.overrides_user_preference = bool(row, 'overrides_user_preference');
669
+ item.name = view ? `view: ${view}` : `${rowTable || 'unknown'} (view rule ${sysId})`;
670
+ Object.assign(item, scriptSummary(row, source, fields));
671
+ } else if (category === 'flows') {
672
+ item.trigger_type = 'record';
673
+ item.on_insert = bool(row, 'on_insert');
674
+ item.on_update = bool(row, 'on_update');
675
+ item.on_delete = bool(row, 'on_delete');
676
+ item.condition = text(row, 'condition') || undefined;
677
+ item.run_flow_in = text(row, 'run_flow_in') || undefined;
678
+ item.run_on_extended = bool(row, 'run_on_extended');
679
+ item.run_when_user_list = text(row, 'run_when_user_list') || undefined;
680
+ item.run_when_setting = text(row, 'run_when_setting') || undefined;
681
+ item.name = rowName || `record trigger ${sysId}`;
682
+ }
683
+
684
+ const critical = ['sys_id', 'name', source.target, 'active'].filter(field => field && fields.has(field));
685
+ const missing = critical.filter(field => !(field in row));
686
+ const missingScripts = (source.scripts || []).filter(field => fields.has(field) && !(field in row));
687
+ if (missing.length || missingScripts.length) {
688
+ const names = [...missing, ...missingScripts];
689
+ item.warnings = [{ code: 'missing_fields', message: `Fields not returned (may be ACL-restricted): ${names.join(', ')}.`, source_table: source.table }];
690
+ }
691
+ return item;
692
+ }
693
+
694
+ async function readRelated(sdk, source, items, warnings) {
695
+ const related = new Map();
696
+ if (!source.related || !items.length) return related;
697
+ const { table, foreignKey, fields } = source.related;
698
+ const ids = items.map(item => item.reference.sys_id).filter(id => SAFE_SYS_ID.test(id));
699
+ if (!ids.length) return related;
700
+ try {
701
+ const available = await dictionaryFields(sdk, table);
702
+ if (!available.has(foreignKey)) {
703
+ warnings.push({ code: 'unsupported_layout', message: `${table} lacks the ${foreignKey} field; field actions were not read.`, source_table: table });
704
+ return related;
705
+ }
706
+ const wanted = [...new Set([...COMMON_FIELDS, foreignKey, ...fields])].filter(field => available.has(field));
707
+ const rows = await sdk.listStrict(table, new URLSearchParams({
708
+ sysparm_query: `${foreignKey}IN${quoteList(ids)}`,
709
+ sysparm_limit: '1000',
710
+ sysparm_fields: wanted.join(','),
711
+ sysparm_display_value: 'all',
712
+ }));
713
+ if (rows.length >= 1000) {
714
+ warnings.push({ code: 'truncated', message: `${table} child read reached the 1000-row bound; some field actions are omitted.`, source_table: table });
715
+ }
716
+ for (const row of rows) {
717
+ const key = rawValue(row, foreignKey);
718
+ if (!key) continue;
719
+ const list = related.get(String(key)) || [];
720
+ list.push(row);
721
+ related.set(String(key), list);
722
+ }
723
+ } catch (error) {
724
+ warnings.push({ code: 'related_read_failed', message: `Child field actions in ${table} could not be read; policy rows alone are incomplete.`, source_table: table, detail: sourceError(error, table).code });
725
+ }
726
+ return related;
727
+ }
728
+
729
+ /**
730
+ * Discover behavior configuration for a table.
731
+ *
732
+ * @param {object} sdk — authenticated reader (listStrict)
733
+ * @param {string} requestedTable
734
+ * @param {object} [options]
735
+ * @returns {Promise<object>} bounded inventory envelope data
736
+ */
737
+ export async function discoverTableBehavior(sdk, requestedTable, options = {}) {
738
+ const table = tableName(requestedTable);
739
+ const categories = normalizeCategories(options.categories);
740
+ const limit = options.limit ?? DEFAULT_LIMIT;
741
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
742
+ throw errUsage(`--limit must be an integer from 1 to ${MAX_LIMIT}.`);
743
+ }
744
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
745
+ if (!Number.isInteger(maxBytes) || maxBytes < MIN_MAX_BYTES || maxBytes > MAX_MAX_BYTES) {
746
+ throw errUsage(`--max-bytes must be an integer from ${MIN_MAX_BYTES} to ${MAX_MAX_BYTES}.`);
747
+ }
748
+ const name = options.name ? String(options.name) : '';
749
+ if (name && (name.length > 128 || /[\^\r\n]/.test(name))) {
750
+ throw errUsage('--name must be at most 128 characters and cannot contain encoded-query characters.');
751
+ }
752
+ const includeInactive = options.includeInactive === true;
753
+ const directOnly = options.directOnly === true;
754
+ const cursors = options.cursors || {};
755
+
756
+ const hierarchy = await loadHierarchy(sdk, table);
757
+ const ancestors = hierarchy.slice(1).map(node => node.name);
758
+ const result = {
759
+ table,
760
+ label: hierarchy[0].label,
761
+ table_sys_id: hierarchy[0].sys_id,
762
+ ancestors,
763
+ filters: {
764
+ categories,
765
+ include_inactive: includeInactive,
766
+ direct_only: directOnly,
767
+ name: name || undefined,
768
+ limit,
769
+ max_bytes: maxBytes,
770
+ },
771
+ visibility: 'accessible_configuration',
772
+ interpretation: 'Configuration inventory only. Conditions are not evaluated, scripts and flows are not executed, and absence is not proof that no other behavior exists.',
773
+ categories: [],
774
+ warnings: [],
775
+ next_cursors: {},
776
+ };
777
+
778
+ const fieldsCache = new Map();
779
+ const fieldsFor = async sourceTable => {
780
+ if (!fieldsCache.has(sourceTable)) fieldsCache.set(sourceTable, dictionaryFields(sdk, sourceTable));
781
+ return fieldsCache.get(sourceTable);
782
+ };
783
+
784
+ const itemPositions = new WeakMap();
785
+ for (const category of categories) {
786
+ const definition = SOURCES[category];
787
+ const section = {
788
+ category,
789
+ label: definition.label,
790
+ layer: definition.layer,
791
+ enforcement: definition.enforcement,
792
+ source_tables: definition.sources.map(source => source.table),
793
+ interpretation: definition.summary,
794
+ status: 'complete',
795
+ supplied_sources: definition.sources.map(source => source.table),
796
+ supported_trigger_types: definition.triggerSupport?.supported,
797
+ unsupported_trigger_types: definition.triggerSupport?.unsupported,
798
+ direct_count: 0,
799
+ inherited_count: 0,
800
+ returned: 0,
801
+ omitted: 0,
802
+ truncated: false,
803
+ has_more: false,
804
+ next_cursor: undefined,
805
+ warnings: [],
806
+ items: [],
807
+ };
808
+ if (definition.triggerSupport) {
809
+ section.trigger_support = {
810
+ supported: definition.triggerSupport.supported,
811
+ unsupported: definition.triggerSupport.unsupported,
812
+ note: 'Only record triggers are inventoried; other trigger families are unsupported and are not guessed by text joins.',
813
+ };
814
+ }
815
+ result.categories.push(section);
816
+
817
+ for (const source of definition.sources) {
818
+ const signature = categorySignature(table, category, { limit, directOnly, includeInactive, name }, ancestors);
819
+ let cursor;
820
+ try {
821
+ cursor = decodeCursor(cursors[category], category, signature);
822
+ } catch (error) {
823
+ if (error.code === 'usage_error') throw error;
824
+ section.status = 'unavailable';
825
+ section.warnings.push({ code: 'invalid_cursor', message: error.message, source_table: source.table });
826
+ continue;
827
+ }
828
+
829
+ let fields;
830
+ try {
831
+ fields = await fieldsFor(source.table);
832
+ } catch (error) {
833
+ section.status = 'unavailable';
834
+ section.warnings.push(sourceError(error, source.table));
835
+ continue;
836
+ }
837
+
838
+ const missing = [source.target, ...(source.inherit ? [source.inherit] : [])].filter(field => !fields.has(field));
839
+ if (missing.length) {
840
+ section.status = 'unsupported';
841
+ section.warnings.push({
842
+ code: 'unsupported_layout',
843
+ message: `${source.table} is missing required field(s) ${missing.join(', ')}; no unfiltered query was issued.`,
844
+ source_table: source.table,
845
+ });
846
+ continue;
847
+ }
848
+
849
+ const activeField = source.activeField || (fields.has('active') ? 'active' : null);
850
+ if (!includeInactive && !activeField) {
851
+ section.warnings.push({ code: 'missing_fields', message: `Active status is unavailable on ${source.table}; candidates may be inactive.`, source_table: source.table });
852
+ }
853
+ const filterField = source.filterField
854
+ || (fields.has('name') ? 'name' : fields.has('short_description') ? 'short_description' : null);
855
+ if (name && !filterField) {
856
+ section.status = 'unsupported';
857
+ section.warnings.push({ code: 'unsupported_layout', message: `Name filtering is unavailable for ${source.table}.`, source_table: source.table });
858
+ continue;
859
+ }
860
+
861
+ const wanted = [...new Set([
862
+ ...COMMON_FIELDS,
863
+ source.target,
864
+ ...(source.fields || []),
865
+ ...(source.scripts || []),
866
+ ...(source.sort || []),
867
+ ...(source.sortPhases || []).flatMap(phase => phase.order || []),
868
+ ...(activeField ? [activeField] : []),
869
+ ])].filter(field => requiredField(source, fields, field));
870
+
871
+ let read;
872
+ try {
873
+ read = await readOrderedRows(sdk, source, {
874
+ requested: table, ancestors, directOnly, includeInactive, name,
875
+ fields, wanted, limit, cursor,
876
+ });
877
+ } catch (error) {
878
+ section.status = 'unavailable';
879
+ section.warnings.push(sourceError(error, source.table));
880
+ continue;
881
+ }
882
+
883
+ section.has_more = read.hasMore;
884
+ const page = read.page;
885
+ const related = await readRelated(sdk, source, page.map(entry => ({ reference: { sys_id: text(entry.row, 'sys_id') } })), section.warnings);
886
+ let truncatedAt = null;
887
+ for (let index = 0; index < page.length; index++) {
888
+ const entry = page[index];
889
+ let item;
890
+ try {
891
+ item = summarize(category, source, entry.row, fields, { requested: table, ancestors, related });
892
+ } catch (error) {
893
+ section.warnings.push({ code: 'malformed_response', message: `Record ${text(entry.row, 'sys_id') || '?'} in ${source.table} was skipped: ${error.message}`, source_table: source.table });
894
+ continue;
895
+ }
896
+ section.items.push(item);
897
+ itemPositions.set(item, { phase: entry.phase, index: entry.index, signature, sourceTable: source.table });
898
+ section.returned += 1;
899
+ if (byteLength(result) > maxBytes - 1024) {
900
+ section.items.pop();
901
+ section.returned -= 1;
902
+ truncatedAt = { phase: entry.phase, index: entry.index };
903
+ section.truncated = true;
904
+ break;
905
+ }
906
+ }
907
+ if (truncatedAt !== null) {
908
+ section.has_more = true;
909
+ section.omitted = page.length - section.items.length;
910
+ section.next_cursor = encodeCursor(category, truncatedAt.phase, truncatedAt.index, signature);
911
+ section.warnings.push({
912
+ code: 'truncated',
913
+ message: `Response budget reached at ${section.items.length} item(s) in ${category}. Items are omitted whole; no script or message body is returned. Continue with its cursor, raise --max-bytes, or lower --limit.`,
914
+ source_table: source.table,
915
+ });
916
+ section.status = 'partial';
917
+ continue;
918
+ }
919
+ if (read.hasMore) {
920
+ section.next_cursor = encodeCursor(category, read.next.phase, read.next.offset, signature);
921
+ section.status = 'partial';
922
+ }
923
+ if (section.warnings.length || section.items.some(item => item.warnings?.length)) section.status = 'partial';
924
+ continue;
925
+ }
926
+ section.direct_count = section.items.filter(item => item.association === 'direct').length;
927
+ section.inherited_count = section.items.filter(item => item.inherited).length;
928
+ if (section.next_cursor) result.next_cursors[category] = section.next_cursor;
929
+ }
930
+
931
+ // Last-resort budget pass: remove items from the last categories first and
932
+ // record the exact continuation point for each. Categories are never dropped
933
+ // silently, and a tight budget never turns into a usage error.
934
+ if (byteLength(result) > maxBytes) {
935
+ for (let index = result.categories.length - 1; index >= 0 && byteLength(result) > maxBytes; index--) {
936
+ const section = result.categories[index];
937
+ while (section.items.length && byteLength(result) > maxBytes) {
938
+ const item = section.items.pop();
939
+ const position = itemPositions.get(item);
940
+ section.returned -= 1;
941
+ section.omitted += 1;
942
+ section.truncated = true;
943
+ section.has_more = true;
944
+ section.status = 'partial';
945
+ if (position) {
946
+ section.next_cursor = encodeCursor(section.category, position.phase, position.index, position.signature);
947
+ }
948
+ if (!section.warnings.some(warning => warning.code === 'truncated')) {
949
+ section.warnings.push({
950
+ code: 'truncated',
951
+ message: 'Response budget reached before this category could be returned in full. Items are omitted whole; continue with its cursor or raise --max-bytes.',
952
+ source_table: position?.sourceTable || section.source_tables[0],
953
+ });
954
+ }
955
+ }
956
+ }
957
+ }
958
+ for (const section of result.categories) {
959
+ section.direct_count = section.items.filter(item => item.association === 'direct').length;
960
+ section.inherited_count = section.items.filter(item => item.inherited).length;
961
+ if (section.next_cursor) result.next_cursors[section.category] = section.next_cursor;
962
+ else delete result.next_cursors[section.category];
963
+ }
964
+
965
+ result.totals = {
966
+ returned: result.categories.reduce((sum, section) => sum + section.returned, 0),
967
+ direct: result.categories.reduce((sum, section) => sum + section.direct_count, 0),
968
+ inherited: result.categories.reduce((sum, section) => sum + section.inherited_count, 0),
969
+ unavailable_categories: result.categories.filter(section => section.status === 'unavailable').length,
970
+ unsupported_categories: result.categories.filter(section => section.status === 'unsupported').length,
971
+ partial_categories: result.categories.filter(section => section.status === 'partial').length,
972
+ };
973
+ if (byteLength(result) > maxBytes) {
974
+ result.budget_exceeded = true;
975
+ result.warnings.push({
976
+ code: 'budget_exceeded',
977
+ message: `Category metadata alone exceeds --max-bytes (${maxBytes}); no items remain to omit. Raise --max-bytes or select fewer categories.`,
978
+ });
979
+ }
980
+ return result;
981
+ }
982
+
983
+ export function formatTableBehavior(data) {
984
+ const lines = [];
985
+ lines.push('');
986
+ lines.push(`\u{1F4CB} Table behavior: ${data.table}${data.label ? ` (${data.label})` : ''}`);
987
+ if (data.ancestors.length) lines.push(` Inherited from: ${data.ancestors.join(' \u2192 ')}`);
988
+ lines.push(` Filters: ${data.filters.categories.join(', ')}${data.filters.direct_only ? ' | direct only' : ''}${data.filters.include_inactive ? ' | including inactive' : ' | active only'}${data.filters.name ? ` | name LIKE ${data.filters.name}` : ''}`);
989
+ lines.push(' Accessible configuration only; conditions are not evaluated and scripts are not executed.');
990
+ lines.push('');
991
+ for (const section of data.categories) {
992
+ const breakdown = section.items.reduce((acc, item) => {
993
+ const key = item.association_detail === 'global_actions' ? 'global'
994
+ : item.association === 'direct' ? 'direct' : 'inherited';
995
+ acc[key] = (acc[key] || 0) + 1;
996
+ return acc;
997
+ }, {});
998
+ const parts = [];
999
+ if (breakdown.direct) parts.push(`${breakdown.direct} direct`);
1000
+ if (breakdown.inherited) parts.push(`${breakdown.inherited} inherited`);
1001
+ if (breakdown.global) parts.push(`${breakdown.global} global`);
1002
+ const counts = parts.length ? ` | ${parts.join(', ')}` : '';
1003
+ lines.push(`\u25B6 ${section.label.toUpperCase()} [${section.enforcement}] \u2014 ${section.status}${counts}`);
1004
+ lines.push('\u2500'.repeat(58));
1005
+ if (section.warnings.length) {
1006
+ for (const warning of section.warnings) lines.push(` ! ${warning.code}: ${warning.message}`);
1007
+ }
1008
+ if (section.trigger_support?.unsupported?.length) {
1009
+ lines.push(` unsupported trigger types: ${section.trigger_support.unsupported.map(trigger => `${trigger.type} (${trigger.table})`).join(', ')}. Only record triggers are inventoried.`);
1010
+ }
1011
+ if (!section.items.length) {
1012
+ lines.push(section.status === 'complete' ? ' (none in accessible configuration)' : ' (no results from available sources)');
1013
+ }
1014
+ for (const item of section.items) {
1015
+ const flags = [item.association, item.table ? `on ${item.table}` : '', item.active === false ? 'inactive' : '', item.scope && item.scope !== 'global' ? item.scope : ''].filter(Boolean);
1016
+ lines.push(` ${item.name}${flags.length ? ` \u2014 ${flags.join(', ')}` : ''}`);
1017
+ const meta = [];
1018
+ if (item.level) meta.push(item.level === 'table' ? 'table-level' : 'column');
1019
+ if (item.element) meta.push(`element ${item.element}`);
1020
+ if (item.internal_type) meta.push(item.internal_type);
1021
+ if (item.max_length !== undefined) meta.push(`max ${item.max_length}`);
1022
+ if (item.base_table) meta.push(`base ${item.base_table}`);
1023
+ if (item.operation) meta.push(item.operation);
1024
+ if (item.event_name) meta.push(item.event_name);
1025
+ if (item.view) meta.push(`view ${item.view}`);
1026
+ if (item.view_empty) meta.push('view empty');
1027
+ if (item.trigger_type) meta.push(`${item.trigger_type} trigger`);
1028
+ if (item.on_insert || item.on_update || item.on_delete) {
1029
+ meta.push(['insert', 'update', 'delete'].filter(operation => item[`on_${operation}`]).join('/'));
1030
+ }
1031
+ if (item.when) meta.push(item.when);
1032
+ if (item.operations?.length) meta.push(item.operations.join('/'));
1033
+ if (item.order !== undefined) meta.push(`order ${item.order}`);
1034
+ if (item.type) meta.push(item.type);
1035
+ if (item.condition) meta.push(`condition: ${item.condition.length > 100 ? item.condition.slice(0, 97) + '...' : item.condition}`);
1036
+ if (meta.length) lines.push(` ${meta.join(' | ')}`);
1037
+ if (item.field_actions?.length) {
1038
+ const actions = item.field_actions.map(action => `${action.field || '?'}${action.mandatory && action.mandatory !== 'ignore' ? ` mandatory=${action.mandatory}` : ''}${action.disabled && action.disabled !== 'ignore' ? ` disabled=${action.disabled}` : ''}${action.visible && action.visible !== 'ignore' ? ` visible=${action.visible}` : ''}`);
1039
+ lines.push(` field actions: ${actions.join('; ')}`);
1040
+ }
1041
+ if (item.has_script) lines.push(` content present (${item.script_bytes} bytes; not retrieved)`);
1042
+ }
1043
+ if (section.next_cursor) lines.push(` ... more available; continue with --cursor ${section.next_cursor}`);
1044
+ if (section.omitted) lines.push(` ${section.omitted} item(s) omitted by the response budget.`);
1045
+ lines.push('');
1046
+ }
1047
+ lines.push(`Returned ${data.totals.returned} item(s): ${data.totals.direct} direct, ${data.totals.inherited} inherited.`);
1048
+ if (data.totals.unavailable_categories || data.totals.unsupported_categories) {
1049
+ lines.push(`Unavailable categories: ${data.totals.unavailable_categories}; unsupported: ${data.totals.unsupported_categories}. These are not empty results.`);
1050
+ }
1051
+ if (data.budget_exceeded) lines.push('Response budget exceeded by category metadata alone; reduce categories or raise --max-bytes.');
1052
+ return lines.join('\n');
1053
+ }