@velaro/cli 1.4.240 → 1.4.242

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.
@@ -1,322 +1,259 @@
1
- import { get, post, getCredentials, messagingGet, messagingPost, messagingPut } from '../api.js';
2
- import { loadStaff } from '../staff-optional.js';
3
-
4
- // ── helpers ──────────────────────────────────────────────────────────────────
5
-
6
- const staffIndex = await loadStaff('commands/index-staff.js');
7
-
8
- // Staff cross-site view is only available when the unpublished staff build is present (the server enforces the real gate).
9
- function isVelaroAdmin(creds) {
10
- return !!staffIndex?.isStaffSite(creds);
11
- }
12
-
13
- function mb(n) {
14
- if (n >= 1024) return `${(n / 1024).toFixed(1)} GB`;
15
- return `${n} MB`;
16
- }
17
-
18
- function bar(used, total, width = 20) {
19
- if (!total) return '[ ] n/a';
20
- const pct = Math.min(used / total, 1);
21
- const filled = Math.round(pct * width);
22
- const color = pct >= 0.9 ? '\x1b[31m' : pct >= 0.7 ? '\x1b[33m' : '\x1b[32m';
23
- return `${color}[${'█'.repeat(filled)}${' '.repeat(width - filled)}]\x1b[0m ${(pct * 100).toFixed(0)}%`;
24
- }
25
-
26
- // ── list ─────────────────────────────────────────────────────────────────────
27
-
28
- const listCommand = {
29
- command: 'list',
30
- describe: 'List indexes. Velaro admins see all physical indexes; customers see their virtual indexes + quota.',
31
- builder: (y) =>
32
- y.option('site', { type: 'number', describe: 'Site ID (restricted, enforced server-side)' }),
33
- handler: async (argv) => {
34
- const creds = await getCredentials();
35
-
36
- if (isVelaroAdmin(creds)) {
37
- // ── Velaro admin: show all physical indexes with storage health ─────────
38
- const stats = await get('/DatabaseTool/SearchIndexStats');
39
-
40
- console.log('\n\x1b[1mPhysical Indexes\x1b[0m');
41
- console.log(` Shared: ${stats.sharedIndexes.length} Dedicated: ${stats.dedicatedIndexes.length} Total: ${stats.totalSlots}`);
42
-
43
- const LIMIT_MB = 160 * 1024;
44
-
45
- console.log('\n\x1b[1mShared Indexes\x1b[0m');
46
- for (const idx of stats.sharedIndexes) {
47
- console.log(`\n \x1b[36m${idx.indexName}\x1b[0m ${idx.sites?.length ?? 0} sites ${idx.totalDocuments.toLocaleString()} docs`);
48
- console.log(` Storage: ${bar(idx.storageMb, LIMIT_MB)} ${mb(idx.storageMb)} / ${mb(LIMIT_MB)}`);
49
- if (idx.sites?.length) {
50
- for (const s of idx.sites.slice(0, 10)) {
51
- const badge = s.assignmentType === 'legacy-fallback' ? '\x1b[33m[legacy]\x1b[0m' :
52
- s.assignmentType === 'dedicated' ? '\x1b[35m[dedicated]\x1b[0m' :
53
- '\x1b[34m[shared]\x1b[0m';
54
- console.log(` Site ${s.siteId.toString().padEnd(8)} ${badge} ${s.documentCount.toLocaleString()} docs`);
55
- }
56
- if (idx.sites.length > 10) console.log(` ... and ${idx.sites.length - 10} more`);
57
- }
58
- }
59
-
60
- if (stats.dedicatedIndexes.length) {
61
- console.log('\n\x1b[1mDedicated Indexes\x1b[0m');
62
- for (const idx of stats.dedicatedIndexes) {
63
- console.log(` \x1b[35m${idx.indexName}\x1b[0m Site ${idx.siteId} ${idx.documentCount.toLocaleString()} docs`);
64
- console.log(` Storage: ${bar(idx.storageMb, LIMIT_MB)} ${mb(idx.storageMb)} / ${mb(LIMIT_MB)}`);
65
- }
66
- }
67
-
68
- const legacy = stats.sharedIndexes.flatMap(s => s.sites ?? []).filter(s => s.assignmentType === 'legacy-fallback').length;
69
- if (legacy > 0) {
70
- console.log(`\n\x1b[33m⚠ ${legacy} legacy site(s) have no index assignment (fallback to velaro-shared-index)\x1b[0m`);
71
- }
72
- } else {
73
- // ── Customer: show their virtual indexes + quota ────────────────────────
74
- const siteId = argv.site ?? creds.siteId;
75
- const [indexes, breakdown] = await Promise.all([
76
- messagingGet('/AzureIndexes/List'),
77
- get(`/DatabaseTool/SearchIndexSite?siteId=${siteId}`).catch(() => null),
78
- ]);
79
-
80
- // Quota from subscription
81
- // GET /Subscription lives on the MESSAGING api (the old admin /Subscription/Get never existed, and its
82
- // .catch(() => null) hid that, so the quota line silently never rendered).
83
- const sub = await messagingGet('/Subscription').catch((err) => {
84
- console.error(`\x1b[33m⚠ Could not read subscription quota: ${err.message}\x1b[0m`);
85
- return null;
86
- });
87
- const chunkCap = sub?.maxIndexedChunkTotal ?? 0;
88
- const usedChunks = indexes.reduce((s, i) => s + (i.documentCount ?? 0), 0);
89
-
90
- console.log('\n\x1b[1mYour Search Indexes\x1b[0m');
91
-
92
- if (chunkCap > 0) {
93
- console.log(`\nQuota: ${bar(usedChunks, chunkCap)} ${usedChunks.toLocaleString()} / ${chunkCap.toLocaleString()} chunks used`);
94
- const remaining = chunkCap - usedChunks;
95
- if (remaining <= 0) {
96
- console.log('\x1b[31m✗ Quota full — new content will not be indexed until you upgrade or remove content.\x1b[0m');
97
- } else if (remaining < chunkCap * 0.1) {
98
- console.log(`\x1b[33m⚠ Only ${remaining.toLocaleString()} chunks remaining. Consider upgrading your plan.\x1b[0m`);
99
- }
100
- }
101
-
102
- if (breakdown) {
103
- const typeLabel = breakdown.assignmentType === 'dedicated' ? '\x1b[35m[dedicated index]\x1b[0m' :
104
- breakdown.assignmentType === 'shared' ? '\x1b[34m[shared index]\x1b[0m' :
105
- '\x1b[33m[legacy]\x1b[0m';
106
- console.log(`\nPhysical index: \x1b[36m${breakdown.physicalIndex}\x1b[0m ${typeLabel}`);
107
- }
108
-
109
- console.log('');
110
- for (const idx of indexes) {
111
- const docs = idx.documentCount != null ? `${idx.documentCount.toLocaleString()} docs` : '';
112
- console.log(` \x1b[36m${idx.name}\x1b[0m (id: ${idx.id}) ${docs}`);
113
- if (idx.description) console.log(` ${idx.description}`);
114
- }
115
-
116
- if (!indexes.length) console.log(' No indexes found. Create one in your bot settings.');
117
- }
118
- console.log('');
119
- },
120
- };
121
-
122
- // ── site (restricted, enforced server-side) ──────────────────────────────────────────────────
123
-
124
- const siteCommand = {
125
- command: 'site <siteId>',
126
- describe: 'Show index breakdown for a specific site (restricted, enforced server-side)',
127
- handler: async (argv) => {
128
- const creds = await getCredentials();
129
- if (!isVelaroAdmin(creds)) {
130
- console.error('This command is restricted, enforced server-side.');
131
- process.exit(1);
132
- }
133
- const data = await get(`/DatabaseTool/SearchIndexSite?siteId=${argv.siteId}`);
134
- console.log(`\nSite ${argv.siteId} → \x1b[36m${data.physicalIndex}\x1b[0m [${data.assignmentType}]`);
135
- console.log(`Total docs: ${data.totalDocuments.toLocaleString()}\n`);
136
- for (const t of data.indexTypes) {
137
- console.log(` ${t.indexName.padEnd(40)} ${t.count.toLocaleString()} docs`);
138
- }
139
- console.log('');
140
- },
141
- };
142
-
143
- // ── provision (restricted, enforced server-side) ─────────────────────────────────────────────
144
-
145
- const provisionCommand = {
146
- command: 'provision <siteId>',
147
- describe: 'Provision a dedicated physical index for a site (restricted, enforced server-side)',
148
- handler: async (argv) => {
149
- const creds = await getCredentials();
150
- if (!isVelaroAdmin(creds)) {
151
- console.error('This command is restricted, enforced server-side.');
152
- process.exit(1);
153
- }
154
- console.log(`Provisioning dedicated index for site ${argv.siteId}...`);
155
- const result = await post('/DatabaseTool/ProvisionDedicatedIndex', { SiteId: argv.siteId });
156
- console.log(`\x1b[32m✓ ${result.message}\x1b[0m`);
157
- console.log(` Index: \x1b[36m${result.indexName}\x1b[0m`);
158
- console.log('\nNote: Re-ingest content to populate the new index.');
159
- },
160
- };
161
-
162
- // ── reingest (customer-facing, credit-gated) ──────────────────────────────────
163
-
164
- const reingestCommand = {
165
- command: 'reingest',
166
- describe: 'Re-ingest all content sources for your site (requires available index quota)',
167
- builder: (y) =>
168
- y
169
- .option('source', {
170
- type: 'string',
171
- describe: 'Specific source to reingest: kb | shopify | bigcommerce | scraper',
172
- })
173
- .option('site', {
174
- type: 'number',
175
- describe: 'Site ID (restricted, enforced server-side)',
176
- }),
177
- handler: async (argv) => {
178
- const creds = await getCredentials();
179
-
180
- // Check quota before allowing reingest
181
- const sub = await messagingGet('/Subscription').catch((err) => {
182
- console.error(`\x1b[33m⚠ Could not read subscription quota (index quota pre-check skipped): ${err.message}\x1b[0m`);
183
- return null;
184
- });
185
- if (!isVelaroAdmin(creds) && sub?.maxIndexedChunkTotal > 0) {
186
- const indexes = await messagingGet('/AzureIndexes/List').catch(() => []);
187
- const usedChunks = indexes.reduce((s, i) => s + (i.documentCount ?? 0), 0);
188
- if (usedChunks >= sub.maxIndexedChunkTotal) {
189
- console.error(`\x1b[31m✗ Index quota full (${usedChunks.toLocaleString()} / ${sub.maxIndexedChunkTotal.toLocaleString()} chunks).\x1b[0m`);
190
- console.error(' Upgrade your plan or remove content before reingesting.');
191
- process.exit(1);
192
- }
193
- }
194
-
195
- const sources = argv.source ? [argv.source] : ['kb', 'shopify', 'bigcommerce', 'scraper'];
196
- const siteParam = isVelaroAdmin(creds) && argv.site ? `?siteId=${argv.site}` : '';
197
-
198
- for (const source of sources) {
199
- try {
200
- console.log(` Syncing ${source}...`);
201
- await messagingPost(`/AzureIndexes/SyncIntegration${siteParam}`, { source, forceAll: true });
202
- console.log(` \x1b[32m✓ ${source} queued\x1b[0m`);
203
- } catch (e) {
204
- console.log(` \x1b[33m⚠ ${source} skipped: ${e.message}\x1b[0m`);
205
- }
206
- }
207
- console.log('\nReingest queued. Run `velaro index list` to monitor progress.');
208
- },
209
- };
210
-
211
- // ── test ─────────────────────────────────────────────────────────────────────
212
-
213
- const testCommand = {
214
- command: 'test <query>',
215
- describe: 'Run a content-search query against your site\'s index and show results',
216
- builder: (y) =>
217
- y
218
- .positional('query', { type: 'string', describe: 'Search query' })
219
- .option('top', { type: 'number', default: 5, describe: 'Number of results to return' })
220
- .option('site', { type: 'number', describe: 'Site ID override (restricted, enforced server-side)' }),
221
- handler: async (argv) => {
222
- const creds = await getCredentials();
223
- const siteParam = isVelaroAdmin(creds) && argv.site ? `&siteId=${argv.site}` : '';
224
- const qs = `q=${encodeURIComponent(argv.query)}&top=${argv.top}${siteParam}`;
225
-
226
- console.log(`\nSearching index for: "${argv.query}"\n`);
227
- const results = await messagingGet(`/AzureIndexes/content-search?${qs}`);
228
-
229
- if (!results?.length) {
230
- console.log(' No results found. Index may be empty — run `velaro ingest --job-id <id>` first.');
231
- return;
232
- }
233
-
234
- for (let i = 0; i < results.length; i++) {
235
- const r = results[i];
236
- console.log(`\x1b[1m[${i + 1}] ${r.label ?? r.sourceId ?? 'unknown'}\x1b[0m`);
237
- console.log(` type: ${r.contentType ?? 'unknown'} index: ${r.indexName ?? ''} id: ${r.sourceId ?? ''}`);
238
- console.log('');
239
- }
240
- },
241
- };
242
-
243
- // ── export ────────────────────────────────────────────────────────────────────
244
-
245
- // -- create (restricted, enforced server-side) -------------------------------------------------
246
- // POST KnowledgeSetup/Staff/{siteId}/create-index on velaro-messaging. Idempotent: an existing
247
- // index with the same (sanitized) name is returned unchanged.
248
-
249
- const createCommand = {
250
- command: 'create',
251
- describe: 'Create a named virtual index on any site (restricted, enforced server-side; idempotent)',
252
- builder: (y) =>
253
- y
254
- .option('site', { type: 'number', demandOption: true, describe: 'Target site ID' })
255
- .option('name', { type: 'string', demandOption: true, describe: 'Index name, e.g. 100140-troubleshooting' })
256
- .option('purpose', {
257
- type: 'string', default: 'general', choices: ['general', 'troubleshooting', 'catalog'],
258
- describe: 'Index purpose',
259
- })
260
- .option('exclude-from-all-sources', { type: 'boolean', describe: 'Keep this index out of the ["*"] all-sources search' })
261
- .option('json', { type: 'boolean', describe: 'Print raw JSON' }),
262
- handler: async (argv) => {
263
- const body = { indexName: argv.name, purpose: argv.purpose };
264
- if (argv['exclude-from-all-sources'] !== undefined) body.excludeFromAllSources = argv['exclude-from-all-sources'];
265
- const idx = await messagingPost(`/KnowledgeSetup/Staff/${encodeURIComponent(argv.site)}/create-index`, body);
266
- if (argv.json) { console.log(JSON.stringify(idx, null, 2)); return; }
267
- console.log(`
268
- Index ready on site ${argv.site}: ${idx.name} (id: ${idx.id}, purpose: ${idx.purpose}, excludeFromAllSources: ${!!idx.excludeFromAllSources})
269
- `);
270
- },
271
- };
272
-
273
- // -- profile (restricted, enforced server-side) --------------------------------------------------
274
- // PUT KnowledgeSetup/Staff/{siteId}/index-profile on velaro-messaging. Apply-if-present: only the
275
- // flags you pass are changed. The index is addressed by name (the endpoint looks up siteId+name).
276
-
277
- const profileCommand = {
278
- command: 'profile',
279
- describe: 'Set the ingestion profile of one index on any site (restricted, enforced server-side; only passed flags change)',
280
- builder: (y) =>
281
- y
282
- .option('site', { type: 'number', demandOption: true, describe: 'Target site ID' })
283
- .option('index', { type: 'string', demandOption: true, describe: 'Index name, e.g. 100140-troubleshooting' })
284
- .option('strategy', { type: 'string', choices: ['procedure', 'section'], describe: 'Chunk strategy' })
285
- .option('chunk-size', { type: 'number', describe: 'Chunk size' })
286
- .option('chunk-overlap', { type: 'number', describe: 'Chunk overlap' })
287
- .option('purpose', { type: 'string', choices: ['general', 'troubleshooting', 'catalog'], describe: 'Index purpose' })
288
- .option('search-size', { type: 'number', describe: 'Results per search' })
289
- .option('exclude-from-all-sources', { type: 'boolean', describe: 'Keep this index out of the ["*"] all-sources search' })
290
- .option('json', { type: 'boolean', describe: 'Print raw JSON' }),
291
- handler: async (argv) => {
292
- const body = { indexName: argv.index };
293
- if (argv.strategy !== undefined) body.chunkStrategy = argv.strategy;
294
- if (argv['chunk-size'] !== undefined) body.chunkSize = argv['chunk-size'];
295
- if (argv['chunk-overlap'] !== undefined) body.chunkOverlap = argv['chunk-overlap'];
296
- if (argv.purpose !== undefined) body.purpose = argv.purpose;
297
- if (argv['search-size'] !== undefined) body.searchSize = argv['search-size'];
298
- if (argv['exclude-from-all-sources'] !== undefined) body.excludeFromAllSources = argv['exclude-from-all-sources'];
299
- const idx = await messagingPut(`/KnowledgeSetup/Staff/${encodeURIComponent(argv.site)}/index-profile`, body);
300
- if (argv.json) { console.log(JSON.stringify(idx, null, 2)); return; }
301
- console.log(`
302
- Profile updated on site ${argv.site}: ${idx.name} (purpose: ${idx.purpose}, strategy: ${idx.chunkStrategy}, size: ${idx.chunkSize}, overlap: ${idx.chunkOverlap}, searchSize: ${idx.searchSize}, excludeFromAllSources: ${!!idx.excludeFromAllSources})
303
- Re-ingest to apply the new chunking to existing content.
304
- `);
305
- },
306
- };
307
-
308
- export const indexCommand = {
309
- command: 'index <subcommand>',
310
- describe: 'Manage search indexes — view quota, physical index health, and reingest content',
311
- builder: (yargs) =>
312
- yargs
313
- .command(listCommand)
314
- .command(siteCommand)
315
- .command(provisionCommand)
316
- .command(reingestCommand)
317
- .command(testCommand)
318
- .command(createCommand)
319
- .command(profileCommand)
320
- .demandCommand(1, 'Specify a subcommand: list, site, provision, reingest, test, create, profile'),
321
- handler: () => {},
322
- };
1
+ import { get, post, getCredentials, messagingGet, messagingPost } from '../api.js';
2
+ import { loadStaff } from '../staff-optional.js';
3
+
4
+ // ── helpers ──────────────────────────────────────────────────────────────────
5
+
6
+ const staffIndex = await loadStaff('commands/index-staff.js');
7
+
8
+ // Staff cross-site view is only available when the unpublished staff build is present (the server enforces the real gate).
9
+ function isVelaroAdmin(creds) {
10
+ return !!staffIndex?.isStaffSite(creds);
11
+ }
12
+
13
+ function mb(n) {
14
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} GB`;
15
+ return `${n} MB`;
16
+ }
17
+
18
+ function bar(used, total, width = 20) {
19
+ if (!total) return '[ ] n/a';
20
+ const pct = Math.min(used / total, 1);
21
+ const filled = Math.round(pct * width);
22
+ const color = pct >= 0.9 ? '\x1b[31m' : pct >= 0.7 ? '\x1b[33m' : '\x1b[32m';
23
+ return `${color}[${'█'.repeat(filled)}${' '.repeat(width - filled)}]\x1b[0m ${(pct * 100).toFixed(0)}%`;
24
+ }
25
+
26
+ // ── list ─────────────────────────────────────────────────────────────────────
27
+
28
+ const listCommand = {
29
+ command: 'list',
30
+ describe: 'List indexes. Velaro admins see all physical indexes; customers see their virtual indexes + quota.',
31
+ builder: (y) =>
32
+ y.option('site', { type: 'number', describe: 'Site ID (restricted, enforced server-side)' }),
33
+ handler: async (argv) => {
34
+ const creds = await getCredentials();
35
+
36
+ if (isVelaroAdmin(creds)) {
37
+ // ── Velaro admin: show all physical indexes with storage health ─────────
38
+ const stats = await get('/DatabaseTool/SearchIndexStats');
39
+
40
+ console.log('\n\x1b[1mPhysical Indexes\x1b[0m');
41
+ console.log(` Shared: ${stats.sharedIndexes.length} Dedicated: ${stats.dedicatedIndexes.length} Total: ${stats.totalSlots}`);
42
+
43
+ const LIMIT_MB = 160 * 1024;
44
+
45
+ console.log('\n\x1b[1mShared Indexes\x1b[0m');
46
+ for (const idx of stats.sharedIndexes) {
47
+ console.log(`\n \x1b[36m${idx.indexName}\x1b[0m ${idx.sites?.length ?? 0} sites ${idx.totalDocuments.toLocaleString()} docs`);
48
+ console.log(` Storage: ${bar(idx.storageMb, LIMIT_MB)} ${mb(idx.storageMb)} / ${mb(LIMIT_MB)}`);
49
+ if (idx.sites?.length) {
50
+ for (const s of idx.sites.slice(0, 10)) {
51
+ const badge = s.assignmentType === 'legacy-fallback' ? '\x1b[33m[legacy]\x1b[0m' :
52
+ s.assignmentType === 'dedicated' ? '\x1b[35m[dedicated]\x1b[0m' :
53
+ '\x1b[34m[shared]\x1b[0m';
54
+ console.log(` Site ${s.siteId.toString().padEnd(8)} ${badge} ${s.documentCount.toLocaleString()} docs`);
55
+ }
56
+ if (idx.sites.length > 10) console.log(` ... and ${idx.sites.length - 10} more`);
57
+ }
58
+ }
59
+
60
+ if (stats.dedicatedIndexes.length) {
61
+ console.log('\n\x1b[1mDedicated Indexes\x1b[0m');
62
+ for (const idx of stats.dedicatedIndexes) {
63
+ console.log(` \x1b[35m${idx.indexName}\x1b[0m Site ${idx.siteId} ${idx.documentCount.toLocaleString()} docs`);
64
+ console.log(` Storage: ${bar(idx.storageMb, LIMIT_MB)} ${mb(idx.storageMb)} / ${mb(LIMIT_MB)}`);
65
+ }
66
+ }
67
+
68
+ const legacy = stats.sharedIndexes.flatMap(s => s.sites ?? []).filter(s => s.assignmentType === 'legacy-fallback').length;
69
+ if (legacy > 0) {
70
+ console.log(`\n\x1b[33m⚠ ${legacy} legacy site(s) have no index assignment (fallback to velaro-shared-index)\x1b[0m`);
71
+ }
72
+ } else {
73
+ // ── Customer: show their virtual indexes + quota ────────────────────────
74
+ const siteId = argv.site ?? creds.siteId;
75
+ const [indexes, breakdown] = await Promise.all([
76
+ messagingGet('/AzureIndexes/List'),
77
+ get(`/DatabaseTool/SearchIndexSite?siteId=${siteId}`).catch(() => null),
78
+ ]);
79
+
80
+ // Quota from subscription
81
+ // GET /Subscription lives on the MESSAGING api (the old admin /Subscription/Get never existed, and its
82
+ // .catch(() => null) hid that, so the quota line silently never rendered).
83
+ const sub = await messagingGet('/Subscription').catch((err) => {
84
+ console.error(`\x1b[33m⚠ Could not read subscription quota: ${err.message}\x1b[0m`);
85
+ return null;
86
+ });
87
+ const chunkCap = sub?.maxIndexedChunkTotal ?? 0;
88
+ const usedChunks = indexes.reduce((s, i) => s + (i.documentCount ?? 0), 0);
89
+
90
+ console.log('\n\x1b[1mYour Search Indexes\x1b[0m');
91
+
92
+ if (chunkCap > 0) {
93
+ console.log(`\nQuota: ${bar(usedChunks, chunkCap)} ${usedChunks.toLocaleString()} / ${chunkCap.toLocaleString()} chunks used`);
94
+ const remaining = chunkCap - usedChunks;
95
+ if (remaining <= 0) {
96
+ console.log('\x1b[31m✗ Quota full — new content will not be indexed until you upgrade or remove content.\x1b[0m');
97
+ } else if (remaining < chunkCap * 0.1) {
98
+ console.log(`\x1b[33m⚠ Only ${remaining.toLocaleString()} chunks remaining. Consider upgrading your plan.\x1b[0m`);
99
+ }
100
+ }
101
+
102
+ if (breakdown) {
103
+ const typeLabel = breakdown.assignmentType === 'dedicated' ? '\x1b[35m[dedicated index]\x1b[0m' :
104
+ breakdown.assignmentType === 'shared' ? '\x1b[34m[shared index]\x1b[0m' :
105
+ '\x1b[33m[legacy]\x1b[0m';
106
+ console.log(`\nPhysical index: \x1b[36m${breakdown.physicalIndex}\x1b[0m ${typeLabel}`);
107
+ }
108
+
109
+ console.log('');
110
+ for (const idx of indexes) {
111
+ const docs = idx.documentCount != null ? `${idx.documentCount.toLocaleString()} docs` : '';
112
+ console.log(` \x1b[36m${idx.name}\x1b[0m (id: ${idx.id}) ${docs}`);
113
+ if (idx.description) console.log(` ${idx.description}`);
114
+ }
115
+
116
+ if (!indexes.length) console.log(' No indexes found. Create one in your bot settings.');
117
+ }
118
+ console.log('');
119
+ },
120
+ };
121
+
122
+ // ── site (restricted, enforced server-side) ──────────────────────────────────────────────────
123
+
124
+ const siteCommand = {
125
+ command: 'site <siteId>',
126
+ describe: 'Show index breakdown for a specific site (restricted, enforced server-side)',
127
+ handler: async (argv) => {
128
+ const creds = await getCredentials();
129
+ if (!isVelaroAdmin(creds)) {
130
+ console.error('This command is restricted, enforced server-side.');
131
+ process.exit(1);
132
+ }
133
+ const data = await get(`/DatabaseTool/SearchIndexSite?siteId=${argv.siteId}`);
134
+ console.log(`\nSite ${argv.siteId} → \x1b[36m${data.physicalIndex}\x1b[0m [${data.assignmentType}]`);
135
+ console.log(`Total docs: ${data.totalDocuments.toLocaleString()}\n`);
136
+ for (const t of data.indexTypes) {
137
+ console.log(` ${t.indexName.padEnd(40)} ${t.count.toLocaleString()} docs`);
138
+ }
139
+ console.log('');
140
+ },
141
+ };
142
+
143
+ // ── provision (restricted, enforced server-side) ─────────────────────────────────────────────
144
+
145
+ const provisionCommand = {
146
+ command: 'provision <siteId>',
147
+ describe: 'Provision a dedicated physical index for a site (restricted, enforced server-side)',
148
+ handler: async (argv) => {
149
+ const creds = await getCredentials();
150
+ if (!isVelaroAdmin(creds)) {
151
+ console.error('This command is restricted, enforced server-side.');
152
+ process.exit(1);
153
+ }
154
+ console.log(`Provisioning dedicated index for site ${argv.siteId}...`);
155
+ const result = await post('/DatabaseTool/ProvisionDedicatedIndex', { SiteId: argv.siteId });
156
+ console.log(`\x1b[32m✓ ${result.message}\x1b[0m`);
157
+ console.log(` Index: \x1b[36m${result.indexName}\x1b[0m`);
158
+ console.log('\nNote: Re-ingest content to populate the new index.');
159
+ },
160
+ };
161
+
162
+ // ── reingest (customer-facing, credit-gated) ──────────────────────────────────
163
+
164
+ const reingestCommand = {
165
+ command: 'reingest',
166
+ describe: 'Re-ingest all content sources for your site (requires available index quota)',
167
+ builder: (y) =>
168
+ y
169
+ .option('source', {
170
+ type: 'string',
171
+ describe: 'Specific source to reingest: kb | shopify | bigcommerce | scraper',
172
+ })
173
+ .option('site', {
174
+ type: 'number',
175
+ describe: 'Site ID (restricted, enforced server-side)',
176
+ }),
177
+ handler: async (argv) => {
178
+ const creds = await getCredentials();
179
+
180
+ // Check quota before allowing reingest
181
+ const sub = await messagingGet('/Subscription').catch((err) => {
182
+ console.error(`\x1b[33m⚠ Could not read subscription quota (index quota pre-check skipped): ${err.message}\x1b[0m`);
183
+ return null;
184
+ });
185
+ if (!isVelaroAdmin(creds) && sub?.maxIndexedChunkTotal > 0) {
186
+ const indexes = await messagingGet('/AzureIndexes/List').catch(() => []);
187
+ const usedChunks = indexes.reduce((s, i) => s + (i.documentCount ?? 0), 0);
188
+ if (usedChunks >= sub.maxIndexedChunkTotal) {
189
+ console.error(`\x1b[31m✗ Index quota full (${usedChunks.toLocaleString()} / ${sub.maxIndexedChunkTotal.toLocaleString()} chunks).\x1b[0m`);
190
+ console.error(' Upgrade your plan or remove content before reingesting.');
191
+ process.exit(1);
192
+ }
193
+ }
194
+
195
+ const sources = argv.source ? [argv.source] : ['kb', 'shopify', 'bigcommerce', 'scraper'];
196
+ const siteParam = isVelaroAdmin(creds) && argv.site ? `?siteId=${argv.site}` : '';
197
+
198
+ for (const source of sources) {
199
+ try {
200
+ console.log(` Syncing ${source}...`);
201
+ await messagingPost(`/AzureIndexes/SyncIntegration${siteParam}`, { source, forceAll: true });
202
+ console.log(` \x1b[32m✓ ${source} queued\x1b[0m`);
203
+ } catch (e) {
204
+ console.log(` \x1b[33m⚠ ${source} skipped: ${e.message}\x1b[0m`);
205
+ }
206
+ }
207
+ console.log('\nReingest queued. Run `velaro index list` to monitor progress.');
208
+ },
209
+ };
210
+
211
+ // ── test ─────────────────────────────────────────────────────────────────────
212
+
213
+ const testCommand = {
214
+ command: 'test <query>',
215
+ describe: 'Run a content-search query against your site\'s index and show results',
216
+ builder: (y) =>
217
+ y
218
+ .positional('query', { type: 'string', describe: 'Search query' })
219
+ .option('top', { type: 'number', default: 5, describe: 'Number of results to return' })
220
+ .option('site', { type: 'number', describe: 'Site ID override (restricted, enforced server-side)' }),
221
+ handler: async (argv) => {
222
+ const creds = await getCredentials();
223
+ const siteParam = isVelaroAdmin(creds) && argv.site ? `&siteId=${argv.site}` : '';
224
+ const qs = `q=${encodeURIComponent(argv.query)}&top=${argv.top}${siteParam}`;
225
+
226
+ console.log(`\nSearching index for: "${argv.query}"\n`);
227
+ const results = await messagingGet(`/AzureIndexes/content-search?${qs}`);
228
+
229
+ if (!results?.length) {
230
+ console.log(' No results found. Index may be empty — run `velaro ingest --job-id <id>` first.');
231
+ return;
232
+ }
233
+
234
+ for (let i = 0; i < results.length; i++) {
235
+ const r = results[i];
236
+ console.log(`\x1b[1m[${i + 1}] ${r.label ?? r.sourceId ?? 'unknown'}\x1b[0m`);
237
+ console.log(` type: ${r.contentType ?? 'unknown'} index: ${r.indexName ?? ''} id: ${r.sourceId ?? ''}`);
238
+ console.log('');
239
+ }
240
+ },
241
+ };
242
+
243
+ // ── export ────────────────────────────────────────────────────────────────────
244
+
245
+ export const indexCommand = {
246
+ command: 'index <subcommand>',
247
+ describe: 'Manage search indexes — view quota, physical index health, and reingest content',
248
+ builder: (yargs) =>
249
+ yargs
250
+ .command(listCommand)
251
+ .command(siteCommand)
252
+ .command(provisionCommand)
253
+ .command(reingestCommand)
254
+ .command(testCommand)
255
+ // Restricted subcommands (create, profile) exist only in the unpublished staff build.
256
+ .command(staffIndex?.restrictedCommands ? staffIndex.restrictedCommands() : [])
257
+ .demandCommand(1, 'Specify a subcommand: list, site, provision, reingest, test'),
258
+ handler: () => {},
259
+ };