@jacebenson/jsn 5.5.10-dev.233.1 → 5.5.10-dev.235.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.10-dev.233.1",
3
+ "version": "5.5.10-dev.235.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": {
package/src/cli.js CHANGED
@@ -42,6 +42,7 @@ import { platformCmd } from './commands/platform.js';
42
42
  import { codesearchCmd } from './commands/codesearch.js';
43
43
  import { versionCmd } from './commands/version.js';
44
44
  import { upgradeCmd } from './commands/upgrade.js';
45
+ import { documentCmd } from './commands/document.js';
45
46
  import { skillCmd, checkSkill } from './commands/skill.js';
46
47
  import { getVersion, checkLatest, getReleaseChannel, getInstallCommand } from './commands/version.js';
47
48
 
@@ -456,6 +457,7 @@ export function buildCLI() {
456
457
  .command(docsCmd(wrap))
457
458
  .command(versionCmd(wrap))
458
459
  .command(upgradeCmd(wrap))
460
+ .command(documentCmd(wrap))
459
461
  .command(discoverCmd(wrap, (argv) => visibleCommandRegistry(cliInstance.commandRegistry(), app.config, argv)))
460
462
  .demandCommand(1, 'You must specify a command')
461
463
  .onParentDiscovery((argv, { path, subcommands }) => {
@@ -0,0 +1,31 @@
1
+ import { declareCapabilities } from '../capabilities.js';
2
+ import { DOCUMENT_BUDGETS, collectInstanceDocumentation, renderInstanceDocumentation, writeDocumentFile } from '../instance-documentation.js';
3
+
4
+ declareCapabilities('document', { mutationSubcommands: [], skipDailyChecks: true });
5
+
6
+ export function documentCmd(wrap) {
7
+ return {
8
+ command: 'document',
9
+ describe: 'Create bounded read-only instance configuration documentation',
10
+ builder: y => y.command({
11
+ command: 'instance',
12
+ describe: 'Generate deterministic Markdown/Mermaid from safe metadata. Requires --profile.',
13
+ builder: child => {
14
+ child.option('output', { type: 'string', describe: 'New Markdown file; never overwrites. POSIX mode 0600; Windows inherits directory ACLs; use a private directory.' });
15
+ for (const [name, [fallback, min, max]] of Object.entries(DOCUMENT_BUDGETS)) {
16
+ const flag = name.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
17
+ child.option(flag, { type: 'number', default: fallback, describe: `${name} budget (${min}–${max})` });
18
+ }
19
+ return child;
20
+ },
21
+ handler: wrap(async (argv, app) => {
22
+ const data = await collectInstanceDocumentation(argv, app);
23
+ data.markdown = renderInstanceDocumentation(data);
24
+ app.output.validateExtraction(data);
25
+ if (argv.output) writeDocumentFile(argv.output, data.markdown);
26
+ const human = !app.output.jqFilter && ['styled', 'markdown'].includes(app.output.effectiveFormat());
27
+ app.output.ok(human ? data.markdown : data);
28
+ }),
29
+ }).demandCommand(1),
30
+ };
31
+ }
@@ -13,9 +13,12 @@ declareCapabilities('scan', { mutationSubcommands: [
13
13
  ] });
14
14
 
15
15
  const hint = (action, cmd, description) => ({ action, cmd, description });
16
- function report(app, argv, data, options) {
17
- const connection = argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
16
+ function connectionSuffix(argv) {
17
+ return argv.profile ? ` --profile ${quoteShellArg(argv.profile)}`
18
18
  : argv.instance ? ` --instance ${quoteShellArg(argv.instance)}` : '';
19
+ }
20
+ function report(app, argv, data, options) {
21
+ const connection = connectionSuffix(argv);
19
22
  app.ok(data, { ...options, breadcrumbs: options.breadcrumbs.map(item => ({ ...item, cmd: item.cmd + connection })) });
20
23
  }
21
24
  const rootHints = () => [hint('checks', 'jsn scan checks list', 'Browse available checks'),
@@ -32,6 +35,18 @@ const itemHints = (group, record) => {
32
35
  hint('delete', `jsn scan ${group} delete ${id}`, 'Delete this definition after confirmation')];
33
36
  };
34
37
 
38
+ // Structured recovery for a dispatched scan whose progress or results cannot be
39
+ // read. It records what was started so an operator can inspect it; resubmission
40
+ // is never recommended because the original execution may still be running.
41
+ function recoveryTarget(target = {}) {
42
+ return { kind: target.kind,
43
+ ...(target.sys_id ? { sys_id: target.sys_id } : {}),
44
+ ...(target.table ? { table: target.table } : {}),
45
+ ...(target.name ? { name: target.name } : {}),
46
+ ...(target.execution_id ? { execution_id: target.execution_id } : {}),
47
+ ...(target.combo_id ? { combo_id: target.combo_id } : {}) };
48
+ }
49
+
35
50
  function executionHints(data) {
36
51
  const id = data.execution_id;
37
52
  return [hint('status', `jsn scan status ${id}`, 'Read execution progress'),
@@ -188,6 +203,7 @@ export function scanCmd(wrap) {
188
203
  await confirmDelete(app, argv, `Start scan of ${plan.target.kind} ${plan.target.name || plan.target.sys_id || plan.target.execution_id || 'the full instance'}${plan.suite_id ? ` using suite ${plan.suite_id}` : ''}?`);
189
204
  const scheduled = await startScan(app.sdk, plan);
190
205
  let data = { ...scheduled, status: 'scheduled', terminal: false };
206
+ let phase = 'progress';
191
207
  if (argv.wait) {
192
208
  try {
193
209
  const deadline = Date.now() + argv.timeout * 1000;
@@ -199,12 +215,24 @@ export function scanCmd(wrap) {
199
215
  // The processor can return before its execution tracker is visible.
200
216
  data = { ...scheduled, status: 'scheduled', terminal: false };
201
217
  }
202
- if (data.terminal) { data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
218
+ if (data.terminal) { phase = 'results'; data = { ...scheduled, ...await scanResults(app.sdk, scheduled.execution_id) }; break; }
203
219
  await new Promise(resolve => setTimeout(resolve, Math.min(2000, Math.max(0, deadline - Date.now()))));
204
220
  }
205
221
  if (!data.terminal) data.wait_timed_out = true;
206
222
  } catch (error) {
207
- throw errAPI(error.status || 0, `Scan ${scheduled.execution_id} was scheduled, but progress could not be read: ${error.message}. Use jsn scan status ${scheduled.execution_id}; do not resubmit automatically.`);
223
+ const id = scheduled.execution_id;
224
+ const connection = connectionSuffix(argv);
225
+ const statusCommand = `jsn scan status ${id}${connection}`;
226
+ // Provider errors may contain credentials or request payloads.
227
+ const wrapped = errAPI(error.status || 0, `Scan ${id} was scheduled, but ${phase} could not be read. Use ${statusCommand}; do not resubmit automatically.`);
228
+ // errAPI replaces the message for 401/403, so the dispatched id and
229
+ // the no-resubmit warning must also survive in the hint.
230
+ wrapped.hint = [wrapped.hint, `Scan ${id} was already dispatched; inspect it with "${statusCommand}" and do not resubmit automatically.`].filter(Boolean).join(' ');
231
+ wrapped.recovery = { execution_id: id, via: scheduled.via, phase,
232
+ target: recoveryTarget(plan.target), suite_id: scheduled.suite_id ?? null, status: 'unverified',
233
+ status_command: statusCommand,
234
+ results_command: `jsn scan results ${id}${connection}`, resubmit: 'forbidden' };
235
+ throw wrapped;
208
236
  }
209
237
  }
210
238
  const breadcrumbs = executionHints(data);
@@ -220,7 +248,14 @@ export function scanCmd(wrap) {
220
248
  builder: p => p.option('limit', { type: 'number', default: 50, describe: 'Maximum findings/check rows (1–200); truncation is reported' }),
221
249
  handler: wrap(async (argv, app) => {
222
250
  const data = await scanResults(app.sdk, argv.id, boundedLimit(argv.limit));
223
- report(app, argv, data, { summary: `Scan ${data.status}; ${data.findings_count ?? 'unknown'} findings; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
251
+ const findings = data.findings_state === 'unretrieved'
252
+ ? `findings unretrieved (${data.findings_count} reported, 0 rows returned)`
253
+ : data.findings_state === 'mismatch'
254
+ ? `findings mismatch (${data.findings_count} reported, ${data.findings_retrieved} retrieved)`
255
+ : data.findings_state === 'truncated'
256
+ ? `findings truncated (${data.findings_retrieved} retrieved; count not reconciled)`
257
+ : `${data.findings_count ?? 'unknown'} findings`;
258
+ report(app, argv, data, { summary: `Scan ${data.status}; ${findings}; ${data.checks_executed ?? 'unknown'} recorded check executions${data.incomplete ? '; incomplete data' : ''}`, breadcrumbs: executionHints(data) });
224
259
  }) })
225
260
  .command({ command: 'cancel <id>', describe: 'Request cancellation of this scan after confirmation',
226
261
  handler: wrap(async (argv, app) => {
package/src/help.js CHANGED
@@ -171,6 +171,7 @@ const DEVELOPER_COMMANDS = [
171
171
  { name: 'graphql', desc: 'GraphQL queries' },
172
172
  { name: 'codesearch', desc: 'Search code across ServiceNow artifacts' },
173
173
  { name: 'docs', desc: 'Local ServiceNow documentation search' },
174
+ { name: 'document', desc: 'Read-only instance configuration documentation' },
174
175
  { name: 'diff', desc: 'Compare records across configured profiles' },
175
176
  { name: 'perf', desc: 'Read-only performance capture and comparison' },
176
177
  { name: 'skill', desc: 'AI agent skill file (show, fetch, install)' },
@@ -276,7 +277,7 @@ function renderConciseHelp(config, registry, width) {
276
277
  `\nCOMMON COMMANDS\n${renderRows(common.map((command) => ({ label: command.name, description: command.desc })), { width, indent: 2 })}`,
277
278
  '',
278
279
  'ALL COMMANDS BY GROUP',
279
- ...wrapText('names only; jsn --all-commands --help has descriptions and flags', { width }),
280
+ ...wrapText('names only; jsn --all-commands --help for details', { width }),
280
281
  renderRows(groups, { width, indent: 2 }),
281
282
  '',
282
283
  'EXAMPLES',
@@ -0,0 +1,237 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { errUsage } from './errors.js';
4
+
5
+ const identity = /^[0-9a-f]{32}$/i;
6
+ const tableName = /^[a-z][a-z0-9_]*$/;
7
+ const common = ['sys_id', 'sys_scope', 'sys_package', 'sys_updated_on'];
8
+ const fields = {
9
+ sys_scope: ['sys_id', 'name', 'scope', 'sys_class_name', 'sys_updated_on'],
10
+ sys_db_object: [...common, 'name', 'label', 'super_class'],
11
+ sys_dictionary: [...common, 'name', 'element', 'column_label', 'internal_type', 'reference', 'mandatory', 'read_only'],
12
+ sys_script: [...common, 'name', 'collection', 'active', 'when', 'order', 'action_insert', 'action_update', 'action_delete', 'action_query'],
13
+ sys_script_client: [...common, 'name', 'table', 'active', 'type', 'field', 'applies_extended'],
14
+ sys_ui_policy: [...common, 'short_description', 'table', 'active', 'on_load', 'reverse_if_false'],
15
+ sys_ui_action: [...common, 'name', 'table', 'active', 'action_name', 'client', 'form_button', 'list_button'],
16
+ sys_script_include: [...common, 'name', 'api_name', 'access', 'active', 'client_callable'],
17
+ sys_hub_flow: [...common, 'name', 'active'],
18
+ sp_page: [...common, 'id', 'title'],
19
+ sp_widget: [...common, 'id', 'name'],
20
+ sp_container: [...common, 'name', 'sp_page', 'order'],
21
+ sp_row: [...common, 'sp_container', 'order'],
22
+ sp_column: [...common, 'sp_row', 'order'],
23
+ sp_instance: [...common, 'title', 'sp_column', 'sp_widget', 'order'],
24
+ sys_rest_message: [...common, 'name', 'active'],
25
+ sys_soap_message: [...common, 'name', 'active'],
26
+ sysauto_script: [...common, 'name', 'active', 'run_type'],
27
+ };
28
+ const labels = { sys_db_object: 'Tables', sys_dictionary: 'Fields', sys_script: 'Business rules', sys_script_client: 'Client scripts', sys_ui_policy: 'UI policies', sys_ui_action: 'UI actions', sys_script_include: 'Script Includes', sys_hub_flow: 'Flows', sp_page: 'Portal pages', sp_widget: 'Portal widgets', sp_container: 'Portal containers', sp_row: 'Portal rows', sp_column: 'Portal columns', sp_instance: 'Widget instances', sys_rest_message: 'REST integrations', sys_soap_message: 'SOAP integrations', sysauto_script: 'Scheduled automation' };
29
+ export const DOCUMENT_BUDGETS = {
30
+ pageSize: [25, 1, 100], discoveryPages: [2, 1, 5], applications: [3, 1, 6], detailPages: [1, 1, 3], maxRequests: [96, 1, 200],
31
+ };
32
+ const raw = input => {
33
+ const value = input && typeof input === 'object' ? input.value : input;
34
+ return ['string', 'number', 'boolean'].includes(typeof value) ? String(value).slice(0, 512) : null;
35
+ };
36
+ const sort = rows => rows.sort((a, b) => String(a.sys_id).localeCompare(String(b.sys_id), 'en'));
37
+ const safeIds = rows => [...new Set(rows.map(row => row.sys_id).filter(value => identity.test(value || '')))];
38
+
39
+ export function validateDocument(argv) {
40
+ if (typeof argv.profile !== 'string' || !argv.profile.trim()) throw errUsage('Instance documentation requires explicit --profile.');
41
+ if (argv.instance) throw errUsage('Use --profile without --instance for instance documentation.');
42
+ const budgets = {};
43
+ for (const [name, [fallback, min, max]] of Object.entries(DOCUMENT_BUDGETS)) {
44
+ const n = argv[name] ?? fallback;
45
+ if (!Number.isInteger(n) || n < min || n > max) throw errUsage(`Invalid ${name}: use an integer from ${min} to ${max}.`);
46
+ budgets[name] = n;
47
+ }
48
+ if (argv.output !== undefined) {
49
+ if (typeof argv.output !== 'string' || !argv.output.trim()) throw errUsage('--output must name a new file.');
50
+ try { fs.lstatSync(argv.output); throw errUsage('--output already exists; refusing to overwrite.'); }
51
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
52
+ if (!fs.statSync(path.dirname(path.resolve(argv.output))).isDirectory()) throw errUsage('--output parent must be a directory.');
53
+ }
54
+ return budgets;
55
+ }
56
+
57
+ /** A namespace string never establishes ownership. Missing/unknown references stay unresolved. */
58
+ export function documentOwner(row, candidates) {
59
+ const ownership = [row.sys_scope, row.sys_package];
60
+ if (!Object.hasOwn(row, 'sys_scope') || !Object.hasOwn(row, 'sys_package') || ownership.some(ref => typeof ref !== 'string' || !ref.trim())) return { kind: 'unresolved', reason: 'missing_ownership_fields' };
61
+ const refs = ownership.filter(ref => ref !== 'global');
62
+ if (refs.some(ref => !candidates.some(c => c.identity === ref))) return { kind: 'unresolved', reason: 'unknown_ownership_reference' };
63
+ if (new Set(refs).size > 1) return { kind: 'unresolved', reason: 'conflicting_ownership_references' };
64
+ return refs.length ? { kind: 'application', identity: refs[0] } : { kind: 'unassigned-global' };
65
+ }
66
+
67
+ export async function collectInstanceDocumentation(argv, app) {
68
+ const budgets = validateDocument(argv);
69
+ app.requireInstance();
70
+ const evidence = { schema_version: 1, profile: argv.profile, observed_at: new Date().toISOString(), status: 'incomplete',
71
+ release_identity: 'unknown', customization_evidence: 'not_collected', budgets, requests_used: 0,
72
+ candidates: [], applications: [], global_candidates: [], global_details: [], unresolved: [], sources: [], portal_relations: [],
73
+ limitations: ['Bounded configuration metadata, not execution, customer authorship, baseline differences or effective access.',
74
+ 'Completeness is unknown. No provider count was collected; short or empty pages do not prove absence.',
75
+ 'Scripts, conditions, defaults, URLs, credentials, bodies, business records and execution telemetry are not collected.',
76
+ 'Instance release/build identity and existing customization evidence were not collected.',
77
+ 'Inherited behavior, flow internals, nested portal rows, catalog configuration and standalone/OOTB changes remain gaps.'] };
78
+ // Every Table API call, including schema discovery, passes this budget and strict reader.
79
+ async function read(table, query, pages = budgets.detailPages, requestedFields = fields[table]) {
80
+ const rows = [], seen = new Set();
81
+ for (let page = 0; page < pages; page++) {
82
+ const source = { id: `source-${evidence.sources.length + 1}`, resource: `/api/now/table/${table}`, table, method: 'GET',
83
+ fields: [...requestedFields], query, observed_at: new Date().toISOString(),
84
+ bounds: { limit: budgets.pageSize, offset: page * budgets.pageSize, page: page + 1, max_pages: pages },
85
+ count: null, continuation: 'unknown', completeness: 'unknown', status: 'not_collected', reasons: [], records: [] };
86
+ evidence.sources.push(source);
87
+ if (evidence.requests_used >= budgets.maxRequests) { source.status = 'truncated'; source.reasons.push('request_budget'); break; }
88
+ evidence.requests_used++;
89
+ try {
90
+ const result = await app.sdk.listStrict(table, new URLSearchParams({ sysparm_fields: requestedFields.join(','), sysparm_query: query,
91
+ sysparm_limit: String(budgets.pageSize), sysparm_offset: String(source.bounds.offset), sysparm_display_value: 'false' }));
92
+ source.count = result.length;
93
+ source.continuation = result.length >= budgets.pageSize ? 'possible' : 'unknown';
94
+ source.status = 'observed';
95
+ if (result.length >= budgets.pageSize && page + 1 === pages) { source.status = 'truncated'; source.reasons.push('page_budget'); }
96
+ if (result.length > budgets.pageSize) source.reasons.push('provider_over_return');
97
+ const missing = new Set();
98
+ for (const input of result.slice(0, budgets.pageSize)) {
99
+ const row = Object.fromEntries(requestedFields.filter(field => {
100
+ if (!Object.hasOwn(input || {}, field)) { missing.add(field); return false; } return true;
101
+ }).map(field => [field, raw(input[field])]));
102
+ source.records.push(row);
103
+ if (!row.sys_id || seen.has(row.sys_id)) { source.reasons.push(row.sys_id ? 'duplicate_record' : 'missing_record_identity'); continue; }
104
+ seen.add(row.sys_id); rows.push({ ...row, source: source.id });
105
+ }
106
+ source.missing_fields = [...missing].sort();
107
+ if (missing.size) { source.reasons.push('missing_fields'); if (source.status === 'observed') source.status = 'missing-fields'; }
108
+ if (!result.length) source.reasons.push('empty_page_not_completeness_proof');
109
+ } catch (error) {
110
+ if (error.status === 403) { source.status = 'denied'; source.reasons.push('http_403'); }
111
+ else if (error.status === 404 || error.code === 'malformed_response') { source.status = 'unavailable'; source.reasons.push(error.status === 404 ? 'http_404' : 'malformed_response'); }
112
+ else throw error;
113
+ break;
114
+ }
115
+ }
116
+ return sort(rows);
117
+ }
118
+ const hierarchy = await read('sys_db_object', 'nameINsys_app,sys_scope,sys_package^ORDERBYsys_id');
119
+ const ownership = await read('sys_dictionary', 'name=sys_metadata^elementINsys_scope,sys_package^ORDERBYsys_id', 1, ['sys_id', 'name', 'element', 'reference']);
120
+ const scopeClass = hierarchy.find(r => r.name === 'sys_scope'), packageClass = hierarchy.find(r => r.name === 'sys_package');
121
+ const validIdentitySchema = scopeClass && packageClass && hierarchy.some(r => r.name === 'sys_app' && r.super_class === scopeClass.sys_id)
122
+ && scopeClass.super_class === packageClass.sys_id && [['sys_scope', 'sys_scope'], ['sys_package', 'sys_package']].every(([element, reference]) => ownership.some(r => r.element === element && r.reference === reference));
123
+ if (!validIdentitySchema) { evidence.limitations.push('Identity schema not established; dependent application and Global discovery refused.'); return evidence; }
124
+ const discovered = await read('sys_scope', 'ORDERBYsys_id', budgets.discoveryPages);
125
+ evidence.candidates = discovered.filter(row => identity.test(row.sys_id || '')).map(row => ({ identity: row.sys_id, name: row.name || 'Unnamed application', namespace: row.scope ?? 'unknown', class: row.sys_class_name ?? 'unknown', source: row.source, selected: false,
126
+ provenance: 'Observed application record; class and Store status do not prove customer authorship.' }));
127
+ const globalApps = evidence.candidates.filter(c => c.namespace === 'global'), scopedApps = evidence.candidates.filter(c => c.namespace !== 'global');
128
+ const selected = [...globalApps.slice(0, 1), ...scopedApps.slice(0, 1), ...evidence.candidates].filter((c, index, list) => list.findIndex(x => x.identity === c.identity) === index).slice(0, budgets.applications);
129
+ for (const candidate of selected) candidate.selected = true;
130
+ const classify = (records, expected, allowDirect = false) => records.filter(record => {
131
+ const owner = documentOwner(record, evidence.candidates);
132
+ if (owner.kind === 'unresolved') { evidence.unresolved.push({ record, ...owner }); return false; }
133
+ return expected ? owner.identity === expected || allowDirect && owner.kind === 'unassigned-global' : owner.kind === 'unassigned-global';
134
+ });
135
+ const portalSchema = await read('sys_dictionary', 'nameINsp_container,sp_row,sp_column,sp_instance^ORDERBYsys_id', 1, ['sys_id', 'name', 'element', 'reference']);
136
+ const portalContracts = [['sp_container', 'sp_page', 'sp_page'], ['sp_row', 'sp_container', 'sp_container'], ['sp_column', 'sp_row', 'sp_row'], ['sp_instance', 'sp_column', 'sp_column'], ['sp_instance', 'sp_widget', 'sp_widget']];
137
+ const portalVerified = portalContracts.every(([name, element, reference]) => portalSchema.some(r => r.name === name && r.element === element && r.reference === reference));
138
+ if (!portalVerified) evidence.limitations.push('Portal reference schema not established; composition collection refused.');
139
+ for (const candidate of selected) {
140
+ const application = { ...candidate, sections: {}, portal_relations: [] };
141
+ evidence.applications.push(application);
142
+ const query = `sys_scope=${candidate.identity}^ORsys_package=${candidate.identity}`;
143
+ const tables = classify(await read('sys_db_object', `${query}^ORDERBYsys_id`), candidate.identity);
144
+ application.sections.sys_db_object = tables;
145
+ const names = [...new Set(tables.map(t => t.name).filter(n => tableName.test(n || '')))];
146
+ for (const table of ['sys_script', 'sys_script_client', 'sys_ui_policy', 'sys_ui_action', 'sys_script_include', 'sys_hub_flow', 'sp_page', 'sp_widget', 'sys_rest_message', 'sys_soap_message', 'sysauto_script']) {
147
+ const target = table === 'sys_script' ? 'collection' : ['sys_script_client', 'sys_ui_policy', 'sys_ui_action'].includes(table) ? 'table' : null;
148
+ const selector = target && names.length ? `${query}^OR${target}IN${names.join(',')}` : query;
149
+ const records = classify(await read(table, `${selector}^ORDERBYsys_id`), candidate.identity, Boolean(target));
150
+ application.sections[table] = records.filter(row => !target || documentOwner(row, evidence.candidates).identity === candidate.identity || names.includes(row[target]));
151
+ }
152
+ application.sections.sys_dictionary = names.length ? classify(await read('sys_dictionary', `nameIN${names.join(',')}^ORDERBYsys_id`), candidate.identity, true) : [];
153
+ if (portalVerified && application.sections.sp_page.length) {
154
+ let parents = application.sections.sp_page;
155
+ for (const [table, field] of portalContracts.slice(0, 4)) {
156
+ const ids = safeIds(parents);
157
+ const records = ids.length ? classify(await read(table, `${field}IN${ids.join(',')}^ORDERBYsys_id`), candidate.identity, true).filter(r => ids.includes(r[field])) : [];
158
+ application.sections[table] = records; parents = records;
159
+ }
160
+ const widgetIds = [...new Set((application.sections.sp_instance || []).map(r => r.sp_widget).filter(v => identity.test(v || '')))];
161
+ if (widgetIds.length) {
162
+ const endpoints = classify(await read('sp_widget', `sys_idIN${widgetIds.join(',')}^ORDERBYsys_id`), candidate.identity, true).filter(r => widgetIds.includes(r.sys_id));
163
+ // Endpoint reads supplement the independent inventory, never replace it.
164
+ // Retain each original row's source, including when the follow-up is denied.
165
+ const widgets = new Map(application.sections.sp_widget.map(row => [row.sys_id, row]));
166
+ for (const endpoint of endpoints) if (!widgets.has(endpoint.sys_id)) widgets.set(endpoint.sys_id, endpoint);
167
+ application.sections.sp_widget = sort([...widgets.values()]);
168
+ }
169
+ for (const instance of application.sections.sp_instance || []) {
170
+ const column = application.sections.sp_column.find(r => r.sys_id === instance.sp_column);
171
+ const row = application.sections.sp_row.find(r => r.sys_id === column?.sp_row);
172
+ const container = application.sections.sp_container.find(r => r.sys_id === row?.sp_container);
173
+ const page = application.sections.sp_page.find(r => r.sys_id === container?.sp_page);
174
+ const widget = application.sections.sp_widget.find(r => r.sys_id === instance.sp_widget);
175
+ if (page && widget) {
176
+ const relation = { application: candidate.identity, page: page.sys_id, widget: widget.sys_id,
177
+ page_title: page.title || page.id, widget_name: widget.name || widget.id,
178
+ path: [page, container, row, column, instance, widget].map(r => ({ sys_id: r.sys_id, source: r.source })), schema_sources: [...new Set(portalSchema.map(r => r.source))] };
179
+ evidence.portal_relations.push(relation); application.portal_relations.push(relation);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ const leads = await read('sys_db_object', 'sys_scope=global^nameSTARTSWITHu_^ORDERBYsys_id');
185
+ evidence.global_candidates = classify(leads).filter(r => r.name?.startsWith('u_'));
186
+ for (const lead of evidence.global_candidates.slice(0, 2)) {
187
+ if (!tableName.test(lead.name)) continue;
188
+ const detail = { table: lead, sections: {} };
189
+ evidence.global_details.push(detail);
190
+ for (const [table, field] of [['sys_dictionary', 'name'], ['sys_script', 'collection'], ['sys_script_client', 'table'], ['sys_ui_policy', 'table'], ['sys_ui_action', 'table']]) detail.sections[table] = classify(await read(table, `${field}=${lead.name}^ORDERBYsys_id`)).filter(r => r[field] === lead.name);
191
+ }
192
+ return evidence;
193
+ }
194
+
195
+ // Numeric entities prevent Markdown/HTML/autolink syntax from metadata labels.
196
+ const md = value => String(value ?? 'unknown').replace(/[^\p{L}\p{N} \n]/gu, char => `&#${char.codePointAt(0)};`).replace(/[\r\n]/g, ' ');
197
+ // Mermaid uses only generated identifiers and an inert, bounded label alphabet.
198
+ const mermaid = value => String(value ?? 'unknown').replace(/[^\p{L}\p{N} ]/gu, ' ').slice(0, 100);
199
+ export function renderInstanceDocumentation(evidence) {
200
+ const lines = ['# Instance configuration documentation', '', `Profile: ${md(evidence.profile)}. Observed: ${md(evidence.observed_at)}.`, '',
201
+ 'Release/build identity: unknown. Coverage: incomplete.', '', ...evidence.limitations.map(text => `- ${md(text)}`), '', '## Application discovery', '',
202
+ '| Application | Namespace | Exact identity | Detail |', '| --- | --- | --- | --- |'];
203
+ for (const c of evidence.candidates) lines.push(`| ${md(c.name)} | ${md(c.namespace)} | ${md(c.identity)} | ${c.selected ? 'selected' : 'deferred by budget'} |`);
204
+ const section = (table, rows) => {
205
+ lines.push(`### ${labels[table] || table}`, '');
206
+ if (!rows.length) { lines.push('No rows established in this bounded collection. See source receipts.', ''); return; }
207
+ const columns = fields[table].filter(f => !['sys_scope', 'sys_package'].includes(f));
208
+ lines.push(`| ${columns.join(' | ')} | Source |`, `| ${columns.map(() => '---').join(' | ')} | --- |`);
209
+ for (const row of rows) lines.push(`| ${columns.map(c => md(row[c])).join(' | ')} | ${md(row.source)} |`);
210
+ lines.push('');
211
+ };
212
+ for (const app of evidence.applications) {
213
+ lines.push(`## ${md(app.name)} ${app.namespace === 'global' ? 'Global application' : 'application'}`, '',
214
+ 'Exact ownership and configured target metadata only. No execution or customer-authorship claim.', '');
215
+ for (const [table, rows] of Object.entries(app.sections)) section(table, rows);
216
+ if (app.portal_relations.length) {
217
+ lines.push('### Verified portal page to widget references', '', '```mermaid', 'flowchart LR');
218
+ app.portal_relations.slice(0, 20).forEach((r, i) => lines.push(` p${i}["${mermaid(r.page_title)}"] -->|configured composition| w${i}["${mermaid(r.widget_name)}"]`));
219
+ lines.push('```', '', 'Collapsed exact-reference paths only. Layout children remain in supporting tables. At most 20 relations drawn.', '');
220
+ }
221
+ }
222
+ lines.push('## Unassigned Global development candidates', '', 'Custom-named table leads only, not proof of customer authorship or baseline changes. Named Global applications are separate.', '');
223
+ section('sys_db_object', evidence.global_candidates);
224
+ for (const detail of evidence.global_details) { lines.push(`### ${md(detail.table.label || detail.table.name)}`, ''); for (const [table, rows] of Object.entries(detail.sections)) section(table, rows); }
225
+ lines.push('## Unresolved ownership', '', `${evidence.unresolved.length} returned records have unresolved ownership. Full projected references and reasons remain in JSON.`, '', '## Source receipts', '',
226
+ `Table requests used: ${evidence.requests_used}/${evidence.budgets.maxRequests}. Provider counts not collected. Completeness unknown.`, '');
227
+ for (const source of evidence.sources) lines.push(`### ${source.id}`, '',
228
+ `Resource: ${md(source.resource)}. Method: GET. Status: ${source.status}. Reasons: ${md(source.reasons.join(', ') || 'none')}.`,
229
+ `Fields: ${md(source.fields.join(', '))}. Query: ${md(source.query)}.`,
230
+ `Observed: ${md(source.observed_at)}. Limit: ${source.bounds.limit}, offset: ${source.bounds.offset}, count: ${source.count ?? 'unknown'}, continuation: ${source.continuation}. Completeness unknown.`, '');
231
+ return lines.join('\n') + '\n';
232
+ }
233
+
234
+ export function writeDocumentFile(destination, markdown) {
235
+ const fd = fs.openSync(destination, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0), 0o600);
236
+ try { fs.writeFileSync(fd, markdown, 'utf8'); } finally { fs.closeSync(fd); }
237
+ }
package/src/output.js CHANGED
@@ -126,6 +126,16 @@ export class OutputWriter {
126
126
  return this.format;
127
127
  }
128
128
 
129
+ // Export callers can preflight exactly the extraction that ok() will emit,
130
+ // before creating a local file or performing another irreversible side effect.
131
+ validateExtraction(data, opts = {}) {
132
+ if (!this.jqFilter) return undefined;
133
+ const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
134
+ const value = resolvePath(envelope, this.jqFilter);
135
+ if (value === undefined) throw errExtractionNotFound(this.jqFilter);
136
+ return value;
137
+ }
138
+
129
139
  ok(data, opts = {}) {
130
140
  // --get extractor: resolve against the JSON envelope and print just that
131
141
  // value as JSON. Takes precedence over styling/table formats — a path
@@ -136,9 +146,7 @@ export class OutputWriter {
136
146
  // typo looked like a successful empty result until the next tool in the
137
147
  // pipeline failed to parse it. Present null/false/0/"" still print as-is.
138
148
  if (this.jqFilter) {
139
- const envelope = { ok: true, data, summary: opts.summary || '', breadcrumbs: opts.breadcrumbs || [], ...(opts.context ? { context: opts.context } : {}) };
140
- const value = resolvePath(envelope, this.jqFilter);
141
- if (value === undefined) throw errExtractionNotFound(this.jqFilter);
149
+ const value = this.validateExtraction(data, opts);
142
150
  const indent = this.verbose && !this.raw ? 2 : undefined;
143
151
  const text = this.raw && typeof value === 'string' ? value : JSON.stringify(value, null, indent);
144
152
  this.writer.write(text + '\n');
package/src/scan.js CHANGED
@@ -100,6 +100,34 @@ export async function scanAjax(sdk, method, parameters) {
100
100
  }
101
101
 
102
102
  const TERMINAL = new Set(['successful', 'failed', 'cancelled']);
103
+ // Execution tracker types that belong to Instance Scan. Exact matches only:
104
+ // no aliases or prefix matching, so unrelated trackers cannot be read as scans.
105
+ const SCAN_TRACKER_TYPES = new Set(['instance_scan', 'point_scan']);
106
+
107
+ // Read the execution back-reference from a result row without guessing: a
108
+ // non-empty value that is not a full sys_id is still "present, but not ours".
109
+ // Strings are checked by type so the legacy String.prototype.link is never read
110
+ // as a reference.
111
+ function hasResultBackReference(value) {
112
+ if (typeof value === 'string') return value !== '';
113
+ if (typeof value === 'object' && value !== null) return Boolean(raw(value) || value.link);
114
+ return false;
115
+ }
116
+
117
+ function resultBackReference(value) {
118
+ if (typeof value === 'object' && value !== null) return referenceId(value);
119
+ return isSysId(String(value ?? '')) ? String(value) : '';
120
+ }
121
+ // 'malformed' means a payload exists but could not be read as a reference.
122
+ // Parsing a reference is not verification: only results can verify linkage.
123
+ function resultLink(value) {
124
+ const text = raw(value);
125
+ if (!text) return { state: 'missing', id: '' };
126
+ try {
127
+ const id = referenceId(JSON.parse(text).result_id);
128
+ return id ? { state: 'linked', id } : { state: 'malformed', id: '' };
129
+ } catch { return { state: 'malformed', id: '' }; }
130
+ }
103
131
  const STATES = { '0': 'pending', '1': 'running', '2': 'successful', '3': 'failed', '4': 'cancelled',
104
132
  pending: 'pending', running: 'running', successful: 'successful', failed: 'failed',
105
133
  cancelled: 'cancelled', canceled: 'cancelled' };
@@ -108,19 +136,25 @@ export async function scanStatus(sdk, id, { allowInitializing = false } = {}) {
108
136
  requireId(id);
109
137
  const tracker = await sdk.get('sys_execution_tracker', id);
110
138
  if (!tracker) throw errNotFound('scan execution', id);
111
- if (!raw(tracker.type) && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
112
- percent_complete: null, message: 'Execution tracker is initializing', result_id: null };
113
- if (raw(tracker.type) === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
114
- percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued', result_id: null };
115
- if (raw(tracker.type) !== 'instance_scan') throw errUsage('This execution tracker is not an Instance Scan.');
139
+ // Missing or denied identity is not evidence that this is our execution.
140
+ const trackerId = tracker.sys_id === undefined || tracker.sys_id === null ? '' : String(raw(tracker.sys_id));
141
+ if (trackerId !== id) throw errUsage('The execution tracker identity does not match the requested execution.');
142
+ const type = String(raw(tracker.type) ?? '');
143
+ const link = resultLink(tracker.result);
144
+ if (!type && allowInitializing) return { execution_id: id, status: 'pending', terminal: false,
145
+ phase: 'initializing', percent_complete: null, message: 'Execution tracker is initializing', result_id: null,
146
+ execution_type: type, result_link: link.state };
147
+ if (type === 'sys.instance_scan.queue') return { execution_id: id, status: 'pending', terminal: false,
148
+ phase: 'queued', percent_complete: raw(tracker.percent_complete) ?? null, message: raw(tracker.message) || 'Scan is queued',
149
+ result_id: null, execution_type: type, result_link: link.state };
150
+ if (!SCAN_TRACKER_TYPES.has(type)) throw errUsage('This execution tracker is not an Instance Scan.');
116
151
  const state = STATES[String(raw(tracker.state)).toLowerCase()] || 'unknown';
117
- let resultId = '';
118
- if (raw(tracker.result)) {
119
- try { resultId = referenceId(JSON.parse(raw(tracker.result)).result_id); } catch { /* reported as unavailable below */ }
120
- }
121
- return { execution_id: id, status: state, terminal: TERMINAL.has(state),
152
+ // result_link only says the tracker's own result JSON parsed; a result row and
153
+ // its back-reference are verified in scanResults, never here.
154
+ return { execution_id: id, status: state, terminal: TERMINAL.has(state), phase: 'dispatched',
122
155
  percent_complete: raw(tracker.percent_complete) ?? null,
123
- message: raw(tracker.message) || '', result_id: resultId || null };
156
+ message: raw(tracker.message) || '', result_id: link.id || null,
157
+ execution_type: type, result_link: link.state };
124
158
  }
125
159
 
126
160
  async function resolveSuite(sdk, identifier) {
@@ -205,19 +239,44 @@ export async function startScan(sdk, plan) {
205
239
  export async function scanResults(sdk, id, limit = 50) {
206
240
  boundedLimit(limit);
207
241
  const status = await scanStatus(sdk, id);
208
- const data = { ...status, checks_executed: null, findings_count: null, checks: [], findings: [],
242
+ const data = { ...status, checks_executed: null, findings_count: null, findings_retrieved: null,
243
+ checks: [], findings: [], result_verified: false, back_reference: 'absent',
244
+ findings_state: 'unknown', checks_state: 'unknown',
209
245
  incomplete: !status.terminal, unavailable: [], truncated: {}, rerun_full: false, reusable_target: false };
210
246
  if (!status.result_id) { data.unavailable.push('scan_result'); data.incomplete = true; return data; }
211
247
  let result;
212
248
  try {
213
249
  result = await sdk.get('scan_result', status.result_id);
214
250
  if (!result) throw new Error('Result unavailable');
215
- data.scan_number = raw(result.number);
216
- const value = raw(result.finding_count);
217
- const count = Number(value);
218
- if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
219
- else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
251
+ // Require the exact linked identity, including when the field is denied.
252
+ const resultId = result.sys_id === undefined || result.sys_id === null ? '' : String(raw(result.sys_id));
253
+ if (resultId !== status.result_id) {
254
+ data.unavailable.push('scan_result.identity');
255
+ data.incomplete = true;
256
+ result = null;
257
+ }
220
258
  } catch { data.unavailable.push('scan_result'); data.incomplete = true; }
259
+ if (result) {
260
+ // The result row must point back to this execution. A point scan always
261
+ // records its execution id; a foreign or absent back-reference means the
262
+ // row cannot be trusted to describe this scan. Only a matching
263
+ // back-reference earns result_verified; a parsed id alone does not.
264
+ const present = hasResultBackReference(result.progress_id);
265
+ const matches = present && resultBackReference(result.progress_id) === status.execution_id;
266
+ data.back_reference = present ? (matches ? 'matched' : 'foreign') : 'absent';
267
+ if ((present && !matches) || (!present && status.execution_type === 'point_scan')) {
268
+ data.unavailable.push('scan_result.back_reference');
269
+ data.incomplete = true;
270
+ result = null;
271
+ } else {
272
+ data.result_verified = matches;
273
+ data.scan_number = raw(result.number);
274
+ const value = raw(result.finding_count);
275
+ const count = Number(value);
276
+ if ((typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value))) && Number.isInteger(count) && count >= 0) data.findings_count = count;
277
+ else { data.unavailable.push('scan_result.finding_count'); data.incomplete = true; }
278
+ }
279
+ }
221
280
  for (const [key, table, fields] of [
222
281
  ['checks', 'scan_check_execution', ['check', 'message', 'execution_time']],
223
282
  ['findings', 'scan_finding', ['check', 'source_table', 'source', 'finding_details', 'count']],
@@ -225,11 +284,27 @@ export async function scanResults(sdk, id, limit = 50) {
225
284
  try {
226
285
  const rows = await sdk.listStrict(table, recordListParams({ limit: limit + 1,
227
286
  query: `result=${status.result_id}^ORDERBYsys_id`, fields, displayValue: 'all' }));
287
+ if (!Array.isArray(rows) || rows.some(row => !row || typeof row !== 'object' || Array.isArray(row))) {
288
+ throw new Error('Unreadable scan rows');
289
+ }
228
290
  data[key] = rows.slice(0, limit);
229
291
  data.truncated[key] = rows.length > limit;
292
+ if (key === 'findings') data.findings_retrieved = rows.length;
230
293
  if (key === 'checks' && !data.truncated[key] && status.terminal) data.checks_executed = rows.length;
231
294
  } catch { data.unavailable.push(table); data.incomplete = true; }
232
295
  }
296
+ // Reported counts must reconcile with retrieved rows. A positive count with
297
+ // nothing retrieved, or any other disagreement, is not a clean zero and its
298
+ // cause is not assumed. Truncated pages cannot be reconciled at all.
299
+ if (data.findings_count === null || data.unavailable.includes('scan_finding')) data.findings_state = 'unknown';
300
+ else if (data.truncated.findings) { data.findings_state = 'truncated'; data.incomplete = true; }
301
+ else if (data.findings_count > 0 && data.findings_retrieved === 0) { data.findings_state = 'unretrieved'; data.incomplete = true; }
302
+ else if (data.findings_count !== data.findings_retrieved) { data.findings_state = 'mismatch'; data.incomplete = true; }
303
+ else data.findings_state = 'verified';
304
+ if (data.unavailable.includes('scan_check_execution')) data.checks_state = 'unknown';
305
+ else if (data.truncated.checks) { data.checks_state = 'truncated'; data.incomplete = true; }
306
+ else if (data.checks.length === 0) data.checks_state = 'empty';
307
+ else data.checks_state = 'verified';
233
308
  const comboId = referenceId(result?.combo);
234
309
  if (comboId) {
235
310
  try { const combo = await sdk.get('scan_combo', comboId); if (combo) { data.reusable_target = true; data.rerun_full = !raw(combo.targets); } }