@jacebenson/jsn 5.5.1 → 5.5.2-dev.173.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.
Files changed (51) hide show
  1. package/README.md +30 -2
  2. package/package.json +1 -1
  3. package/src/app.js +15 -2
  4. package/src/auth/mfa.js +85 -0
  5. package/src/cli-adapter.js +18 -4
  6. package/src/cli.js +26 -8
  7. package/src/commands/_generic.js +10 -2
  8. package/src/commands/_ticket.js +12 -4
  9. package/src/commands/approvals.js +1 -0
  10. package/src/commands/auth.js +15 -8
  11. package/src/commands/cases.js +1 -1
  12. package/src/commands/cmdb.js +1 -1
  13. package/src/commands/discover.js +1 -0
  14. package/src/commands/docs/client.js +17 -7
  15. package/src/commands/docs/community.js +4 -4
  16. package/src/commands/docs/db.js +26 -11
  17. package/src/commands/docs/docs.js +30 -13
  18. package/src/commands/docs/embed.js +2 -2
  19. package/src/commands/docs/index-worker.js +1 -1
  20. package/src/commands/docs/index.js +4 -3
  21. package/src/commands/docs/ingest.js +4 -4
  22. package/src/commands/docs/install.js +19 -17
  23. package/src/commands/docs/local.js +6 -4
  24. package/src/commands/docs/refresh.js +3 -3
  25. package/src/commands/docs/releases.js +27 -0
  26. package/src/commands/docs/search.js +3 -3
  27. package/src/commands/docs/serve.js +3 -3
  28. package/src/commands/docs/server.js +13 -10
  29. package/src/commands/docs/service-snapshot.js +3 -3
  30. package/src/commands/docs/snapshot.js +32 -11
  31. package/src/commands/docs/sync-service.js +8 -6
  32. package/src/commands/docs/sync.js +24 -15
  33. package/src/commands/flows.js +70 -5
  34. package/src/commands/knowledge.js +1 -0
  35. package/src/commands/records.js +12 -3
  36. package/src/commands/setup.js +20 -8
  37. package/src/commands/tickets.js +11 -3
  38. package/src/errors.js +23 -1
  39. package/src/flow-create.js +1237 -57
  40. package/src/flow-inspection.js +26 -2
  41. package/src/help.js +95 -21
  42. package/src/helpers.js +20 -1
  43. package/src/output.js +19 -5
  44. package/src/prompts.js +9 -0
  45. package/src/record-command-profiles.js +8 -4
  46. package/src/record-profiles.js +1 -0
  47. package/src/records-engine.js +2 -1
  48. package/src/sdk.js +157 -15
  49. package/src/setup-preferences.js +3 -3
  50. package/src/table-read-params.js +9 -0
  51. package/src/welcome.js +34 -36
@@ -5,9 +5,11 @@ import path from 'node:path';
5
5
  import os from 'node:os';
6
6
  import Database from 'better-sqlite3';
7
7
  import { docsReaderLease } from './locks.js';
8
+ import { AppError } from '../../errors.js';
8
9
 
9
10
  const LEGACY_DOCS_DIR_NAME = 'servicenow-cli/docs';
10
11
  const DOCS_DIR_NAME = 'docs';
12
+ export const DEFAULT_DOCS_RELEASE = 'australia'; // Bump when a new release family ships.
11
13
 
12
14
  function xdgCacheHome() {
13
15
  if (process.env.XDG_CACHE_HOME) return process.env.XDG_CACHE_HOME;
@@ -79,16 +81,29 @@ export function getDocsDbPath() {
79
81
  return path.join(getDocsCacheDir(), 'docs.db');
80
82
  }
81
83
 
82
- export function getDocsSourceDir() {
83
- return path.join(getDocsCacheDir(), 'source');
84
+ export function resolveDocsRelease(value, config = {}) {
85
+ const release = value ?? config.docs?.release ?? DEFAULT_DOCS_RELEASE;
86
+ if (typeof release !== 'string' || !/^[a-z0-9-]{1,40}$/.test(release)) {
87
+ throw new AppError('usage_error', 'Documentation release must contain 1–40 lowercase letters, digits or dashes.');
88
+ }
89
+ return release;
90
+ }
91
+
92
+ export function resolveDocsDbPath(release = DEFAULT_DOCS_RELEASE) {
93
+ release = resolveDocsRelease(release);
94
+ return release === DEFAULT_DOCS_RELEASE ? getDocsDbPath() : path.join(jsnDataHome(), DOCS_DIR_NAME, 'releases', release, 'docs.db');
95
+ }
96
+
97
+ export function getDocsSourceDir(release) {
98
+ return path.join(path.dirname(resolveDocsDbPath(release)), 'source');
84
99
  }
85
100
 
86
- export function getDocsSourceMarkdownDir() {
87
- return path.join(getDocsSourceDir(), 'markdown');
101
+ export function getDocsSourceMarkdownDir(release) {
102
+ return path.join(getDocsSourceDir(release), 'markdown');
88
103
  }
89
104
 
90
- export function getDocsCommunityDir() {
91
- return path.join(getDocsCacheDir(), 'community');
105
+ export function getDocsCommunityDir(release) {
106
+ return path.join(path.dirname(resolveDocsDbPath(release)), 'community');
92
107
  }
93
108
 
94
109
  export function ensureDocsCacheDir() {
@@ -122,15 +137,15 @@ export function* walkDocs(roots) {
122
137
  }
123
138
 
124
139
  export function defaultDocsRoots(opts = {}) {
125
- const communityDir = opts.communityDir || getDocsCommunityDir();
140
+ const communityDir = opts.communityDir || getDocsCommunityDir(opts.release);
126
141
  return [
127
- { dir: opts.docsDir || getDocsSourceMarkdownDir(), prefix: '' },
142
+ { dir: opts.docsDir || getDocsSourceMarkdownDir(opts.release), prefix: '' },
128
143
  { dir: communityDir, prefix: 'community/' },
129
144
  ];
130
145
  }
131
146
 
132
147
  export function openDocsDb(opts = {}) {
133
- const dbPath = opts.dbPath || getDocsDbPath();
148
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
134
149
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
135
150
  const release = docsReaderLease(dbPath);
136
151
  let db;
@@ -156,8 +171,8 @@ export function closeDocsDb(db) {
156
171
  }
157
172
  }
158
173
 
159
- export function docsDbExists() {
160
- return fs.existsSync(getDocsDbPath());
174
+ export function docsDbExists(release) {
175
+ return fs.existsSync(resolveDocsDbPath(release));
161
176
  }
162
177
 
163
178
  export function getSchemaVersion(db) {
@@ -1,16 +1,19 @@
1
1
  // Documentation search always uses the same API, hosted or self-hosted.
2
- import { searchHostedDocs, getHostedDoc, getHostedDocsStatus } from './client.js';
2
+ import { searchHostedDocs, getHostedDoc, getHostedDocsStatus, configuredDocsService } from './client.js';
3
3
  import { documentationService } from './local.js';
4
4
  import { startDocumentationServer } from './server.js';
5
5
  import { declareCapabilities } from '../../capabilities.js';
6
6
  import { AppError } from '../../errors.js';
7
+ import { resolveDocsRelease } from './db.js';
8
+ import { listDocsReleases } from './releases.js';
7
9
 
8
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
9
11
 
10
12
  async function search(argv, app) {
11
13
  const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
12
- const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, serviceUrl: await documentationService(app.config) });
13
- const lines = [];
14
+ 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)) });
15
+ const summary = `${result.count} of ${result.total} result(s) for "${result.query}" in ${result.release}`;
16
+ const lines = [summary, ''];
14
17
  for (const row of result.results) {
15
18
  lines.push(`[${row.id}] ${row.title || row.path}`, ` ${row.path}`);
16
19
  const summary = String(row.summary || row.snippet || '').replace(/\s+/g, ' ').trim();
@@ -21,16 +24,16 @@ async function search(argv, app) {
21
24
  if (result.count && next < result.total && next <= 10000) lines.push(`… ${result.total - next} more results (use --offset ${next} for the next page)`);
22
25
  if (!result.count) lines.push('No matching documents. Try fewer words or a different term.');
23
26
  if (result.count) lines.push('Read with "jsn docs --path <exact-path>"; IDs can be pinned with --revision.');
24
- app.ok({ ...result, _formatted: lines.join('\n') + '\n' }, { summary: `${result.count} of ${result.total} result(s) for "${result.query}"` });
27
+ app.ok({ ...result, _formatted: lines.join('\n') + '\n' }, { summary });
25
28
  }
26
29
  async function read(argv, app) {
27
30
  const maxLines = argv.lines ?? 80;
28
31
  if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
29
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, serviceUrl: await documentationService(app.config) });
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)) });
30
33
  const title = row.title || row.path;
31
34
  const lines = row.body.split('\n');
32
35
  const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
33
- app.ok({ ...row, _formatted: `${title}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title}` });
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}` });
34
37
  }
35
38
 
36
39
  export function docsCmd(wrap) {
@@ -41,6 +44,7 @@ export function docsCmd(wrap) {
41
44
  builder: y => y
42
45
  .usage('Usage: jsn docs "search terms" [options]')
43
46
  .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
47
+ .option('release', { type: 'string', describe: 'Documentation family (docs.release config, otherwise australia)' })
44
48
  .option('serve', { type: 'boolean', describe: 'Run the shared documentation server (downloads its index automatically)' })
45
49
  .option('host', { type: 'string', default: '127.0.0.1', describe: 'Server bind address with --serve' })
46
50
  .option('port', { type: 'number', default: 3000, describe: 'Server port with --serve' })
@@ -50,32 +54,45 @@ export function docsCmd(wrap) {
50
54
  .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
51
55
  .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
52
56
  .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
57
+ .command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
58
+ const releases = listDocsReleases();
59
+ 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)` });
60
+ }) })
61
+ .command({ command: 'sync', describe: 'Clone or update a documentation family and its local index',
62
+ builder: y => y.option('embed', { type: 'boolean', default: true }).option('ingest', { type: 'boolean', default: true }),
63
+ handler: wrap(async (argv, app) => {
64
+ const { syncDocs } = await import('./sync.js');
65
+ const release = resolveDocsRelease(argv.release, app.config);
66
+ app.ok({ ...syncDocs({ release, embed: argv.embed, noIngest: argv.ingest === false }), release });
67
+ }),
68
+ })
53
69
  // Compatibility spellings remain callable without becoming another menu.
54
70
  .command({ command: 'install', hidden: true,
55
71
  builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'] })
56
72
  .option('manifest-url', { type: 'string' }),
57
73
  handler: wrap(async (argv, app) => {
58
74
  const { installDocumentation } = await import('./install.js');
59
- app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] }));
75
+ app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'], release: resolveDocsRelease(argv.release, app.config), serviceUrl: configuredDocsService(app.config) }));
60
76
  }),
61
77
  })
62
78
  .command({ command: 'search <query..>', hidden: true, handler: wrap(search) })
63
79
  .command({ command: 'show <id-or-path>', hidden: true, handler: wrap(read) })
64
- .command({ command: 'status', hidden: true, handler: wrap(async (_argv, app) => {
65
- const data = await getHostedDocsStatus({ serviceUrl: await documentationService(app.config) });
66
- app.ok(data, { summary: `Documentation service: ${data.state}` });
80
+ .command({ command: 'status', hidden: true, handler: wrap(async (argv, app) => {
81
+ const data = await getHostedDocsStatus({ release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
82
+ app.ok(data, { summary: `Documentation service: ${data.state} in ${data.release}` });
67
83
  }) }),
68
84
  handler: wrap(async (argv, app) => {
69
85
  if (argv.serve) {
70
86
  if (!Number.isInteger(argv.port) || argv.port < 0 || argv.port > 65535) throw new AppError('usage_error', 'Use a port between 0 and 65535.');
71
- const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port });
72
- app.ok({ url, state: 'listening' }, { summary: 'Documentation server started; the index updates automatically.' });
87
+ const release = resolveDocsRelease(argv.release, app.config);
88
+ const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port, release });
89
+ app.ok({ url, release, state: 'listening' }, { summary: `Documentation server started for ${release}; the index updates automatically.` });
73
90
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
74
91
  return;
75
92
  }
76
93
  if (argv.path) return read(argv, app);
77
94
  if (argv.query?.length) return search(argv, app);
78
- const service = await documentationService(app.config);
95
+ const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
79
96
  const summary = 'Search ServiceNow documentation';
80
97
  app.ok({ command: 'docs', service,
81
98
  _formatted: `jsn docs "search terms"\njsn docs --path <exact-path>\n\nService: ${service}\nChange documentation preferences in jsn setup → Defaults and documentation.\nNo ServiceNow connection is needed. Hosted mode downloads no database.\n`,
@@ -1,11 +1,11 @@
1
1
  // Populate HRR phase-vector embeddings for semantic reranking.
2
2
 
3
3
  import fs from 'node:fs';
4
- import { withDocsDb, getDocsDbPath } from './db.js';
4
+ import { withDocsDb, resolveDocsDbPath } from './db.js';
5
5
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
6
6
 
7
7
  export function embedDocs(opts = {}) {
8
- const dbPath = opts.dbPath || getDocsDbPath();
8
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
9
9
 
10
10
  if (!fs.existsSync(dbPath)) {
11
11
  throw new Error(`Database not found: ${dbPath}. Run "jsn docs sync" first.`);
@@ -6,7 +6,7 @@ try {
6
6
  for await (const line of readline.createInterface({ input: process.stdin, crlfDelay: Infinity })) {
7
7
  try {
8
8
  const { operation, arguments: args = {} } = JSON.parse(line);
9
- if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR);
9
+ if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR, process.env.JSN_DOCS_RELEASE || undefined);
10
10
  const value = operation === 'summary' ? documentationSummary(args) : operation === 'revision' ? index.revision()
11
11
  : operation === 'search' ? index.search(args) : operation === 'document' ? index.document(args) : null;
12
12
  process.stdout.write(JSON.stringify({ value }) + '\n');
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import Database from 'better-sqlite3';
5
+ import { resolveDocsDbPath } from './db.js';
5
6
 
6
7
  export class DocumentationError extends Error {
7
8
  constructor(message, status = 503) { super(message); this.status = status; }
@@ -47,12 +48,12 @@ export function documentationSummary(input) {
47
48
  };
48
49
  }
49
50
  export class DocumentationIndex {
50
- constructor(storage) {
51
- try { this.db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
51
+ constructor(storage, release) {
52
+ try { this.db = new Database(release ? resolveDocsDbPath(release) : path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
52
53
  catch { throw new DocumentationError('Documentation is being prepared. Please try again shortly.'); }
53
54
  }
54
55
  close() { this.db.close(); }
55
- revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || ''; }
56
+ revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || this.db.prepare("SELECT value FROM meta WHERE key = 'snapshot_revision'").get()?.value || ''; }
56
57
  search({ query, limit = 20, offset = 0, bundle } = {}) {
57
58
  const text = String(query || '').trim();
58
59
  if (!text || text.length > 200) throw new DocumentationError('Enter a search of 1 to 200 characters.', 400);
@@ -7,14 +7,14 @@ import { docsReaderLease } from './locks.js';
7
7
  import { installDatabase } from './replace.js';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { parseFrontmatter } from '../../frontmatter.js';
10
- import { withDocsDb, initDocsSchema, getDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
10
+ import { withDocsDb, initDocsSchema, resolveDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
11
11
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
12
12
 
13
13
  export function ingestDocs(opts = {}) {
14
- const dbPath = opts.dbPath || getDocsDbPath();
14
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
15
15
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
16
16
  const staging = `${dbPath}.${randomUUID()}.building`;
17
- const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir() : null);
17
+ const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir(opts.release) : null);
18
18
  if (resource) fs.mkdirSync(path.dirname(resource), { recursive: true });
19
19
  const releaseSource = resource && !opts.sourceLeaseHeld ? docsReaderLease(resource) : () => {};
20
20
  try {
@@ -25,7 +25,7 @@ export function ingestDocs(opts = {}) {
25
25
  } finally { releaseSource(); fs.rmSync(staging, { force: true }); }
26
26
  }
27
27
  function ingestStagedDocs(opts = {}) {
28
- const dbPath = opts.dbPath || getDocsDbPath();
28
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
29
29
  const embed = opts.embed !== false;
30
30
  const roots = opts.roots || defaultDocsRoots(opts);
31
31
 
@@ -3,36 +3,37 @@ import path from 'node:path';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { docsReaderLease } from './locks.js';
6
- import { getDocsDbPath, getDocsCacheDir, getDocsSourceDir } from './db.js';
7
- import { fetchManifest, installSnapshot, snapshotEstimate, validateDatabase, installDatabase, docsSnapshotStatus, DEFAULT_MANIFEST_URL } from './snapshot.js';
6
+ import { resolveDocsDbPath, resolveDocsRelease, getDocsSourceDir } from './db.js';
7
+ import { fetchManifest, fetchReleaseManifest, installSnapshot, snapshotEstimate, validateDatabase, installDatabase, docsSnapshotStatus, DEFAULT_MANIFEST_URL } from './snapshot.js';
8
8
  import { canUsePicker } from '../../helpers.js';
9
9
  import { errUsageHint } from '../../errors.js';
10
10
 
11
11
  export async function installDocumentation(source, options = {}) {
12
- if (source === 'skip') return { source, skipped: true };
12
+ const release = resolveDocsRelease(options.release);
13
+ const target = resolveDocsDbPath(release);
14
+ if (source === 'skip') return { source, release, skipped: true };
13
15
  if (source === 'snapshot') {
14
- const manifestURL = options.manifestURL || DEFAULT_MANIFEST_URL;
15
- const manifest = options.manifest || await fetchManifest(manifestURL);
16
+ const { manifestURL, manifest } = options.manifest ? { manifest: options.manifest, manifestURL: options.manifestURL || DEFAULT_MANIFEST_URL } : await fetchReleaseManifest({ ...options, release });
16
17
  process.stderr.write(`Prebuilt searchable database: ${snapshotEstimate(manifest)}.\n`);
17
- return installSnapshot({ manifestURL, manifest });
18
+ return installSnapshot({ manifestURL, manifest, release, dbPath: target });
18
19
  }
19
20
  if (source !== 'github') throw errUsageHint('Choose a documentation source.', 'Use jsn docs install --source snapshot|github|skip');
20
21
  process.stderr.write('Raw GitHub source: approximately 51,000 files plus local indexing; estimated 5–25 minutes including semantic indexing (prior runs ~5 minutes; validation full build ~21 minutes; actual time and size vary).\n');
21
- fs.mkdirSync(getDocsCacheDir(), { recursive: true });
22
- const staging = fs.mkdtempSync(path.join(getDocsCacheDir(), '.github-install-'));
22
+ fs.mkdirSync(path.dirname(target), { recursive: true });
23
+ const staging = fs.mkdtempSync(path.join(path.dirname(target), '.github-install-'));
23
24
  try {
24
25
  const { syncDocs } = await import('./sync.js');
25
26
  const { ingestDocs } = await import('./ingest.js');
26
- const repoDir = getDocsSourceDir(), dbPath = path.join(staging, 'docs.db');
27
- syncDocs({ repoDir, markdownDir: path.join(repoDir, 'markdown'), noIngest: true, embed: false });
27
+ const repoDir = getDocsSourceDir(release), dbPath = path.join(staging, 'docs.db');
28
+ syncDocs({ release, repoDir, markdownDir: path.join(repoDir, 'markdown'), noIngest: true, embed: false });
28
29
  const releaseSource = docsReaderLease(repoDir);
29
30
  let result;
30
31
  try { result = ingestDocs({ dbPath, roots: [{ dir: path.join(repoDir, 'markdown'), prefix: '' }], embed: true }); }
31
32
  finally { releaseSource(); }
32
33
  if (result.errors) throw new Error('Raw documentation indexing failed; existing index retained');
33
34
  validateDatabase(dbPath);
34
- installDatabase(dbPath, getDocsDbPath(), { afterInstall: () => fs.rmSync(`${getDocsDbPath()}.snapshot.json`, { force: true }) });
35
- return { source, documents: result.count, dbPath: getDocsDbPath() };
35
+ installDatabase(dbPath, target, { afterInstall: () => fs.rmSync(`${target}.snapshot.json`, { force: true }) });
36
+ return { source, release, documents: result.count, dbPath: target };
36
37
  } finally { fs.rmSync(staging, { recursive: true, force: true }); }
37
38
  }
38
39
  export async function chooseDocumentationSource() {
@@ -59,25 +60,26 @@ export async function offerDocumentation(_app, _argv = {}) {
59
60
  return installDocumentation(source, { manifest: approvedManifest });
60
61
  }
61
62
  export async function ensureDocumentation(app, argv) {
62
- if (fs.existsSync(getDocsDbPath())) { scheduleFreshnessCheck(); return; }
63
+ const release = resolveDocsRelease(argv.release, app.config);
64
+ if (fs.existsSync(resolveDocsDbPath(release))) { scheduleFreshnessCheck(release); return; }
63
65
  if (!canUsePicker(app, argv)) throw errUsageHint('No local documentation index. Documentation installation is optional and requires a source choice.',
64
66
  'Run jsn docs install --source snapshot for a verified prebuilt database, or --source github for raw files + local indexing (estimated 5–25 minutes). Use --source skip to defer.');
65
67
  const result = await offerDocumentation(app, argv);
66
68
  if (result.skipped) throw errUsageHint('Documentation installation skipped.', 'Run jsn docs install --source snapshot|github when ready.');
67
69
  }
68
- export function scheduleFreshnessCheck() {
70
+ export function scheduleFreshnessCheck(release) {
69
71
  if (process.env.JSN_NO_DOCS_CHECK === '1') return;
70
- const receipt = docsSnapshotStatus();
72
+ const receipt = docsSnapshotStatus(release);
71
73
  if (!receipt) return;
72
74
  try {
73
- const stamp = `${getDocsDbPath()}.check-stamp`;
75
+ const stamp = `${resolveDocsDbPath(release)}.check-stamp`;
74
76
  try {
75
77
  if (Date.now() - fs.statSync(stamp).mtimeMs < 86400000) return;
76
78
  fs.rmSync(stamp);
77
79
  } catch (error) { if (error.code !== 'ENOENT') return; }
78
80
  fs.writeFileSync(stamp, '', { flag: 'wx' });
79
81
  // A separate bounded worker prevents network from delaying local search.
80
- const child = spawn(process.execPath, [fileURLToPath(new URL('./snapshot-check.js', import.meta.url)), getDocsDbPath()], {
82
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./snapshot-check.js', import.meta.url)), resolveDocsDbPath(release)], {
81
83
  detached: true, stdio: 'ignore', windowsHide: true,
82
84
  });
83
85
  child.on('error', () => {});
@@ -6,6 +6,7 @@ import { setTimeout as delay } from 'node:timers/promises';
6
6
  import { AppError } from '../../errors.js';
7
7
  import { configuredDocsService, docsServiceUrl } from './client.js';
8
8
  import os from 'node:os';
9
+ import { resolveDocsDbPath } from './db.js';
9
10
 
10
11
  function storageDirectory() { return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
11
12
  async function healthy(state) {
@@ -17,7 +18,8 @@ async function healthy(state) {
17
18
  return response.ok && (await response.json()).service === 'jsn-docs';
18
19
  } catch { return false; }
19
20
  }
20
- export async function ensureLocalDocumentation({ storage = storageDirectory() } = {}) {
21
+ export async function ensureLocalDocumentation({ storage = storageDirectory(), release } = {}) {
22
+ if (release) storage = path.dirname(resolveDocsDbPath(release));
21
23
  fs.mkdirSync(storage, { recursive: true, mode: 0o700 });
22
24
  const stateFile = path.join(storage, 'server.json'), lock = path.join(storage, 'server-start.lock');
23
25
  const state = () => { try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch { return {}; } };
@@ -43,7 +45,7 @@ export async function ensureLocalDocumentation({ storage = storageDirectory() }
43
45
  const log = fs.openSync(path.join(storage, 'server.log'), 'a', 0o600);
44
46
  try {
45
47
  child = fork(fileURLToPath(new URL('./server.js', import.meta.url)), [], { detached: true, execArgv: [],
46
- env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_HOST: '127.0.0.1', JSN_DOCS_PORT: '0' }, stdio: ['ignore', log, log, 'ipc'] });
48
+ env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_RELEASE: release || '', JSN_DOCS_HOST: '127.0.0.1', JSN_DOCS_PORT: '0' }, stdio: ['ignore', log, log, 'ipc'] });
47
49
  } finally { fs.closeSync(log); }
48
50
  const next = await new Promise((resolve, reject) => {
49
51
  const timer = setTimeout(() => { child.kill(); reject(new Error('Timed out starting the documentation server.')); }, 10_000);
@@ -61,8 +63,8 @@ export async function ensureLocalDocumentation({ storage = storageDirectory() }
61
63
  throw new AppError('network_error', 'Could not start the local documentation service.', error.message);
62
64
  } finally { fs.rmSync(lock, { recursive: true, force: true }); }
63
65
  }
64
- export async function documentationService(config = {}) {
66
+ export async function documentationService(config = {}, release) {
65
67
  if (process.env.JSN_DOCS_URL) return docsServiceUrl(process.env.JSN_DOCS_URL);
66
- if (config.docs?.source === 'local') return (await ensureLocalDocumentation()).url;
68
+ if (config.docs?.source === 'local') return (await ensureLocalDocumentation({ release })).url;
67
69
  return configuredDocsService(config);
68
70
  }
@@ -7,17 +7,17 @@ import { docsReaderLease } from './locks.js';
7
7
  import { errUsageHint } from '../../errors.js';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { parseFrontmatter } from '../../frontmatter.js';
10
- import { withDocsDb, getDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
10
+ import { withDocsDb, resolveDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
11
11
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
12
12
 
13
13
  export function refreshDocs(opts = {}) {
14
- const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir() : null);
14
+ const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir(opts.release) : null);
15
15
  if (resource) fs.mkdirSync(path.dirname(resource), { recursive: true });
16
16
  const release = resource && !opts.sourceLeaseHeld ? docsReaderLease(resource) : () => {};
17
17
  try { return refreshDocsLocked(opts); } finally { release(); }
18
18
  }
19
19
  function refreshDocsLocked(opts = {}) {
20
- const dbPath = opts.dbPath || getDocsDbPath();
20
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
21
21
  const roots = opts.roots || defaultDocsRoots(opts);
22
22
 
23
23
  if (roots.some(root => (!root.prefix || opts.roots) && (!fs.existsSync(root.dir) || !fs.statSync(root.dir).isDirectory()))) {
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import Database from 'better-sqlite3';
4
+ import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, getMeta } from './db.js';
5
+ import { docsReaderLease } from './locks.js';
6
+
7
+ // Local discovery deliberately does not depend on the hosted service.
8
+ export function listDocsReleases() {
9
+ const directory = path.join(path.dirname(resolveDocsDbPath()), 'releases');
10
+ const families = new Set([DEFAULT_DOCS_RELEASE]);
11
+ if (fs.existsSync(directory)) for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
12
+ if (entry.isDirectory() && /^[a-z0-9-]{1,40}$/.test(entry.name)) families.add(entry.name);
13
+ }
14
+ const rows = [];
15
+ for (const release of [...families].sort()) {
16
+ const indexPath = resolveDocsDbPath(release);
17
+ if (!fs.existsSync(indexPath)) continue;
18
+ const unlock = docsReaderLease(indexPath);
19
+ let db;
20
+ try {
21
+ db = new Database(indexPath, { readonly: true, fileMustExist: true });
22
+ rows.push({ release, revision: getMeta(db, 'source_revision') || getMeta(db, 'snapshot_revision'),
23
+ documents: db.prepare('SELECT COUNT(*) AS n FROM docs').get().n, indexPath, default: release === DEFAULT_DOCS_RELEASE });
24
+ } finally { db?.close(); unlock(); }
25
+ }
26
+ return rows;
27
+ }
@@ -1,7 +1,7 @@
1
1
  // CLI search against the docs SQLite database.
2
2
 
3
3
  import fs from 'node:fs';
4
- import { getDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
4
+ import { resolveDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
5
5
  import { sanitizeFts5Query } from './fts.js';
6
6
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
7
7
 
@@ -20,7 +20,7 @@ function safeParse(s) {
20
20
  * handle (pass opts.dbPath to target a non-default database — used by tests).
21
21
  */
22
22
  export function getDocByIdOrPath(idOrPath, opts = {}) {
23
- const dbPath = opts.dbPath || getDocsDbPath();
23
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
24
24
  const db = openDocsDb({ dbPath });
25
25
  try {
26
26
  let row;
@@ -44,7 +44,7 @@ export function getDocByIdOrPath(idOrPath, opts = {}) {
44
44
  }
45
45
 
46
46
  export function searchDocs(opts = {}) {
47
- const dbPath = opts.dbPath || getDocsDbPath();
47
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
48
48
  const q = (opts.query || '').toString().trim();
49
49
  if (!q) {
50
50
  throw new Error('Query is required.');
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import http from 'node:http';
6
6
  import { URL } from 'node:url';
7
7
  import Database from 'better-sqlite3';
8
- import { getDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
8
+ import { resolveDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
9
9
  import { sanitizeFts5Query } from './fts.js';
10
10
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
11
11
 
@@ -65,7 +65,7 @@ function serveStatic(req, res, filePath) {
65
65
  }
66
66
 
67
67
  export function serveDocs(opts = {}) {
68
- const dbPath = opts.dbPath || getDocsDbPath();
68
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
69
69
  const port = parseInt(opts.port, 10) || 3000;
70
70
  const host = opts.host || '127.0.0.1';
71
71
 
@@ -254,7 +254,7 @@ export function serveDocs(opts = {}) {
254
254
  if (resolved) return;
255
255
  resolved = true;
256
256
  server.removeListener('error', onError);
257
- process.stderr.write(`ServiceNow docs search listening on http://${host}:${currentPort}\n`);
257
+ process.stderr.write(`ServiceNow docs search for ${opts.release || 'default'} listening on http://${host}:${currentPort}\n`);
258
258
  resolve({ server, port: currentPort, host, dbPath });
259
259
  }
260
260
 
@@ -2,12 +2,14 @@ import http from 'node:http';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
+ import { resolveDocsDbPath, resolveDocsRelease } from './db.js';
5
6
  import { fork } from 'node:child_process';
6
7
  import { fileURLToPath } from 'node:url';
7
8
  import { DocumentationIndex, documentationStatus } from './index.js';
8
9
 
9
10
  export function serviceStorage() { return process.env.DOCS_STORAGE_DIR || path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
10
- export async function startDocumentationServer({ storage = serviceStorage(), host = '127.0.0.1', port = 0, refresh = true } = {}) {
11
+ export async function startDocumentationServer({ storage = serviceStorage(), host = '127.0.0.1', port = 0, refresh = true, release } = {}) {
12
+ if (release !== undefined) { release = resolveDocsRelease(release); storage = path.dirname(resolveDocsDbPath(release)); }
11
13
  fs.mkdirSync(storage, { recursive: true });
12
14
  let worker;
13
15
  const server = http.createServer((req, res) => {
@@ -16,15 +18,16 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
16
18
  let index;
17
19
  try {
18
20
  const url = new URL(req.url, 'http://localhost');
19
- if (url.pathname === '/up') return send(200, { service: 'jsn-docs' });
20
- if (url.pathname === '/api/docs/status') return send(200, documentationStatus(storage));
21
+ if (url.pathname === '/up') return send(200, { service: 'jsn-docs', release });
22
+ if (release && url.searchParams.has('release') && url.searchParams.get('release') !== release) return send(400, { error: `This documentation server serves ${release}.`, hint: `Use --release ${release}.` });
23
+ if (url.pathname === '/api/docs/status') return send(200, { ...documentationStatus(storage), release });
21
24
  if (!['/api/docs/search', '/api/docs/document'].includes(url.pathname) && !/^\/api\/docs\/\d{1,18}$/.test(url.pathname)) return send(404, { error: 'Not found.' });
22
- index = new DocumentationIndex(storage);
25
+ index = new DocumentationIndex(storage, release);
23
26
  const params = Object.fromEntries(url.searchParams);
24
- 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 }));
27
+ 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 });
25
28
  const revision = index.revision();
26
29
  if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
27
- return send(200, { revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
30
+ return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
28
31
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
29
32
  finally { index?.close(); }
30
33
  });
@@ -36,7 +39,7 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
36
39
  const log = fs.openSync(path.join(storage, 'sync.log'), 'a', 0o600);
37
40
  try {
38
41
  worker = fork(fileURLToPath(new URL('./sync-service.js', import.meta.url)), [], {
39
- env: { ...process.env, DOCS_STORAGE_DIR: storage }, stdio: ['ignore', log, log, 'ipc'], execArgv: [],
42
+ env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_RELEASE: release || '' }, stdio: ['ignore', log, log, 'ipc'], execArgv: [],
40
43
  });
41
44
  worker.on('exit', () => { worker = null; });
42
45
  worker.on('error', () => { worker = null; });
@@ -52,9 +55,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
52
55
  }
53
56
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
54
57
  try {
55
- const { server, url } = await startDocumentationServer({ host: process.env.JSN_DOCS_HOST || '127.0.0.1', port: Number(process.env.JSN_DOCS_PORT || 0) });
56
- if (process.send) { process.send({ url, pid: process.pid }); process.disconnect(); }
57
- else process.stdout.write(`Documentation service listening at ${url}\n`);
58
+ const { server, url } = await startDocumentationServer({ host: process.env.JSN_DOCS_HOST || '127.0.0.1', port: Number(process.env.JSN_DOCS_PORT || 0), release: process.env.JSN_DOCS_RELEASE || undefined });
59
+ if (process.send) { process.send({ url, pid: process.pid, release: process.env.JSN_DOCS_RELEASE || undefined }); process.disconnect(); }
60
+ else process.stdout.write(`Documentation service${process.env.JSN_DOCS_RELEASE ? ` for ${process.env.JSN_DOCS_RELEASE}` : ''} listening at ${url}\n`);
58
61
  for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { server.close(); });
59
62
  } catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
60
63
  }
@@ -6,10 +6,10 @@ import { gzipSync } from 'node:zlib';
6
6
  import Database from 'better-sqlite3';
7
7
  import { validateDatabase, validateManifest } from './snapshot.js';
8
8
 
9
- export async function publishServiceSnapshot(storage) {
9
+ export async function publishServiceSnapshot(storage, { dbPath = path.join(storage, 'docs.sqlite3'), release } = {}) {
10
10
  const output = path.join(storage, 'snapshots');
11
11
  fs.mkdirSync(output, { recursive: true });
12
- const db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true });
12
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
13
13
  const temporary = fs.mkdtempSync(path.join(output, '.export-'));
14
14
  try {
15
15
  const revision = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value;
@@ -31,7 +31,7 @@ export async function publishServiceSnapshot(storage) {
31
31
  const compressed = gzipSync(bytes);
32
32
  const sha256 = createHash('sha256').update(compressed).digest('hex');
33
33
  const name = `docs-${revision}-${sha256}.sqlite.gz`;
34
- const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision,
34
+ const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision, ...(release ? { release } : {}),
35
35
  documents, sha256, compressedBytes: compressed.length, databaseBytes: bytes.length,
36
36
  builtAt: new Date().toISOString(), url: `https://jsn.jace.pro/docs-index/artifacts/${name}` });
37
37
  fs.writeFileSync(path.join(temporary, name), compressed);