@jacebenson/jsn 5.5.7 → 5.5.8-dev.220.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/README.md +16 -1
- package/package.json +5 -6
- package/skills/servicenow/SKILL.md +9 -1
- package/src/app.js +4 -79
- package/src/auth/credential-store.js +33 -8
- package/src/auth/windows-credential-store.js +85 -0
- package/src/auth/windows-credential-store.ps1 +163 -0
- package/src/bounded-reads.js +13 -0
- package/src/capabilities.js +8 -3
- package/src/cli-adapter.js +26 -3
- package/src/cli.js +13 -14
- package/src/command-families.js +68 -0
- package/src/commands/_generic.js +1 -0
- package/src/commands/_ticket.js +1 -1
- package/src/commands/actions.js +9 -4
- package/src/commands/approvals.js +1 -1
- package/src/commands/atf.js +1 -1
- package/src/commands/attachments.js +1 -1
- package/src/commands/auth.js +21 -2
- package/src/commands/codesearch.js +11 -2
- package/src/commands/compare.js +22 -0
- package/src/commands/customizations.js +3 -4
- package/src/commands/decisiontables.js +4 -0
- package/src/commands/docs/docs.js +5 -5
- package/src/commands/domains.js +1 -1
- package/src/commands/eval.js +11 -5
- package/src/commands/flows.js +24 -7
- package/src/commands/groupmembers.js +1 -1
- package/src/commands/grouproles.js +1 -1
- package/src/commands/groups.js +1 -1
- package/src/commands/midservers.js +4 -11
- package/src/commands/perf.js +2 -3
- package/src/commands/plugins.js +9 -0
- package/src/commands/records.js +12 -2
- package/src/commands/scopes.js +1 -1
- package/src/commands/scrapi.js +2 -2
- package/src/commands/setup.js +4 -34
- package/src/commands/skipped-updates.js +2 -3
- package/src/commands/store.js +4 -1
- package/src/commands/subscriptions.js +47 -0
- package/src/commands/tickets.js +1 -1
- package/src/commands/users.js +1 -1
- package/src/commands/workflows.js +3 -5
- package/src/config.js +1 -0
- package/src/context.js +8 -56
- package/src/docs-links.js +28 -0
- package/src/flow-create.js +9 -0
- package/src/help.js +4 -0
- package/src/helpers.js +17 -24
- package/src/instance-inventory.js +184 -0
- package/src/intended-context.js +68 -0
- package/src/mutation-context.js +69 -46
- package/src/output.js +1 -1
- package/src/paginated-search.js +146 -178
- package/src/picker-ui.js +20 -0
- package/src/prompt-engine.js +176 -0
- package/src/prompts.js +293 -43
- package/src/records/inspect.js +30 -16
- package/src/records-engine.js +2 -2
- package/src/schedule-cache.js +96 -0
- package/src/schedules/itom-2026-04-09.json +121 -0
- package/src/schedules/public-inventory.json +6224 -0
- package/src/sdk-batch.js +2 -1
- package/src/sdk.js +42 -16
- package/src/setup-preferences.js +2 -2
- package/src/subscriptions.js +176 -0
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
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
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
|
+
}
|
package/src/mutation-context.js
CHANGED
|
@@ -2,73 +2,96 @@
|
|
|
2
2
|
import process from 'node:process';
|
|
3
3
|
import { collectCapabilities } from './capabilities.js';
|
|
4
4
|
import { isMutationCommand } from './mutations.js';
|
|
5
|
-
import {
|
|
6
|
-
import { canUsePicker, getStringField, quoteShellArg } from './helpers.js';
|
|
5
|
+
import { canUsePicker, quoteShellArg } from './helpers.js';
|
|
7
6
|
import { confirm } from './prompts.js';
|
|
8
|
-
import { AppError, CodeConfirmationRequired
|
|
7
|
+
import { AppError, CodeConfirmationRequired } from './errors.js';
|
|
8
|
+
import { contextFailure, exactContextRecord, intendedContext, readWriteContext } from './intended-context.js';
|
|
9
9
|
|
|
10
10
|
export function needsMutationContext(argv) {
|
|
11
11
|
if (!isMutationCommand(argv)) return false;
|
|
12
12
|
const caps = collectCapabilities().get(argv._?.[0]) || {};
|
|
13
|
+
if (caps.mutationContext === 'operational') return false;
|
|
13
14
|
if (caps.mutationContextReadMethods?.includes(String(argv.method || 'GET').toUpperCase())) return false;
|
|
14
15
|
return !caps.mutationContextExemptSubcommands?.some(sub =>
|
|
15
16
|
sub.split(' ').every((part, index) => argv._?.[index + 1] === part));
|
|
16
17
|
}
|
|
17
18
|
|
|
18
|
-
|
|
19
|
-
|
|
19
|
+
// Table ancestry, not a command-name heuristic, decides generic record writes.
|
|
20
|
+
async function isCustomizationTable(sdk, table) {
|
|
21
|
+
if (!table) throw contextFailure('Cannot classify a write without its table.');
|
|
22
|
+
const seen = new Set();
|
|
23
|
+
let row = await exactContextRecord(sdk, 'sys_db_object', 'name', table);
|
|
24
|
+
for (let depth = 0; depth < 32; depth++) {
|
|
25
|
+
const name = row.name?.value ?? row.name;
|
|
26
|
+
if (!name || seen.has(name)) throw contextFailure('Table ancestry is incomplete or cyclic.');
|
|
27
|
+
if (name === 'sys_metadata') return true;
|
|
28
|
+
seen.add(name);
|
|
29
|
+
if (!Object.hasOwn(row, 'super_class')) throw contextFailure('Table ancestry is unreadable.');
|
|
30
|
+
const parent = row.super_class?.value ?? row.super_class;
|
|
31
|
+
if (!parent) return false;
|
|
32
|
+
row = await sdk.get('sys_db_object', parent);
|
|
33
|
+
if (!row) throw contextFailure('Table ancestry is unreadable.');
|
|
34
|
+
}
|
|
35
|
+
throw contextFailure('Table ancestry exceeds the verification bound.');
|
|
20
36
|
}
|
|
21
37
|
|
|
22
38
|
export async function guardMutationContext(app, argv, { ask = confirm, rawArgs = process.argv.slice(2) } = {}) {
|
|
23
39
|
if (!needsMutationContext(argv) || !app.sdk) return null;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
40
|
+
const caps = collectCapabilities().get(argv._?.[0]) || {};
|
|
41
|
+
if (caps.mutationContext === 'table' && !await isCustomizationTable(app.sdk, caps.table || argv.table)) return null;
|
|
42
|
+
const expected = intendedContext(app, argv);
|
|
43
|
+
const interactive = canUsePicker(app, argv);
|
|
44
|
+
if (!interactive && (!expected.scope || !expected.update_set)) throw contextFailure('Noninteractive customization writes require intended scope and update set.');
|
|
45
|
+
// Header application is not an established effective-domain provider contract.
|
|
46
|
+
if (expected.domain !== undefined || app.session?.domain || app.session?.profile?.domain_separation || app.sdk.domain) {
|
|
47
|
+
throw contextFailure('Effective domain cannot be proven for customization writes. X-Now-Domain propagation does not verify domain selection; domain-scoped writes are not supported by this guard.');
|
|
48
|
+
}
|
|
49
|
+
let context;
|
|
50
|
+
try { context = await readWriteContext(app.sdk); }
|
|
51
|
+
catch (error) { throw contextFailure(`Cannot verify capture context: ${error.message}`); }
|
|
52
|
+
if (app.session?.username && context.user.user_name !== app.session.username) throw contextFailure('Current user differs from the selected profile.');
|
|
53
|
+
const fail = message => { const error = contextFailure(message); error.context = context; throw error; };
|
|
54
|
+
if (context.application_id !== context.update_set.application_id) fail('Selected scope and update set belong to different applications.');
|
|
55
|
+
if (!['in progress', 'in_progress'].includes(context.update_set.state.toLowerCase())) fail('Selected capture update set is not in progress.');
|
|
56
|
+
if (expected.scope !== undefined) {
|
|
57
|
+
const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', expected.scope);
|
|
58
|
+
if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Intended scope does not match fresh selected scope.');
|
|
33
59
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (!context.scope || !updateSet) context.diagnostics.push(diagnostic('capture_context_unknown',
|
|
38
|
-
'Capture context could not be determined. Identify the intended scope and update set before development changes.', 'jsn updatesets list'));
|
|
39
|
-
const appId = getStringField(updateSet || {}, 'application');
|
|
40
|
-
const rawAppId = updateSet?.application?.value || appId;
|
|
41
|
-
if (application?.appSysId && rawAppId && application.appSysId !== rawAppId) {
|
|
42
|
-
context.diagnostics.push(diagnostic('update_set_scope_mismatch',
|
|
43
|
-
`Selected scope ${context.scope} and update set ${updateSet.name} belong to different applications; changes may not be captured in this set.`,
|
|
44
|
-
`jsn scopes set ${quoteShellArg(rawAppId)}`));
|
|
60
|
+
if (caps.transactionScopeOption && argv[caps.transactionScopeOption] !== undefined) {
|
|
61
|
+
const scope = await exactContextRecord(app.sdk, 'sys_scope', 'scope', argv[caps.transactionScopeOption]);
|
|
62
|
+
if ((scope.sys_id?.value ?? scope.sys_id) !== context.application_id) fail('Command transaction scope differs from verified intended scope.');
|
|
45
63
|
}
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
error.context = context; throw error;
|
|
64
|
+
if (expected.update_set !== undefined) {
|
|
65
|
+
const set = await exactContextRecord(app.sdk, 'sys_update_set', 'name', expected.update_set);
|
|
66
|
+
if ((set.sys_id?.value ?? set.sys_id) !== context.update_set.sys_id) fail('Intended update set does not match fresh selected update set.');
|
|
50
67
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
68
|
+
// Never align/switch a session implicitly. Persisted and effective selections
|
|
69
|
+
// are independent evidence; both must agree before customization can proceed.
|
|
70
|
+
const [scopeResponse, setResponse] = await Promise.all([
|
|
71
|
+
app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/application`, { method: 'GET', readOnly: true }),
|
|
72
|
+
app.sdk.request(`${app.sdk.baseURL}/api/now/ui/concoursepicker/updateset`, { method: 'GET', readOnly: true }),
|
|
73
|
+
]);
|
|
74
|
+
if (scopeResponse?.result?.current !== context.application_id || setResponse?.result?.current?.sysId !== context.update_set.sys_id) fail('Effective session context is unknown or differs from the selected preferences. No context was switched.');
|
|
75
|
+
context.verified = true;
|
|
76
|
+
if (caps.mutationContext === 'table') context.table = caps.table || argv.table;
|
|
77
|
+
context.source = 'fresh_preferences_and_session';
|
|
78
|
+
context.expected = expected;
|
|
79
|
+
context.diagnostics = [];
|
|
80
|
+
context.approval_required = context.scope.toLowerCase() === 'global' && context.update_set.name.toLowerCase() === 'default';
|
|
81
|
+
context.approved = false;
|
|
82
|
+
if (interactive && (!expected.scope || !expected.update_set) && !context.approval_required) {
|
|
83
|
+
if (!await ask({ message: `Confirm customization in scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id})?`, default: false })) fail('Customization context was not confirmed.');
|
|
84
|
+
context.approved = true;
|
|
85
|
+
}
|
|
86
|
+
if (context.approval_required) {
|
|
87
|
+
context.diagnostics.push({ code: 'global_default_update_set', severity: 'warning', message: 'Global + Default requires approval for this exact operation.' });
|
|
57
88
|
if (argv.force) context.approved = true;
|
|
58
|
-
else if (
|
|
59
|
-
context.approved = await ask({ message: `Scope: Global; update set: Default. ${context.diagnostics.at(-1).message} Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
|
|
60
|
-
}
|
|
89
|
+
else if (interactive) context.approved = await ask({ message: `Scope: Global; update set: Default. Approve this exact mutation: ${['jsn', ...rawArgs].map(quoteShellArg).join(' ')}?`, default: false });
|
|
61
90
|
if (!context.approved) {
|
|
62
|
-
const
|
|
63
|
-
const rerun = ['jsn', ...rawArgs.filter(arg => arg !== '--force')].map(quoteShellArg).join(' ') + (rawArgs.includes('--profile') ? '' : target);
|
|
64
|
-
const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.',
|
|
65
|
-
`Select a dedicated set: jsn updatesets set; or jsn updatesets create --name "My Feature". Ask the user to approve this exact operation, then rerun: ${rerun} --force`);
|
|
91
|
+
const error = new AppError(CodeConfirmationRequired, 'Mutation in Global scope + Default update set requires explicit approval.', 'Select a dedicated set or obtain user approval for this exact operation, then rerun with --force and explicit expectations.');
|
|
66
92
|
error.context = context; throw error;
|
|
67
93
|
}
|
|
68
94
|
}
|
|
69
|
-
if (
|
|
70
|
-
process.stderr.write(`Mutation context: scope ${context.scope || 'unknown'}; update set ${updateSet?.name || 'unknown'}${updateSet?.sys_id ? ` (${updateSet.sys_id})` : ''}.\n`);
|
|
71
|
-
for (const item of context.diagnostics) process.stderr.write(`Warning (${item.code}): ${item.message} Run: ${item.remediation.command}\n`);
|
|
72
|
-
}
|
|
95
|
+
if (interactive) process.stderr.write(`Mutation context: scope ${context.scope}; update set ${context.update_set.name} (${context.update_set.sys_id}); user ${context.user.user_name}.\n`);
|
|
73
96
|
return context;
|
|
74
97
|
}
|
package/src/output.js
CHANGED
|
@@ -136,7 +136,7 @@ export class OutputWriter {
|
|
|
136
136
|
// typo looked like a successful empty result until the next tool in the
|
|
137
137
|
// pipeline failed to parse it. Present null/false/0/"" still print as-is.
|
|
138
138
|
if (this.jqFilter) {
|
|
139
|
-
const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [] };
|
|
139
|
+
const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
|
|
140
140
|
const value = resolvePath(envelope, this.jqFilter);
|
|
141
141
|
if (value === undefined) throw errExtractionNotFound(this.jqFilter);
|
|
142
142
|
const indent = this.verbose && !this.raw ? 2 : undefined;
|