@jacebenson/jsn 5.5.9 → 5.5.10

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,276 @@
1
+ import { AppError, errUsage } from './errors.js';
2
+ import { inventorySources, readInventory } from './instance-inventory.js';
3
+ import { MAX_SESSION_REPLAYS } from './session-recovery.js';
4
+
5
+ const candidates = {
6
+ entitlements: ['license_details', 'subscription_entitlement'],
7
+ allocation: ['subscription_detail', 'account_subscription_entitlement', 'instance_subscription_entitlement'],
8
+ consumption: ['itom_lu_ci_counts', 'usageanalytics_count', 'itom_lu_licensable_cis'],
9
+ };
10
+ const limits = { metadata_requests: 96, data_requests: 16, inheritance_depth: 16, dictionary_rows: 200 };
11
+ const namePattern = /^[a-zA-Z0-9_]+$/;
12
+ const idPattern = /^[a-f0-9]{32}$/i;
13
+ const raw = value => value && typeof value === 'object' ? value.value : value;
14
+ const text = value => typeof raw(value) === 'string' ? raw(value) : '';
15
+ const fail = reason => { throw new AppError(reason, 'Evidence source unavailable.'); };
16
+ const numeric = ['integer', 'longint', 'decimal', 'float', 'numeric'];
17
+ const strings = ['string', 'choice'];
18
+ const dates = ['glide_date', 'glide_date_time'];
19
+ // Field names are a conservative projection vocabulary, not a product meter or
20
+ // a claim that any particular subscription table implements these fields.
21
+ const fields = {
22
+ product_name: strings, product_code: strings, sku: strings,
23
+ license_type: strings, subscription_type: strings, unit: strings,
24
+ status: [...strings, 'integer'], state: [...strings, 'integer'],
25
+ active: ['boolean'], is_latest: ['boolean'],
26
+ quantity: numeric, purchased_quantity: numeric, allocated_quantity: numeric,
27
+ allocated: numeric, used: numeric, consumption: numeric, count: numeric,
28
+ ci_count: numeric, licensable_count: numeric,
29
+ sample_date: dates, start_date: dates, end_date: dates, effective_date: dates,
30
+ sys_updated_on: dates,
31
+ };
32
+
33
+ export function evidenceLimit(value = 50) {
34
+ if (!Number.isInteger(value) || value < 1 || value > 200) throw errUsage('--limit must be an integer from 1 to 200.');
35
+ return value;
36
+ }
37
+
38
+ function reason(error) {
39
+ if (error?.status === 401 || error?.code === 'auth_error') throw new AppError('auth_error', 'Authentication failed while reading subscription evidence.');
40
+ if (error?.status === 403 || error?.code === 'forbidden') return 'forbidden';
41
+ if (error?.status === 404) return 'missing-or-hidden';
42
+ return ['malformed', 'schema-unavailable', 'metadata-cap', 'inheritance-limit', 'request-budget', 'ambiguous-schema'].includes(error?.code) ? error.code : 'unavailable';
43
+ }
44
+
45
+ function safeValue(value, type) {
46
+ value = raw(value);
47
+ if (value === null || value === undefined || value === '') return null;
48
+ if (numeric.includes(type)) return /^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(String(value)) && Number.isFinite(Number(value)) ? String(value) : null;
49
+ if (type === 'boolean') return value === true || value === 'true' || value === '1' ? true : value === false || value === 'false' || value === '0' ? false : null;
50
+ if (dates.includes(type)) return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z?)?$/.test(value) ? value : null;
51
+ // Do not emit reference display values, URLs, emails, sys_ids, free-form
52
+ // descriptions, or control characters. Product/status labels remain observations.
53
+ return typeof value === 'string' && /^[\w ()+.,:/-]{1,120}$/.test(value)
54
+ && !/https?:|www\.|[a-f0-9]{32}/i.test(value) ? value : null;
55
+ }
56
+
57
+ // The inventory's single installed-tab page is a known read-only POST, not a
58
+ // general exception to GET-only evidence reads. Match its exact URL and payload
59
+ // before bypassing the SDK's method-based readOnly guard; retain no-touch auth.
60
+ export async function requestSubscriptionEvidence(sdk, endpoint, options = {}) {
61
+ const method = options.method || 'GET';
62
+ const installedURL = `${sdk.baseURL}/api/sn_appclient/appmanager/apps?${new URLSearchParams({ tab_context: 'installed', sysparm_limit: '200', sysparm_offset: '0' })}`;
63
+ const installedDiscovery = method === 'POST' && endpoint === installedURL && options.body === '{}'
64
+ && Object.keys(options).every(key => key === 'method' || key === 'body');
65
+ const url = new URL(endpoint);
66
+ const tableRead = method === 'GET' && url.origin === new URL(sdk.baseURL).origin
67
+ && !url.username && !url.password && !url.hash && /^\/api\/now\/(table|stats)\/[a-zA-Z0-9_]+$/.test(url.pathname);
68
+ if (!tableRead && !installedDiscovery) fail('unsafe-evidence-request');
69
+ return sdk.request(endpoint, { ...options, method, readOnly: !installedDiscovery, touchLastSeen: false, timeout: 10000 });
70
+ }
71
+
72
+ export async function subscriptionEvidence(sdk, { limit = 50 } = {}) {
73
+ evidenceLimit(limit);
74
+ const requests = { metadata: 0, data: 0 };
75
+ const cache = new Map();
76
+ async function request(kind, endpoint, options = {}) {
77
+ const cap = limits[`${kind}_requests`];
78
+ if (requests[kind] >= cap) fail('request-budget');
79
+ requests[kind]++;
80
+ try { return await requestSubscriptionEvidence(sdk, endpoint, options); }
81
+ catch (error) {
82
+ const code = reason(error);
83
+ throw new AppError(code, 'Evidence source unavailable.', '', code === 'forbidden' ? 403 : code === 'missing-or-hidden' ? 404 : 0);
84
+ }
85
+ }
86
+ async function rows(kind, table, query, projection, cap) {
87
+ const params = new URLSearchParams({ sysparm_query: query, sysparm_fields: projection.join(','), sysparm_limit: String(cap), sysparm_display_value: 'false', sysparm_exclude_reference_link: 'true' });
88
+ const response = await request(kind, `${sdk.baseURL}/api/now/table/${table}?${params}`);
89
+ if (!Array.isArray(response?.result) || response.result.length > cap || response.result.some(r => !r || typeof r !== 'object' || Array.isArray(r))) fail('malformed');
90
+ return response.result;
91
+ }
92
+ function metadata(table, query, projection, cap) {
93
+ const key = `${table}:${query}`;
94
+ if (!cache.has(key)) cache.set(key, rows('metadata', table, query, projection, cap));
95
+ return cache.get(key);
96
+ }
97
+ async function schema(table) {
98
+ const selected = new Map(), references = [], visited = new Set();
99
+ let query = `name=${table}`;
100
+ for (let depth = 0; depth < limits.inheritance_depth; depth++) {
101
+ const definitions = await metadata('sys_db_object', query, ['sys_id', 'name', 'super_class'], 2);
102
+ if (!definitions.length) fail('schema-unavailable');
103
+ if (definitions.length !== 1) fail('ambiguous-schema');
104
+ const definition = definitions[0], name = text(definition.name), parent = text(definition.super_class);
105
+ if (!namePattern.test(name) || (depth === 0 && name !== table) || visited.has(name)
106
+ || !idPattern.test(text(definition.sys_id)) || typeof raw(definition.super_class) !== 'string') fail('malformed');
107
+ visited.add(name);
108
+ const dictionary = await metadata('sys_dictionary', `name=${name}^elementISNOTEMPTY^ORDERBYelement`, ['name', 'element', 'internal_type', 'reference'], limits.dictionary_rows + 1);
109
+ if (dictionary.length > limits.dictionary_rows) fail('metadata-cap');
110
+ const local = new Set();
111
+ for (const row of dictionary) {
112
+ const element = text(row.element), type = text(row.internal_type), target = text(row.reference);
113
+ if (text(row.name) !== name || !namePattern.test(element) || !namePattern.test(type) || local.has(element)
114
+ || !Object.hasOwn(row, 'reference') || typeof raw(row.reference) !== 'string') fail('malformed');
115
+ local.add(element);
116
+ if (selected.has(element)) continue;
117
+ if (target && !namePattern.test(target)) fail('malformed');
118
+ selected.set(element, { type, reference: target });
119
+ if (target) references.push({ table: name, field: element, target });
120
+ }
121
+ if (!parent) return { fields: selected, references, hierarchy: [...visited] };
122
+ if (!idPattern.test(parent)) fail('malformed');
123
+ query = `sys_id=${parent}`;
124
+ }
125
+ fail('inheritance-limit');
126
+ }
127
+ const capturedAt = new Date().toISOString();
128
+ const report = {
129
+ captured_at: capturedAt, authoritative: false,
130
+ limitations: [
131
+ 'Provider-visible instance evidence only; not purchased rights, contract validity, compliance, billable seats or bills.',
132
+ 'Installed apps/plugins are possibilities and hints only. Nonproduction installs do not prove production deployment or bills. Environment and production status are not detected.',
133
+ 'No subscription-to-app joins, cross-source totals, SKU applicability, meters or 90-day averages are inferred. Source field labels do not establish charging semantics.',
134
+ 'Missing/forbidden sources are unavailable, not zero. Successful empty results mean no visible rows, not absence of rights or use. ACL visibility and snapshot consistency are unknown.',
135
+ ],
136
+ entitlements: [], allocation: [], consumption: [],
137
+ access: { source: 'sys_user_has_role', status: 'unavailable', reason: 'SDK aggregate supports count and groupBy, not a bounded distinct-user aggregate; role assignments are not allocated or billable seats. No user-role rows were fetched.' },
138
+ installed_hints: [],
139
+ request_budget: {
140
+ limits: { ...limits }, used: requests,
141
+ http_attempt_ceiling: { metadata: limits.metadata_requests * (1 + MAX_SESSION_REPLAYS), data: limits.data_requests * (1 + MAX_SESSION_REPLAYS) },
142
+ scope: 'Collector SDK dispatch caps and API HTTP attempt ceilings including bounded SDK session replay; authentication bootstrap/refresh is separate. Each API attempt has a 10-second timeout.',
143
+ },
144
+ };
145
+ function source(table) {
146
+ return { source: table, observed_at: capturedAt, status: 'unavailable', reason: null, observations: null,
147
+ freshness: { collection: capturedAt, source_updated_on: 'unknown; collection time is not source freshness' },
148
+ coverage: { complete: false, limit, truncated: null, visibility: 'provider-visible only; no completeness claim' } };
149
+ }
150
+ for (const [section, tables] of Object.entries(candidates)) for (const table of tables) {
151
+ const result = source(table);
152
+ report[section].push(result);
153
+ try {
154
+ const info = await schema(table);
155
+ const projection = [...info.fields].filter(([name, field]) => fields[name]?.includes(field.type) && !field.reference).map(([name]) => name);
156
+ result.schema = { status: 'verified-visible', hierarchy: info.hierarchy, fields: projection.map(name => ({ name, type: info.fields.get(name).type })), references: info.references };
157
+ if (!projection.length) fail('schema-unavailable');
158
+ const latest = table === 'subscription_detail' && projection.includes('is_latest');
159
+ result.query = `${latest ? 'is_latest=true^' : ''}ORDERBYsys_id`;
160
+ if (table === 'subscription_detail') result.latest_filter = latest ? 'verified boolean is_latest=true' : 'unavailable; current/latest allocation is not established';
161
+ const page = await rows('data', table, result.query, projection, limit + 1);
162
+ result.observations = page.slice(0, limit).map(row => Object.fromEntries(projection.map(name => [name, safeValue(row[name], info.fields.get(name).type)])));
163
+ result.status = page.length ? 'observed' : 'no-visible-rows';
164
+ result.coverage.truncated = page.length > limit;
165
+ result.coverage.returned = result.observations.length;
166
+ result.freshness.source_updated_on = projection.includes('sys_updated_on') ? 'Per-row sys_updated_on where visible and valid; not a source-wide freshness guarantee' : 'unavailable; no verified update timestamp';
167
+ } catch (error) { result.reason = reason(error); }
168
+ }
169
+ // Existing inventory readers preserve installation evidence and provider count
170
+ // uncertainty. The same schema gate applies before their known projections.
171
+ const verifiedInventoryFields = new Map();
172
+ const inventorySDK = {
173
+ baseURL: sdk.baseURL,
174
+ request: (endpoint, options) => request('data', endpoint, options),
175
+ listStrict: async (table, params, options) => {
176
+ const safeParams = new URLSearchParams(params);
177
+ safeParams.set('sysparm_fields', safeParams.get('sysparm_fields').split(',').filter(name => verifiedInventoryFields.get(table)?.has(name)).join(','));
178
+ const response = await request('data', `${sdk.baseURL}/api/now/table/${table}?${safeParams}`, options);
179
+ if (!Array.isArray(response?.result)) fail('malformed');
180
+ return response.result;
181
+ },
182
+ };
183
+ for (const kind of ['store', 'plugins']) {
184
+ const descriptor = inventorySources[kind], result = source(descriptor.table);
185
+ result.kind = kind;
186
+ report.installed_hints.push(result);
187
+ try {
188
+ const info = await schema(descriptor.table);
189
+ if (descriptor.fields.some(name => !info.fields.has(name) || info.fields.get(name).reference)) fail('schema-unavailable');
190
+ verifiedInventoryFields.set(descriptor.table, new Set([...info.fields].filter(([, field]) => !field.reference).map(([name]) => name)));
191
+ result.schema = { status: 'verified-visible', hierarchy: info.hierarchy, fields: descriptor.fields.map(name => ({ name, type: info.fields.get(name).type })) };
192
+ const inventory = await readInventory(inventorySDK, kind, 1);
193
+ if (inventory.coverage.reason === 'auth_error') fail('auth_error');
194
+ result.provider_coverage = inventory.coverage;
195
+ result.coverage.returned = Math.min(inventory.items.size, limit);
196
+ result.coverage.truncated = inventory.items.size > limit || inventory.coverage.status !== 'complete';
197
+ result.status = inventory.items.size ? 'observed' : inventory.coverage.status === 'complete' ? 'no-visible-rows' : 'unavailable';
198
+ result.reason = inventory.coverage.reason;
199
+ result.observations = result.status === 'unavailable' ? null : [...inventory.items.values()].slice(0, limit).map(item => ({
200
+ name: safeValue(item.name, 'string'), version: safeValue(item.version, 'string'), active: item.active,
201
+ ...(kind === 'store' ? { installed: item.installed, installation_evidence: item.installation_evidence } : { installation_evidence: 'platform plugin state; activation is not purchased entitlement' }),
202
+ }));
203
+ result.freshness.source_updated_on = 'unavailable; observed inventory state, not deployment history';
204
+ } catch (error) { result.reason = reason(error); }
205
+ }
206
+ return report;
207
+ }
208
+
209
+ const sourceTitles = {
210
+ license_details: 'Subscription forms', subscription_entitlement: 'Subscription entitlements',
211
+ subscription_detail: 'Allocation observations', account_subscription_entitlement: 'Account allocation',
212
+ instance_subscription_entitlement: 'Instance allocation', itom_lu_ci_counts: 'ITOM CI counts',
213
+ usageanalytics_count: 'Usage analytics', itom_lu_licensable_cis: 'ITOM licensable CI observations',
214
+ sys_store_app: 'Store applications', v_plugin: 'Platform plugins',
215
+ };
216
+ const fieldLabels = {
217
+ product_name: 'Product', name: 'Name',
218
+ product_code: 'Product code', sku: 'SKU', license_type: 'License type', subscription_type: 'Subscription type',
219
+ unit: 'Unit', status: 'Status', state: 'State', active: 'Active', is_latest: 'Latest',
220
+ quantity: 'Quantity', purchased_quantity: 'Purchased quantity', allocated_quantity: 'Allocated quantity',
221
+ allocated: 'Allocated', used: 'Used', consumption: 'Consumption', count: 'Count', ci_count: 'CI count',
222
+ licensable_count: 'Licensable count', sample_date: 'Sample date', start_date: 'Start date',
223
+ end_date: 'End date', effective_date: 'Effective date', sys_updated_on: 'Updated', version: 'Version',
224
+ installed: 'Installed', installation_evidence: 'Install evidence',
225
+ };
226
+ const humanReasons = {
227
+ forbidden: 'access denied', 'missing-or-hidden': 'missing or hidden', 'schema-unavailable': 'schema unavailable',
228
+ malformed: 'incomplete or invalid response', 'metadata-cap': 'metadata limit reached',
229
+ 'inheritance-limit': 'schema ancestry limit reached', 'request-budget': 'request limit reached',
230
+ 'ambiguous-schema': 'ambiguous schema', page_limit_no_provider_total: 'no provider total; bounded page only',
231
+ };
232
+ const humanValue = value => value === null || value === undefined ? 'Unavailable'
233
+ : value === true ? 'Yes' : value === false ? 'No'
234
+ : value === 'appclient_installed_tab' ? 'Observed in installed Store tab'
235
+ : value === 'local_version_and_install_date' ? 'Local version and install date'
236
+ : value === 'platform plugin state; activation is not purchased entitlement' ? 'Plugin state, not purchased entitlement'
237
+ : String(value);
238
+
239
+ export function formatSubscriptionEvidence(report) {
240
+ const lines = ['Subscription evidence', `Observed: ${report.captured_at}`,
241
+ 'Source observations only. Not a contract, compliance verdict, billable seats or bills.',
242
+ 'Installed apps/plugins are possibilities, not proof of purchased rights.',
243
+ 'Nonproduction installs do not prove production deployment or bills.',
244
+ 'No environment detection, cross-source totals, licensing meters or 90-day averages.',
245
+ 'Missing data is unavailable, not zero. Empty reads mean no visible rows.'];
246
+ for (const [section, title] of [
247
+ ['entitlements', 'Entitlement evidence'], ['allocation', 'Allocation evidence'],
248
+ ['consumption', 'Consumption evidence'], ['installed_hints', 'Installed app and plugin hints'],
249
+ ]) {
250
+ lines.push('', title, '-'.repeat(title.length));
251
+ for (const source of report[section]) {
252
+ lines.push('', sourceTitles[source.source] || source.source);
253
+ if (source.status === 'unavailable') lines.push(` Unavailable: ${humanReasons[source.reason] || 'source could not be read'}.`);
254
+ else if (source.status === 'no-visible-rows') lines.push(' No visible rows.');
255
+ else if (source.reason) lines.push(` Note: ${humanReasons[source.reason] || source.reason.replaceAll('_', ' ')}.`);
256
+ for (const [index, row] of (source.observations || []).entries()) {
257
+ lines.push(` ${row.product_name || row.name || `Observation ${index + 1}`}`);
258
+ for (const [key, value] of Object.entries(row)) {
259
+ if ((key === 'product_name' || key === 'name') && value) continue;
260
+ const label = fieldLabels[key] || key.replaceAll('_', ' ');
261
+ lines.push(` ${label.padEnd(19)} ${humanValue(value)}`);
262
+ }
263
+ }
264
+ lines.push(` Source: ${source.source}`);
265
+ const shown = source.coverage.returned === undefined ? 'not established' : `${source.coverage.returned} shown`;
266
+ const more = source.coverage.truncated === true ? '; more rows may exist' : '';
267
+ lines.push(` Coverage: ${shown}, limit ${source.coverage.limit}${more}; completeness unknown.`);
268
+ lines.push(` Freshness: ${source.freshness.source_updated_on.startsWith('Per-row') ? 'See Updated values; source-wide freshness unknown.' : 'Not established.'}`);
269
+ if (source.latest_filter) lines.push(` Latest allocation: ${source.latest_filter.startsWith('verified') ? 'latest rows only (is_latest=true).' : 'not established.'}`);
270
+ }
271
+ }
272
+ lines.push('', 'Access evidence', '---------------', 'Unavailable: bounded distinct-user aggregation is not supported by this SDK.',
273
+ 'No user-role rows fetched. Role assignments are not allocated or billable seats.',
274
+ `Source: ${report.access.source} (not queried).`);
275
+ return lines.join('\n');
276
+ }
@@ -0,0 +1,258 @@
1
+ import { errUsage } from './errors.js';
2
+ import { App } from './app.js';
3
+ import { applySession } from './session.js';
4
+ import { quoteShellArg } from './helpers.js';
5
+ import { discoverSkippedUpdates, raw } from './skipped-updates.js';
6
+ import { fetchTableResult } from './commands/atf.js';
7
+ import { scanResults } from './scan.js';
8
+ import { getReport } from './customizations.js';
9
+ import { tableReadParams } from './table-read-params.js';
10
+
11
+ const fieldName = /^[a-z][a-z0-9_]*$/;
12
+ const idPattern = /^[0-9a-f]{32}$/i;
13
+ const value = (row, field) => raw(row?.[field]);
14
+ const timestamp = row => value(row, 'sys_updated_on') || value(row, 'sys_created_on') || null;
15
+ const fieldsMissing = (fields, rows) => fields.filter(field => rows.some(row => !Object.hasOwn(row, field)));
16
+ const safeFields = new Set(['sys_id', 'sys_updated_on', 'sys_created_on', 'name', 'number', 'state', 'status',
17
+ 'severity', 'priority', 'disposition', 'resolution_status', 'short_description', 'description',
18
+ 'upgrade_preview', 'preview', 'version', 'target_version', 'source', 'target', 'source_instance',
19
+ 'target_instance', 'requested', 'scheduled', 'started', 'completed', 'start_time', 'end_time',
20
+ 'table', 'condition', 'active', 'preserve', 'exclude', 'upgrade_history', 'test', 'test_suite',
21
+ 'type', 'result', 'percent_complete', 'message']);
22
+
23
+ export function validatePrep(argv) {
24
+ if (!argv.profile && !argv.instance) throw errUsage('Upgrade preparation requires explicit --profile or --instance.');
25
+ if (!Number.isInteger(argv.limit) || argv.limit < 1 || argv.limit > 200) throw errUsage('--limit must be an integer from 1 to 200.');
26
+ if (argv.target !== undefined && (typeof argv.target !== 'string' || !argv.target.trim())) throw errUsage('--target must be nonempty.');
27
+ for (const name of argv.relatedProfile || []) if (typeof name !== 'string' || !name) throw errUsage('Supply explicit related profile names.');
28
+ }
29
+
30
+ /** Only Table API GETs are exposed to collectors, including reused readers. */
31
+ export async function collectUpgradePrep(argv, app) {
32
+ validatePrep(argv);
33
+ app.requireInstance();
34
+ const related = (argv.relatedProfile || []).map(name => {
35
+ const profile = app.config.profiles[name];
36
+ if (!profile?.instance_url) throw errUsage(`Unknown related profile: ${name}`);
37
+ const relatedApp = new App(app.config);
38
+ applySession(relatedApp, { profile: name });
39
+ return { profile: name, instance: relatedApp.getEffectiveInstance(), sdk: relatedApp.sdk };
40
+ });
41
+ const report = { generated_at: new Date().toISOString(), status: 'incomplete', target: argv.target || null,
42
+ target_basis: argv.target ? 'operator_selection_not_eligibility_guarantee' : 'not_selected',
43
+ sources: [], findings: [], activities: [], limitations: [
44
+ 'Read-only preparation evidence, not a readiness certification or upgrade executor.',
45
+ 'Offered targets are local metadata, not a fresh eligibility guarantee. No future target is selected automatically.',
46
+ 'Last completed platform history is not the live node build. Historical skips are not predicted skips.',
47
+ 'Version suffixes are not security advisories. Store metadata is not target compatibility or purchase authorization.',
48
+ 'Missing retrieval evidence does not establish absence of backups. ATF/scan success does not establish UAT or coverage.',
49
+ 'All reads are bounded; timestamps and inaccessible fields require human review. No topology is inferred from profile names.',
50
+ ] };
51
+ const addFinding = (kind, status, source, detail, metadata = {}) => {
52
+ const finding = { id: `finding-${report.findings.length + 1}`, kind, status,
53
+ source_refs: source ? [source.id] : [], record_ids: metadata.record_ids || [], detail, ...metadata };
54
+ report.findings.push(finding);
55
+ return finding;
56
+ };
57
+ const activity = (kind, action, refs = [], dependencies = [], completion = '') => report.activities.push({
58
+ id: `activity-${report.activities.length + 1}`, kind, status: 'pending', action,
59
+ source_refs: refs, depends_on: dependencies, completion_check: completion,
60
+ });
61
+ async function collectContext(context, lower = false) {
62
+ const { profile, instance } = context;
63
+ function reference(table, params, id) {
64
+ const fields = (params.get('sysparm_fields') || '').split(',').filter(Boolean);
65
+ const query = params.get('sysparm_query') || '';
66
+ const path = `/api/now/table/${table}${id ? `/${id}` : ''}`;
67
+ const source = { id: `source-${report.sources.length + 1}`, profile: profile || null, instance, table,
68
+ fields, encoded_query: query, requested_record_ids: id ? [id] : [], record_ids: [], observed_at: new Date().toISOString(), source_timestamps: [],
69
+ bounds: { limit: Number(params.get('sysparm_limit')) || 1, offset: Number(params.get('sysparm_offset')) || 0,
70
+ truncation: 'unknown' }, status: 'not_checked', method: 'GET', path, params: Object.fromEntries(params),
71
+ read_command: `jsn records ${id ? `get --table ${table} --sys-id ${quoteShellArg(id)}` : `list --table ${table}`} --instance ${quoteShellArg(instance)}${profile ? ` --profile ${quoteShellArg(profile)}` : ''}${!id ? ` --query ${quoteShellArg(query)} --limit ${params.get('sysparm_limit') || 1} --offset ${params.get('sysparm_offset') || 0} --display-values ${params.get('sysparm_display_value') === 'all' ? 'both' : params.get('sysparm_display_value') === 'true' ? 'display' : 'raw'} --no-count` : ''}${fields.length ? ` --fields ${quoteShellArg(fields.join(','))}` : ''} --json` };
72
+ report.sources.push(source);
73
+ return source;
74
+ }
75
+ const sdk = Object.fromEntries(['list', 'listStrict', 'get'].map(method => [method, async (table, argument) => {
76
+ if (!fieldName.test(table)) throw errUsage('Unsafe evidence table.');
77
+ const params = method === 'get' ? new URLSearchParams() : tableReadParams(argument, context.sdk);
78
+ const source = reference(table, params, method === 'get' ? argument : null);
79
+ try {
80
+ const result = await context.sdk[method === 'list' ? 'listStrict' : method](table, argument);
81
+ const rows = Array.isArray(result) ? result : result ? [result] : [];
82
+ source.records = rows;
83
+ source.record_ids = rows.map(row => value(row, 'sys_id')).filter(Boolean);
84
+ source.missing_fields = fieldsMissing(source.fields, rows);
85
+ source.source_timestamps = rows.map(row => ({ sys_id: value(row, 'sys_id'), timestamp: timestamp(row) }));
86
+ source.bounds.truncation = method === 'get' ? 'no' : rows.length >= source.bounds.limit ? 'possible' : 'no';
87
+ source.status = rows.length ? 'observed' : 'missing';
88
+ source.stale_record_ids = rows.filter(row => timestamp(row) && Date.parse(timestamp(row)) < Date.now() - 30 * 86400000).map(row => value(row, 'sys_id'));
89
+ return result;
90
+ } catch (error) {
91
+ source.status = [401, 403].includes(error.status) ? 'inaccessible' : error.status === 404 ? 'missing' : 'error';
92
+ source.http_status = error.status || null;
93
+ // Do not expose transport messages, which can include credentials/URLs.
94
+ throw error;
95
+ }
96
+ }]));
97
+ async function read(table, fields, query = 'ORDERBYsys_id', limit = argv.limit) {
98
+ try { return await sdk.listStrict(table, new URLSearchParams({ sysparm_fields: fields,
99
+ sysparm_query: query, sysparm_limit: String(limit), sysparm_display_value: 'false' })); }
100
+ catch { return []; }
101
+ }
102
+ const last = () => report.sources.at(-1);
103
+ async function schema(table) {
104
+ const rows = await read('sys_dictionary', 'sys_id,name,element,reference,sys_updated_on',
105
+ `name=${table}^elementISNOTEMPTY^ORDERBYelement`, 200);
106
+ return rows.map(row => value(row, 'element')).filter(field => fieldName.test(field));
107
+ }
108
+ async function dynamic(table, query) {
109
+ const known = await schema(table);
110
+ if (!known.length) {
111
+ addFinding('schema_gap', last().status === 'observed' ? 'missing' : last().status, last(), `Readable dictionary fields for ${table} are incomplete; no data query attempted.`);
112
+ return [];
113
+ }
114
+ const fields = [...new Set(['sys_id', ...known.filter(field => safeFields.has(field))])];
115
+ const rows = await read(table, fields.join(','), query || 'ORDERBYsys_id');
116
+ return rows;
117
+ }
118
+ if (lower) {
119
+ for (const table of ['sys_update_set', 'sys_remote_update_set']) {
120
+ const rows = await dynamic(table);
121
+ addFinding('lower_environment_preservation', rows.length ? 'observed' : last().status, last(),
122
+ `${table} evidence for explicitly related profile; retrieval is not a backup or proof of recoverability.`, { records: rows });
123
+ }
124
+ return;
125
+ }
126
+ await read('upgrade_center_metadata', 'sys_id,scheduled_version,upgrade_scheduled_on,end_of_life,near_end_of_life,sys_updated_on');
127
+ const schedules = last();
128
+ addFinding('scheduling', schedules.status, schedules, 'Recorded scheduling and lifecycle metadata only; blank schedules do not select an upgrade.');
129
+ const targets = await read('upgrade_preview_version', 'sys_id,label,value,upgrade_center_metadata,sys_updated_on');
130
+ const targetSource = last();
131
+ addFinding('offered_targets', targetSource.status, targetSource, 'Locally offered platform targets; eligibility must be confirmed separately.', { records: targets });
132
+ if (argv.target) {
133
+ const matches = targets.filter(row => [value(row, 'sys_id'), value(row, 'value'), value(row, 'label')].includes(argv.target));
134
+ addFinding('target_selection', matches.length === 1 ? 'observed' : 'missing', targetSource,
135
+ matches.length === 1 ? 'Exact local target metadata match, not eligibility certification.' : 'Target was not uniquely observed in this bounded catalog.', { records: matches });
136
+ }
137
+ const history = await read('sys_upgrade_history', 'sys_id,from_version,to_version,upgrade_started,upgrade_finished,sys_updated_on',
138
+ 'to_versionSTARTSWITHglide^upgrade_finishedISNOTEMPTY^ORDERBYDESCupgrade_finished');
139
+ addFinding('last_completed_platform_history', last().status, last(), 'Historical completed platform upgrade, not live node build.', { records: history.slice(0, 1) });
140
+ const apps = await read('sys_store_app', 'sys_id,name,scope,version,latest_version,update_available,sys_updated_on',
141
+ 'update_available=true^NQlatest_versionISNOTEMPTY^ORDERBYsys_id');
142
+ const storeSource = last();
143
+ for (const row of apps) {
144
+ // raw() stringifies scalar and reference values, including booleans.
145
+ const flagValue = value(row, 'update_available');
146
+ const flag = ['true', '1'].includes(flagValue) ? true : ['false', '0'].includes(flagValue) ? false : null;
147
+ const readableVersion = field => {
148
+ const fieldValue = row[field]?.value ?? row[field];
149
+ return typeof fieldValue === 'string' && fieldValue.trim() ? fieldValue : '';
150
+ };
151
+ const installed = readableVersion('version'), latest = readableVersion('latest_version');
152
+ if (flag === false && (!latest || latest === installed)) continue;
153
+ const contradictory = Boolean(flag !== null && installed && latest && flag === (installed === latest));
154
+ addFinding(contradictory ? 'store_metadata_conflict' : 'store_update_candidate', contradictory ? 'verified_problem' : flag === null ? 'missing' : 'observed', storeSource,
155
+ contradictory ? 'Update flag contradicts recorded versions; verify catalog metadata before deciding.'
156
+ : flag === null ? 'Update availability flag is missing or unrecognized; recorded versions are candidate evidence only, not a verified contradiction.'
157
+ : 'Store update candidate; target compatibility remains unverified.',
158
+ { record_ids: [value(row, 'sys_id')], record: row });
159
+ }
160
+ for (const table of ['upgrade_preview', 'upgrade_preview_log']) {
161
+ const rows = await dynamic(table);
162
+ const source = last();
163
+ addFinding('existing_preview', source.status, source, 'Existing preview only; scope/target/time must be checked. Severity and priority are retained exactly, never inferred.', { records: rows });
164
+ for (const row of rows.filter(row => ['severity', 'priority', 'disposition'].some(field => value(row, field)))) {
165
+ addFinding('preview_finding', 'observed', source, 'Provider preview metadata requires operator triage; numeric priority is not interpreted as severity.',
166
+ { record_ids: [value(row, 'sys_id')], metadata: Object.fromEntries(['severity', 'priority', 'disposition', 'resolution_status'].filter(field => Object.hasOwn(row, field)).map(field => [field, row[field]])) });
167
+ }
168
+ }
169
+ try {
170
+ const skipped = await discoverSkippedUpdates(sdk, { limit: argv.limit });
171
+ addFinding('historical_skips', last().status, last(), 'Unresolved historical skipped updates, not predicted future skips.', { evidence: skipped });
172
+ } catch { addFinding('historical_skips', last()?.status || 'error', last(), 'Historical skip reader could not establish valid unresolved evidence.'); }
173
+ const cloneTables = await read('sys_db_object', 'sys_id,name,label,sys_updated_on', 'nameLIKEclone^ORDERBYname', 5);
174
+ for (const row of cloneTables.slice(0, 4)) {
175
+ const table = value(row, 'name');
176
+ if (!fieldName.test(table)) continue;
177
+ const rows = await dynamic(table);
178
+ addFinding('clone_evidence', last().status, last(), `Dictionary-established ${table}; role and relation to this upgrade need operator confirmation.`, { records: rows });
179
+ }
180
+ if (!cloneTables.length) addFinding('clone_gap', last().status, last(), 'Clone requests/history/preservers/exclusions were not established. Ask an administrator for readable schema and recovery evidence.');
181
+ for (const table of ['sys_atf_test_result', 'sys_atf_test_suite_result']) {
182
+ const rows = await read(table, 'sys_id,sys_created_on,sys_updated_on', 'ORDERBYDESCsys_created_on', Math.min(argv.limit, 3));
183
+ for (const row of rows) if (idPattern.test(value(row, 'sys_id'))) {
184
+ try {
185
+ const firstSource = report.sources.length;
186
+ const evidence = await fetchTableResult({ sdk }, value(row, 'sys_id'));
187
+ addFinding('existing_atf', evidence?.status === 'failed' ? 'verified_problem' : evidence ? 'observed' : 'missing', last(), 'Existing ATF result; reader may infer status. Verify scope, timestamp, target relevance and business coverage.',
188
+ { evidence, source_refs: report.sources.slice(firstSource).map(source => source.id) });
189
+ } catch { /* Exact failed read is retained in sources. */ }
190
+ }
191
+ }
192
+ const scans = await read('sys_execution_tracker', 'sys_id,type,sys_created_on,sys_updated_on', 'type=instance_scan^ORDERBYDESCsys_created_on', Math.min(argv.limit, 3));
193
+ for (const row of scans) if (idPattern.test(value(row, 'sys_id'))) {
194
+ try {
195
+ const firstSource = report.sources.length;
196
+ const evidence = await scanResults(sdk, value(row, 'sys_id'), argv.limit);
197
+ addFinding('existing_scan', evidence.findings.length ? 'verified_problem' : evidence.incomplete ? 'missing' : 'observed', last(), 'Existing scan result only; inspect target scope/time and incomplete evidence.',
198
+ { evidence, source_refs: report.sources.slice(firstSource).map(source => source.id) });
199
+ } catch { /* Exact failed read is retained in sources. */ }
200
+ }
201
+ }
202
+ await collectContext({ profile: argv.profile || null, instance: app.getEffectiveInstance(), sdk: app.sdk });
203
+ for (const context of related) await collectContext(context, true);
204
+ if (!related.length) addFinding('lower_environment_preservation', 'not_checked', null,
205
+ 'No related profiles supplied. Provide --related-profile explicitly to inspect lower-environment update-set preservation/retrieval; topology is not inferred.');
206
+ if (argv.customizations) {
207
+ const capture = getReport(argv.customizations);
208
+ if (!capture || capture.instance !== app.getEffectiveInstance()) throw errUsage('Customization capture must exist and match the selected instance exactly.');
209
+ addFinding('customization_capture', 'observed', null, 'Existing local customization capture; assess age and bounds before reuse.', { evidence: capture });
210
+ } else addFinding('customization_capture', 'not_checked', null, 'Supply --customizations with an existing local capture; no capture is persisted by this briefing.');
211
+ for (const source of report.sources) {
212
+ if (source.missing_fields?.length) addFinding('unreadable_fields', 'missing', source,
213
+ 'Requested fields were absent in returned records; absent fields are not blank values.', { fields: source.missing_fields });
214
+ if (source.stale_record_ids?.length) addFinding('stale_evidence', 'stale', source, 'Records older than 30 days; revalidate relevance, not necessarily invalid.', { record_ids: source.stale_record_ids });
215
+ if (source.bounds.truncation !== 'no') addFinding('bounded_evidence', 'missing', source, 'Evidence may be truncated; paginate this exact read before drawing absence conclusions.');
216
+ if (['missing', 'inaccessible', 'error'].includes(source.status) || source.missing_fields?.length
217
+ || source.stale_record_ids?.length || source.bounds.truncation !== 'no') {
218
+ activity('evidence_gap', 'Obtain readable, current, completely paginated evidence or document why unavailable.',
219
+ [source.id], [], 'Rerun exact GET; resolve absent fields, revalidate old records and record complete bounds.');
220
+ }
221
+ }
222
+ activity('preserve_workflows', 'Inventory customizations, lower-environment update sets, clone preservation/exclusions and recovery ownership before a technical upgrade.',
223
+ report.sources.filter(s => /update_set|clone|upgrade_history/.test(s.table)).map(s => s.id), [], 'Owners verify preservation and retrieval evidence; absence of retrieval is not absence of backups.');
224
+ activity('technical_upgrade_review', 'Review exact platform/Store targets and preview dispositions with owners; preserve existing workflows where supported.',
225
+ report.sources.filter(s => /upgrade|store/.test(s.table)).map(s => s.id), ['activity-' + report.activities.length], 'Document chosen targets, compatibility, unavoidable behavior changes and resolved preview decisions.');
226
+ const technicalReviewId = report.activities.at(-1).id;
227
+ for (const [kind, action, completion] of [
228
+ ['release_changes', 'Obtain official target-specific deprecations, migrations, security advisories and default changes; never infer them from a version suffix.', 'Owners cite authoritative release documentation and validate affected workflows.'],
229
+ ['recovery', 'Validate backups, restore rehearsal, downtime, rollback decision points and accountable owners.', 'Recovery owner records tested procedure and acceptable recovery point/time.'],
230
+ ['uat', 'Define integration regression scope and business-owner UAT; map existing ATF/scan evidence to that scope.', 'Owners sign off representative workflows and document uncovered scope.'],
231
+ ['optional_activation', 'Plan controlled later optional feature activation separately from technical upgrade; identify unavoidable changes first.', 'Feature owners approve opt-in rollout, testing and rollback separately.'],
232
+ ]) activity(kind, action, [], kind === 'optional_activation' ? [technicalReviewId] : [], completion);
233
+ return report;
234
+ }
235
+
236
+ function findingSummary(finding) {
237
+ const parts = [`${finding.id} [${finding.status}] ${finding.kind}: ${finding.detail}`,
238
+ `(${finding.source_refs.join(', ') || 'human/local evidence'})`];
239
+ if (finding.record) {
240
+ const row = finding.record;
241
+ parts.push(`${value(row, 'name')}: installed=${value(row, 'version')} catalog=${value(row, 'latest_version')} update_available=${value(row, 'update_available')}`);
242
+ }
243
+ if (finding.metadata) parts.push(JSON.stringify(finding.metadata));
244
+ if (finding.records?.length) {
245
+ const row = finding.records[0];
246
+ parts.push(`Observed records: ${finding.records.length}; first=${value(row, 'label') || value(row, 'name') || value(row, 'to_version') || value(row, 'sys_id')}`);
247
+ }
248
+ return parts.join(' ');
249
+ }
250
+
251
+ export function prepSummary(report) {
252
+ return ['Upgrade preparation — incomplete evidence, not readiness certification',
253
+ `Target: ${report.target || 'not selected (discovery only)'}`,
254
+ `Sources: ${report.sources.length}; findings: ${report.findings.length}; activities: ${report.activities.length}`,
255
+ ...report.findings.map(findingSummary),
256
+ ...report.activities.map(a => `${a.id}: ${a.action} Completion: ${a.completion_check}`),
257
+ 'Use --json or --get data.sources for exact GET provenance and bounds.'].join('\n');
258
+ }