@jacebenson/jsn 5.5.9-dev.221.1 → 5.5.9-dev.223.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.5.9-dev.221.1",
3
+ "version": "5.5.9-dev.223.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": {
@@ -46,6 +46,17 @@ function storageError(message) {
46
46
  error.code = 'credential_storage_error';
47
47
  return error;
48
48
  }
49
+ /**
50
+ * The plaintext warning belongs to the moment a credential is stored, not to
51
+ * every command that reads one back.
52
+ *
53
+ * It used to fire on the read path too, which meant once per process, which
54
+ * means once per command — every read, list, or search printed it on stderr.
55
+ * That is noise in a terminal and permanently in an agent transcript, and it
56
+ * told nobody anything they could act on at that moment. The storage mode is
57
+ * reported instead by `jsn auth status`, and the warning is emitted when the
58
+ * choice is actually made (login, setup, token save).
59
+ */
49
60
  let plaintextWarningShown = false;
50
61
  function warnPlaintext() {
51
62
  if (plaintextWarningShown) return;
@@ -251,7 +262,6 @@ export function loadCredentials(instance, username, injectedStore) {
251
262
  // Reads (including local status) never persist or migrate credentials. A
252
263
  // subsequent explicit login/save or token refresh performs verified retirement.
253
264
  if (!plaintextAllowed()) throw refusal();
254
- warnPlaintext();
255
265
  const creds = readPrivateState('credentials', key);
256
266
  return creds ? { ...creds, auth_source: 'file' } : null;
257
267
  }
@@ -278,10 +288,28 @@ export function saveCredentials(instance, creds, username, injectedStore) {
278
288
  return;
279
289
  }
280
290
  if (!plaintextAllowed()) throw secureFailure || refusal();
281
- warnPlaintext();
291
+ // Re-stamping last_seen after a successful call is bookkeeping, not a storage
292
+ // decision. Warning on it put the message on every command again, which is
293
+ // what this change is meant to stop; only a change to the secret material
294
+ // (a real login or token refresh) is worth the warning.
295
+ if (materialChanged(key, creds)) warnPlaintext();
282
296
  writePrivateState('credentials', key, creds);
283
297
  }
284
298
 
299
+ /** True when the incoming credential material differs from what is on disk. */
300
+ function materialChanged(key, creds) {
301
+ let previous;
302
+ try { previous = readPrivateState('credentials', key); } catch { return true; }
303
+ if (!previous) return true;
304
+ const material = (value) => {
305
+ // last_seen is bookkeeping; auth_source is derived by the loader and never
306
+ // part of the stored secret.
307
+ const { last_seen: _seen, auth_source: _source, ...rest } = value || {};
308
+ return JSON.stringify(rest, Object.keys(rest).sort());
309
+ };
310
+ return material(previous) !== material(creds);
311
+ }
312
+
285
313
  /**
286
314
  * Delete credentials for an instance keyed by <username>@<instance>.
287
315
  */
@@ -144,7 +144,20 @@ export class LocalCLI {
144
144
  onParentDiscovery(fn) { this.parentDiscovery = fn; return this; }
145
145
  demandCommand(count, message) { this.root.demand = { count, message }; return this; }
146
146
  help() { this.helpEnabled = true; return this; }
147
- version() { return this; }
147
+ /**
148
+ * `--version`: print the tool's version and exit.
149
+ *
150
+ * A command's own version comes from the package manifest, so the root flag
151
+ * has to be answered by the parser before dispatch. `.version(false)` (used
152
+ * by the previous `jsn --version` wiring) silently removed the flag, so the
153
+ * token was tolerated as an unknown option and the page fell through to the
154
+ * root help — a script or agent asking "what version is this?" got 2 KB of
155
+ * help text instead of a version string.
156
+ */
157
+ version(value = false) {
158
+ this.versionText = value === false ? undefined : String(value);
159
+ return this;
160
+ }
148
161
  strictCommands() { this.strictCmd = true; return this; }
149
162
  strictOptions() { return this; }
150
163
  fail(fn) { this.failHandler = fn; return this; }
@@ -443,6 +456,13 @@ export class LocalCLI {
443
456
  const node = path.at(-1) || this.root;
444
457
  node.build();
445
458
  if (commandArgs.includes('--help') || commandArgs.includes('-h')) { this._help(node, path.map((n) => n.name)); return; }
459
+ // The root `--version` flag is answered here, before any command dispatch
460
+ // or demand-command failure, so `jsn --version` is a one-line answer.
461
+ if (this.versionText !== undefined && !path.length
462
+ && (commandArgs.includes('--version') || commandArgs.includes('-V'))) {
463
+ process.stdout.write(`${this.versionText}\n`);
464
+ return;
465
+ }
446
466
  const firstWord = this.args.find((arg, index) => !discoveryConsumed.has(index) && !arg.startsWith('-'));
447
467
  if (this.strictCmd && !path.length && firstWord && !this._lookup(this.root.children, firstWord)) {
448
468
  return this._fail(`Unknown command: ${firstWord}`);
package/src/cli.js CHANGED
@@ -486,8 +486,9 @@ export function buildCLI() {
486
486
  })(argv);
487
487
  })
488
488
  .epilogue(renderTips())
489
+ .option('version', { type: 'boolean', alias: 'V', describe: 'Show the jsn version' })
489
490
  .help('help', 'Show help')
490
- .version(false)
491
+ .version(getVersion())
491
492
  .strictCommands()
492
493
  .strictOptions(false)
493
494
  .fail((msg, err) => {
@@ -33,7 +33,7 @@ declareCapabilities('midservers', { mutationContext: 'operational', mutationSubc
33
33
  export const midserversCmd = wrap => ({ ...midserversCmdDefinition, load: () => require('./commands/midservers.js').midserversCmd(wrap) });
34
34
 
35
35
  export const subscriptionsCmdDefinition = {
36
- command: 'subscriptions [subcommand]', describe: 'Inspect local metering schedules and compare illustrative ITOM populations',
36
+ command: 'subscriptions [subcommand]', describe: 'Inspect subscription evidence, local schedules and illustrative ITOM populations',
37
37
  };
38
38
  declareCapabilities('subscriptions', { noInstance: true, skipDailyChecks: true, mutationSubcommands: [] });
39
39
  export const subscriptionsCmd = wrap => ({ ...subscriptionsCmdDefinition, load: () => require('./commands/subscriptions.js').subscriptionsCmd(wrap) });
@@ -65,6 +65,17 @@ export function renderAuthStatus(result, summary, { details = false } = {}) {
65
65
  if (profiles.some(profile => profile.read_only !== true)) lines.push(' Read/write: permits profile operations, subject to each command\'s guards.');
66
66
  if (profiles.some(profile => profile.skip_confirmations !== true)) lines.push(' Confirm: guarded deletes require confirmation; --force bypasses this prompt, not read-only.');
67
67
  if (profiles.some(profile => profile.skip_confirmations === true)) lines.push(' No prompt: profile skips standard delete confirmation; command-specific safeguards still apply.');
68
+ // Storage mode is a standing property of a profile, so it belongs in status
69
+ // rather than in a warning repeated on every command that reads credentials.
70
+ const plaintextProfiles = profiles.filter(profile => profile.auth_source === 'file' || profile.diagnostics?.auth_source === 'file');
71
+ if (plaintextProfiles.length) {
72
+ lines.push('', 'Credential storage:');
73
+ for (const profile of plaintextProfiles) {
74
+ const label = profile.name || 'profile';
75
+ lines.push(` ${label}: portable plaintext file; backups and copies can expose it.`
76
+ + ` Move it to the OS credential store: jsn auth login --profile ${quoteShellArg(label)}`);
77
+ }
78
+ }
68
79
  lines.push('ACCESS is a JSN profile setting, not ServiceNow ACL authorization.',
69
80
  'CREDENTIALS describes local availability; only CONNECTION Verified confirms the status probe succeeded.');
70
81
  if (profiles.some(profile => profile.diagnostics?.probe?.code === 'not_requested')) lines.push('', 'Connection not checked (--local).');
@@ -1,4 +1,5 @@
1
1
  import { subscriptionsCmdDefinition } from '../command-families.js';
2
+ import { subscriptionEvidence, formatSubscriptionEvidence, evidenceLimit } from '../subscription-evidence.js';
2
3
  import { refreshSchedules } from '../schedule-cache.js';
3
4
  import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
5
 
@@ -22,7 +23,16 @@ export function subscriptionsCmd(wrap) {
22
23
  };
23
24
  return {
24
25
  ...subscriptionsCmdDefinition,
25
- builder: y => y.command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
+ builder: y => y.command({ command: 'evidence', describe: 'Show subscription evidence and installed-app hints (read-only)',
27
+ builder: b => b.option('limit', { type: 'number', default: 50, describe: 'Maximum observations per source (integer 1–200)' }),
28
+ handler: wrap(async (argv, app) => {
29
+ const limit = evidenceLimit(argv.limit);
30
+ app.requireInstance();
31
+ const report = await subscriptionEvidence(app.sdk, { limit });
32
+ Object.defineProperty(report, '_formatted', { value: formatSubscriptionEvidence(report) });
33
+ app.ok(report, { summary: 'Bounded instance evidence; contractual authority and completeness unverified' });
34
+ }),
35
+ }).command({ command: 'refresh', describe: 'Explicitly download and validate schedule catalog; retain last-good on failure', builder: b => b.option('manifest-url', { type: 'string' }), handler: wrap(async (argv, app) => {
26
36
  const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
37
  const manifest = argv.manifestUrl || process.env.JSN_SCHEDULES_MANIFEST_URL || app.config?.docs?.schedule_manifest_url || (origin ? new URL('/subscription-schedules/v1/manifest.json', origin).href : undefined);
28
38
  const provenance = await refreshSchedules(manifest);
@@ -1,9 +1,12 @@
1
1
  // Intent comes from the task, never from the current provider preferences.
2
2
  import { assertSafeExactMatch, getStringField } from './helpers.js';
3
3
  import { errUsageHint } from './errors.js';
4
+ import { readEffectiveUpdateSet } from './context.js';
4
5
 
5
- export function contextFailure(message) {
6
- return errUsageHint(message, 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.');
6
+ const CONTEXT_HINT = 'Supply --expect-scope and --expect-update-set from the task. Select context explicitly with scopes set / updatesets set, then retry. --force never overrides missing or mismatched intent.';
7
+
8
+ export function contextFailure(message, hint = CONTEXT_HINT) {
9
+ return errUsageHint(message, hint);
7
10
  }
8
11
  const raw = (record, key) => record?.[key]?.value ?? record?.[key];
9
12
  export async function exactContextRecord(sdk, table, field, identifier) {
@@ -25,14 +28,74 @@ export async function readWriteContext(sdk) {
25
28
  }));
26
29
  if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
27
30
  const user = { sys_id: raw(users[0], 'sys_id'), user_name: getStringField(users[0], 'user_name') };
28
- async function preference(name) {
29
- const rows = await sdk.list('sys_user_preference', new URLSearchParams({
30
- sysparm_query: `user=${user.sys_id}^name=${name}`, sysparm_limit: '2', sysparm_fields: 'value',
31
- }));
32
- if (rows.length !== 1 || !raw(rows[0], 'value') || raw(rows[0], 'value') === '-') throw contextFailure(`Current ${name} preference is unknown.`);
31
+ /**
32
+ * Read one persisted capture-context preference.
33
+ *
34
+ * A missing row is not the same failure as an unreadable one. On a fresh
35
+ * instance nobody has ever picked an update set, so there is genuinely
36
+ * nothing to verify a customization write against — and the old message
37
+ * ("Current sys_update_set preference is unknown") named an internal
38
+ * preference key and pointed at --expect-* flags that cannot create a
39
+ * selection. An agent following that hint retries the same dead end. Each
40
+ * branch below says what is actually wrong and names the command that fixes
41
+ * it.
42
+ */
43
+ async function preference({ key, label, remediation, sessionTruth }) {
44
+ let rows;
45
+ try {
46
+ rows = await sdk.list('sys_user_preference', new URLSearchParams({
47
+ sysparm_query: `user=${user.sys_id}^name=${key}`, sysparm_limit: '2', sysparm_fields: 'value',
48
+ }));
49
+ } catch (error) {
50
+ throw contextFailure(
51
+ `Could not read the persisted ${label} for ${user.user_name}: ${error.message}`,
52
+ `Confirm the instance is reachable and retry. Do not retry the write until the selection can be read.`,
53
+ );
54
+ }
55
+ if (rows.length === 0) {
56
+ throw contextFailure(
57
+ `No ${label} is selected for ${user.user_name}, so there is no capture context to verify this write against.${await sessionNote(sessionTruth)}`,
58
+ `Select one first, then rerun the same command: ${remediation}. --expect-scope and --expect-update-set assert an existing selection; they cannot create one.`,
59
+ );
60
+ }
61
+ if (rows.length > 1) {
62
+ throw contextFailure(
63
+ `${rows.length} persisted ${label} preferences exist for ${user.user_name}, so the capture context is ambiguous.`,
64
+ `Resolve the duplicate preferences for this user, then retry: ${remediation}`,
65
+ );
66
+ }
67
+ if (!raw(rows[0], 'value') || raw(rows[0], 'value') === '-') {
68
+ throw contextFailure(
69
+ `The ${label} for ${user.user_name} is saved but empty, so the capture context is unreadable.`,
70
+ `Select one again, then rerun the same command: ${remediation}`,
71
+ );
72
+ }
33
73
  return raw(rows[0], 'value');
34
74
  }
35
- const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
75
+ // Failure-path diagnostic only: the provider's session picker is a different
76
+ // source from the persisted preference, and saying so stops an agent from
77
+ // assuming a fresh session already has a set selected.
78
+ async function sessionNote(readSession) {
79
+ if (!readSession) return '';
80
+ try {
81
+ const effective = await readSession();
82
+ if (!effective?.sys_id) return '';
83
+ return `\nThe session picker reports "${effective.label || effective.name || effective.sys_id}" (${effective.sys_id}); that selection is not persisted for this user and is not used for a customization write.`;
84
+ } catch {
85
+ return '';
86
+ }
87
+ }
88
+ const [scopeId, setId] = await Promise.all([
89
+ preference({
90
+ key: 'apps.current_app', label: 'application scope',
91
+ remediation: 'jsn scopes set "<scope value or name>"',
92
+ }),
93
+ preference({
94
+ key: 'sys_update_set', label: 'update set',
95
+ remediation: 'jsn updatesets set "<update set name>"',
96
+ sessionTruth: () => readEffectiveUpdateSet(sdk),
97
+ }),
98
+ ]);
36
99
  const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
37
100
  const applicationId = raw(set, 'application');
38
101
  if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
@@ -48,7 +48,14 @@ export async function guardMutationContext(app, argv, { ask = confirm, rawArgs =
48
48
  }
49
49
  let context;
50
50
  try { context = await readWriteContext(app.sdk); }
51
- catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
51
+ catch (error) {
52
+ // A structured failure already explains which selection is missing and
53
+ // which command fixes it. Prefixing it with "Cannot verify capture
54
+ // context" buried that remediation and replaced it with the generic
55
+ // --expect-* hint, which cannot create a selection.
56
+ if (error?.hint) throw error;
57
+ throw contextFailure(`Cannot verify capture context: ${error.message}`);
58
+ }
52
59
  if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
53
60
  const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
54
61
  if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
@@ -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
+ }