@jacebenson/jsn 5.5.7 → 5.5.8

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.
Files changed (63) hide show
  1. package/README.md +16 -1
  2. package/package.json +5 -6
  3. package/skills/servicenow/SKILL.md +9 -1
  4. package/src/app.js +4 -79
  5. package/src/bounded-reads.js +13 -0
  6. package/src/capabilities.js +8 -3
  7. package/src/cli-adapter.js +26 -3
  8. package/src/cli.js +13 -14
  9. package/src/command-families.js +68 -0
  10. package/src/commands/_generic.js +1 -0
  11. package/src/commands/_ticket.js +1 -1
  12. package/src/commands/actions.js +9 -4
  13. package/src/commands/approvals.js +1 -1
  14. package/src/commands/atf.js +1 -1
  15. package/src/commands/attachments.js +1 -1
  16. package/src/commands/auth.js +21 -2
  17. package/src/commands/codesearch.js +11 -2
  18. package/src/commands/compare.js +22 -0
  19. package/src/commands/customizations.js +3 -4
  20. package/src/commands/decisiontables.js +4 -0
  21. package/src/commands/docs/docs.js +5 -5
  22. package/src/commands/domains.js +1 -1
  23. package/src/commands/eval.js +11 -5
  24. package/src/commands/flows.js +24 -7
  25. package/src/commands/groupmembers.js +1 -1
  26. package/src/commands/grouproles.js +1 -1
  27. package/src/commands/groups.js +1 -1
  28. package/src/commands/midservers.js +4 -11
  29. package/src/commands/perf.js +2 -3
  30. package/src/commands/plugins.js +9 -0
  31. package/src/commands/records.js +12 -2
  32. package/src/commands/scopes.js +1 -1
  33. package/src/commands/scrapi.js +2 -2
  34. package/src/commands/setup.js +4 -34
  35. package/src/commands/skipped-updates.js +2 -3
  36. package/src/commands/store.js +4 -1
  37. package/src/commands/subscriptions.js +47 -0
  38. package/src/commands/tickets.js +1 -1
  39. package/src/commands/users.js +1 -1
  40. package/src/commands/workflows.js +3 -5
  41. package/src/config.js +1 -0
  42. package/src/context.js +8 -56
  43. package/src/docs-links.js +28 -0
  44. package/src/flow-create.js +9 -0
  45. package/src/help.js +4 -0
  46. package/src/helpers.js +17 -24
  47. package/src/instance-inventory.js +184 -0
  48. package/src/intended-context.js +68 -0
  49. package/src/mutation-context.js +69 -46
  50. package/src/output.js +1 -1
  51. package/src/paginated-search.js +146 -178
  52. package/src/picker-ui.js +20 -0
  53. package/src/prompt-engine.js +176 -0
  54. package/src/prompts.js +293 -43
  55. package/src/records/inspect.js +30 -16
  56. package/src/records-engine.js +2 -2
  57. package/src/schedule-cache.js +96 -0
  58. package/src/schedules/itom-2026-04-09.json +121 -0
  59. package/src/schedules/public-inventory.json +6224 -0
  60. package/src/sdk-batch.js +2 -1
  61. package/src/sdk.js +42 -16
  62. package/src/setup-preferences.js +2 -2
  63. package/src/subscriptions.js +176 -0
@@ -0,0 +1,47 @@
1
+ import { subscriptionsCmdDefinition } from '../command-families.js';
2
+ import { refreshSchedules } from '../schedule-cache.js';
3
+ import { loadSchedule, scheduleCatalog, scheduleSnapshot, formatSchedule, estimateSubscription, formatEstimate } from '../subscriptions.js';
4
+
5
+
6
+ export function subscriptionsCmd(wrap) {
7
+ const local = (argv, app) => {
8
+ const snapshot = scheduleSnapshot();
9
+ const schedules = scheduleCatalog({ product: argv.product, sku: argv.sku, id: argv.id, snapshot });
10
+ const data = { provenance: snapshot.provenance, schedules, coverage: { index_documents: new Set(snapshot.schedules.map(s => s.source_url)).size, archive: 'unavailable', sku_mapping: 'only explicitly normalized codes; empty results do not establish absence of rights' } };
11
+ Object.defineProperty(data, '_formatted', { value: [
12
+ `Local catalog snapshot (${data.provenance.source}; ${data.provenance.freshness}; revision ${data.provenance.revision || 'bundled'}; retrieved ${data.provenance.retrieved_at || 'bundled'}; stale ${data.provenance.stale}); contractual applicability unverified. Archive unavailable.`,
13
+ ...schedules.flatMap(s => [
14
+ `${s.id} | ${s.product} | ${s.effective_date || s.source_version || 'date unverified'} | ${s.normalization_status || 'not specified'}`,
15
+ s.source_url,
16
+ `Measurement: ${s.measurement || 'not specified; inspection only'}. SKU mapping: ${(s.skus || []).join(', ') || 'unverified'}`,
17
+ ...(s.unknowns || s.limitations || []),
18
+ ...(argv.id ? [formatSchedule(s)] : []),
19
+ ]),
20
+ ].join('\n') });
21
+ app.ok(data, { summary: 'Local dated metering schedules, not purchased rights' });
22
+ };
23
+ return {
24
+ ...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
+ const origin = process.env.JSN_DOCS_URL || app.config?.docs?.url;
27
+ 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
+ const provenance = await refreshSchedules(manifest);
29
+ app.ok({ provenance }, { summary: 'Validated schedule cache refreshed' });
30
+ }) }).command({ command: 'schedules', describe: 'Inspect validated cache or bundled source-backed schedules offline', builder: b => b.option('product', { type: 'string' }).option('sku', { type: 'string' }).option('id', { type: 'string' }), handler: wrap(local) })
31
+ .command({ command: 'estimate <product>', describe: 'Read-only ITOM population comparison, not billing or a 90-day meter',
32
+ builder: b => b.positional('product', { type: 'string', describe: 'ITOM; arbitrary SKUs and HRSD unsupported' })
33
+ .option('schedule', { type: 'string', describe: 'Explicit dated schedule ID from subscriptions schedules' })
34
+ .option('assume-eligible', { type: 'boolean', default: false, describe: 'Hypothetically treat mapped populations as managed and component-eligible, exclusions unknown' }),
35
+ handler: wrap(async (argv, app) => {
36
+ // Validate unsupported selections before requesting an instance.
37
+ const selected = loadSchedule(argv.schedule);
38
+ if (String(argv.product).toUpperCase() !== 'ITOM' || selected.measurement !== 'illustrative-population') await estimateSubscription(null, argv.product, { schedule: argv.schedule });
39
+ app.requireInstance();
40
+ const report = await estimateSubscription(app.sdk, argv.product, { schedule: argv.schedule, assumeEligible: argv.assumeEligible });
41
+ Object.defineProperty(report, '_formatted', { value: formatEstimate(report) });
42
+ app.ok(report, { summary: 'Incomplete illustrative ITOM population comparison; no authoritative total' });
43
+ }),
44
+ }),
45
+ handler: wrap(local),
46
+ };
47
+ }
@@ -4,7 +4,7 @@ import { getRecord, listRecords, recordListParams, createRecord, updateRecord, d
4
4
  import { resolveSysId } from '../resolve-record.js';
5
5
  import { declareCapabilities } from '../capabilities.js';
6
6
 
7
- declareCapabilities('tickets', { mutationSubcommands: ['create', 'update', 'delete'] });
7
+ declareCapabilities('tickets', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
8
8
 
9
9
  export function ticketsCmd(wrap) {
10
10
  return {
@@ -2,7 +2,7 @@ import { formatRecordForDisplay, getStringField, interactiveList, resolveFieldsP
2
2
  import { resolveRecord, resolveSysId } from '../resolve-record.js';
3
3
  import { declareCapabilities } from '../capabilities.js';
4
4
 
5
- declareCapabilities('users', { mutationSubcommands: ['create', 'update', 'delete'] });
5
+ declareCapabilities('users', { mutationContext: 'operational', mutationSubcommands: ['create', 'update', 'delete'] });
6
6
 
7
7
  export function usersCmd(wrap) {
8
8
  return {
@@ -1,4 +1,4 @@
1
- import { declareCapabilities } from '../capabilities.js';
1
+ import { workflowsCmdDefinition } from '../command-families.js';
2
2
  import { errUsage } from '../errors.js';
3
3
  import {
4
4
  inspectWorkflow,
@@ -11,7 +11,7 @@ import {
11
11
  // request in workflow-inspection.js is a Table API GET. Declaring no mutation
12
12
  // subcommands keeps the mutation guard and read-only profiles aligned with
13
13
  // what the command can actually do.
14
- declareCapabilities('workflows', { mutationSubcommands: [] });
14
+
15
15
 
16
16
  // A curated human view belongs to the command; keeping it non-enumerable
17
17
  // leaves the JSON envelope free of presentation text.
@@ -42,9 +42,7 @@ export function selectWorkflowStep(data, number) {
42
42
 
43
43
  export function workflowsCmd(wrap) {
44
44
  return {
45
- command: 'workflows [subcommand]',
46
- aliases: ['workflow'],
47
- describe: 'Inspect legacy Workflow Editor workflows (read-only)',
45
+ ...workflowsCmdDefinition,
48
46
  builder: (yargs) => yargs
49
47
  .command({
50
48
  command: 'list',
package/src/config.js CHANGED
@@ -58,6 +58,7 @@ function loadFromFile(cfg, filePath, source) {
58
58
  if (fileCfg.connection_defaults && typeof fileCfg.connection_defaults === 'object') cfg.connectionDefaults = fileCfg.connection_defaults;
59
59
  if (fileCfg.docs && typeof fileCfg.docs === 'object') cfg.docs = fileCfg.docs;
60
60
  }
61
+ if (source === 'local' && Object.hasOwn(fileCfg, 'write_context')) cfg.writeContext = fileCfg.write_context;
61
62
  if (fileCfg.instance_url) {
62
63
  cfg.instanceURL = fileCfg.instance_url;
63
64
  cfg.sources.instance_url = source;
package/src/context.js CHANGED
@@ -122,62 +122,14 @@ export async function readEffectiveUpdateSet(sdk) {
122
122
  };
123
123
  }
124
124
 
125
- /**
126
- * Make the warmed session's effective capture set match the persisted choice
127
- * before content writes, and verify the result.
128
- *
129
- * A fresh CLI invocation is a fresh authenticated session; the persisted
130
- * preference is the user's intentional choice, but nothing guarantees the new
131
- * session inherited it (`jsn updatesets create`/`set` may have selected the set
132
- * in a session that has since ended). When the two disagree, re-apply the
133
- * persisted selection through the same picker contract and verify it.
134
- *
135
- * Returns a report instead of throwing when the effective selection cannot be
136
- * read at all (for example an auth mode that cannot keep a UI session). A
137
- * readable-but-unalignable mismatch throws, so a content write never proceeds
138
- * into a set the CLI would then wrongly report.
139
- */
125
+ /** Verify capture consistency without ever changing the session. */
140
126
  export async function alignUpdateSetCapture(sdk, intended) {
141
- const intendedId = intended?.sys_id || '';
142
- let effective;
143
- try {
144
- effective = await readEffectiveUpdateSet(sdk);
145
- } catch (error) {
146
- return {
147
- intended: intended || null,
148
- effective: null,
149
- aligned: null,
150
- action: 'unverified',
151
- reason: `effective session selection could not be read: ${error.message}`,
152
- };
153
- }
154
- const report = { intended: intended || null, effective, aligned: null, action: 'none' };
155
- if (!intendedId) {
156
- report.reason = 'no persisted update-set selection (Default or unreadable preference)';
157
- return report;
158
- }
159
- if (effective.sys_id === intendedId) {
160
- report.aligned = true;
161
- return report;
162
- }
163
- try {
164
- await setCurrentUpdateSet(sdk, null, intendedId);
165
- } catch (error) {
166
- const message = `Session capture context could not be aligned with the selected update set before any content write. `
167
- + `This session resolves to ${effective.sys_id || 'an empty selection'} (${effective.name || 'unknown'}), `
168
- + `but the persisted selection is ${intended?.name || intendedId} (${intendedId}). ${error.message} `
169
- + 'No content was written. Re-select explicitly with `jsn updatesets set` in an interactive session, '
170
- + 'or use an auth profile that keeps a UI session, then retry.';
171
- const failure = new Error(message, { cause: error });
172
- failure.capture_context = { ...report, aligned: false, action: 'select_failed' };
173
- throw failure;
174
- }
175
- report.previous_effective = effective;
176
- report.effective = await readEffectiveUpdateSet(sdk);
177
- report.action = 'selected';
178
- report.aligned = report.effective.sys_id === intendedId;
179
- if (!report.aligned) {
180
- report.reason = 'session still resolves to a different set after re-selection';
127
+ const effective = await readEffectiveUpdateSet(sdk);
128
+ const report = { intended: intended || null, effective, aligned: false, action: 'refused' };
129
+ if (!intended?.sys_id || effective.sys_id !== intended.sys_id) {
130
+ const error = new Error('Effective capture set differs from the persisted selection or is unknown. No context was switched; select it explicitly with jsn updatesets set.');
131
+ error.capture_context = report;
132
+ throw error;
181
133
  }
182
- return report;
134
+ return { ...report, aligned: true, action: 'none' };
183
135
  }
@@ -0,0 +1,28 @@
1
+ // GENERATED FILENAME: keep in sync with site/config/docs-links.json.
2
+ // The npm package ships only cli/, so this projection is checked in and verified
3
+ // by site/test/docs_links_test.rb. Edit the registry, then regenerate this file.
4
+ export const SITE_ORIGIN = 'https://jsn.jace.pro';
5
+ export const ROOT_DOC_LINK = '/docs/';
6
+ export const DOC_LINKS = Object.freeze({
7
+ codesearch: '/features/servicenow-code-search-cli/',
8
+ docs: '/docs/cli-guide/#jsn-cli-guide',
9
+ flows: '/docs/flows/#flow-definition-search',
10
+ records: '/docs/records/#watching-a-servicenow-record',
11
+ updatesets: '/docs/updatesets/#transfer-an-update-set',
12
+ midservers: '/docs/midservers/#remote-mid-management-over-ssh',
13
+ setup: '/docs/setup/#connect-an-instance',
14
+ auth: '/docs/setup/#authentication-lifecycle-review',
15
+ skill: '/docs/agents/#use-jsn-with-ai-agents',
16
+ });
17
+
18
+ /** Absolute documentation URL for one registered command family, or null when
19
+ * the family has no migrated guide. Callers decide how to render a miss. */
20
+ export function resolveDocLink(name) {
21
+ const path = DOC_LINKS[name];
22
+ return path ? `${SITE_ORIGIN}${path}` : null;
23
+ }
24
+
25
+ /** Absolute documentation URL for one registered command family. */
26
+ export function docLink(name) {
27
+ return resolveDocLink(name) || `${SITE_ORIGIN}${ROOT_DOC_LINK}`;
28
+ }
@@ -1914,6 +1914,10 @@ async function planManifestSteps({ manifest, beforeDefinition, existingActions,
1914
1914
  export async function createFlowFromManifest(sdk, instance, inputManifest, options = {}) {
1915
1915
  const manifest = validateFlowManifest(inputManifest);
1916
1916
  const scope = manifest.scope;
1917
+ if (sdk.mutationContext?.verified) {
1918
+ const { assertMutationScope } = await import('./intended-context.js');
1919
+ assertMutationScope(sdk.mutationContext, scope, 'Flow creation transaction');
1920
+ }
1917
1921
  const idFactory = options.idFactory || (() => randomUUID());
1918
1922
  const readUpdateSet = options.readUpdateSet || (async () => null);
1919
1923
  const snapshots = [];
@@ -2141,6 +2145,11 @@ export async function updateFlowFromManifest(sdk, instance, identifier, inputMan
2141
2145
  const published = !lifecycle.draft;
2142
2146
  const targetScope = stringValue(target.flow.sys_scope) || stringValue(target.flow.scope);
2143
2147
  const scope = manifest.scope ?? targetScope;
2148
+ if (sdk.mutationContext?.verified) {
2149
+ const { assertMutationScope } = await import('./intended-context.js');
2150
+ assertMutationScope(sdk.mutationContext, targetScope, 'Resolved flow target');
2151
+ assertMutationScope(sdk.mutationContext, scope, 'Flow update transaction');
2152
+ }
2144
2153
  const readUpdateSet = options.readUpdateSet || (async () => null);
2145
2154
  if (!scope) throw new Error(`Flow ${flowId} has no transaction scope`);
2146
2155
  if (manifest.scope !== undefined && targetScope && manifest.scope !== targetScope) throw new Error(`Flow ${flowId} scope does not match the update manifest`);
package/src/help.js CHANGED
@@ -10,6 +10,8 @@
10
10
  // (`approvals`, `cmdb`, `docs`, `perf`, `platform`, … were missing from the
11
11
  // hand-written list while being fully registered).
12
12
 
13
+ import { SITE_ORIGIN, ROOT_DOC_LINK } from './docs-links.js';
14
+
13
15
  const COMMON_COMMANDS = [
14
16
  'incidents', 'requests', 'tasks', 'changes', 'approvals', 'knowledge', 'records', 'setup', 'discover',
15
17
  ];
@@ -23,6 +25,7 @@ const CONCISE_EXAMPLES = [
23
25
  ];
24
26
 
25
27
  const CONCISE_MORE = [
28
+ { label: `${SITE_ORIGIN}${ROOT_DOC_LINK}`, description: 'Guides: install, setup, safety, output, agents and feature references' },
26
29
  { label: 'jsn <command> <action> --help', description: 'Options for one command or action' },
27
30
  { label: 'jsn discover <word>', description: 'Find commands by task words' },
28
31
  { label: 'jsn discover --table <table>', description: 'Find commands configured for a table' },
@@ -289,6 +292,7 @@ TIPS
289
292
  "jsn --json" prints the registered command surface as JSON for scripts and agents
290
293
 
291
294
  LEARN MORE
295
+ Documentation and feature references: https://jsn.jace.pro/docs/
292
296
  Some list commands offer a picker in an interactive terminal with automatic output.
293
297
  Arrow keys browse (10 visible items); type to search; scroll to load more; Enter selects; Esc cancels.
294
298
  Picker eligibility and search fields vary by command. Explicit output formats (including --json) skip pickers.
package/src/helpers.js CHANGED
@@ -448,31 +448,24 @@ export async function interactiveList({ app, table, singular, columns, limit = 5
448
448
 
449
449
  // Paginated source adapter: (term, offset, { signal }) => choices[]
450
450
  async function serverSource(term, offset, { signal: _signal } = {}) {
451
- try {
452
- const params = new URLSearchParams();
453
- params.set('sysparm_limit', String(limit));
454
- params.set('sysparm_display_value', 'all');
455
- if (pickerFields) params.set('sysparm_fields', pickerFields);
456
- if (term) {
457
- params.set('sysparm_query', `${baseQuery}${labelField}LIKE${term}^ORDERBYDESCsys_updated_on`);
458
- } else {
459
- params.set('sysparm_query', baseQuery + 'ORDERBYDESCsys_updated_on');
460
- params.set('sysparm_offset', String(offset));
461
- }
462
- const records = await app.sdk.list(table, params);
463
- if (!Array.isArray(records)) {
464
- console.error('SDK non-array:', typeof records);
465
- return [];
466
- }
467
- return records.map(r => ({
468
- name: formatLabel ? formatLabel(r) : (getStringField(r, labelField) || getStringField(r, 'sys_id')),
469
- value: formatValue ? formatValue(r) : r,
470
- }));
471
- } catch (err) {
472
- if (isTerminalAuthError(err)) throw err;
473
- console.error('serverSource error:', err.message || err);
474
- return [];
451
+ const params = new URLSearchParams();
452
+ params.set('sysparm_limit', String(limit));
453
+ params.set('sysparm_display_value', 'all');
454
+ if (pickerFields) params.set('sysparm_fields', pickerFields);
455
+ if (term) {
456
+ params.set('sysparm_query', `${baseQuery}${labelField}LIKE${term}^ORDERBYDESCsys_updated_on`);
457
+ } else {
458
+ params.set('sysparm_query', baseQuery + 'ORDERBYDESCsys_updated_on');
459
+ params.set('sysparm_offset', String(offset));
475
460
  }
461
+ // Only a successful empty page means exhausted. Let the picker render
462
+ // failures and retry this offset; preserve terminal auth errors unchanged.
463
+ const records = await app.sdk.list(table, params);
464
+ if (!Array.isArray(records)) throw new Error(`Could not list ${table}: list returned a non-array result`);
465
+ return records.map(r => ({
466
+ name: formatLabel ? formatLabel(r) : (getStringField(r, labelField) || getStringField(r, 'sys_id')),
467
+ value: formatValue ? formatValue(r) : r,
468
+ }));
476
469
  }
477
470
 
478
471
  const selected = await prompt({
@@ -0,0 +1,184 @@
1
+ import { resolveSession } from './session.js';
2
+ import { errUsage } from './errors.js';
3
+ import { listApplications } from './store.js';
4
+
5
+ export async function readObservedStoreApps(sdk, maxPages, tableFailure) {
6
+ const items = new Map(), localIds = new Set();
7
+ const coverage = { table: 'sn_appclient/appmanager/apps', tab: 'installed', status: 'unknown', fetched: 0, total: null, reason: 'no_provider_total', table_failure: tableFailure, observed_items_usable: true, exhaustion: 'not_reached' };
8
+ try {
9
+ for (let page = 0; page < maxPages; page++) {
10
+ // Reuse the production Store discovery transport. Its page_full is a
11
+ // client heuristic, NOT provider has_more or an exhaustiveness guarantee.
12
+ const result = await listApplications(sdk, { tab: 'installed', limit: 200, offset: coverage.fetched });
13
+ if (!result.apps.length) { coverage.exhaustion = 'empty_page_observed'; return { items, coverage }; }
14
+ if (result.apps.length > 200) throw Object.assign(new Error(), { code: 'invalid_page_size' });
15
+ for (const row of result.apps) {
16
+ if (!row.scope?.trim() || !row.sys_id?.trim() || !row.name?.trim() || !row.version?.trim()) throw Object.assign(new Error(), { code: 'missing_fields' });
17
+ if (items.has(row.scope) || localIds.has(row.sys_id)) throw Object.assign(new Error(), { code: 'duplicate_or_invalid_identity' });
18
+ localIds.add(row.sys_id);
19
+ items.set(row.scope, { id: row.scope, name: row.name, version: row.version, available_version: row.latest_version, active: null, installed: true, installation_evidence: 'appclient_installed_tab', observation_verified: true });
20
+ coverage.fetched++;
21
+ }
22
+ }
23
+ coverage.reason = 'page_limit_no_provider_total';
24
+ } catch (error) {
25
+ coverage.reason = error.status === 403 ? 'forbidden' : error.code || 'unreadable_source';
26
+ coverage.observed_items_usable = false;
27
+ }
28
+ return { items, coverage };
29
+ }
30
+
31
+
32
+ // Separate inventories: a Store application may also expose platform plugins.
33
+ // Neither inventory is a substitute for the other; custom sys_app rows are excluded.
34
+ export const inventorySources = {
35
+ plugins: { table: 'v_plugin', key: 'id', fields: ['sys_id', 'id', 'name', 'version', 'active'] },
36
+ store: { table: 'sys_store_app', key: 'scope', fields: ['sys_id', 'scope', 'name', 'version', 'active', 'install_date'] },
37
+ };
38
+ const text = value => {
39
+ const raw = value && typeof value === 'object' ? value.value : value;
40
+ return typeof raw === 'string' ? raw : typeof raw === 'boolean' ? String(raw) : null;
41
+ };
42
+
43
+ export async function readInventory(sdk, kind, maxPages = 30) {
44
+ const source = inventorySources[kind];
45
+ if (!source) throw errUsage('Unknown inventory kind');
46
+ if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100) throw errUsage('--max-pages must be an integer from 1 to 100');
47
+ const coverage = { table: source.table, status: 'unknown', fetched: 0, total: null, reason: null };
48
+ const items = new Map();
49
+ const seen = new Set();
50
+ const countParams = new URLSearchParams({ sysparm_count: 'true' });
51
+ const count = async () => {
52
+ const response = await sdk.request(`${sdk.baseURL}/api/now/stats/${source.table}?${countParams}`, { method: 'GET', ...(kind === 'store' ? { stateful: true } : {}) });
53
+ const value = response?.result?.stats?.count;
54
+ if (value == null || !/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw Object.assign(new Error(), { code: 'unreadable_count' });
55
+ return Number(value);
56
+ };
57
+ try {
58
+ coverage.total = await count();
59
+ for (let page = 0; coverage.fetched < coverage.total && page < maxPages; page++) {
60
+ const rows = await sdk.listStrict(source.table, {
61
+ sysparm_fields: [...source.fields, ...(kind === 'store' ? ['latest_version'] : [])].join(','), sysparm_query: 'ORDERBYsys_id',
62
+ sysparm_display_value: 'false', sysparm_exclude_reference_link: 'true',
63
+ sysparm_limit: 200, sysparm_offset: coverage.fetched,
64
+ }, kind === 'store' ? { stateful: true } : {});
65
+ if (!Array.isArray(rows) || !rows.length || rows.length > 200) throw Object.assign(new Error(), { code: 'unstable_pagination' });
66
+ for (const row of rows) {
67
+ if (!row || source.fields.some(field => !Object.hasOwn(row, field) || text(row[field]) === null)) throw Object.assign(new Error(), { code: 'missing_fields' });
68
+ const key = text(row[source.key]);
69
+ const id = text(row.sys_id);
70
+ if (!key?.trim() || !id?.trim() || seen.has(id) || items.has(key)) throw Object.assign(new Error(), { code: 'duplicate_or_invalid_identity' });
71
+ seen.add(id);
72
+ const active = text(row.active);
73
+ const allowed = kind === 'plugins' ? ['active', 'inactive'] : ['true', 'false'];
74
+ if (!allowed.includes(active)) throw Object.assign(new Error(), { code: 'unknown_state' });
75
+ items.set(key, { id: key, name: text(row.name), version: text(row.version) || null, active: kind === 'plugins' ? active === 'active' : active === 'true', ...(kind === 'store' ? { installed: text(row.version) && text(row.install_date) ? true : null, installation_evidence: text(row.version) && text(row.install_date) ? 'local_version_and_install_date' : 'unknown', available_version: text(row.latest_version) || null } : {}) });
76
+ coverage.fetched++;
77
+ }
78
+ }
79
+ if (coverage.fetched !== coverage.total) throw Object.assign(new Error(), { code: 'page_limit_or_count_mismatch' });
80
+ if (await count() !== coverage.total) throw Object.assign(new Error(), { code: 'count_changed' });
81
+ coverage.status = 'complete';
82
+ } catch (error) {
83
+ // Never include provider text, hostnames or credentials in a comparison report.
84
+ coverage.reason = error.status === 403 ? 'forbidden' : error.status === 401 ? 'auth_error' : error.code || 'unreadable_source';
85
+ }
86
+ if (kind === 'store' && coverage.reason === 'forbidden') return readObservedStoreApps(sdk, maxPages, coverage.reason);
87
+ return { items, coverage };
88
+ }
89
+
90
+ export function recommendAlignment(before, after, reliable, kind) {
91
+ if (!reliable) return [{ action: 'investigate_access', message: 'Investigate source/target access and incomplete coverage before planning changes.' }];
92
+ if (!before) return [{ action: 'review_target_only', message: 'Review or retain target-only item; no automatic removal recommended.' }];
93
+ if (!after) {
94
+ if (kind === 'store' && before.installed === true) return [{ action: 'install', message: `Install Store application on target at source installed version ${before.version}; verify entitlement and compatibility first.` }];
95
+ if (kind === 'plugins' && before.active === true) return [{ action: 'activate', message: `Locate and activate plugin on target to match source; verify availability and dependencies first (source version ${before.version ?? 'unknown'}).` }];
96
+ return [{ action: 'review_presence', message: 'Review source-only item and its installation/activation evidence before planning changes.' }];
97
+ }
98
+ if (kind === 'store' && (before.installed == null || after.installed == null)) return [{ action: 'investigate_installation', message: `Investigate installation evidence before alignment (source local version ${before.version ?? 'unknown'}; target local version ${after.version ?? 'unknown'}). An empty version or install date does not prove not installed.` }];
99
+ const actions = [];
100
+ if (kind === 'store' && before.installed === true && after.installed === false) actions.push({ action: 'install', message: `Install Store application on target at source version ${before.version}; verify entitlement and compatibility first.` });
101
+ if (before.active === true && after.active === false) actions.push({ action: kind === 'plugins' ? 'activate' : 'review_activation', message: kind === 'plugins' ? 'Activate plugin on target to match active source; verify prerequisites first.' : 'Review application activation on target to match active source.' });
102
+ if (before.active === false && after.active === true) actions.push({ action: 'review_activation', message: 'Target is active while source is inactive; review impact rather than automatically deactivating.' });
103
+ if (before.version !== after.version) {
104
+ const parse = value => typeof value === 'string' && /^\d+(?:\.\d+)*$/.test(value) ? value.split('.').map(BigInt) : null;
105
+ const a = parse(before.version), b = parse(after.version);
106
+ let order = 0;
107
+ if (a && b) for (let i = 0; i < Math.max(a.length, b.length); i++) { if ((b[i] ?? 0n) !== (a[i] ?? 0n)) { order = (b[i] ?? 0n) > (a[i] ?? 0n) ? 1 : -1; break; } }
108
+ const versions = `target ${after.version ?? 'unknown'}; source ${before.version ?? 'unknown'}`;
109
+ actions.push({ action: !a || !b || order >= 0 ? 'review_version' : 'align_version', message: !a || !b ? `Review version alignment (${versions}); provider version order is unknown, do not assume downgrade support.` : order > 0 ? `Review newer target version (${versions}); no downgrade recommended.` : order === 0 ? `Review equivalent numeric versions with different provider labels (${versions}).` : `Align target to source version after verifying supported upgrade availability (${versions}).` });
110
+ }
111
+ if (kind === 'store' && before.installed === false && after.installed === true) actions.push({ action: 'review_installation', message: 'Review or retain target installation; no automatic uninstall recommended.' });
112
+ if (!actions.length && (!before.version || !after.version)) actions.push({ action: 'investigate_version', message: 'Investigate missing installed-version evidence.' });
113
+ return actions.length ? actions : [{ action: 'none', message: kind === 'store' && (before.active == null || after.active == null) ? 'Observed installed versions match; no version action needed. Activation is unreported.' : 'No action needed; observed versions and states match.' }];
114
+ }
115
+
116
+ export function compareInventories(source, destination, kind = 'plugins') {
117
+ return [...new Set([...source.items.keys(), ...destination.items.keys()])].sort().map(id => {
118
+ const before = source.items.get(id) || null;
119
+ const after = destination.items.get(id) || null;
120
+ const inventoriesComplete = source.coverage.status === 'complete' && destination.coverage.status === 'complete';
121
+ const observedPair = kind === 'store' && before && after && (source.coverage.status === 'complete' || before.observation_verified === true && source.coverage.observed_items_usable) && (destination.coverage.status === 'complete' || after.observation_verified === true && destination.coverage.observed_items_usable);
122
+ const reliable = inventoriesComplete || observedPair;
123
+ let status = 'unknown';
124
+ const changes = [];
125
+ if (reliable) {
126
+ if (!before) status = 'target_only';
127
+ else if (!after) status = 'source_only';
128
+ else {
129
+ for (const field of ['version', 'active', 'installed']) {
130
+ if (field === 'active' && (before.active == null || after.active == null)) continue;
131
+ if (before[field] !== after[field]) changes.push(field);
132
+ }
133
+ status = kind === 'store' && (before.installed == null || after.installed == null) || before.version === null || after.version === null ? 'unknown' : changes.length ? 'different' : 'matching';
134
+ }
135
+ }
136
+ return { id, name: before?.name || after?.name || id, status, evidence: inventoriesComplete ? 'complete_inventory' : observedPair ? 'observed_pair' : 'incomplete_inventory', changes, before, after, recommendations: recommendAlignment(before, after, reliable, kind) };
137
+ });
138
+ }
139
+
140
+ export function formatInventoryComparison(data, verbose = false) {
141
+ const lines = [`${data.kind}: ${data.source} -> ${data.target} (align TARGET ${data.target} to SOURCE ${data.source})`, data.complete ? 'Complete visible inventories' : 'INCOMPLETE inventory: absences unknown; verified observed pairs can still be compared',
142
+ ...Object.entries(data.coverage).map(([side, c]) => `${side}: ${c.status}, ${c.fetched}/${c.total ?? '?'} rows${c.reason ? ` (${c.reason})` : ''}`),
143
+ `${data.records.length} identities; ${Object.entries(data.counts).map(([key, value]) => `${value} ${key}`).join(', ')}`,
144
+ 'ID | STATUS | SOURCE -> TARGET | WHAT TO DO ON TARGET'];
145
+ const value = item => item ? `${item.version ?? 'version unknown'}, ${item.active === null ? 'activation unknown' : item.active ? 'active' : 'inactive'}${Object.hasOwn(item, 'installed') ? `, ${item.installed == null ? 'installation unknown' : item.installed ? 'installed' : 'not installed'}, available ${item.available_version ?? 'unknown'}` : ''}` : 'not observed';
146
+ const differences = data.records.filter(row => row.status !== 'matching');
147
+ const shown = verbose ? differences : differences.slice(0, 50);
148
+ for (const row of shown) lines.push(`${row.name || row.id} [${row.id}] | ${row.status} | ${value(row.before)} -> ${value(row.after)} | ${row.recommendations.map(item => item.message).join(' ')}`);
149
+ if (shown.length < differences.length) lines.push(`${differences.length - shown.length} additional rows omitted; --verbose shows all differences.`);
150
+ lines.push('Matching rows need no action and are omitted; --json includes all rows. Read-only visible inventory, not entitlement or Store connectivity.');
151
+ return lines.join('\n');
152
+ }
153
+
154
+ export async function compareInstanceInventory(argv, app, kind, emit = true) {
155
+ const targetName = argv.target || argv.destination;
156
+ if (!argv.source || !targetName) throw errUsage('Provide --source and --target profile names');
157
+ const sdk = name => {
158
+ const s = resolveSession({ profile: name }, app.config);
159
+ if (s.unknownProfile || !s.profile || !s.instance) throw errUsage(`Unknown or unconfigured profile: ${name}`);
160
+ return app.getSDKForProfile(s.instance, { profileName: name, profile: s.profile, username: s.username, authMethod: s.profile.auth_method, domain: s.domain });
161
+ };
162
+ // Resolve both profiles before making any request. Sequential bounded reads.
163
+ const sourceSDK = sdk(argv.source), destinationSDK = sdk(targetName);
164
+ const source = await readInventory(sourceSDK, kind, argv.maxPages);
165
+ const destination = await readInventory(destinationSDK, kind, argv.maxPages);
166
+ const records = compareInventories(source, destination, kind);
167
+ const counts = Object.fromEntries(['matching', 'different', 'source_only', 'target_only', 'unknown'].map(status => [status, records.filter(row => row.status === status).length]));
168
+ const data = { kind, source: argv.source, target: targetName, complete: source.coverage.status === 'complete' && destination.coverage.status === 'complete', coverage: { source: source.coverage, target: destination.coverage }, counts, records };
169
+ Object.defineProperty(data, '_formatted', { value: formatInventoryComparison(data, argv.verbose), enumerable: false });
170
+ if (emit) {
171
+ app.ok(data, { summary: `${kind} comparison${data.complete ? '' : ' (incomplete)'}` });
172
+ if (!data.complete) process.exitCode = 1;
173
+ }
174
+ return data;
175
+ }
176
+
177
+ export const inventoryCompareCommand = (wrap, kind) => ({
178
+ command: 'compare', describe: `Compare ${kind === 'store' ? 'Store application' : 'plugin'} inventories across explicit profiles (read-only)`,
179
+ builder: p => p.option('source', { type: 'string', demandOption: true, describe: 'Source profile alias, desired baseline for --target' })
180
+ .option('target', { alias: 'destination', type: 'string', demandOption: true, describe: 'Target profile to align to the desired --source baseline' })
181
+ .option('max-pages', { type: 'number', default: 30, describe: 'Per-side page budget, 200 rows/page (1–100); limits remain incomplete' })
182
+ .epilogue('Align target to source without changing either instance:\njsn compare --source pdi --target vendor\njsn compare --source pdi --target vendor --json\njsn compare --source pdi --target vendor --get data.inventories.store.coverage\nIncomplete coverage exits 1 and recommends investigating access, not installing or removing. Numeric versions are ordered conservatively; newer target versions require review, never automatic downgrade.'),
183
+ handler: wrap((argv, app) => compareInstanceInventory(argv, app, kind)),
184
+ });
@@ -0,0 +1,68 @@
1
+ // Intent comes from the task, never from the current provider preferences.
2
+ import { assertSafeExactMatch, getStringField } from './helpers.js';
3
+ import { errUsageHint } from './errors.js';
4
+
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.');
7
+ }
8
+ const raw = (record, key) => record?.[key]?.value ?? record?.[key];
9
+ export async function exactContextRecord(sdk, table, field, identifier) {
10
+ if (typeof identifier !== 'string' || !identifier.trim()) throw contextFailure(`Missing intended ${table} identifier.`);
11
+ assertSafeExactMatch(identifier);
12
+ const byId = /^[a-f0-9]{32}$/i.test(identifier) || identifier === 'global';
13
+ const records = await sdk.list(table, new URLSearchParams({
14
+ sysparm_query: `${byId ? 'sys_id' : field}=${identifier}${!byId && table === 'sys_scope' ? `^ORname=${identifier}` : ''}`,
15
+ sysparm_limit: '2', sysparm_display_value: 'all',
16
+ }));
17
+ if (records.length !== 1 || !raw(records[0], 'sys_id')) throw contextFailure(`Intended ${table} is missing, unreadable or ambiguous.`);
18
+ return records[0];
19
+ }
20
+
21
+ export async function readWriteContext(sdk) {
22
+ const users = await sdk.list('sys_user', new URLSearchParams({
23
+ sysparm_query: 'user_name=javascript:gs.getUserName()', sysparm_limit: '2',
24
+ sysparm_fields: 'sys_id,user_name,name', sysparm_display_value: 'all',
25
+ }));
26
+ if (users.length !== 1 || !raw(users[0], 'sys_id') || !getStringField(users[0], 'user_name')) throw contextFailure('Current user is unknown.');
27
+ 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.`);
33
+ return raw(rows[0], 'value');
34
+ }
35
+ const [scopeId, setId] = await Promise.all([preference('apps.current_app'), preference('sys_update_set')]);
36
+ const [scope, set] = await Promise.all([sdk.get('sys_scope', scopeId), sdk.get('sys_update_set', setId)]);
37
+ const applicationId = raw(set, 'application');
38
+ if (!getStringField(scope || {}, 'scope') || !getStringField(set || {}, 'name') || !applicationId || !getStringField(set || {}, 'state')) throw contextFailure('Capture context is incomplete or unreadable.');
39
+ return {
40
+ user, scope: getStringField(scope, 'scope'), application_id: scopeId,
41
+ update_set: { sys_id: setId, name: getStringField(set, 'name'), state: getStringField(set, 'state'), application_id: applicationId },
42
+ source: 'fresh_preferences', domain: { verified: false, status: 'unverified', reason: 'X-Now-Domain is a request header, not proof of effective domain.' },
43
+ };
44
+ }
45
+
46
+ export function assertMutationScope(context, value, label = 'Mutation target') {
47
+ if (!context?.verified) return;
48
+ const scope = value?.value ?? value;
49
+ if (!scope || scope !== context.application_id) throw contextFailure(`${label} scope is unknown or differs from verified intended scope.`);
50
+ }
51
+
52
+ export async function assertMutationRecordScope(app, table, id) {
53
+ if (!app.mutationContext?.verified) return;
54
+ const record = await app.sdk.get(table, id);
55
+ assertMutationScope(app.mutationContext, record?.sys_scope, 'Resolved target');
56
+ }
57
+
58
+ export function intendedContext(app, argv) {
59
+ const saved = app.config.writeContext;
60
+ if (saved !== undefined) {
61
+ if (!saved || typeof saved !== 'object' || Array.isArray(saved)
62
+ || !saved.profile || saved.profile !== app.session?.profileName
63
+ || !saved.instance_url || saved.instance_url !== app.session?.instance) {
64
+ throw contextFailure('Task-local write_context must bind the selected profile and exact instance_url.');
65
+ }
66
+ }
67
+ return { scope: argv.expectScope ?? saved?.scope, update_set: argv.expectUpdateSet ?? saved?.update_set, domain: argv.expectDomain ?? saved?.domain };
68
+ }