@jacebenson/jsn 5.5.3-dev.181.1 → 5.5.3-dev.183.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.3-dev.181.1",
3
+ "version": "5.5.3-dev.183.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": {
@@ -28,6 +28,7 @@
28
28
  "@inquirer/core": "^10.3.2",
29
29
  "@inquirer/prompts": "^7.10.1",
30
30
  "better-sqlite3": "^13.1.1",
31
+ "commonmark": "^0.31.2",
31
32
  "js-yaml": "^5.5.0",
32
33
  "saxes": "^6.0.0",
33
34
  "turndown": "^7.2.5"
@@ -0,0 +1,53 @@
1
+ // Historical baseline: Jace Benson, https://github.com/arnoudkooi/SN-Utils/issues/91.
2
+ // Candidates, not assumed schema: each field is validated by GraphQL before use.
3
+ // No active-only filters: inactive artifacts are useful search results too.
4
+ export const CODESEARCH_CATALOG = Object.fromEntries(Object.entries({
5
+ bsm_action: 'name script',
6
+ cmn_map_page: 'name script',
7
+ content_block_programmatic: 'name programmatic_content',
8
+ ecc_agent_script_include: 'name script',
9
+ kb_navons: 'name script',
10
+ metric_definition: 'name script',
11
+ process_step_approval: 'name approver_script',
12
+ sc_cat_item_producer: 'name delivery_plan_script entitlement_script post_insert_script script',
13
+ sp_angular_provider: 'name script',
14
+ sp_search_source: 'name data_fetch_script facet_generation_script search_page_template typeahead_template',
15
+ sp_widget: 'name template script client_script link css',
16
+ sysauto_script: 'name script condition',
17
+ sysevent_email_action: 'name advanced_condition message message_html sms_alternate subject',
18
+ sysevent_email_template: 'name message message_html sms_alternate subject',
19
+ sysevent_in_email_action: 'name script filter_conditions condition_script',
20
+ sysevent_script_action: 'name script condition_script event_name',
21
+ sys_app_quota: 'query',
22
+ sys_dictionary: 'dynamic_ref_qual reference_qual attributes default_value calculation',
23
+ sys_dictionary_override: 'reference_qual attributes default_value calculation',
24
+ sys_filter_option_dynamic: 'name script_reference_id script',
25
+ sys_installation_exit: 'name script',
26
+ sys_processor: 'name script description path class_name',
27
+ sys_properties: 'name choices value',
28
+ sys_relationship: 'name apply_to query_from query_with',
29
+ sys_script: 'name script condition filter_condition',
30
+ sys_script_ajax: 'name script',
31
+ sys_script_client: 'name script',
32
+ sys_script_email: 'name script',
33
+ sys_script_fix: 'name script',
34
+ sys_script_include: 'name script description',
35
+ sys_script_validator: 'description validator',
36
+ sys_security_acl: 'name script condition',
37
+ sys_transform_entry: 'source_script',
38
+ sys_transform_map: 'name script',
39
+ sys_transform_script: 'script',
40
+ sys_trigger: 'name script job_context',
41
+ sys_ui_action: 'name script condition onclick',
42
+ sys_ui_context_menu: 'name action_script condition on_show_script',
43
+ sys_ui_list_control: 'columns_condition edit_condition empty_condition filter_condition link_condition new_condition',
44
+ sys_ui_macro: 'name xml',
45
+ sys_ui_page: 'name client_script html processing_script',
46
+ sys_ui_policy: 'short_description script_false script_true conditions',
47
+ sys_ui_script: 'name script',
48
+ sys_variable_value: 'value',
49
+ sys_web_service: 'name script',
50
+ sys_widgets: 'name script',
51
+ sys_ws_operation: 'name operation_script',
52
+ wf_activity_definition: 'name script',
53
+ }).map(([table, fields]) => [table, fields.split(' ')]));
@@ -0,0 +1,177 @@
1
+ import { AppError, errAuth, errForbidden, errUsage } from './errors.js';
2
+ import { CODESEARCH_CATALOG } from './codesearch-catalog.js';
3
+
4
+ const identifier = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
5
+ const value = (v) => v && typeof v === 'object' ? v.value : v;
6
+ const isAccessFailure = (error) => ['auth_error', 'forbidden', 'mfa_required', 'mfa_code_rejected'].includes(error.code)
7
+ || /\b401\b|\b403\b|access denied|not authorized|\bforbidden\b|\bunauthorized\b|\bunauthenticated\b/i.test(`${error.status || ''} ${error.message}`);
8
+ function literal(text, label) {
9
+ // Glide encoded-query has no reliable literal escape for separators or eval.
10
+ if (/[\^\r\n\0]/.test(text) || /javascript:/i.test(text)) {
11
+ throw errUsage(`${label} cannot contain encoded-query separators or javascript:`);
12
+ }
13
+ return text;
14
+ }
15
+ function fail(message, code = 'api_error') {
16
+ return new AppError(code, message);
17
+ }
18
+ export function matchingRows(record, table, fields, term) {
19
+ if (!term) throw errUsage('A search term is required');
20
+ const rows = [];
21
+ const needle = term.toLowerCase();
22
+ for (const field of fields) {
23
+ const text = String(value(record[field]) ?? '');
24
+ let matches = 0;
25
+ const lines = [];
26
+ let context = '';
27
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
28
+ const lower = line.toLowerCase();
29
+ let position = 0;
30
+ let count = 0;
31
+ while ((position = lower.indexOf(needle, position)) !== -1) {
32
+ count++;
33
+ position += needle.length;
34
+ }
35
+ if (count) {
36
+ matches += count;
37
+ lines.push(index + 1);
38
+ if (!context) context = line.trim().slice(0, 240);
39
+ }
40
+ }
41
+ if (matches) rows.push({ table, name: String(value(record.name) ?? value(record.short_description) ?? value(record.sys_id)),
42
+ field, lines: lines.join(','), matches, context, sys_id: value(record.sys_id) });
43
+ }
44
+ return rows;
45
+ }
46
+
47
+ export async function searchGraphQL(app, options) {
48
+ const { term, table, scope, allScopes = true, searchGroup = 'sn_devstudio.Studio Search Group',
49
+ limit = 100, pageSize = 250, maxPages = 20, maxRequests = 1000 } = options;
50
+ if (!term?.trim()) throw errUsage('A search term is required');
51
+ literal(term, 'Search term');
52
+ if (scope) literal(scope, 'Scope');
53
+ if (table && !identifier.test(table)) throw errUsage('Invalid table identifier');
54
+ for (const [name, number, max] of [['limit', limit, 100000], ['page-size', pageSize, 1000],
55
+ ['max-pages', maxPages, 1000], ['max-requests', maxRequests, 10000]]) {
56
+ if (!Number.isInteger(number) || number < 1 || number > max) throw errUsage(`${name} must be an integer from 1 to ${max}`);
57
+ }
58
+ if (!allScopes && !scope) throw errUsage('--no-all-scopes requires an explicit --scope');
59
+ const base = app.getEffectiveInstance();
60
+ let requests = 0;
61
+ const coverage = [];
62
+ const records = [];
63
+ const definitions = new Map(Object.entries(CODESEARCH_CATALOG).map(([name, fields]) => [name, { fields: [...fields], filters: [] }]));
64
+ // Search-group configuration is additive; never silently omit configured fields.
65
+ let configuration = { status: 'complete' };
66
+ try {
67
+ const params = new URLSearchParams({ sysparm_query: `search_group.name=${literal(searchGroup, 'Search group')}^ORDERBYsys_id`,
68
+ sysparm_limit: '1001', sysparm_fields: 'table,search_fields,additional_filter', sysparm_display_value: 'false' });
69
+ requests++;
70
+ const payload = await app.sdk.request(`${base}/api/now/table/sn_codesearch_table?${params}`);
71
+ if (!Array.isArray(payload?.result)) throw fail('Unreadable sn_codesearch_table response');
72
+ if (payload.result.length > 1000) throw fail('Search configuration exceeds 1000 rows');
73
+ for (const row of payload.result) {
74
+ const name = value(row.table);
75
+ const fields = String(value(row.search_fields) ?? '').split(/[,\s]+/).filter(Boolean);
76
+ if (!identifier.test(name) || !fields.length || fields.some((f) => !identifier.test(f)) || !Object.hasOwn(row, 'additional_filter')) {
77
+ throw fail('Invalid configured table or search fields');
78
+ }
79
+ const definition = definitions.get(name) || { fields: [], filters: [] };
80
+ definition.fields = [...new Set([...definition.fields, ...fields])];
81
+ const filter = String(value(row.additional_filter) ?? '').replace(/\^EQ$/, '');
82
+ if (/javascript:|(?:^|\^)ORDERBY|(?:^|\^)GROUPBY|(?:^|\^)EQ(?:\^|$)|[\r\n\0]/i.test(filter)) {
83
+ // Configuration is data, not permission to execute scripts or reorder.
84
+ definition.invalidFilter = 'Configured additional_filter contains script or query control directives';
85
+ }
86
+ if (filter) definition.filters.push(filter);
87
+ definitions.set(name, definition);
88
+ }
89
+ } catch (error) {
90
+ if (isAccessFailure(error)) throw error;
91
+ configuration = { status: 'partial', reason: error.message };
92
+ }
93
+ if (table && !definitions.has(table)) throw errUsage(`No curated or configured fields for ${table}`);
94
+ const targets = table ? [[table, definitions.get(table)]] : [...definitions];
95
+ let matchedRecords = 0;
96
+ for (const [name, definition] of targets) {
97
+ const status = { table: name, fields: definition.fields, status: 'partial', pages: 0, fetched: 0, reason: 'request budget' };
98
+ coverage.push(status);
99
+ if (definition.invalidFilter) { status.reason = definition.invalidFilter; continue; }
100
+ if (matchedRecords >= limit) { status.reason = 'record limit'; continue; }
101
+ const seen = new Set();
102
+ let fields = [...definition.fields];
103
+ let previous = '';
104
+ for (let page = 0; page < maxPages; page++) {
105
+ if (requests >= maxRequests) { status.reason = 'request budget'; break; }
106
+ // Distribute restrictions into every OR/NQ branch so filters cannot escape scope.
107
+ const branches = definition.filters.length ? definition.filters.flatMap((filter) => filter.split('^NQ')) : [''];
108
+ const query = branches.map((filter) => [filter, scope ? `sys_scope.scope=${scope}` : '',
109
+ fields.map((field) => `${field}LIKE${term}`).join('^OR')].filter(Boolean).join('^')).join('^NQ') + '^ORDERBYsys_id';
110
+ const selection = [...new Set(['sys_id', ...(scope ? ['sys_scope'] : []), ...fields])].map((field) => `${field} { value }`).join(' ');
111
+ const graphql = `query { GlideRecord_Query { ${name}(queryConditions: ${JSON.stringify(query)}, pagination: {limit: ${pageSize}, offset: ${page * pageSize}}) { _results { ${selection} } } } }`;
112
+ requests++;
113
+ let payload;
114
+ try {
115
+ payload = await app.sdk.request(`${base}/api/now/graphql`, { method: 'POST', body: JSON.stringify({ query: graphql }) });
116
+ const envelope = payload?.result ?? payload;
117
+ if (payload?.errors?.length || envelope?.errors?.length) {
118
+ const errors = payload.errors || envelope.errors;
119
+ if (errors.some((error) => /UNAUTHENTICATED/i.test(error.extensions?.code || ''))) {
120
+ throw errAuth(`GraphQL authentication rejected: ${errors.map((error) => error.message).join('; ')}`);
121
+ }
122
+ if (errors.some((error) => /FORBIDDEN|ACCESS_DENIED/i.test(error.extensions?.code || ''))) {
123
+ throw errForbidden(`GraphQL access denied: ${errors.map((error) => error.message).join('; ')}`);
124
+ }
125
+ throw fail(errors.map((e) => e.message || String(e)).join('; '), 'graphql_error');
126
+ }
127
+ if (payload?.ok === false || envelope?.error) throw fail(JSON.stringify(envelope.error || payload.error));
128
+ const rows = envelope?.data?.GlideRecord_Query?.[name]?._results;
129
+ if (!Array.isArray(rows)) throw fail('GraphQL response is missing _results');
130
+ status.pages++;
131
+ if (!rows.length) {
132
+ status.status = status.unsupportedFields?.length ? 'partial' : 'complete';
133
+ if (status.unsupportedFields?.length) status.reason = `Unsupported fields: ${status.unsupportedFields.join(', ')}`;
134
+ else delete status.reason;
135
+ break;
136
+ }
137
+ for (const row of rows) {
138
+ const id = value(row.sys_id);
139
+ if (!id || seen.has(id) || (previous && id <= previous)) throw fail('Unstable pagination: missing, duplicate or unordered sys_id');
140
+ if ([...fields, ...(scope ? ['sys_scope'] : [])].some((field) => !Object.hasOwn(row, field) || row[field] == null)) throw fail('GraphQL omitted a requested field (schema or access restriction)');
141
+ previous = id;
142
+ seen.add(id);
143
+ status.fetched++;
144
+ const hits = matchingRows(row, name, fields, term);
145
+ if (hits.length) { records.push(...hits); matchedRecords++; }
146
+ if (matchedRecords >= limit) break;
147
+ }
148
+ if (matchedRecords >= limit) { status.reason = 'record limit'; break; }
149
+ status.reason = 'page budget';
150
+ } catch (error) {
151
+ if (isAccessFailure(error)) {
152
+ if (error.code === 'graphql_error') {
153
+ throw /\b401\b|unauthorized|unauthenticated/i.test(error.message) ? errAuth(error.message) : errForbidden(error.message);
154
+ }
155
+ throw error;
156
+ }
157
+ // Only explicit schema-validation failures may narrow the selection.
158
+ // Never reinterpret ACL errors or missing data as nonexistent fields.
159
+ const missing = [...error.message.matchAll(/Cannot query field ["'](\w+)["']/g)]
160
+ .map((match) => match[1]).filter((field) => fields.includes(field));
161
+ if (missing.length && error.code === 'graphql_error') {
162
+ status.unsupportedFields = [...new Set([...(status.unsupportedFields || []), ...missing])];
163
+ fields = fields.filter((field) => !missing.includes(field));
164
+ if (fields.length) { page--; continue; }
165
+ }
166
+ status.reason = error.message;
167
+ status.status = /Cannot query field|Unknown field|Unknown type/i.test(error.message) ? 'unsupported' : 'partial';
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ const state = configuration.status === 'complete' && coverage.every((item) => item.status === 'complete') ? 'complete' :
173
+ coverage.every((item) => item.status === 'unsupported') ? 'unsupported' : 'partial';
174
+ return { term, count: records.length, records, recordCount: matchedRecords, fieldCount: records.length,
175
+ matchCount: records.reduce((sum, row) => sum + row.matches, 0), status: state,
176
+ coverage, configuration, requests, hint: 'Flow internals require separate jsn flows search; no flow downloads are performed.' };
177
+ }
@@ -1,50 +1,20 @@
1
- // jsn codesearch — search across ServiceNow code artifacts (script includes,
2
- // business rules, client scripts, UI actions, ...) via the sn_codesearch
3
- // plugin REST API. Issue #180.
4
-
5
- import { errUsage } from '../errors.js';
6
-
7
- const DEFAULT_SEARCH_GROUP = 'sn_devstudio.Studio Search Group';
8
-
9
- // Flatten the API's nested shape into one row per record/field so the output
10
- // controller can render it as a table / CSV / JSON.
11
- //
12
- // API shape:
13
- // result: [ { recordType, hits: [ { name, className, tableLabel,
14
- // matches: [ { field, fieldLabel,
15
- // lineMatches: [ { line, context, escaped } ] } ] } ] } ] }
16
- // NOTE: with ?table=<t> the API returns a single object, not an array.
17
- export function flattenHits(result) {
18
- const groups = Array.isArray(result) ? result : (result ? [result] : []);
19
- const rows = [];
20
- for (const group of groups) {
21
- for (const hit of group.hits || []) {
22
- for (const match of hit.matches || []) {
23
- const lines = (match.lineMatches || []).filter((lm) => lm.context);
24
- rows.push({
25
- table: hit.className || group.recordType,
26
- name: hit.name,
27
- field: match.field,
28
- lines: lines.map((lm) => lm.line).join(','),
29
- matches: lines.length,
30
- context: lines[0]?.context?.trim() || '',
31
- sys_id: hit.sys_id || hit.sysId || '',
32
- });
33
- }
34
- }
1
+ // GraphQL read-only queries; no sn_codesearch engine or Flow downloads.
2
+ import { searchGraphQL } from '../codesearch-graphql.js';
3
+
4
+ export function renderCodeSearch(data) {
5
+ const out = [`${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}`];
6
+ for (const row of data.records) {
7
+ out.push(`${row.table} ${row.name} .${row.field} (lines ${row.lines})`);
8
+ if (row.context) out.push(` ${row.context}`);
35
9
  }
36
- return rows;
37
- }
38
-
39
- // Pre-rendered text view for styled/terminal output (output.js uses
40
- // data._formatted when present).
41
- function renderFormatted(rows, term) {
42
- if (rows.length === 0) return `No code matches for "${term}".\n`;
43
- const out = [];
44
- for (const r of rows) {
45
- out.push(`${r.table} ${r.name} .${r.field} (lines ${r.lines})`);
46
- if (r.context) out.push(` ${r.context}`);
10
+ if (!data.records.length) out.push(`No visible code matches for "${data.term}".`);
11
+ const gaps = data.coverage.filter((item) => item.status !== 'complete');
12
+ for (const gap of gaps) {
13
+ out.push(`${gap.table}: ${gap.status} (${gap.reason})`);
14
+ if (gap.unsupportedFields?.length) out.push(` Unsupported fields: ${gap.unsupportedFields.join(', ')}`);
47
15
  }
16
+ if (data.configuration.status !== 'complete') out.push(`Search configuration: ${data.configuration.reason}`);
17
+ out.push(data.hint);
48
18
  return out.join('\n') + '\n';
49
19
  }
50
20
 
@@ -52,52 +22,26 @@ export function codesearchCmd(wrap) {
52
22
  return {
53
23
  command: 'codesearch [subcommand]',
54
24
  aliases: ['codesearch'],
55
- describe: 'Search code across ServiceNow artifacts (script includes, business rules, client scripts, ...)',
56
- builder: (yargs) => yargs
57
- .command({
58
- command: 'search <term>',
59
- describe: 'Search code for a term (e.g. "codesearch search GlideAjax")',
60
- builder: (y) => y
61
- .positional('term', { type: 'string', describe: 'Search term' })
62
- .option('limit', { alias: 'l', type: 'number', default: 100, describe: 'Max results' })
63
- .option('table', { alias: 't', type: 'string', describe: 'Restrict to one source table (e.g. sys_script_include)' })
64
- .option('scope', { alias: 's', type: 'string', describe: 'Restrict to an app scope (e.g. x_my_app)' })
65
- .option('search-group', { type: 'string', default: DEFAULT_SEARCH_GROUP, describe: 'Search group to use' })
66
- .option('all-scopes', { type: 'boolean', default: true, describe: 'Search across all scopes (default true)' }),
67
- handler: wrap(async (argv, app) => {
68
- if (!argv.term || !argv.term.trim()) {
69
- throw errUsage('A search term is required', 'Example: jsn codesearch search GlideAjax');
70
- }
71
-
72
- const params = new URLSearchParams();
73
- params.set('term', argv.term);
74
- params.set('limit', String(argv.limit));
75
- params.set('search_group', argv.searchGroup);
76
- params.set('search_all_scopes', String(argv.allScopes));
77
- if (argv.table) params.set('table', argv.table);
78
- if (argv.scope) params.set('scope', argv.scope);
79
-
80
- const url = `${app.getEffectiveInstance()}/api/sn_codesearch/code_search/search?${params.toString()}`;
81
- let payload;
82
- try {
83
- payload = await app.sdk.request(url);
84
- } catch (err) {
85
- if (err.code === 'api_error' && /404/.test(err.message)) {
86
- err.message += '\n\nHint: the sn_codesearch plugin may not be active on this instance.';
87
- }
88
- throw err;
89
- }
90
-
91
- const result = payload?.result || [];
92
- const rows = flattenHits(result);
93
-
94
- app.ok(
95
- { term: argv.term, count: rows.length, records: rows, _formatted: renderFormatted(rows, argv.term) },
96
- { summary: `${rows.length} code match(es) for "${argv.term}"` },
97
- );
98
- }),
99
- })
100
- .demandCommand(1, 'Specify a subcommand: search'),
25
+ describe: 'Search code across ServiceNow artifacts with read-only GraphQL queries',
26
+ builder: (yargs) => yargs.command({
27
+ command: 'search <term>',
28
+ describe: 'Search code; Flow internals require separate jsn flows search',
29
+ builder: (y) => y
30
+ .positional('term', { type: 'string', describe: 'Literal case-insensitive search term (no encoded-query separators)' })
31
+ .option('limit', { alias: 'l', type: 'number', default: 100, describe: 'Max matching records (coverage is partial when reached)' })
32
+ .option('table', { alias: 't', type: 'string', describe: 'Restrict to a curated or configured source table' })
33
+ .option('scope', { alias: 's', type: 'string', describe: 'Restrict to an app scope (e.g. x_my_app)' })
34
+ .option('search-group', { type: 'string', default: 'sn_devstudio.Studio Search Group', describe: 'Layer configured fields and filters from this group over the curated catalog' })
35
+ .option('all-scopes', { type: 'boolean', default: true, describe: 'Search all scopes; false requires --scope' })
36
+ .option('page-size', { type: 'number', default: 250, describe: 'GraphQL page window size (max 1000)' })
37
+ .option('max-pages', { type: 'number', default: 20, describe: 'Maximum pages per table (max 1000)' })
38
+ .option('max-requests', { type: 'number', default: 1000, describe: 'Data-call budget including configuration, excluding SDK auth/bootstrap (max 10000)' }),
39
+ handler: wrap(async (argv, app) => {
40
+ const data = await searchGraphQL(app, argv);
41
+ Object.defineProperty(data, '_formatted', { value: renderCodeSearch(data), enumerable: false });
42
+ app.ok(data, { summary: `${data.recordCount} record(s), ${data.fieldCount} field(s), ${data.matchCount} match(es) — ${data.status}` });
43
+ }),
44
+ }).demandCommand(1, 'Specify a subcommand: search'),
101
45
  handler: () => {},
102
46
  };
103
47
  }
@@ -1,5 +1,6 @@
1
1
  // Public documentation service. Deliberately independent of instance credentials.
2
2
  import { AppError } from '../../errors.js';
3
+ import { selectDocument, SECTION_PROTOCOL } from './sections.js';
3
4
 
4
5
  export const DEFAULT_DOCS_URL = 'https://jsn.jace.pro';
5
6
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
@@ -73,12 +74,27 @@ export async function searchHostedDocs(options = {}) {
73
74
  export async function getHostedDoc(idOrPath, options = {}) {
74
75
  const identifier = String(idOrPath || '');
75
76
  if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
77
+ if ((options.outline && options.section !== undefined) || (options.section !== undefined && !String(options.section).trim())) throw new AppError('usage_error', 'Use either --outline or one nonempty --section.');
76
78
  const numeric = /^\d+$/.test(identifier);
77
79
  const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
78
80
  ...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
81
+ outline: options.outline || undefined, section: options.section,
79
82
  }, options);
80
- if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
81
- return { ...data.document, release: options.release ?? data.release, revision: data.revision, service };
83
+ const targeted = options.outline || options.section !== undefined;
84
+ const native = data?.section_protocol === SECTION_PROTOCOL;
85
+ if (!data?.document || typeof data.document.path !== 'string' || typeof data.revision !== 'string' ||
86
+ (!(targeted && native && options.outline) && typeof data.document.body !== 'string')) throw invalidResponse();
87
+ if (options.revision && data.revision !== options.revision) throw new AppError('api_error', 'Documentation revision mismatch. Refresh the outline.');
88
+ if (options.release && data.document.release && data.document.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.document.release}, expected ${options.release}.`);
89
+ let row = { ...data.document, release: options.release ?? data.release ?? data.document.release, revision: data.revision, service };
90
+ if (targeted) {
91
+ if (!native) row = selectDocument(row, options);
92
+ const mode = options.outline ? 'outline' : 'section';
93
+ if (row.retrieval?.protocol !== SECTION_PROTOCOL || row.retrieval?.mode !== mode ||
94
+ (options.outline ? !Array.isArray(row.outline) : !row.section || row.retrieval.subtree_complete !== true)) throw invalidResponse();
95
+ row.retrieval = { ...row.retrieval, execution: native ? 'service' : 'client-fallback', full_document_transferred: !native };
96
+ }
97
+ return row;
82
98
  }
83
99
  export async function getHostedDocsStatus(options = {}) {
84
100
  const { data, service } = await request('api/docs/status', { release: options.release }, options);
@@ -9,6 +9,10 @@ import { listDocsReleases } from './releases.js';
9
9
 
10
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
11
 
12
+ function presented(data, text) {
13
+ return Object.defineProperty(data, '_formatted', { value: text, enumerable: false });
14
+ }
15
+
12
16
  async function search(argv, app) {
13
17
  const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
14
18
  const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
@@ -29,11 +33,18 @@ async function search(argv, app) {
29
33
  async function read(argv, app) {
30
34
  const maxLines = argv.lines ?? 80;
31
35
  if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
32
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
36
+ const row = await getHostedDoc(argv.path || argv['id-or-path'], { outline: argv.outline, section: argv.section, revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
33
37
  const title = row.title || row.path;
38
+ const provenance = `${row.path}\nRelease: ${row.release} | Revision: ${row.revision}\nService: ${row.service}`;
39
+ if (row.outline) {
40
+ const text = row.outline.map(h => `${' '.repeat(h.ancestors.length)}${h.title} [lines ${h.start_line}–${h.end_line}]\n${' '.repeat(h.ancestors.length)} ${h.id}`).join('\n');
41
+ return app.ok(presented(row, `${title}\n${provenance}\n\n${text || 'No selectable headings.'}\n\nUse --section '<ID>' with this --path. Selection includes preamble and ancestor introductions.\nOther sections and linked prerequisites may still matter.\nRetrieval: ${row.retrieval.execution}; full document transferred: ${row.retrieval.full_document_transferred}\n`));
42
+ }
34
43
  const lines = row.body.split('\n');
35
44
  const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
36
- app.ok({ ...row, _formatted: `Doc ${row.id}: ${title} in ${row.release}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title} in ${row.release}` });
45
+ const content = row.section ? row.body : lines.slice(0, maxLines).join('\n') + hint;
46
+ const context = row.section ? `\nComplete selected subtree: ${row.section.title}\n${row.retrieval.context_policy}\nOther sections to check: ${row.retrieval.context_sections.map(h => h.title).join('; ') || 'none'}.\nUse --outline to retrieve their IDs.\nSemantic answer completeness: unknown. Retrieval: ${row.retrieval.execution}.\n` : '';
47
+ app.ok(presented(row, `Doc ${row.id}: ${title} in ${row.release}\n${provenance}${context}\n${content}\n`), { summary: `Doc ${row.id}: ${title} in ${row.release}` });
37
48
  }
38
49
 
39
50
  export function docsCmd(wrap) {
@@ -53,7 +64,9 @@ export function docsCmd(wrap) {
53
64
  .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
54
65
  .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
55
66
  .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
56
- .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
67
+ .option('outline', { type: 'boolean', describe: 'List revision-bound section IDs for --path, without document body' })
68
+ .option('section', { type: 'string', describe: 'Read a complete subtree by outline ID or exact unique heading; includes ancestor introductions' })
69
+ .option('lines', { type: 'number', default: 80, describe: 'Full-document human preview lines; JSON and selected sections are not truncated' })
57
70
  .command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
58
71
  const releases = listDocsReleases();
59
72
  app.ok({ releases, _formatted: releases.length ? releases.map(row => `${row.release}${row.default ? ' (default)' : ''} ${row.revision || 'unknown'} ${row.documents} documents ${row.indexPath}`).join('\n') + '\n' : 'No local documentation families installed.\n' }, { summary: `${releases.length} local documentation release(s)` });
@@ -90,6 +103,7 @@ export function docsCmd(wrap) {
90
103
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
91
104
  return;
92
105
  }
106
+ if ((argv.outline || argv.section !== undefined) && !argv.path) throw new AppError('usage_error', 'Use --path with --outline or --section.');
93
107
  if (argv.path) return read(argv, app);
94
108
  if (argv.query?.length) return search(argv, app);
95
109
  const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
@@ -1,5 +1,6 @@
1
1
  // One search engine for the hosted website and the optional local service.
2
2
  import fs from 'node:fs';
3
+ import { selectDocument } from './sections.js';
3
4
  import path from 'node:path';
4
5
  import Database from 'better-sqlite3';
5
6
  import { resolveDocsDbPath } from './db.js';
@@ -72,11 +73,11 @@ export class DocumentationIndex {
72
73
  .all(...binds, text, text, text, limit, offset).map(documentationSummary);
73
74
  return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
74
75
  }
75
- document({ id, path: docPath } = {}) {
76
+ document({ id, path: docPath, outline = false, section } = {}) {
76
77
  const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
77
78
  const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
78
79
  : /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
79
80
  if (!row) throw new DocumentationError('Document not found.', 404);
80
- return row;
81
+ return outline || section !== undefined ? selectDocument({ ...row, revision: this.revision() }, { outline, section }) : row;
81
82
  }
82
83
  }
@@ -0,0 +1,59 @@
1
+ // CommonMark source positions let us slice original text, never reserialize tables/code.
2
+ import * as commonmark from 'commonmark';
3
+ import { createHash } from 'node:crypto';
4
+ import { AppError } from '../../errors.js';
5
+
6
+ export const SECTION_PROTOCOL = 'sections-v1';
7
+ function failure(message) { return new AppError('usage_error', message, 'Use --outline for exact titles and revision-bound IDs.', 400); }
8
+ export function selectDocument(row, { outline = false, section } = {}) {
9
+ if (outline && section !== undefined) throw failure('Use either --outline or --section, not both.');
10
+ if (section !== undefined && !String(section).trim()) throw failure('Section must not be empty.');
11
+ if (!outline && section === undefined) return row;
12
+ const body = row.body;
13
+ const starts = [0];
14
+ for (const match of body.matchAll(/\r\n|\n|\r/g)) starts.push(match.index + match[0].length);
15
+ const ast = new commonmark.Parser().parse(body);
16
+ const headings = [];
17
+ for (let node = ast.firstChild; node; node = node.next) {
18
+ if (node.type !== 'heading') continue; // Never split lists, blockquotes or HTML blocks.
19
+ let title = '', walker = node.walker(), event;
20
+ while ((event = walker.next())) {
21
+ if (event.entering && ['text', 'code'].includes(event.node.type)) title += event.node.literal;
22
+ if (event.entering && ['softbreak', 'linebreak'].includes(event.node.type)) title += ' ';
23
+ }
24
+ headings.push({ title, depth: node.level, start_line: node.sourcepos[0][0], start: starts[node.sourcepos[0][0] - 1] });
25
+ }
26
+ const identity = createHash('sha256').update(JSON.stringify([SECTION_PROTOCOL, row.path, row.release, row.revision, body])).digest('hex').slice(0, 24);
27
+ const stack = [];
28
+ for (let i = 0; i < headings.length; i++) {
29
+ const h = headings[i];
30
+ while (stack.length && headings[stack.at(-1)].depth >= h.depth) stack.pop();
31
+ h.ancestors = stack.map(n => headings[n].id);
32
+ h.id = `s1:${identity}:${i + 1}`;
33
+ const next = headings.slice(i + 1).find(n => n.depth <= h.depth);
34
+ h.end = next?.start ?? body.length;
35
+ h.end_line = next ? next.start_line - 1 : starts.length;
36
+ h.introEnd = headings[i + 1]?.start ?? body.length;
37
+ stack.push(i);
38
+ }
39
+ const publicHeading = ({ start: _start, end: _end, introEnd: _introEnd, ...h }) => h; // Offsets remain an implementation detail.
40
+ const metadata = { protocol: SECTION_PROTOCOL, document_complete: false, semantic_completeness: 'unknown', truncated: false,
41
+ heading_policy: 'CommonMark top-level ATX/setext; container and HTML headings are not boundaries' };
42
+ const { body: _body, ...identityRow } = row;
43
+ if (outline) return { ...identityRow, outline: headings.map(publicHeading), retrieval: { ...metadata, mode: 'outline', total_lines: starts.length, context_policy: 'Selection includes preamble and ancestor introductions; other sections may contain relevant context.' } };
44
+ const matches = headings.filter(h => h.id === section || h.title === section);
45
+ if (!matches.length) throw failure('No matching section. IDs are document- and revision-bound; refresh the outline.');
46
+ if (matches.length !== 1) throw failure(`Ambiguous section ${JSON.stringify(section)}. Choose an ID: ${matches.map(h => `${h.id} (${h.title}, line ${h.start_line})`).join('; ')}`);
47
+ const h = matches[0];
48
+ const spans = [];
49
+ const add = (start, end, kind) => { if (end > start) spans.push({ start, end, kind }); };
50
+ add(0, headings[0]?.start ?? body.length, 'preamble');
51
+ for (const id of h.ancestors) { const a = headings.find(n => n.id === id); add(a.start, a.introEnd, 'ancestor-introduction'); }
52
+ add(h.start, h.end, 'section-subtree');
53
+ return { ...identityRow, body: spans.map(s => body.slice(s.start, s.end)).join(''), section: publicHeading(h), retrieval: {
54
+ ...metadata, mode: 'section', subtree_complete: true, document_complete: spans.reduce((n, s) => n + s.end - s.start, 0) === body.length,
55
+ context_policy: 'Preamble and ancestor introductions included. Sibling sections and linked prerequisites are not automatically included; read the full document when needed.',
56
+ context_sections: headings.filter(n => !spans.some(s => n.start >= s.start && n.start < s.end)).map(n => ({ id: n.id, title: n.title })),
57
+ included_spans: spans.map(s => ({ start_offset: s.start, end_offset: s.end, kind: s.kind })),
58
+ } };
59
+ }
@@ -1,4 +1,5 @@
1
1
  import http from 'node:http';
2
+ import { SECTION_PROTOCOL } from './sections.js';
2
3
  import fs from 'node:fs';
3
4
  import path from 'node:path';
4
5
  import os from 'node:os';
@@ -27,7 +28,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
27
28
  if (url.pathname === '/api/docs/search') return send(200, { ...index.search({ query: params.q, limit: params.limit ?? 20, offset: params.offset ?? 0, bundle: params.bundle }), release });
28
29
  const revision = index.revision();
29
30
  if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
30
- return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
31
+ if (params.outline !== undefined && params.outline !== 'true') return send(400, { error: 'outline must be true.' });
32
+ const document = index.document({ path: params.path, id: url.pathname.split('/').at(-1), outline: params.outline === 'true', section: params.section });
33
+ return send(200, { release, revision, section_protocol: SECTION_PROTOCOL, document });
31
34
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
32
35
  finally { index?.close(); }
33
36
  });