qualiloop 0.1.0 → 0.3.0

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/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { basename, resolve as resolvePath } from 'node:path';
3
4
  import { createInterface } from 'node:readline/promises';
4
5
  import { Command, CommanderError, Help, Option } from 'commander';
5
6
  import { ApiError, EXIT, QualiloopClient, VERSION } from './api.js';
@@ -7,6 +8,7 @@ import { login } from './auth.js';
7
8
  import { bundledCatalog, bundledGuide, loadCatalog } from './catalog.js';
8
9
  import { credentialsPath, forgetCredentials, resolveProject, setDefaultProject, storedCredentials, } from './config.js';
9
10
  import * as connect from './connect.js';
11
+ import { EXPORT_FORMATS, dateOr, exportFormat, fetchCorrectedPairs } from './export.js';
10
12
  import { CLIENTS, DEFAULT_CLIENTS, install, snippets } from './mcp/install.js';
11
13
  import { serveStdio } from './mcp/server.js';
12
14
  import { fields, output, table } from './output.js';
@@ -92,6 +94,14 @@ const intArg = (value) => {
92
94
  throw new ApiError(`${value} is not a number.`, 400, EXIT.usage);
93
95
  return parsed;
94
96
  };
97
+ const readText = (file) => {
98
+ try {
99
+ return readFileSync(file === '-' ? 0 : file, 'utf8');
100
+ }
101
+ catch (error) {
102
+ throw new ApiError(`Cannot read ${file}: ${error.message}`, 400, EXIT.usage);
103
+ }
104
+ };
95
105
  const limitOption = (what, fallback, most) => new Option('--limit <n>', `most ${what} to show (up to ${most})`).default(fallback);
96
106
  const limitOf = (opts, most) => {
97
107
  const limit = intArg(String(opts.limit));
@@ -129,10 +139,11 @@ const failOnOption = () => new Option('--fail-on <severity>', 'with --wait, exit
129
139
  .default('major');
130
140
  const browserLogin = (client, out, browser) => login(client, {
131
141
  browser,
132
- onStarted: ({ url, code, opened }) => {
142
+ onStarted: ({ url, code, opened, expiresIn }) => {
133
143
  out.progress(`${opened ? 'Opened' : 'Open'} ${url}\n` +
134
144
  `Check that the page shows ${code}, then approve. No account yet? Create one from that page.`);
135
- out.progress('Waiting for approval...');
145
+ const minutes = Math.max(1, Math.round(expiresIn / 60));
146
+ out.progress(`Waiting for approval, up to ${minutes} minutes. This carries on by itself once it is approved...`);
136
147
  },
137
148
  });
138
149
  const signedInAs = (result) => `Signed in to ${result.url} as ${result.user?.email ?? 'you'}` +
@@ -200,6 +211,23 @@ tokens
200
211
  const revoked = await client.request('DELETE', `/v1/cli/tokens/${intArg(id)}`);
201
212
  out.result(revoked, () => `Revoked ${revoked.name}.`);
202
213
  }));
214
+ program
215
+ .command('usage')
216
+ .description('Your plan and conversation credits, worded as the billing page words them.')
217
+ .action(run(async ({ client, out }) => {
218
+ const result = await client.action('get_usage');
219
+ out.result(result, () => {
220
+ const lines = [`${result.plan}: ${result.usage_line}`];
221
+ if (!result.unlimited) {
222
+ lines.push(`Monthly balance ${Number(result.monthly_balance).toLocaleString('en-US')}, one-time ${Number(result.one_time_balance).toLocaleString('en-US')}`);
223
+ }
224
+ if (result.period_end)
225
+ lines.push(`Period ends ${String(result.period_end).slice(0, 10)}`);
226
+ if (result.message)
227
+ lines.push(String(result.message));
228
+ return lines.join('\n');
229
+ });
230
+ }));
203
231
  const projects = program.command('projects').description('Your projects.');
204
232
  projects
205
233
  .command('list', { isDefault: true })
@@ -241,6 +269,110 @@ projects
241
269
  setDefaultProject(client.url, String(result.number));
242
270
  out.result({ project: result.number, name: result.name }, () => `Commands now use project #${result.number} ${result.name}.`);
243
271
  }));
272
+ projects
273
+ .command('delete <project>')
274
+ .description('Delete a project with its tests, runs, conversations and results. Admins only.')
275
+ .option('--yes', 'delete without asking')
276
+ .action(run(async ({ client, out, opts }, given) => {
277
+ if (!opts.yes) {
278
+ const found = await client.action('get_project', { project: given });
279
+ if (!(await confirm(`Delete project #${found.number} ${found.name} with everything in it?`))) {
280
+ out.result({ deleted: false, project: found.number }, () => 'Not deleted.');
281
+ return EXIT.ok;
282
+ }
283
+ }
284
+ const result = await client.action('delete_project', { project: given });
285
+ out.result(result, () => `Deleted project #${result.project_number} ${result.name}.`);
286
+ }));
287
+ const uiTools = projects
288
+ .command('ui-tools')
289
+ .description("The agent's tools whose output the app shows as a component; their output is not checked as an answer.");
290
+ uiTools
291
+ .command('list [project]', { isDefault: true })
292
+ .description('The saved list, and the tools seen in recent traces.')
293
+ .action(run(async ({ client, out, project }, given) => {
294
+ const result = await client.action('get_ui_tools', {
295
+ project: given ?? project,
296
+ });
297
+ out.result(result, () => [
298
+ `Shown as UI: ${result.ui_tools.length ? result.ui_tools.join(', ') : 'none'}`,
299
+ result.discovered_tools.length
300
+ ? table(result.discovered_tools, [
301
+ ['name', 'Tool seen in traces', 40],
302
+ ['calls', 'Calls'],
303
+ ['suggested_ui', 'Looks like UI'],
304
+ ['shown_as_ui', 'Shown as UI'],
305
+ ])
306
+ : 'No tools seen in traces yet.',
307
+ ].join('\n\n'));
308
+ }));
309
+ uiTools
310
+ .command('set <tools...>')
311
+ .description('Replace the list with these tool names.')
312
+ .action(run(async ({ client, out, project }, tools) => {
313
+ const result = await client.action('set_ui_tools', { project, tools });
314
+ out.result(result, () => `Shown as UI: ${result.ui_tools.join(', ') || 'none'}.`);
315
+ }));
316
+ uiTools
317
+ .command('clear')
318
+ .description('Empty the list: every tool output is checked as an answer.')
319
+ .action(run(async ({ client, out, project }) => {
320
+ const result = await client.action('set_ui_tools', { project, tools: [] });
321
+ out.result(result, () => 'No tool is shown as UI now.');
322
+ }));
323
+ program
324
+ .command('dashboard')
325
+ .description('The project dashboard for a period: verdicts, quality scores, tokens and cost, problem categories.')
326
+ .addOption(new Option('--period <period>', 'the period (default last_7_days; --from or --to make it custom)').choices([
327
+ 'today',
328
+ 'last_7_days',
329
+ 'last_30_days',
330
+ 'all_time',
331
+ 'custom',
332
+ ]))
333
+ .option('--from <date>', 'start of a custom period (YYYY-MM-DD or a time)')
334
+ .option('--to <date>', 'end of a custom period (YYYY-MM-DD, the whole day, or a time)')
335
+ .addOption(new Option('--source <source>', "tests for Test Lab runs, live for the agent's real traffic").choices(['tests', 'live']))
336
+ .option('--timezone <zone>', "the IANA time zone 'today' is counted in", 'UTC')
337
+ .action(run(async ({ client, out, project, opts }) => {
338
+ const result = await client.action('get_dashboard', {
339
+ project,
340
+ period: opts.period,
341
+ from: opts.from,
342
+ to: opts.to,
343
+ source: opts.source,
344
+ timezone: opts.timezone,
345
+ });
346
+ const scores = result.quality_scores.filter((item) => item.average !== null && item.average !== undefined);
347
+ out.result(result, () => [
348
+ fields([
349
+ ['Project', `#${result.project_number} ${result.project}`],
350
+ ['Period', `${result.period.label} (${result.source})`],
351
+ ['Summary', result.summary.headline],
352
+ ['Conversations', `${result.conversations.judged} judged, ${result.conversations.clean} clean, ${result.conversations.with_minor_problems} minor, ${result.conversations.with_major_problems} major`],
353
+ ['Clean', result.conversations.clean_percent === null ? null : `${result.conversations.clean_percent}%`],
354
+ ['Tests', `${result.tests.total} run, ${result.tests.clean} clean, ${result.tests.with_minor_problems} minor, ${result.tests.with_major_problems} major`],
355
+ ['Turns', result.turns.total],
356
+ ['Tokens per turn', result.turns.tokens_per_turn],
357
+ ['Cost per turn (USD)', result.turns.cost_per_turn_usd],
358
+ ['Cached input', result.turns.cached_input_tokens_percent === null ? null : `${result.turns.cached_input_tokens_percent}%`],
359
+ ...scores.map((item) => [`Quality: ${item.label}`, item.average]),
360
+ ['Link', result.url],
361
+ ]),
362
+ ...(result.summary.points ?? []).map((point) => `- ${point}`),
363
+ result.problem_categories.length
364
+ ? `\n${table(result.problem_categories, [
365
+ ['id', 'ID'],
366
+ ['severity', 'Severity'],
367
+ ['problems', 'Problems'],
368
+ ['share_percent', '% conv.'],
369
+ ['title', 'Problem category', 60],
370
+ ])}`
371
+ : '',
372
+ ]
373
+ .filter(Boolean)
374
+ .join('\n'));
375
+ }));
244
376
  const knowledge = program
245
377
  .command('knowledge')
246
378
  .description('System knowledge: what QualiLoop knows of the agent, its coverage, and exploring it.');
@@ -256,30 +388,79 @@ knowledge.configureHelp({
256
388
  .filter((sub) => !(sub.name() in SUPER_ADMIN_KNOWLEDGE) || knowledgeAdminShown.has(sub.name()));
257
389
  },
258
390
  });
391
+ const SECTION_NAMES = {
392
+ capability: 'Capabilities',
393
+ fact: 'Facts',
394
+ entity_group: 'Entity groups',
395
+ entity: 'Entities',
396
+ component: 'Components',
397
+ state: 'States',
398
+ action: 'Actions',
399
+ transition: 'Transitions',
400
+ };
401
+ const stateWords = (state) => String(state ?? '').replace(/_/g, ' ');
402
+ const CONFIRMED_STATES = new Set(['observed', 'intended']);
403
+ const foundLine = (row) => {
404
+ const counts = (row ?? {});
405
+ const found = Number(counts.found ?? 0);
406
+ if (!found)
407
+ return 'none found yet';
408
+ const confirmed = Number(counts.confirmed ?? 0);
409
+ const others = Object.entries(counts.states ?? {})
410
+ .filter(([state]) => !CONFIRMED_STATES.has(state))
411
+ .map(([state, count]) => `${count} ${stateWords(state)}`);
412
+ return (`${found} found, ${confirmed} confirmed${confirmed < found ? ' yet' : ''}` +
413
+ (others.length ? ` (${others.join(', ')})` : ''));
414
+ };
415
+ const STATE_NOTE = 'Observed (seen in a conversation or trace) or intended (stated by a source) means confirmed. ' +
416
+ 'Coverage counts an item once it is confirmed or the agent reported it; until then Covered shows -.';
259
417
  knowledge
260
418
  .command('summary', { isDefault: true })
261
- .description('The agent at a glance: capabilities and test coverage.')
262
- .action(run(async ({ client, out, project }) => {
263
- const result = await client.action('get_knowledge', { project });
419
+ .description('The agent at a glance: every capability with its state, entities, and test coverage.')
420
+ .addOption(limitOption('capabilities', '50', 500))
421
+ .action(run(async ({ client, out, project, opts }) => {
422
+ const result = await client.action('get_knowledge', { project, limit: limitOf(opts, 500) });
264
423
  const sources = result.sources ?? [];
424
+ const found = result.found ?? {};
425
+ const general = result.general ?? {};
426
+ const cover = result.coverage;
427
+ const coverage = !cover
428
+ ? 'not measured yet'
429
+ : cover.percent != null
430
+ ? `${cover.percent}% (${cover.covered} of ${cover.total} confirmed or reported items)`
431
+ : 'nothing to measure yet: an item counts once it is confirmed or the agent reported it';
432
+ const groups = Number(found.entity_group?.found ?? 0);
433
+ const entities = foundLine(found.entity) + (Number(found.entity?.found ?? 0) && groups ? `, in ${groups} groups` : '');
434
+ const retired = Number(result.sources_retired ?? 0);
435
+ const total = Number(result.capabilities_total ?? result.capabilities.length);
436
+ const pairs = [['Project', result.project]];
437
+ if (general.name)
438
+ pairs.push(['Agent', general.name]);
439
+ if (general.summary)
440
+ pairs.push(['Summary', general.summary]);
441
+ pairs.push(['Capabilities', foundLine(found.capability)], ['Entities', entities], ['Coverage', coverage], [
442
+ 'Sources',
443
+ sources.length
444
+ ? sources.map((row) => row.name).join(', ')
445
+ : retired
446
+ ? `none in force, ${retired} retired (qualiloop knowledge sources)`
447
+ : 'none (qualiloop connect knowledge)',
448
+ ], ['Exploring now', result.exploring], ['Link', result.url]);
449
+ const rendered = table(result.capabilities.map((row) => ({ ...row, state: stateWords(row.state) })), [
450
+ ['name', 'Capability', 50],
451
+ ['state', 'State'],
452
+ ['covered', 'Covered'],
453
+ ]);
265
454
  out.result(result, () => [
266
- fields([
267
- ['Project', result.project],
268
- ['Coverage', result.coverage ? `${result.coverage.percent}% (${result.coverage.covered}/${result.coverage.total})` : '-'],
269
- ['Sources', sources.length ? sources.map((row) => row.name).join(', ') : 'none (qualiloop connect knowledge)'],
270
- ['Exploring now', result.exploring],
271
- ['Link', result.url],
272
- ]),
455
+ fields(pairs),
273
456
  '',
274
- table(result.capabilities, [
275
- ['name', 'Capability', 50],
276
- ['confirmed', 'Confirmed'],
277
- ]) || 'No capabilities known yet.',
457
+ listed(rendered, result.capabilities.length, total, 'No capabilities found yet. Exploration and test conversations find them.'),
458
+ ...(result.capabilities.some((row) => !row.confirmed) ? ['', STATE_NOTE] : []),
278
459
  ].join('\n'));
279
460
  }));
280
461
  knowledge
281
462
  .command('list')
282
- .description('The items QualiLoop knows, by section, with their ids. Super admins see every section and status.')
463
+ .description('Every item QualiLoop knows, confirmed or not, by section, with its id and state. Super admins see every section and status.')
283
464
  .option('--section <section>', 'only one section: capability, entity_group, entity (super admins: also fact, component, state, action, transition)')
284
465
  .addOption(limitOption('items', '100', 1000))
285
466
  .action(run(async ({ client, out, project, opts }) => {
@@ -292,11 +473,28 @@ knowledge
292
473
  ['id', 'ID'],
293
474
  ['section', 'Section'],
294
475
  ['name', 'Name', 45],
295
- ['confirmed', 'Confirmed'],
476
+ ['state', 'State'],
477
+ ['covered', 'Covered'],
296
478
  ];
479
+ if (result.items.some((row) => row.group))
480
+ columns.push(['group', 'Group', 30]);
481
+ if (result.items.some((row) => row.identifier))
482
+ columns.push(['identifier', 'Identifier', 30]);
297
483
  if (result.full)
298
484
  columns.push(['intended', 'Intended'], ['observed', 'Observed'], ['reported', 'Reported'], ['projected', 'Projected']);
299
- out.result(result, () => listed(table(result.items, columns), result.items.length, result.total, 'Nothing known yet.'));
485
+ const rows = result.items.map((row) => ({ ...row, state: stateWords(row.state) }));
486
+ const counts = Object.entries(result.found ?? {}).map(([section, row]) => `${SECTION_NAMES[section] ?? section}: ${foundLine(row)}`);
487
+ out.result(result, () => {
488
+ const shown = listed(table(rows, columns), result.items.length, result.total, 'Nothing known yet.');
489
+ if (!result.total)
490
+ return shown;
491
+ return [
492
+ shown,
493
+ '',
494
+ ...counts,
495
+ ...(result.items.some((row) => !row.confirmed) ? ['', STATE_NOTE] : []),
496
+ ].join('\n');
497
+ });
300
498
  }));
301
499
  knowledge
302
500
  .command('show <id>')
@@ -372,7 +570,7 @@ knowledge
372
570
  }));
373
571
  knowledge
374
572
  .command('explore')
375
- .description('Explore the agent: 3 rounds of up to 8 conversations, up to 24 conversation credits, not judged.')
573
+ .description("Explore the agent: 3 rounds of up to 8 conversations, up to 24 conversation credits (the project's first exploration is free), not judged.")
376
574
  .option('--note <text>', 'what to look at more closely')
377
575
  .action(run(async (ctx) => {
378
576
  const { client, out, project, opts } = ctx;
@@ -380,7 +578,14 @@ knowledge
380
578
  project,
381
579
  note: opts.note,
382
580
  });
383
- out.result(result, () => `Started exploration #${result.exploration.number ?? result.exploration.id}: up to ${result.most_credits} conversations, so up to ${result.most_credits} conversation credits.\nFollow it: qualiloop knowledge explorations${projectFlag(ctx)}`);
581
+ const conversations = Number(result.exploration.rounds ?? 3) * Number(result.exploration.conversations_per_round ?? 8);
582
+ const cost = result.exploration.free
583
+ ? `up to ${conversations} conversations, free as the project's first exploration`
584
+ : `up to ${result.most_credits} conversations, so up to ${result.most_credits} conversation credits`;
585
+ const waiting = result.exploration.waiting
586
+ ? '\nThe knowledge is being updated. The exploration waits for that to finish and then starts by itself.'
587
+ : '';
588
+ out.result(result, () => `Started exploration #${result.exploration.number ?? result.exploration.id}: ${cost}.${waiting}\nFollow it: qualiloop knowledge explorations${projectFlag(ctx)}`);
384
589
  }));
385
590
  knowledge
386
591
  .command('explorations')
@@ -390,6 +595,7 @@ knowledge
390
595
  out.result(result, () => table(result.explorations.map((row) => ({
391
596
  ...row,
392
597
  number: row.number ?? row.id,
598
+ status: row.waiting ? 'waiting for the knowledge update' : row.status,
393
599
  round: `${row.current_round ?? 0}/${row.rounds ?? '-'}`,
394
600
  })), [
395
601
  ['number', 'Number'],
@@ -404,7 +610,7 @@ const ORIGIN_LABEL = {
404
610
  code: 'coding agent',
405
611
  manual: 'by hand',
406
612
  connector: 'connection settings',
407
- trace: 'seen in traces',
613
+ trace: 'seen in traces (earlier version)',
408
614
  };
409
615
  const KIND_LABEL = { system_prompt: 'System prompt', tools: 'Tools', documentation: 'Documentation' };
410
616
  knowledge
@@ -436,12 +642,28 @@ knowledge
436
642
  .command('source <id>')
437
643
  .description('One source: its current text, versions, and what it states.')
438
644
  .option('--max-chars <n>', 'most characters of the text to show', '20000')
645
+ .option('--show-version <n>', "show this version's text instead of the current one")
646
+ .option('--diff <n>', 'show the changes from this version to the one shown')
439
647
  .action(run(async ({ client, out, project, opts }, id) => {
440
648
  const result = await client.action('get_source', {
441
649
  project,
442
650
  source: intArg(id),
443
651
  max_chars: intArg(String(opts.maxChars)),
652
+ version: opts.showVersion === undefined ? undefined : intArg(String(opts.showVersion)),
653
+ compare_to: opts.diff === undefined ? undefined : intArg(String(opts.diff)),
444
654
  });
655
+ const shown = result.shown_version !== undefined && result.shown_version !== result.version
656
+ ? [`Showing version ${result.shown_version}.`, '']
657
+ : [];
658
+ const body = result.diff !== undefined
659
+ ? [
660
+ String(result.diff) || `No changes from version ${result.compared_to}.`,
661
+ ...(result.diff_cut ? ['\n(the diff is cut; more with --max-chars)'] : []),
662
+ ]
663
+ : [
664
+ String(result.text ?? ''),
665
+ ...(result.text_cut ? [`\n(${result.text_chars} characters; more with --max-chars)`] : []),
666
+ ];
445
667
  out.result(result, () => [
446
668
  fields([
447
669
  ['Source', `${result.id} ${result.name}`],
@@ -451,12 +673,12 @@ knowledge
451
673
  ['Agent', result.component],
452
674
  ['Placeholders', result.placeholders],
453
675
  ['Seen at steps', result.trace_steps],
454
- ['Versions', result.versions.length],
676
+ ['Versions', result.versions.map((row) => row.number).join(', ')],
455
677
  ['Link', result.url],
456
678
  ]),
457
679
  '',
458
- String(result.text ?? ''),
459
- ...(result.text_cut ? [`\n(${result.text_chars} characters; more with --max-chars)`] : []),
680
+ ...shown,
681
+ ...body,
460
682
  ...(result.states.length
461
683
  ? ['', table(result.states, [['node_id', 'Item'], ['section', 'Section'], ['name', 'It states', 60]])]
462
684
  : []),
@@ -464,44 +686,196 @@ knowledge
464
686
  }));
465
687
  knowledge
466
688
  .command('add-doc <name>')
467
- .description('Add a document the agent answers from, or a new version of one added by hand (admins, ML team).')
689
+ .description('Add a document the agent answers from, or a system prompt with --kind system_prompt; the same name again ' +
690
+ 'saves a new version (admins, ML team).')
468
691
  .requiredOption('--file <path>', 'the text, from a file (or - for stdin)')
692
+ .addOption(new Option('--kind <kind>', 'documentation (default) or system_prompt').choices(['documentation', 'system_prompt']))
469
693
  .action(run(async ({ client, out, project, opts }, name) => {
470
- const file = String(opts.file);
471
- let text;
472
- try {
473
- text = readFileSync(file === '-' ? 0 : file, 'utf8');
474
- }
475
- catch (error) {
476
- throw new ApiError(`Cannot read ${file}: ${error.message}`, 400, EXIT.usage);
477
- }
478
- const result = await client.action('save_documentation', { project, name, text });
694
+ const text = readText(String(opts.file));
695
+ const result = await client.action('save_documentation', {
696
+ project,
697
+ name,
698
+ text,
699
+ kind: opts.kind,
700
+ });
479
701
  out.result(result, () => `Saved ${result.source.name} as source ${result.source.id}, version ${result.source.version}.` +
480
702
  (result.fill_queued || result.change_queued ? ' QualiLoop reads it into the system knowledge.' : ''));
481
703
  }));
482
704
  knowledge
483
705
  .command('retire-source <id>')
484
706
  .description('Take a source added by hand or seen in traces out of force (admins, ML team). Its versions are kept.')
485
- .action(run(async ({ client, out, project }, id) => {
707
+ .action(run(async (ctx, id) => {
708
+ const { client, out, project } = ctx;
486
709
  const result = await client.action('retire_source', { project, source: intArg(id) });
487
- out.result(result, () => `Retired ${result.source.name}. Restore it in System Knowledge, Sources.`);
710
+ out.result(result, () => `Retired ${result.source.name}. Bring it back with: ` +
711
+ `qualiloop knowledge restore-source ${result.source.id}${projectFlag(ctx)}`);
712
+ }));
713
+ knowledge
714
+ .command('restore-source <id>')
715
+ .description('Put a retired source back in force with the version it had (admins, ML team).')
716
+ .action(run(async ({ client, out, project }, id) => {
717
+ const result = await client.action('restore_source', { project, source: intArg(id) });
718
+ out.result(result, () => `Restored ${result.source.name}, version ${result.source.version}.`);
719
+ }));
720
+ knowledge
721
+ .command('unmatched')
722
+ .description('System messages in the traces that match no source, with their ids. The judge reads each in its own ' +
723
+ 'conversation only; save one that is a prompt with save-unmatched.')
724
+ .option('--max-chars <n>', 'most characters of each text to show', '300')
725
+ .action(run(async ({ client, out, project, opts }) => {
726
+ const result = await client.action('list_unmatched_texts', { project, max_chars: Math.max(100, intArg(String(opts.maxChars))) });
727
+ const notKept = Number(result.not_kept ?? 0);
728
+ const note = notKept
729
+ ? `\n${result.capped ? 'At least ' : ''}${notKept} more seen in the last ${result.max_age_days} days are ` +
730
+ `not kept; the list keeps the ${result.kept_most} seen most recently.`
731
+ : '';
732
+ out.result(result, () => result.texts.length
733
+ ? result.texts
734
+ .map((row) => [
735
+ `${row.id} at ${row.step}, ${row.chars} characters, ${row.conversations_seen} conversations, ` +
736
+ `last seen ${row.last_seen_at}`,
737
+ ` ${String(row.text).split('\n').join('\n ')}${row.text_cut ? ' ...' : ''}`,
738
+ ].join('\n'))
739
+ .join('\n\n') + note
740
+ : `Every system text in the traces matches a source.${note}`);
741
+ }));
742
+ knowledge
743
+ .command('save-unmatched <id>')
744
+ .description('Save a text from `knowledge unmatched` as a system prompt source: --name for a new source, or --source for a ' +
745
+ 'new version of one (admins, ML team).')
746
+ .option('--name <name>', 'the new source name')
747
+ .option('--source <id>', 'the source to save it as a new version of')
748
+ .action(run(async ({ client, out, project, opts }, id) => {
749
+ if ((opts.name === undefined) === (opts.source === undefined)) {
750
+ throw new ApiError('Give --name for a new source, or --source for a new version of one.', 400, EXIT.usage);
751
+ }
752
+ const result = await client.action('save_unmatched_text', {
753
+ project,
754
+ text: intArg(id),
755
+ name: opts.name,
756
+ source: opts.source === undefined ? undefined : intArg(String(opts.source)),
757
+ });
758
+ out.result(result, () => `Saved as ${result.source.name}, source ${result.source.id}, version ${result.source.version}.` +
759
+ (result.fill_queued || result.change_queued ? ' QualiLoop reads it into the system knowledge.' : ''));
760
+ }));
761
+ knowledge
762
+ .command('link-source <id> [component]')
763
+ .description('Tie a system prompt to the agent or subagent it instructs: a component, by its id or exact name (admins, ML team).')
764
+ .option('--none', 'remove the link')
765
+ .action(run(async ({ client, out, project, opts }, id, component) => {
766
+ if (opts.none ? component !== undefined : component === undefined) {
767
+ throw new ApiError('Give a component, or --none to remove the link.', 400, EXIT.usage);
768
+ }
769
+ const result = await client.action('link_source_component', {
770
+ project,
771
+ source: intArg(id),
772
+ component: component === undefined ? null : /^\d+$/.test(component) ? Number(component) : component,
773
+ });
774
+ out.result(result, () => result.component
775
+ ? `Linked ${result.source.name} to ${result.component}.`
776
+ : `${result.source.name} is linked to no component.`);
777
+ }));
778
+ const privateObjects = knowledge
779
+ .command('private')
780
+ .description('Private objects: values the simulated user holds, such as account numbers. Names and ids only; values are never shown.');
781
+ privateObjects
782
+ .command('list', { isDefault: true })
783
+ .description('List the categories and items, by name and id.')
784
+ .action(run(async ({ client, out, project }) => {
785
+ const result = await client.action('list_private_objects', {
786
+ project,
787
+ });
788
+ out.result(result, () => result.categories.length
789
+ ? result.categories
790
+ .map((category) => [
791
+ `${category.name}${category.description ? `: ${category.description}` : ''}`,
792
+ table(category.items.map((item) => ({
793
+ ...item,
794
+ fields: Array.isArray(item.fields) ? item.fields.join(', ') : '',
795
+ })), [
796
+ ['id', 'ID', 36],
797
+ ['description', 'Description', 50],
798
+ ['fields', 'Fields', 40],
799
+ ]) || ' No items.',
800
+ ].join('\n'))
801
+ .join('\n\n')
802
+ : 'No private objects. Add them with: qualiloop knowledge private set --file <json>');
803
+ }));
804
+ privateObjects
805
+ .command('set')
806
+ .description('Add or change categories and items from a JSON file (admins, ML team): {"categories": [{"name", "rename_to"?, ' +
807
+ '"description"?, "items": [{"id"?, "description"?, "value"?}]}]}. An item without an id is added; one with an ' +
808
+ 'id keeps its value unless a new one is given. What is not named is kept.')
809
+ .requiredOption('--file <path>', 'the JSON, from a file (or - for stdin)')
810
+ .action(run(async ({ client, out, project, opts }) => {
811
+ const file = String(opts.file);
812
+ let body;
813
+ try {
814
+ body = JSON.parse(readText(file));
815
+ }
816
+ catch (error) {
817
+ if (error instanceof ApiError)
818
+ throw error;
819
+ throw new ApiError(`${file} is not JSON: ${error.message}`, 400, EXIT.usage);
820
+ }
821
+ const categories = Array.isArray(body) ? body : body?.categories;
822
+ if (!Array.isArray(categories)) {
823
+ throw new ApiError(`${file} needs a "categories" list.`, 400, EXIT.usage);
824
+ }
825
+ const result = await client.action('set_private_objects', { project, categories });
826
+ out.result(result, () => {
827
+ const added = result.categories_added ?? [];
828
+ const changed = result.categories_changed ?? [];
829
+ return [
830
+ `Saved private objects: ${result.items_added} items added, ${result.items_changed} changed.`,
831
+ ...(added.length ? [`New categories: ${added.join(', ')}`] : []),
832
+ ...(changed.length ? [`Changed categories: ${changed.join(', ')}`] : []),
833
+ ].join('\n');
834
+ });
835
+ }));
836
+ privateObjects
837
+ .command('delete <category>')
838
+ .description('Delete a category with its items, or only the items given with --item (admins, ML team).')
839
+ .option('--item <id...>', 'only these items, by id')
840
+ .option('--yes', 'delete without asking')
841
+ .action(run(async ({ client, out, project, opts }, category) => {
842
+ const items = opts.item;
843
+ if (!opts.yes) {
844
+ const what = items?.length ? `${items.length} items from private object category ${category}` : `private object category ${category} with its items`;
845
+ if (!(await confirm(`Delete ${what}?`))) {
846
+ out.result({ deleted: false, category }, () => 'Not deleted.');
847
+ return EXIT.ok;
848
+ }
849
+ }
850
+ const result = await client.action('delete_private_objects', { project, category, items });
851
+ out.result(result, () => result.category_deleted
852
+ ? `Deleted ${result.category} and its ${result.items_deleted} items.`
853
+ : `Deleted ${result.items_deleted} items from ${result.category}.`);
488
854
  }));
489
855
  program
490
856
  .command('change <description...>')
491
- .description('Tell QualiLoop the agent changed, so it re-checks what the change touches.')
492
- .option('--no-explore', 'record the change without exploring again')
857
+ .description('Tell QualiLoop the agent changed, so it marks what the change touches as possibly out of date.')
858
+ .option('--explore', 'also explore what the change touches (uses conversation credits)')
493
859
  .action(run(async ({ client, out, project, opts }, words) => {
494
860
  const result = await client.action('report_change', {
495
861
  project,
496
862
  description: words.join(' '),
497
- explore: opts.explore !== false,
863
+ explore: opts.explore === true,
498
864
  });
499
- out.result(result, () => `Change recorded in ${result.project}.${result.exploring ? ' QualiLoop explores what it touches again.' : ''}`);
865
+ out.result(result, () => [
866
+ `Change recorded in ${result.project}.`,
867
+ result.exploring
868
+ ? 'QualiLoop explores what it touches again.'
869
+ : result.exploration_note
870
+ ? String(result.exploration_note)
871
+ : 'To explore what it touches, run this again with --explore.',
872
+ ].join(' '));
500
873
  }));
501
874
  const testColumns = [
502
875
  ['id', 'ID'],
503
876
  ['name', 'Name', 45],
504
877
  ['mode', 'Mode'],
878
+ ['category', 'Category', 25],
505
879
  ['last', 'Last run'],
506
880
  ['suites', 'Suites'],
507
881
  ];
@@ -515,15 +889,29 @@ tests
515
889
  .description('List the saved tests of the project.')
516
890
  .option('--suite <suite>', 'only the tests of this suite (id or name)')
517
891
  .option('--search <text>', 'only tests whose name contains this')
892
+ .addOption(new Option('--mode <mode>', 'only tests of this mode').choices(['regular', 'red_team', 'bias']))
893
+ .option('--category <category>', 'only the regular tests of this category (id or name)')
894
+ .option('--new', 'only tests a generation wrote that nobody has opened yet')
895
+ .addOption(new Option('--sort <order>', 'latest change, name, latest run or most runs first')
896
+ .choices(['updated', 'name', 'last_run', 'runs']))
518
897
  .addOption(limitOption('tests', '100', 1000))
519
898
  .action(run(async ({ client, out, project, opts }) => {
520
899
  const result = await client.action('list_tests', {
521
900
  project,
522
901
  suite: opts.suite,
523
902
  search: opts.search,
903
+ mode: opts.mode,
904
+ category: typeof opts.category === 'string' ? idOrName(opts.category) : undefined,
905
+ new_only: opts.new ? true : undefined,
906
+ sort: opts.sort,
524
907
  limit: limitOf(opts, 1000),
525
908
  });
526
- out.result(result, () => listed(table(result.tests.map((row) => ({ ...row, last: lastRun(row) })), testColumns), result.tests.length, result.total, 'No tests.'));
909
+ out.result(result, () => listed(table(result.tests.map((row) => ({
910
+ ...row,
911
+ last: lastRun(row),
912
+ category: row.category?.name ?? '',
913
+ name: row.new ? `${row.name} (new)` : row.name,
914
+ })), testColumns), result.tests.length, result.total, 'No tests.'));
527
915
  }));
528
916
  tests
529
917
  .command('show <id>')
@@ -533,29 +921,92 @@ tests
533
921
  out.result(result, () => fields([
534
922
  ['Test', `${result.id} ${result.name}`],
535
923
  ['Mode', `${result.mode} (${result.run_type})`],
924
+ ...(result.attack_type ? [['Attack', result.attack_type]] : []),
925
+ ...(result.bias
926
+ ? [['Bias', `${result.bias.bias_type}: ${result.bias.group_a} vs ${result.bias.group_b}`]]
927
+ : []),
928
+ ...(result.category ? [['Category', result.category.name]] : []),
536
929
  ['Instructions', result.instructions],
537
930
  ['Persona', result.persona],
538
931
  ['Steps', result.steps],
932
+ ...(result.send_steps_literally ? [['Steps sent', 'exactly as written']] : []),
539
933
  ['Turns', result.max_turns],
540
934
  ['Conversations', result.conversations],
935
+ ...(Object.keys(result.variables ?? {}).length
936
+ ? [
937
+ [
938
+ 'Variables',
939
+ `${Object.entries(result.variables)
940
+ .map(([name, values]) => `${name}=${values.join(',')}`)
941
+ .join('; ')} (${result.variable_mode})`,
942
+ ],
943
+ ]
944
+ : []),
945
+ ...(result.channel === 'voice'
946
+ ? [['Channel', `voice${result.voice_id ? ` (${result.voice_id})` : ''}`]]
947
+ : []),
541
948
  ['Suites', result.suites],
542
949
  ['Last run', lastRun(result)],
543
950
  ]));
544
951
  }));
952
+ const repeat = (value, all = []) => [...all, value];
953
+ const idOrName = (value) => (/^\d+$/.test(value) ? Number(value) : value);
954
+ const variablesOf = (given) => {
955
+ if (!given)
956
+ return undefined;
957
+ const out = {};
958
+ for (const item of given) {
959
+ const at = item.indexOf('=');
960
+ if (at < 1)
961
+ throw new ApiError(`--var takes name=value1,value2, not ${item}.`, 400, EXIT.usage);
962
+ out[item.slice(0, at).trim()] = item
963
+ .slice(at + 1)
964
+ .split(',')
965
+ .map((value) => value.trim())
966
+ .filter(Boolean);
967
+ }
968
+ return out;
969
+ };
545
970
  const testFieldOptions = (command) => command
546
971
  .option('--instructions <text>', 'what the simulated user wants and how they behave')
547
972
  .option('--persona <text>', 'who the simulated user is')
548
- .option('--step <text>', 'a scripted step, in order (repeat)', (value, all = []) => [...all, value])
973
+ .option('--step <text>', 'a scripted step, in order (repeat)', repeat)
549
974
  .option('--turns <n>', 'most turns of one conversation')
550
- .option('--conversations <n>', 'conversations per run')
551
- .option('--language <language>', 'the language the simulated user speaks');
975
+ .option('--conversations <n>', 'conversations per run (matched pairs for a bias test)')
976
+ .option('--language <language>', 'the language the simulated user speaks')
977
+ .option('--bias <type>', 'make it a bias test of this type (gender, age, location, ...); give --group-a and --group-b')
978
+ .option('--group-a <group>', 'bias test: the first group compared')
979
+ .option('--group-b <group>', 'bias test: the second group compared')
980
+ .option('--category <category>', 'regular test: its category (id or name)')
981
+ .option('--var <name=values>', 'a variable for {{name}} placeholders, values split by commas (repeat)', repeat)
982
+ .addOption(new Option('--variable-order <order>', 'how a conversation picks a value').choices(['random', 'sequential']))
983
+ .option('--literal', 'send each step exactly as written')
984
+ .option('--no-literal', 'let the simulated user phrase the steps')
985
+ .addOption(new Option('--channel <channel>', 'how the simulated user reaches the agent (voice needs ElevenLabs)').choices(['text', 'voice']))
986
+ .option('--voice-id <id>', 'the ElevenLabs voice the simulated user speaks with');
987
+ const testFields = (opts) => ({
988
+ instructions: opts.instructions,
989
+ persona: opts.persona,
990
+ max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
991
+ conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
992
+ language: opts.language,
993
+ bias_type: opts.bias,
994
+ group_a: opts.groupA,
995
+ group_b: opts.groupB,
996
+ category: typeof opts.category === 'string' ? idOrName(opts.category) : undefined,
997
+ variables: opts.clearVariables ? {} : variablesOf(opts.var),
998
+ variable_mode: opts.variableOrder,
999
+ send_steps_literally: opts.literal,
1000
+ channel: opts.channel,
1001
+ voice_id: opts.voiceId,
1002
+ });
552
1003
  testFieldOptions(tests
553
1004
  .command('create')
554
1005
  .description('Write a new saved test.')
555
1006
  .requiredOption('--name <name>', 'a short name for the test'))
556
1007
  .option('--red-team <attack>', 'make it an attack of this type (prompt_injection, jailbreak, data_leak, ...)')
557
1008
  .option('--single', 'one message per prompt instead of a conversation')
558
- .option('--suite <suite>', 'add it to this suite (repeat)', (value, all = []) => [...all, value])
1009
+ .option('--suite <suite>', 'add it to this suite (repeat)', repeat)
559
1010
  .action(run(async (ctx) => {
560
1011
  const { client, out, project, opts } = ctx;
561
1012
  if (!opts.instructions)
@@ -563,13 +1014,9 @@ testFieldOptions(tests
563
1014
  const result = await client.action('create_test', {
564
1015
  project,
565
1016
  name: opts.name,
566
- instructions: opts.instructions,
567
- persona: opts.persona,
1017
+ ...testFields(opts),
568
1018
  steps: opts.step,
569
- max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
570
- conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
571
- language: opts.language,
572
- mode: opts.redTeam ? 'red_team' : 'regular',
1019
+ mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : 'regular',
573
1020
  attack_type: opts.redTeam,
574
1021
  shape: opts.single ? 'single' : 'conversation',
575
1022
  suites: opts.suite,
@@ -592,26 +1039,83 @@ tests
592
1039
  const result = await client.action('delete_test', { project, test });
593
1040
  out.result(result, () => `Deleted test ${result.id} ${result.name}.`);
594
1041
  }));
1042
+ tests
1043
+ .command('seen [test-ids...]')
1044
+ .description('Take the New mark off generated tests.')
1045
+ .option('--all', 'every new test of the project')
1046
+ .action(run(async ({ client, out, project, opts }, ids = []) => {
1047
+ if (Boolean(opts.all) === ids.length > 0)
1048
+ throw new ApiError('Give test ids or --all.', 400, EXIT.usage);
1049
+ const result = await client.action('mark_tests_seen', {
1050
+ project,
1051
+ tests: ids.length ? ids.map(intArg) : undefined,
1052
+ all: opts.all ? true : undefined,
1053
+ });
1054
+ out.result(result, () => result.tests.length ? `Marked ${result.tests.length} test(s) seen: ${result.tests.join(', ')}.` : 'No new test to mark.');
1055
+ }));
595
1056
  testFieldOptions(tests.command('edit <id>').description('Change a saved test; only what you give changes.').option('--name <name>', 'a new name'))
596
1057
  .option('--no-steps', 'remove the scripted steps')
1058
+ .option('--regular', 'make it a regular test')
1059
+ .option('--red-team <attack>', 'make it an attack of this type, or change its attack type')
1060
+ .addOption(new Option('--shape <shape>', 'a conversation, or one message per prompt').choices(['conversation', 'single']))
1061
+ .option('--clear-variables', 'remove every variable')
597
1062
  .action(run(async ({ client, out, project, opts }, id) => {
598
1063
  const result = await client.action('update_test', {
599
1064
  project,
600
1065
  test: intArg(id),
601
1066
  name: opts.name,
602
- instructions: opts.instructions,
603
- persona: opts.persona,
1067
+ ...testFields(opts),
604
1068
  steps: opts.steps === false ? [] : opts.step,
605
- max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
606
- conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
607
- language: opts.language,
1069
+ mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : opts.regular ? 'regular' : undefined,
1070
+ attack_type: opts.redTeam,
1071
+ shape: opts.shape,
608
1072
  });
609
1073
  out.result(result, () => `Updated test ${result.id}: ${result.updated.join(', ')}.`);
610
1074
  }));
1075
+ tests
1076
+ .command('copy <id>')
1077
+ .description('Save a copy of a saved test with every field, in the same suites.')
1078
+ .option('--name <name>', 'the copy\'s name (default: the name with (copy) after it)')
1079
+ .option('--suite <suite>', 'put the copy in this suite instead of the test\'s own (repeat)', repeat)
1080
+ .action(run(async (ctx, id) => {
1081
+ const { client, out, project, opts } = ctx;
1082
+ const result = await client.action('copy_test', {
1083
+ project,
1084
+ test: intArg(id),
1085
+ name: opts.name,
1086
+ suites: opts.suite,
1087
+ });
1088
+ out.result(result, () => `Saved test ${result.id} ${result.name}, a copy of test ${id}. Change it: qualiloop tests edit ${result.id}${projectFlag(ctx)}`);
1089
+ }));
1090
+ tests
1091
+ .command('draft <description...>')
1092
+ .description('Fill in a test from a description, or a change to one with --test. Saves nothing.')
1093
+ .option('--test <id>', 'draft a change to this saved test')
1094
+ .addOption(new Option('--mode <mode>', 'keep the draft in this mode').choices(['regular', 'red_team', 'bias']))
1095
+ .action(run(async ({ client, out, project, opts }, words) => {
1096
+ const result = await client.action('draft_test', {
1097
+ project,
1098
+ instruction: words.join(' '),
1099
+ test: opts.test ? intArg(String(opts.test)) : undefined,
1100
+ mode: opts.mode,
1101
+ });
1102
+ const shown = result.changed ?? result.fields;
1103
+ out.result(result, () => [
1104
+ Object.keys(shown).length
1105
+ ? fields(Object.entries(shown).map(([key, value]) => [key, value]))
1106
+ : 'Nothing to change.',
1107
+ '',
1108
+ result.changed
1109
+ ? `Not saved. Save the changes with qualiloop tests edit ${opts.test} and these fields.`
1110
+ : 'Not saved. Save it with qualiloop tests create and these fields, or run this with --json.',
1111
+ ].join('\n'));
1112
+ }));
611
1113
  const launched = async (ctx, result) => {
612
1114
  const { out, project, opts } = ctx;
613
- for (const item of result.failed)
614
- out.progress(`Test ${item.test_id} did not start: ${item.reason}`);
1115
+ for (const item of result.failed) {
1116
+ const what = item.test_id !== undefined ? `Test ${item.test_id}` : `Run #${item.run_number}`;
1117
+ out.progress(`${what} did not start: ${item.reason}`);
1118
+ }
615
1119
  if (!result.batch_id || !result.started.length) {
616
1120
  out.result(result, () => 'Nothing started.');
617
1121
  return EXIT.failed;
@@ -665,10 +1169,19 @@ const waitOptions = (command, waitFlag = true) => {
665
1169
  return command.addOption(failOnOption()).option('--timeout <minutes>', 'most minutes to wait', '60');
666
1170
  };
667
1171
  waitOptions(program
668
- .command('run <test-ids...>')
669
- .description('Run saved tests now, as one batch.')
670
- .option('--label <label>', 'what Test Results calls this launch')).action(run(async (ctx, ids) => {
671
- const result = await ctx.client.action('run_tests', { project: ctx.project, tests: ids.map(intArg), label: ctx.opts.label });
1172
+ .command('run [test-ids...]')
1173
+ .description('Run saved tests now, as one batch. With --category and no ids, every test of the category.')
1174
+ .option('--label <label>', 'what Test Results calls this launch')
1175
+ .option('--category <category>', 'a test category (id or name): the launch is a category run named after it')).action(run(async (ctx, ids = []) => {
1176
+ const category = ctx.opts.category;
1177
+ if (!ids.length && !category)
1178
+ throw new ApiError('Give the test ids to run, or --category.', 400, EXIT.usage);
1179
+ const result = await ctx.client.action('run_tests', {
1180
+ project: ctx.project,
1181
+ tests: ids.map(intArg),
1182
+ label: ctx.opts.label,
1183
+ category: category === undefined ? undefined : suiteRef(category),
1184
+ });
672
1185
  return launched(ctx, result);
673
1186
  }));
674
1187
  const suites = program.command('suites').description('Suites of saved tests.');
@@ -718,6 +1231,20 @@ suites
718
1231
  out.result(result, () => `Added ${result.added} test(s) to suite ${result.suite.id} ${result.suite.name}` +
719
1232
  (Number(result.added) < ids.length ? '; the others were in it already.' : '.'));
720
1233
  }));
1234
+ suites
1235
+ .command('edit <suite>')
1236
+ .description('Rename a suite (id, name, or core) or change its description.')
1237
+ .option('--name <name>', 'a new name')
1238
+ .option('--description <text>', 'what the suite is for; empty removes it')
1239
+ .action(run(async ({ client, out, project, opts }, suite) => {
1240
+ const result = await client.action('update_suite', {
1241
+ project,
1242
+ suite: suiteRef(suite),
1243
+ name: opts.name,
1244
+ description: opts.description,
1245
+ });
1246
+ out.result(result, () => `Suite ${result.suite.id} is now ${result.suite.name}.`);
1247
+ }));
721
1248
  waitOptions(suites.command('run <suite>').description('Run every test of a suite (id, name, or core).')).action(run(async (ctx, suite) => {
722
1249
  const result = await ctx.client.action('run_suite', { project: ctx.project, suite: suiteRef(suite) });
723
1250
  return launched(ctx, result);
@@ -746,45 +1273,141 @@ suites
746
1273
  out.result(result, () => `Deleted suite ${result.id} ${result.name}` + (result.tests_deleted ? ` and its ${result.tests} test(s).` : '.'));
747
1274
  }));
748
1275
  const runs = program.command('runs').description('Test runs and their results.');
1276
+ const offsetOption = () => new Option('--offset <n>', 'skip this many, for the next page').default('0');
1277
+ const offsetOf = (opts) => {
1278
+ const offset = intArg(String(opts.offset ?? '0'));
1279
+ if (offset < 0)
1280
+ throw new ApiError('--offset takes 0 or more.', 400, EXIT.usage);
1281
+ return offset;
1282
+ };
1283
+ const testModeOption = () => new Option('--mode <mode>', 'only tests of this mode').choices(['regular', 'red_team', 'bias']);
1284
+ const fromOption = () => new Option('--from <date>', 'only what started on or after this date (YYYY-MM-DD) or time');
1285
+ const toOption = () => new Option('--to <date>', 'only what started on or before this date (the whole day) or time');
1286
+ const paged = (rendered, shown, total, offset, empty) => {
1287
+ if (!rendered)
1288
+ return empty;
1289
+ if (offset + shown >= total)
1290
+ return rendered;
1291
+ return `${rendered}\n\n${offset + 1} to ${offset + shown} of ${total} shown. Next page: --offset ${offset + shown}.`;
1292
+ };
749
1293
  runs
750
1294
  .command('list', { isDefault: true })
751
- .description('Recent runs, newest first.')
1295
+ .description('Recent runs, newest first, filtered as Test Results filters them.')
752
1296
  .option('--batch <id>', 'only the runs of one launch')
753
1297
  .option('--status <status>', 'only runs in this status')
1298
+ .addOption(testModeOption())
1299
+ .addOption(new Option('--result <result>', 'only finished runs with this result').choices(['clean', 'minor', 'major', 'not_reviewed']))
1300
+ .addOption(fromOption())
1301
+ .addOption(toOption())
1302
+ .addOption(new Option('--started <how>', 'started by a schedule or by hand').choices(['scheduled', 'manual']))
1303
+ .option('--category <category>', 'only runs with a problem in this problem category (id or title)')
1304
+ .option('--test <id>', 'only runs of this saved test')
1305
+ .option('--schedule <id>', 'only runs this schedule started')
1306
+ .option('--search <text>', 'only runs whose test name contains this')
754
1307
  .addOption(limitOption('runs', '20', 500))
1308
+ .addOption(offsetOption())
755
1309
  .action(run(async ({ client, out, project, opts }) => {
1310
+ const offset = offsetOf(opts);
756
1311
  const result = await client.action('list_runs', {
757
1312
  project,
758
1313
  batch: opts.batch,
759
1314
  status: opts.status,
1315
+ mode: opts.mode,
1316
+ result: opts.result,
1317
+ from: opts.from,
1318
+ to: opts.to,
1319
+ started: opts.started,
1320
+ category: opts.category ? suiteRef(String(opts.category)) : undefined,
1321
+ test: opts.test ? intArg(String(opts.test)) : undefined,
1322
+ schedule: opts.schedule ? intArg(String(opts.schedule)) : undefined,
1323
+ search: opts.search,
760
1324
  limit: limitOf(opts, 500),
1325
+ offset,
761
1326
  });
762
- out.result(result, () => listed(table(result.runs, [
1327
+ out.result(result, () => paged(table(result.runs, [
763
1328
  ['run_number', 'Run'],
764
1329
  ['name', 'Test', 40],
1330
+ ['mode', 'Mode'],
765
1331
  ['status_label', 'Status'],
766
1332
  ['outcome', 'Outcome'],
767
1333
  ['major_problems', 'Major'],
768
1334
  ['minor_problems', 'Minor'],
769
- ]), result.runs.length, result.total, 'No runs.'));
1335
+ ]), result.runs.length, result.total, offset, 'No runs.'));
770
1336
  }));
771
1337
  runs
772
1338
  .command('show <run>')
773
- .description('One run: status, outcome and problems found.')
1339
+ .description('One run: status, outcome, problems found and quality scores.')
774
1340
  .action(run(async ({ client, out, project }, number) => {
775
- const result = await client.action('get_run', { project, run_number: intArg(number) });
1341
+ const result = await client.action('get_run', {
1342
+ project,
1343
+ run_number: intArg(number),
1344
+ });
1345
+ const summary = result.judging_summary;
1346
+ const scores = (summary?.quality_scores ?? []).filter((item) => item.average !== null && item.average !== undefined);
1347
+ const reasons = summary?.unjudged_reasons ?? [];
776
1348
  out.result(result, () => fields([
777
1349
  ['Run', `#${result.run_number} ${result.name}`],
778
1350
  ['Status', result.status_label],
779
1351
  ['Outcome', result.outcome],
780
1352
  ['Passed', result.test_passed],
1353
+ ['Summary', summary?.headline],
781
1354
  ['Conversations', result.conversations],
1355
+ ['Not reviewed', summary?.unjudged_conversations],
1356
+ ...reasons.map((item) => [
1357
+ ' Why',
1358
+ Number(summary?.unjudged_conversations) > 1
1359
+ ? `${item.conversations} ${item.conversations === 1 ? 'conversation' : 'conversations'}: ${item.reason}`
1360
+ : item.reason,
1361
+ ]),
782
1362
  ['Major problems', result.major_problems],
783
1363
  ['Minor problems', result.minor_problems],
1364
+ ['Quality (1-5)', summary?.quality_average],
1365
+ ...scores.map((item) => [` ${item.label}`, item.average]),
784
1366
  ['Error', result.error_message],
785
1367
  ['Link', result.url],
786
1368
  ]));
787
1369
  }));
1370
+ runs
1371
+ .command('batches')
1372
+ .description('Launches, newest first: tests started together count as one, as the Suites view lists them.')
1373
+ .addOption(new Option('--kind <kind>', 'only launches of this kind').choices(['suite', 'schedule', 'selection', 'category', 'single']))
1374
+ .option('--suite <suite>', 'only the launches of this suite (id or name)')
1375
+ .addOption(new Option('--status <status>', 'still running or completed').choices(['running', 'completed']))
1376
+ .addOption(testModeOption())
1377
+ .addOption(fromOption())
1378
+ .addOption(toOption())
1379
+ .option('--search <text>', 'only launches whose label or a test name contains this')
1380
+ .addOption(limitOption('launches', '20', 100))
1381
+ .addOption(offsetOption())
1382
+ .action(run(async ({ client, out, project, opts }) => {
1383
+ const offset = offsetOf(opts);
1384
+ const result = await client.action('list_batches', {
1385
+ project,
1386
+ kind: opts.kind,
1387
+ suite: opts.suite ? suiteRef(String(opts.suite)) : undefined,
1388
+ status: opts.status,
1389
+ mode: opts.mode,
1390
+ from: opts.from,
1391
+ to: opts.to,
1392
+ search: opts.search,
1393
+ limit: limitOf(opts, 100),
1394
+ offset,
1395
+ });
1396
+ out.result(result, () => paged(table(result.batches.map((row) => ({
1397
+ ...row,
1398
+ passing: row.no_major_percent === null || row.no_major_percent === undefined ? null : `${row.no_major_percent}%`,
1399
+ runs: Array.isArray(row.run_numbers) ? row.run_numbers.map((value) => `#${value}`) : null,
1400
+ })), [
1401
+ ['batch_id', 'Batch', 36],
1402
+ ['label', 'Launch', 36],
1403
+ ['status', 'Status'],
1404
+ ['tests', 'Tests'],
1405
+ ['passing', 'No major'],
1406
+ ['major_problems', 'Major'],
1407
+ ['minor_problems', 'Minor'],
1408
+ ['runs', 'Runs', 30],
1409
+ ]), result.batches.length, result.total, offset, 'No launches.'));
1410
+ }));
788
1411
  runs
789
1412
  .command('delete <run>')
790
1413
  .description('Delete a run with its conversations and problems. A run still working is stopped first.')
@@ -801,6 +1424,63 @@ runs
801
1424
  const result = await client.action('delete_run', { project, run_number: runNumber });
802
1425
  out.result(result, () => `Deleted run #${result.run_number} ${result.name}.`);
803
1426
  }));
1427
+ const runsAgainArgs = (numbers, opts) => {
1428
+ if (!numbers.length && !opts.batch)
1429
+ throw new ApiError('Give the run numbers, or --batch.', 400, EXIT.usage);
1430
+ return { runs: numbers.map(intArg), batch: opts.batch };
1431
+ };
1432
+ waitOptions(runs
1433
+ .command('restart [runs...]')
1434
+ .description('Run the tests of earlier runs again, as new runs in one batch. A saved test runs as it stands now.')
1435
+ .option('--batch <id>', 'every run of one launch')).action(run(async (ctx, numbers = []) => {
1436
+ const result = await ctx.client.action('restart_runs', { project: ctx.project, ...runsAgainArgs(numbers, ctx.opts) });
1437
+ return launched(ctx, result);
1438
+ }));
1439
+ runs
1440
+ .command('rejudge [runs...]')
1441
+ .description('Judge the conversations of finished runs again with the current rules. Nothing is sent to the agent.')
1442
+ .option('--batch <id>', 'every run of one launch')
1443
+ .action(run(async (ctx, numbers = []) => {
1444
+ const { client, out, project, opts } = ctx;
1445
+ const result = await client.action('rejudge_runs', { project, ...runsAgainArgs(numbers, opts) });
1446
+ out.result(result, () => [
1447
+ result.judging.length
1448
+ ? `Judging again: ${result.judging.map((number) => `#${number}`).join(', ')}. Wait for it: qualiloop runs wait ${result.batch_id}${projectFlag(ctx)}`
1449
+ : 'Nothing is being judged.',
1450
+ ...result.skipped.map((item) => `Run #${item.run_number} skipped: ${item.reason}`),
1451
+ ].join('\n'));
1452
+ return result.judging.length ? EXIT.ok : EXIT.failed;
1453
+ }));
1454
+ runs
1455
+ .command('rejudge-conversation <conversation>')
1456
+ .description('Judge one conversation again now, test or live. Nothing is sent to the agent.')
1457
+ .action(run(async (ctx, conversation) => {
1458
+ const { client, out, project } = ctx;
1459
+ const result = await client.action('rejudge_conversation', { project, conversation });
1460
+ out.result(result, () => result.judging
1461
+ ? `Judging ${conversation} again. Read it in a minute: qualiloop conversation ${conversation}${projectFlag(ctx)}`
1462
+ : `${conversation} is being judged already, or has nothing to judge.`);
1463
+ }));
1464
+ runs
1465
+ .command('delete-conversation <run> <conversation>')
1466
+ .description('Delete one conversation of a finished run, with its verdict and problems.')
1467
+ .option('--yes', 'delete without asking')
1468
+ .action(run(async ({ client, out, project, opts }, number, conversation) => {
1469
+ const runNumber = intArg(number);
1470
+ if (!opts.yes) {
1471
+ const found = await client.action('get_run', { project, run_number: runNumber });
1472
+ if (!(await confirm(`Delete conversation ${conversation} of run #${found.run_number} ${found.name}?`))) {
1473
+ out.result({ deleted: false, run_number: runNumber, conversation }, () => 'Not deleted.');
1474
+ return EXIT.ok;
1475
+ }
1476
+ }
1477
+ const result = await client.action('delete_conversation', {
1478
+ project,
1479
+ run_number: runNumber,
1480
+ conversation,
1481
+ });
1482
+ out.result(result, () => `Deleted conversation ${result.conversation} of run #${result.run_number}.`);
1483
+ }));
804
1484
  waitOptions(runs
805
1485
  .command('wait <batch>')
806
1486
  .description('Wait for the runs of one launch to finish (the batch run --wait prints), and exit by --fail-on.'), false).action(run(async (ctx, batch) => follow(ctx, ctx.project, batch)));
@@ -816,7 +1496,8 @@ problems
816
1496
  .description('Problems, newest first.')
817
1497
  .option('--run <n>', 'only problems of this run')
818
1498
  .addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']))
819
- .option('--category <text>', 'only problems of a category whose title contains this')
1499
+ .option('--category <id>', 'only problems of this category: its id, or part of its title')
1500
+ .option('--unsorted', 'only problems no category holds yet')
820
1501
  .addOption(modeOption())
821
1502
  .addOption(sourceOption())
822
1503
  .addOption(limitOption('problems', '20', 200))
@@ -826,6 +1507,7 @@ problems
826
1507
  run_number: opts.run ? intArg(String(opts.run)) : undefined,
827
1508
  severity: opts.severity,
828
1509
  category: opts.category,
1510
+ unsorted: opts.unsorted ? true : undefined,
829
1511
  mode: opts.mode,
830
1512
  source: opts.source,
831
1513
  limit: limitOf(opts, 200),
@@ -907,6 +1589,149 @@ categories
907
1589
  });
908
1590
  out.result(result, () => `Category ${result.id} ${result.category} is ${result.solved ? 'solved' : 'open again'}.`);
909
1591
  }));
1592
+ categories
1593
+ .command('delete <id>')
1594
+ .description('Delete a category (id or title) and every problem in it.')
1595
+ .option('--never-flag', 'also add a do-not-flag rule written from the category')
1596
+ .option('--yes', 'delete without asking')
1597
+ .action(run(async ({ client, out, project, opts }, id) => {
1598
+ const category = suiteRef(id);
1599
+ if (!opts.yes) {
1600
+ const found = await client.action('get_problem_category', { project, category });
1601
+ if (!(await confirm(`Delete category ${found.id} ${found.title} and its ${found.problems} problems?`))) {
1602
+ out.result({ deleted: false, id: found.id }, () => 'Not deleted.');
1603
+ return EXIT.ok;
1604
+ }
1605
+ }
1606
+ const result = await client.action('delete_problem_category', {
1607
+ project,
1608
+ category,
1609
+ add_to_never_flag: Boolean(opts.neverFlag),
1610
+ });
1611
+ out.result(result, () => `Deleted category ${result.id} ${result.category} and its ${result.deleted_problems} problems.` +
1612
+ (result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
1613
+ }));
1614
+ problems
1615
+ .command('severity <id> <severity>')
1616
+ .description("Upgrade a problem to major or downgrade it to minor; the new tier replaces the judge's everywhere.")
1617
+ .action(run(async ({ client, out, project }, id, severity) => {
1618
+ if (!['major', 'minor'].includes(severity))
1619
+ throw new ApiError('Say major or minor.', 400, EXIT.usage);
1620
+ const result = await client.action('set_problem_severity', { project, problem: intArg(id), severity });
1621
+ out.result(result, () => `Problem ${result.id} ${result.title} is ${result.severity} (was ${result.previous_severity}).`);
1622
+ }));
1623
+ problems
1624
+ .command('delete <id>')
1625
+ .description('Delete a problem for good; nothing of it remains, unlike dismiss.')
1626
+ .option('--with-category', 'also delete its category and every problem in it')
1627
+ .option('--never-flag', 'also add a do-not-flag rule written from its category or the problem')
1628
+ .option('--yes', 'delete without asking')
1629
+ .action(run(async ({ client, out, project, opts }, id) => {
1630
+ const problem = intArg(id);
1631
+ const what = opts.withCategory ? `problem ${problem} with its category and every problem in it` : `problem ${problem}`;
1632
+ if (!opts.yes && !(await confirm(`Delete ${what}?`))) {
1633
+ out.result({ deleted: false, id: problem }, () => 'Not deleted.');
1634
+ return EXIT.ok;
1635
+ }
1636
+ const result = await client.action('delete_problem', {
1637
+ project,
1638
+ problem,
1639
+ delete_category: Boolean(opts.withCategory),
1640
+ add_to_never_flag: Boolean(opts.neverFlag),
1641
+ });
1642
+ out.result(result, () => `Deleted problem ${result.id} ${result.title}` +
1643
+ (result.deleted_category ? ` with category ${result.deleted_category} (${result.deleted_problems} problems)` : '') +
1644
+ '.' +
1645
+ (result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
1646
+ }));
1647
+ problems
1648
+ .command('sort')
1649
+ .description('Sort problems into categories now instead of waiting for the next test batch.')
1650
+ .addOption(new Option('--scope <scope>', 'unsorted: the problems in no category, now; unsolved or solved: every problem on that tab again, in the background')
1651
+ .choices(['unsorted', 'unsolved', 'solved'])
1652
+ .default('unsorted'))
1653
+ .action(run(async ({ client, out, project, opts }) => {
1654
+ const result = await client.action('sort_problems', { project, scope: opts.scope });
1655
+ out.result(result, () => result.background
1656
+ ? `Sorting the ${result.scope} problems again in the background. Then: qualiloop problems categories`
1657
+ : result.skipped
1658
+ ? String(result.skipped)
1659
+ : `Sorted ${result.sorted} problems; ${result.new_categories} new categories, ${result.updated_fixes} fixes rewritten.`);
1660
+ }));
1661
+ const checksRender = (result) => {
1662
+ const limit = result.max_tokens_per_turn ? `${result.max_tokens_per_turn} tokens` : 'no limit set';
1663
+ return [
1664
+ fields([
1665
+ ['Token limit per turn', result.token_budget_enabled ? `on, ${limit}` : `off (${limit})`],
1666
+ ['Unanswered messages', result.no_answer_enabled ? 'reported' : 'not reported'],
1667
+ ['Link', result.url],
1668
+ ]),
1669
+ '',
1670
+ table(result.custom_checks, [
1671
+ ['id', 'ID'],
1672
+ ['severity', 'Severity'],
1673
+ ['title', 'Custom check', 50],
1674
+ ['description', 'Description', 50],
1675
+ ]) || 'No custom checks.',
1676
+ ].join('\n');
1677
+ };
1678
+ const onOff = (value, flag) => {
1679
+ if (value === undefined)
1680
+ return undefined;
1681
+ if (!['on', 'off'].includes(String(value)))
1682
+ throw new ApiError(`${flag} takes on or off.`, 400, EXIT.usage);
1683
+ return value === 'on';
1684
+ };
1685
+ const checks = problems
1686
+ .command('checks')
1687
+ .description('Checks: the token limit per turn, unanswered messages, and custom checks added by hand.');
1688
+ checks
1689
+ .command('list', { isDefault: true })
1690
+ .description('Show the checks.')
1691
+ .action(run(async ({ client, out, project }) => {
1692
+ const result = await client.action('get_checks', { project });
1693
+ out.result(result, () => checksRender(result));
1694
+ }));
1695
+ checks
1696
+ .command('add <title...>')
1697
+ .description('Add a custom check: the judge looks for it in every conversation from now on.')
1698
+ .addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']).makeOptionMandatory())
1699
+ .option('--description <text>', 'what counts as this problem')
1700
+ .action(run(async ({ client, out, project, opts }, words) => {
1701
+ const result = await client.action('create_custom_check', {
1702
+ project,
1703
+ title: words.join(' ').trim(),
1704
+ severity: opts.severity,
1705
+ description: opts.description,
1706
+ });
1707
+ out.result(result, () => `Added custom check ${result.id} ${result.title} (${result.severity}).\n` +
1708
+ 'Move earlier problems into it: qualiloop problems sort');
1709
+ }));
1710
+ checks
1711
+ .command('set')
1712
+ .description('Change the token limit per turn and the unanswered messages check; only what you give changes.')
1713
+ .option('--token-limit <on|off>', 'turn the token limit per turn on or off')
1714
+ .option('--max-tokens <n>', 'the most tokens one turn may use')
1715
+ .option('--unanswered <on|off>', 'report a conversation whose last message got no reply')
1716
+ .action(run(async ({ client, out, project, opts }) => {
1717
+ const result = await client.action('set_checks', {
1718
+ project,
1719
+ token_budget_enabled: onOff(opts.tokenLimit, '--token-limit'),
1720
+ max_tokens_per_turn: opts.maxTokens === undefined ? undefined : intArg(String(opts.maxTokens)),
1721
+ no_answer_enabled: onOff(opts.unanswered, '--unanswered'),
1722
+ });
1723
+ out.result(result, () => checksRender(result));
1724
+ }));
1725
+ checks
1726
+ .command('import-elevenlabs')
1727
+ .description("Add a custom check for each success criterion of the project's ElevenLabs agent. Names already taken are left as they are.")
1728
+ .action(run(async ({ client, out, project }) => {
1729
+ const result = await client.action('elevenlabs_import_criteria', { project });
1730
+ out.result(result, () => [
1731
+ result.added.length ? `Added: ${result.added.join(', ')}` : 'No new checks.',
1732
+ ...(result.existing.length ? [`Already there: ${result.existing.join(', ')}`] : []),
1733
+ ].join('\n'));
1734
+ }));
910
1735
  problems
911
1736
  .command('dismiss <id>')
912
1737
  .description('Mark a problem a false alarm: it stops counting but stays on its conversation.')
@@ -961,6 +1786,52 @@ rules
961
1786
  });
962
1787
  out.result(result, () => `Removed: ${result.removed}\n\n${rulesRender(result)}`);
963
1788
  }));
1789
+ program
1790
+ .command('conversations')
1791
+ .description('Tested conversations across runs, newest first, clean ones included, as the Conversations view lists them.')
1792
+ .option('--run <n>', 'only the conversations of this run')
1793
+ .option('--batch <id>', 'only the conversations of one launch')
1794
+ .addOption(new Option('--verdict <verdict>', 'only conversations with this verdict').choices([
1795
+ 'major',
1796
+ 'minor',
1797
+ 'clean',
1798
+ 'not_reviewed',
1799
+ 'pending',
1800
+ ]))
1801
+ .addOption(testModeOption())
1802
+ .addOption(fromOption())
1803
+ .addOption(toOption())
1804
+ .option('--search <text>', 'only conversations whose test name or id contains this')
1805
+ .addOption(limitOption('conversations', '50', 200))
1806
+ .addOption(offsetOption())
1807
+ .action(run(async ({ client, out, project, opts }) => {
1808
+ const offset = offsetOf(opts);
1809
+ const result = await client.action('list_conversations', {
1810
+ project,
1811
+ run_number: opts.run ? intArg(String(opts.run)) : undefined,
1812
+ batch: opts.batch,
1813
+ verdict: opts.verdict,
1814
+ mode: opts.mode,
1815
+ from: opts.from,
1816
+ to: opts.to,
1817
+ search: opts.search,
1818
+ limit: limitOf(opts, 200),
1819
+ offset,
1820
+ });
1821
+ out.result(result, () => paged(table(result.conversations, [
1822
+ ['conversation', 'Conversation', 36],
1823
+ ['run_number', 'Run'],
1824
+ ['test', 'Test', 36],
1825
+ ['verdict', 'Verdict'],
1826
+ ['major_problems', 'Major'],
1827
+ ['minor_problems', 'Minor'],
1828
+ ['turns', 'Turns'],
1829
+ ]), result.conversations.length, result.total, offset, 'No conversations.') + (result.conversations.length ? '\n\nRead one: qualiloop conversation <id>' : ''));
1830
+ }));
1831
+ const sourceLines = (problem) => (problem.evidence ?? [])
1832
+ .map((item) => item.knowledge_source)
1833
+ .filter((source) => Boolean(source))
1834
+ .map((source) => ` Quotes ${source.name} (source ${source.id}, version ${source.version_number ?? '-'}${source.current ? '' : ', no longer in force'})`);
964
1835
  const traceLines = (trace) => {
965
1836
  if (!trace)
966
1837
  return [];
@@ -987,9 +1858,181 @@ program
987
1858
  ]),
988
1859
  '',
989
1860
  `Verdict: ${result.verdict?.status ?? 'not judged'}`,
990
- ...result.problems.map((problem) => `\n[${problem.severity}] ${problem.title}\n ${problem.explanation}${problem.suggested_fix ? `\n Fix: ${problem.suggested_fix}` : ''}`),
1861
+ ...result.problems.map((problem) => [
1862
+ `\n[${problem.severity}] ${problem.title}\n ${problem.explanation}${problem.suggested_fix ? `\n Fix: ${problem.suggested_fix}` : ''}`,
1863
+ ...sourceLines(problem),
1864
+ ].join('\n')),
1865
+ ].join('\n'));
1866
+ }));
1867
+ const reportPeriod = (row) => row.period_start
1868
+ ? `${String(row.period_start).slice(0, 10)} to ${String(row.period_end ?? '').slice(0, 10) || 'now'}`
1869
+ : `${row.runs_selected ?? 0} run(s)`;
1870
+ const reports = program.command('reports').description('Reports: frozen snapshots of test results to read and share.');
1871
+ reports
1872
+ .command('list', { isDefault: true })
1873
+ .description('The project\'s reports, newest first.')
1874
+ .addOption(limitOption('reports', '20', 200))
1875
+ .action(run(async ({ client, out, project, opts }) => {
1876
+ const result = await client.action('list_reports', {
1877
+ project,
1878
+ limit: limitOf(opts, 200),
1879
+ });
1880
+ out.result(result, () => listed(table(result.reports.map((row) => ({ ...row, covers: reportPeriod(row) })), [
1881
+ ['id', 'ID'],
1882
+ ['title', 'Title', 45],
1883
+ ['status', 'Status'],
1884
+ ['covers', 'Covers', 26],
1885
+ ['modes', 'Modes', 24],
1886
+ ['shared', 'Shared'],
1887
+ ]), result.reports.length, result.total, 'No reports yet. Make one with: qualiloop reports create'));
1888
+ }));
1889
+ reports
1890
+ .command('show <id>')
1891
+ .description('One report: its verdict, numbers and issues with their fixes.')
1892
+ .action(run(async ({ client, out, project }, id) => {
1893
+ const result = await client.action('get_report', {
1894
+ project,
1895
+ report: intArg(id),
1896
+ });
1897
+ out.result(result, () => [
1898
+ fields([
1899
+ ['Report', `${result.id} ${result.title}`],
1900
+ ['Status', result.status],
1901
+ ['Covers', reportPeriod(result)],
1902
+ ['Modes', result.modes],
1903
+ ['Shared', result.shared ? `yes, until ${result.share_expires_at ?? 'revoked'}` : 'no'],
1904
+ ['Verdict', result.decision?.title],
1905
+ ['Pass rate', result.numbers?.pass_rate === undefined ? undefined : `${result.numbers.pass_rate}%`],
1906
+ ['Error', result.error],
1907
+ ['Link', result.url],
1908
+ ]),
1909
+ ...(result.next_step ? ['', String(result.next_step)] : []),
1910
+ ...(result.issues?.length
1911
+ ? [
1912
+ '',
1913
+ table(result.issues, [
1914
+ ['ref', 'Ref'],
1915
+ ['title', 'Issue', 50],
1916
+ ['major_problems', 'Major'],
1917
+ ['minor_problems', 'Minor'],
1918
+ ['fix', 'Fix', 60],
1919
+ ]),
1920
+ ]
1921
+ : []),
1922
+ ].join('\n'));
1923
+ }));
1924
+ reports
1925
+ .command('create')
1926
+ .description('Make a report of chosen runs, the last few days or a date range. Builds in about a minute.')
1927
+ .option('--title <title>', 'the report\'s title')
1928
+ .option('--runs <numbers...>', 'run numbers to report on')
1929
+ .option('--days <n>', 'the runs of the last this many days (default 30 without --runs or --from)')
1930
+ .option('--from <date>', 'the runs from this day, YYYY-MM-DD (UTC)')
1931
+ .option('--to <date>', 'with --from, the last day to include, YYYY-MM-DD (UTC); default now')
1932
+ .addOption(new Option('--mode <modes...>', 'test modes to include (default all)').choices(['regular', 'red_team', 'bias']))
1933
+ .option('--exclude-minor', 'leave minor problems out')
1934
+ .option('--all-conversations', 'list every conversation, not only those with problems')
1935
+ .option('--language <language>', 'the language to write it in', 'English')
1936
+ .action(run(async ({ client, out, project, opts }) => {
1937
+ const result = await client.action('create_report', {
1938
+ project,
1939
+ title: opts.title,
1940
+ runs: (opts.runs ?? []).map(intArg),
1941
+ days: opts.days === undefined ? undefined : intArg(String(opts.days)),
1942
+ from_date: opts.from,
1943
+ to_date: opts.to,
1944
+ modes: opts.mode,
1945
+ exclude_minor: Boolean(opts.excludeMinor),
1946
+ include_all_conversations: Boolean(opts.allConversations),
1947
+ language: opts.language,
1948
+ });
1949
+ out.result(result, () => `Started report ${result.id} ${result.title}.\n${result.next_step ?? ''}`.trim());
1950
+ }));
1951
+ reports
1952
+ .command('rebuild <id>')
1953
+ .alias('update')
1954
+ .description('Build a report again from the results as they are now, with its period, runs and options. Keeps its id and share link.')
1955
+ .action(run(async ({ client, out, project }, id) => {
1956
+ const result = await client.action('rebuild_report', { project, report: intArg(id) });
1957
+ out.result(result, () => `Updating report ${result.id} ${result.title}.\n${result.next_step ?? ''}`.trim());
1958
+ }));
1959
+ reports
1960
+ .command('share <id>')
1961
+ .description('Make a public link to a ready report: anyone with the link and its password can read it without signing in. Replaces an earlier link.')
1962
+ .addOption(new Option('--expires <days>', 'days until the link stops working').choices(['7', '30', '90', '365', 'never']).default('30'))
1963
+ .option('--password <password>', 'the password the link asks for, 8 to 128 characters; it stays in your shell history (default: a strong one is made)')
1964
+ .action(run(async ({ client, out, project, opts }, id) => {
1965
+ const result = await client.action('share_report', {
1966
+ project,
1967
+ report: intArg(id),
1968
+ expires_in_days: opts.expires === 'never' ? null : intArg(String(opts.expires)),
1969
+ password: opts.password,
1970
+ });
1971
+ out.result(result, () => [
1972
+ fields([
1973
+ ['Link', result.share_url],
1974
+ ['Password', result.password],
1975
+ ['Expires', result.expires_at ?? 'never'],
1976
+ ]),
1977
+ '',
1978
+ 'Shown only this once: QualiLoop keeps only a hash of the link and the password.',
1979
+ ...(result.replaced_earlier_link ? ['The earlier link and password no longer work.'] : []),
991
1980
  ].join('\n'));
992
1981
  }));
1982
+ reports
1983
+ .command('unshare <id>')
1984
+ .description('Revoke a report\'s public link: the link and its password stop working at once.')
1985
+ .action(run(async ({ client, out, project }, id) => {
1986
+ const result = await client.action('unshare_report', { project, report: intArg(id) });
1987
+ out.result(result, () => result.was_shared
1988
+ ? `Report ${result.id} ${result.title} is no longer shared.`
1989
+ : `Report ${result.id} ${result.title} was not shared.`);
1990
+ }));
1991
+ reports
1992
+ .command('delete <id>')
1993
+ .description('Delete a report. Its public link stops working; the runs and problems stay.')
1994
+ .option('--yes', 'delete without asking')
1995
+ .action(run(async ({ client, out, project, opts }, id) => {
1996
+ const reportId = intArg(id);
1997
+ if (!opts.yes) {
1998
+ const found = await client.action('get_report', { project, report: reportId });
1999
+ if (!(await confirm(`Delete report ${found.id} ${found.title}?`))) {
2000
+ out.result({ deleted: false, id: reportId }, () => 'Not deleted.');
2001
+ return EXIT.ok;
2002
+ }
2003
+ }
2004
+ const result = await client.action('delete_report', { project, report: reportId });
2005
+ out.result(result, () => `Deleted report ${result.id} ${result.title}.`);
2006
+ }));
2007
+ const DOWNLOADS = {
2008
+ pdf: { path: 'pdf', extension: 'pdf' },
2009
+ 'summary-csv': { path: 'summary-csv', extension: 'csv' },
2010
+ csv: { path: 'csv', extension: 'csv' },
2011
+ };
2012
+ reports
2013
+ .command('download <id>')
2014
+ .description('Save a ready report as the executive PDF, the test summary CSV, or the CSV of all conversations.')
2015
+ .addOption(new Option('--format <format>', 'pdf, summary-csv (one row per test) or csv (every conversation)')
2016
+ .choices(Object.keys(DOWNLOADS))
2017
+ .default('pdf'))
2018
+ .option('--out <file>', 'where to save it; - for stdout (default: the name QualiLoop gives it, here)')
2019
+ .action(run(async ({ client, out, project, opts }, id) => {
2020
+ const reportId = intArg(id);
2021
+ const found = await client.action('get_report', { project, report: reportId });
2022
+ if (found.status !== 'ready') {
2023
+ throw new ApiError(`Report ${found.id} is ${found.status}, not ready. ${found.next_step ?? ''}`.trim(), 409, EXIT.usage);
2024
+ }
2025
+ const format = DOWNLOADS[String(opts.format)];
2026
+ const file = await client.download(`/v1/reports/${found.id}/${format.path}`);
2027
+ const target = opts.out;
2028
+ if (target === '-') {
2029
+ process.stdout.write(file.data);
2030
+ return;
2031
+ }
2032
+ const where = resolvePath(target || basename(file.filename || `qualiloop-report-${found.id}.${format.extension}`));
2033
+ writeFileSync(where, file.data);
2034
+ out.result({ id: found.id, format: opts.format, file: where, bytes: file.data.length }, () => `Saved ${where}`);
2035
+ }));
993
2036
  const gateRunRender = (result) => [
994
2037
  fields([
995
2038
  ['Gate run', `#${result.gate_run_number ?? result.org_number} ${result.gate ?? result.release_gate_name ?? ''}`],
@@ -1096,13 +2139,261 @@ gate
1096
2139
  const result = await client.action('cancel_gate_run', { gate_run_number: intArg(number) });
1097
2140
  out.result(result, () => `Cancelled gate run #${result.gate_run_number}: CI treats it as not passed.`);
1098
2141
  }));
2142
+ const packRefs = (values, project, key) => (values ?? []).map((value) => {
2143
+ const at = value.lastIndexOf(':');
2144
+ const owner = at >= 0 ? value.slice(0, at) : project;
2145
+ return { project: owner === undefined ? undefined : idOrName(owner), [key]: intArg(at >= 0 ? value.slice(at + 1) : value) };
2146
+ });
2147
+ const gateRender = (gateRow) => fields([
2148
+ ['Gate', `${gateRow.id} ${gateRow.name}`],
2149
+ ['Pack', gateRow.pack],
2150
+ ['Pass %', gateRow.required_pass_percentage],
2151
+ ['CI time limit', `${gateRow.ci_timeout_minutes} minutes`],
2152
+ ['Active', gateRow.active],
2153
+ ]);
2154
+ const packRender = (pack) => [
2155
+ fields([
2156
+ ['Pack', `${pack.id} ${pack.name}`],
2157
+ ['Description', pack.description],
2158
+ ['Gates', Array.isArray(pack.gates) && pack.gates.length ? pack.gates.join(', ') : 'none'],
2159
+ ]),
2160
+ '',
2161
+ table(pack.tests, [
2162
+ ['kind', 'Kind'],
2163
+ ['id', 'ID'],
2164
+ ['name', 'Test', 45],
2165
+ ['project_number', 'Project'],
2166
+ ]),
2167
+ ].join('\n');
2168
+ gate
2169
+ .command('create <name>')
2170
+ .description('Create a release gate for a pack of tests.')
2171
+ .requiredOption('--pack <pack>', 'the pack it runs (id or name, see qualiloop gate packs)')
2172
+ .option('--pass-percent <n>', 'the share of tests that must pass', '95')
2173
+ .option('--timeout <minutes>', 'how long CI waits for a run before it fails', '60')
2174
+ .option('--off', 'create it turned off: CI calls are refused')
2175
+ .action(run(async ({ client, out, opts }, name) => {
2176
+ const result = await client.action('create_release_gate', {
2177
+ name,
2178
+ pack: idOrName(String(opts.pack)),
2179
+ required_pass_percentage: intArg(String(opts.passPercent)),
2180
+ ci_timeout_minutes: intArg(String(opts.timeout)),
2181
+ active: !opts.off,
2182
+ });
2183
+ out.result(result, () => `${gateRender(result.gate)}\n\n${result.next_step ?? ''}`.trimEnd());
2184
+ }));
2185
+ gate
2186
+ .command('edit <gate>')
2187
+ .description('Change a release gate; only what you give changes.')
2188
+ .option('--name <name>', 'a new name')
2189
+ .option('--pack <pack>', 'run this pack instead (id or name)')
2190
+ .option('--pass-percent <n>', 'the share of tests that must pass')
2191
+ .option('--timeout <minutes>', 'how long CI waits for a run before it fails')
2192
+ .addOption(new Option('--on', 'turn it on').conflicts('off'))
2193
+ .option('--off', 'turn it off: CI calls are refused')
2194
+ .action(run(async ({ client, out, opts }, gateRef) => {
2195
+ const result = await client.action('update_release_gate', {
2196
+ gate: idOrName(gateRef),
2197
+ name: opts.name,
2198
+ pack: opts.pack === undefined ? undefined : idOrName(String(opts.pack)),
2199
+ required_pass_percentage: opts.passPercent === undefined ? undefined : intArg(String(opts.passPercent)),
2200
+ ci_timeout_minutes: opts.timeout === undefined ? undefined : intArg(String(opts.timeout)),
2201
+ active: opts.on ? true : opts.off ? false : undefined,
2202
+ });
2203
+ out.result(result, () => `${result.changes.join('\n')}\n\n${gateRender(result.gate)}`);
2204
+ }));
2205
+ gate
2206
+ .command('delete <gate>')
2207
+ .description("Delete a release gate and its deploy tokens. Its pack and its past runs stay.")
2208
+ .option('--yes', 'delete without asking')
2209
+ .action(run(async ({ client, out, opts }, gateRef) => {
2210
+ if (!opts.yes) {
2211
+ if (!(await confirm(`Delete release gate ${gateRef}? CI jobs that call it will be refused.`))) {
2212
+ out.result({ deleted: false, gate: gateRef }, () => 'Not deleted.');
2213
+ return EXIT.ok;
2214
+ }
2215
+ }
2216
+ const result = await client.action('delete_release_gate', { gate: idOrName(gateRef) });
2217
+ out.result(result, () => `Deleted release gate ${result.id} ${result.name}. Its ${result.runs_kept} past runs stay.`);
2218
+ }));
2219
+ gate
2220
+ .command('history <pack>')
2221
+ .description("A pack's gate runs, newest first, with each test's verdict in each run.")
2222
+ .addOption(limitOption('gate runs', '10', 100))
2223
+ .action(run(async ({ client, out, opts }, packRef) => {
2224
+ const result = await client.action('get_pack_history', {
2225
+ pack: idOrName(packRef),
2226
+ limit: limitOf(opts, 100),
2227
+ });
2228
+ out.result(result, () => {
2229
+ if (!result.gate_runs.length)
2230
+ return `Pack ${result.pack} has no gate runs yet.`;
2231
+ const runs = result.gate_runs;
2232
+ const names = [];
2233
+ for (const gateRun of runs)
2234
+ for (const item of gateRun.tests ?? []) {
2235
+ const label = `${item.test ?? '(deleted)'}${item.project_number ? ` (#${item.project_number})` : ''}`;
2236
+ if (!names.includes(label))
2237
+ names.push(label);
2238
+ }
2239
+ const rows = names.map((label) => {
2240
+ const row = { test: label };
2241
+ for (const gateRun of runs) {
2242
+ const item = (gateRun.tests ?? []).find((test) => `${test.test ?? '(deleted)'}${test.project_number ? ` (#${test.project_number})` : ''}` === label);
2243
+ row[`run${gateRun.gate_run_number}`] = item ? (item.verdict ?? item.status) : '';
2244
+ }
2245
+ return row;
2246
+ });
2247
+ const decisions = { test: 'Decision' };
2248
+ for (const gateRun of runs)
2249
+ decisions[`run${gateRun.gate_run_number}`] = gateRun.decision ?? gateRun.status;
2250
+ const columns = [
2251
+ ['test', 'Test', 40],
2252
+ ...runs.map((gateRun) => [`run${gateRun.gate_run_number}`, `#${gateRun.gate_run_number}`]),
2253
+ ];
2254
+ return listed(table([...rows, decisions], columns), runs.length, result.total, '');
2255
+ });
2256
+ }));
2257
+ gate
2258
+ .command('ci-snippet <gate>')
2259
+ .description("Print the shell script that runs a gate from CI. It reads the gate's deploy token from $QUALILOOP_RELEASE_GATE_TOKEN; create the token in the app.")
2260
+ .addOption(new Option('--format <format>', 'shell script, GitHub Actions step, or the qualiloop CLI').choices(['shell', 'github', 'cli']).default('shell'))
2261
+ .action(run(async ({ client, out, opts }, gateRef) => {
2262
+ const { gates } = await client.action('list_release_gates');
2263
+ const wanted = gateRef.trim().toLowerCase();
2264
+ const exact = gates.filter((row) => String(row.id) === gateRef.trim() || String(row.name).toLowerCase() === wanted);
2265
+ const found = exact.length ? exact : gates.filter((row) => String(row.name).toLowerCase().includes(wanted));
2266
+ if (found.length !== 1) {
2267
+ const names = found.map((row) => `${row.id} ${row.name}`).join(', ');
2268
+ throw new ApiError(found.length ? `'${gateRef}' matches several gates: ${names}. Use the id.` : `No release gate '${gateRef}'. \`qualiloop gates\` lists them.`, found.length ? 400 : 404, found.length ? EXIT.usage : EXIT.notFound);
2269
+ }
2270
+ const chosen = found[0];
2271
+ const script = gateCiScript(client.url, Number(chosen.id));
2272
+ const format = String(opts.format);
2273
+ const text = format === 'github'
2274
+ ? gateGithubStep(script)
2275
+ : format === 'cli'
2276
+ ? gateCliStep(client.url)
2277
+ : script;
2278
+ out.result({ gate: chosen.name, id: chosen.id, format, script: text, ci_timeout_minutes: chosen.ci_timeout_minutes }, () => text);
2279
+ }));
2280
+ const packCommand = gate.command('pack').alias('packs').description('Release gate packs: the set of tests a gate runs.');
2281
+ packCommand
2282
+ .command('list', { isDefault: true })
2283
+ .description("List the organization's packs and their tests.")
2284
+ .action(run(async ({ client, out }) => {
2285
+ const result = await client.action('list_gate_packs');
2286
+ out.result(result, () => result.packs.length
2287
+ ? table(result.packs.map((pack) => ({ ...pack, gates: Array.isArray(pack.gates) ? pack.gates.join(', ') : '' })), [
2288
+ ['id', 'ID'],
2289
+ ['name', 'Pack', 40],
2290
+ ['test_count', 'Tests'],
2291
+ ['gates', 'Gates', 40],
2292
+ ])
2293
+ : 'No packs yet. Make one: qualiloop gate pack create <name> --test <project>:<id>');
2294
+ }));
2295
+ packCommand
2296
+ .command('create <name>')
2297
+ .description('Create a pack from saved tests and schedules of any project.')
2298
+ .option('--test <project:id>', 'a saved test, as <project>:<test id>, or a bare id in the -p project (repeat)', repeat)
2299
+ .option('--schedule <project:id>', 'a schedule, as <project>:<schedule id> (repeat)', repeat)
2300
+ .option('--description <text>', 'what the pack is for')
2301
+ .action(run(async ({ client, out, project, opts }, name) => {
2302
+ const result = await client.action('create_gate_pack', {
2303
+ name,
2304
+ description: opts.description,
2305
+ tests: packRefs(opts.test, project, 'test'),
2306
+ schedules: packRefs(opts.schedule, project, 'schedule'),
2307
+ });
2308
+ out.result(result, () => `${packRender(result.pack)}\n\nMake a gate for it: qualiloop gate create <name> --pack ${result.pack.id}`);
2309
+ }));
2310
+ packCommand
2311
+ .command('edit <pack>')
2312
+ .description('Change a pack. --test and --schedule each replace that kind of test as a whole; leave one out to keep it.')
2313
+ .option('--name <name>', 'a new name')
2314
+ .option('--description <text>', 'a new description')
2315
+ .option('--test <project:id>', 'a saved test, as <project>:<test id> (repeat)', repeat)
2316
+ .option('--schedule <project:id>', 'a schedule, as <project>:<schedule id> (repeat)', repeat)
2317
+ .option('--no-tests', 'remove every saved test')
2318
+ .option('--no-schedules', 'remove every schedule')
2319
+ .action(run(async ({ client, out, project, opts }, packRef) => {
2320
+ const listOf = (given, keep, key) => keep === false ? [] : given === undefined ? undefined : packRefs(given, project, key);
2321
+ const result = await client.action('update_gate_pack', {
2322
+ pack: idOrName(packRef),
2323
+ name: opts.name,
2324
+ description: opts.description,
2325
+ tests: listOf(opts.test, opts.tests, 'test'),
2326
+ schedules: listOf(opts.schedule, opts.schedules, 'schedule'),
2327
+ });
2328
+ out.result(result, () => `${result.changes.join('\n')}\n\n${packRender(result.pack)}`);
2329
+ }));
2330
+ packCommand
2331
+ .command('delete <pack>')
2332
+ .description('Delete a pack. Its tests and past gate runs stay. A pack a gate still runs is not deleted.')
2333
+ .option('--yes', 'delete without asking')
2334
+ .action(run(async ({ client, out, opts }, packRef) => {
2335
+ if (!opts.yes) {
2336
+ if (!(await confirm(`Delete pack ${packRef}?`))) {
2337
+ out.result({ deleted: false, pack: packRef }, () => 'Not deleted.');
2338
+ return EXIT.ok;
2339
+ }
2340
+ }
2341
+ const result = await client.action('delete_gate_pack', { pack: idOrName(packRef) });
2342
+ out.result(result, () => `Deleted pack ${result.id} ${result.name}.`);
2343
+ }));
2344
+ const gateCiScript = (url, gateId) => {
2345
+ const api = `${url.replace(/\/+$/, '')}/v1`;
2346
+ return `RESPONSE=$(curl -s -X POST "${api}/release-gates/hooks/${gateId}/runs" \\
2347
+ -H "Authorization: Bearer $QUALILOOP_RELEASE_GATE_TOKEN" \\
2348
+ -H "Content-Type: application/json" \\
2349
+ -d '{"name":"Deploy run","external_ref":"'"$GIT_SHA"'"}')
2350
+ RUN_ID=$(echo "$RESPONSE" | jq -r '.id // empty')
2351
+ if [ -z "$RUN_ID" ]; then
2352
+ echo "QualiLoop did not start the release gate: $RESPONSE" >&2
2353
+ exit 1
2354
+ fi
2355
+ LIMIT_MINUTES=$(echo "$RESPONSE" | jq -r '.ci_timeout_minutes // 60')
2356
+ DEADLINE=$((SECONDS + LIMIT_MINUTES * 60))
2357
+
2358
+ while true; do
2359
+ RESULT=$(curl -s "${api}/release-gates/hooks/runs/$RUN_ID" \\
2360
+ -H "Authorization: Bearer $QUALILOOP_RELEASE_GATE_TOKEN")
2361
+ STATUS=$(echo "$RESULT" | jq -r '.status')
2362
+ DECISION=$(echo "$RESULT" | jq -r '.decision // empty')
2363
+ if [ "$STATUS" = "completed" ]; then
2364
+ PASSED=$(echo "$RESULT" | jq -r '.pass_percentage')
2365
+ NEEDED=$(echo "$RESULT" | jq -r '.required_pass_percentage')
2366
+ echo "QualiLoop release gate: $DECISION, $PASSED% passed, $NEEDED% needed."
2367
+ [ "$DECISION" = "pass" ] && exit 0 || exit 1
2368
+ fi
2369
+ if [ "$SECONDS" -ge "$DEADLINE" ]; then
2370
+ echo "QualiLoop release gate run $RUN_ID did not finish within $LIMIT_MINUTES minutes. Failing the deploy." >&2
2371
+ exit 1
2372
+ fi
2373
+ sleep 10
2374
+ done`;
2375
+ };
2376
+ const gateGithubStep = (script) => `- name: Run QualiLoop release gate
2377
+ env:
2378
+ QUALILOOP_RELEASE_GATE_TOKEN: \${{ secrets.QUALILOOP_RELEASE_GATE_TOKEN }}
2379
+ GIT_SHA: \${{ github.sha }}
2380
+ run: |
2381
+ ${script
2382
+ .split('\n')
2383
+ .map((line) => (line ? ` ${line}` : ''))
2384
+ .join('\n')}`;
2385
+ const gateCliStep = (url) => `- name: Run QualiLoop release gate
2386
+ run: npx qualiloop gate run --wait --ref "$GITHUB_SHA"
2387
+ env:
2388
+ QUALILOOP_URL: ${url.replace(/\/+$/, '')}
2389
+ QUALILOOP_GATE_KEY: \${{ secrets.QUALILOOP_RELEASE_GATE_TOKEN }}`;
1099
2390
  const generate = program
1100
2391
  .command('generate')
1101
2392
  .description('Have QualiLoop write tests from one prompt.')
1102
2393
  .argument('[prompt...]', 'what to test, in plain words')
1103
2394
  .option('--suite <suite>', 'add the tests to this suite (id or name)')
1104
2395
  .option('--new-suite <name>', 'make a new suite for them')
1105
- .option('--max <n>', 'most tests to write')
2396
+ .option('--max <n>', 'most tests to write, up to 300')
1106
2397
  .option('--wait', 'wait until the tests are saved')
1107
2398
  .option('--timeout <minutes>', 'most minutes to wait', '15')
1108
2399
  .action(run(async ({ client, out, project, opts }, words = []) => {
@@ -1155,6 +2446,49 @@ generate
1155
2446
  ? `Generation ${result.id} had already finished (${result.status}); nothing to cancel.`
1156
2447
  : `Cancelling generation ${result.id}. It stops at its next step and saves nothing: qualiloop generate status ${result.id}`);
1157
2448
  }));
2449
+ generate
2450
+ .command('list')
2451
+ .description('The latest generations of the project, newest first.')
2452
+ .option('--everyone', "everyone's generations, not only yours")
2453
+ .addOption(limitOption('generations', '10', 50))
2454
+ .action(run(async ({ client, out, project, opts }) => {
2455
+ const result = await client.action('list_generations', {
2456
+ project,
2457
+ mine: opts.everyone ? false : undefined,
2458
+ limit: limitOf(opts, 50),
2459
+ });
2460
+ out.result(result, () => table(result.generations, [
2461
+ ['id', 'Id'],
2462
+ ['status', 'Status'],
2463
+ ['saved_tests', 'Saved'],
2464
+ ['prompt', 'Prompt', 60],
2465
+ ['created_at', 'Started'],
2466
+ ]) || 'No generations yet.');
2467
+ }));
2468
+ program
2469
+ .command('export [project]')
2470
+ .description("Export the project's corrected pairs (turns with a saved correction) to a file, in one of the Export page's formats.")
2471
+ .addOption(new Option('--format <format>', 'the file format')
2472
+ .choices(EXPORT_FORMATS.map((item) => item.id))
2473
+ .default('openai-chat-jsonl'))
2474
+ .option('--from <date>', 'first day, YYYY-MM-DD (default 30 days ago)')
2475
+ .option('--to <date>', 'last day, YYYY-MM-DD (default today)')
2476
+ .option('--out <file>', 'the file to write (default qualiloop-<project>-<format>-<from>-to-<to>.<ext>)')
2477
+ .action(run(async ({ client, out, project, opts }, given) => {
2478
+ const format = exportFormat(String(opts.format));
2479
+ const from = dateOr(opts.from, 30);
2480
+ const to = dateOr(opts.to, 0);
2481
+ if (from > to)
2482
+ throw new ApiError('--from must be on or before --to.', 400, EXIT.usage);
2483
+ const found = await fetchCorrectedPairs(client, given ?? project, from, to);
2484
+ if (!found.items.length) {
2485
+ out.result({ project: found.number, written: false, items: 0 }, () => `No corrected pairs in project #${found.number} ${found.name} from ${from} to ${to}.`);
2486
+ return EXIT.ok;
2487
+ }
2488
+ const file = opts.out ?? `qualiloop-${found.number}-${format.id}-${from}-to-${to}.${format.extension}`;
2489
+ writeFileSync(file, format.render(found.items), 'utf8');
2490
+ out.result({ project: found.number, written: true, file, format: format.id, items: found.items.length }, () => `Wrote ${found.items.length} corrected pairs to ${file}.`);
2491
+ }));
1158
2492
  const connectCommand = program
1159
2493
  .command('connect')
1160
2494
  .argument('[project]', 'the project: its number or name')
@@ -1239,7 +2573,9 @@ connectCommand
1239
2573
  ['Project', `#${result.project.number} ${result.project.name}`],
1240
2574
  ['Traces address', result.tracing.traces_url],
1241
2575
  ['Project key', `${result.tracing.project_key} (write it with: qualiloop connect env)`],
1242
- ['Saved endpoint', result.target ? result.target.base_url : 'none yet'],
2576
+ ['Saved connection', connect.targetAddress(result.target)],
2577
+ ...(result.target ? [['Agent name', result.target.name]] : []),
2578
+ ['Scoring with traces', !result.project.traces_disabled],
1243
2579
  ['Live traffic', result.project.live_data_enabled],
1244
2580
  ['QualiLoop calls from', result.outbound_addresses],
1245
2581
  ]),
@@ -1289,27 +2625,48 @@ connectCommand
1289
2625
  }));
1290
2626
  connectCommand
1291
2627
  .command('rename')
1292
- .description("Rename the project, describe it, or name its environment.")
2628
+ .description("Rename the project, describe it, name its environment, or name the agent on the saved endpoint.")
1293
2629
  .option('--name <name>')
1294
2630
  .option('--description <text>')
1295
2631
  .addOption(new Option('--environment <env>').choices(['local', 'dev', 'staging', 'prod']))
2632
+ .option('--agent-name <name>', "the agent's name on the saved endpoint, as the connection settings show it")
1296
2633
  .action(run(async (ctx) => {
1297
- const result = await connect.updateProject(ctx.client, { project: connectProject(ctx) }, {
2634
+ const options = { project: connectProject(ctx) };
2635
+ const project = {
1298
2636
  name: ctx.opts.name,
1299
2637
  description: ctx.opts.description,
1300
2638
  environment: ctx.opts.environment,
1301
- });
1302
- ctx.out.result(result, () => actedOn(result, 'Project updated.'));
2639
+ };
2640
+ const agentName = ctx.opts.agentName;
2641
+ const projectGiven = Object.values(project).some((value) => value !== undefined);
2642
+ if (!projectGiven && agentName === undefined) {
2643
+ throw new ApiError('Give --name, --description, --environment or --agent-name.', 400, EXIT.usage);
2644
+ }
2645
+ const updated = projectGiven ? await connect.updateProject(ctx.client, options, project) : null;
2646
+ const named = agentName !== undefined ? await connect.updateTarget(ctx.client, options, { name: agentName }) : null;
2647
+ const result = {
2648
+ ...(updated ?? {}),
2649
+ ...(named ? { project: named.project, target: named.target } : {}),
2650
+ };
2651
+ const lines = [
2652
+ ...(updated ? ['Project updated.'] : []),
2653
+ ...(named ? [`Agent name: ${String(named.target?.name ?? agentName)}.`] : []),
2654
+ ];
2655
+ ctx.out.result(result, () => actedOn(result, lines.join('\n')));
1303
2656
  }));
1304
2657
  connectCommand
1305
2658
  .command('target')
1306
- .description('Save the endpoint QualiLoop calls, from a JSON file (or - for stdin).')
2659
+ .description('Save how QualiLoop reaches the agent, from a JSON file (or - for stdin): an endpoint, or mode dify, async_session, browser, elevenlabs or gohighlevel with its block. Secrets come from variables: --auth-header, or <field>_env in a block (elevenlabs.api_key_env, gohighlevel.private_token_env, browser.browserbase_context_id_env, observability.secret_key_env).')
1307
2660
  .requiredOption('--file <path>', 'the body of PUT /v1/setup/target')
2661
+ .addOption(new Option('--mode <mode>', 'the connection mode; wins over the one in the file').choices([...connect.MODES]))
1308
2662
  .option('--auth-header <Name=VARIABLE>', 'send header Name with the value of VARIABLE, read from the environment or --env-file')
1309
2663
  .option('--auth-prefix <prefix>', 'put this before the value, such as "Bearer "')
1310
- .option('--env-file <path>', 'where to read VARIABLE when the environment lacks it', '.env')
2664
+ .option('--env-file <path>', 'where to read a VARIABLE when the environment lacks it', '.env')
1311
2665
  .action(run(async (ctx) => {
1312
2666
  const body = connect.readJson(String(ctx.opts.file));
2667
+ if (ctx.opts.mode)
2668
+ body.mode = ctx.opts.mode;
2669
+ body.env_file = String(ctx.opts.envFile);
1313
2670
  if (ctx.opts.authHeader) {
1314
2671
  const [name, variable] = String(ctx.opts.authHeader).split('=');
1315
2672
  if (!name || !variable)
@@ -1317,10 +2674,33 @@ connectCommand
1317
2674
  body.auth_header_name = name;
1318
2675
  body.auth_header_env = variable;
1319
2676
  body.auth_header_prefix = ctx.opts.authPrefix;
1320
- body.env_file = String(ctx.opts.envFile);
1321
2677
  }
1322
2678
  const result = await connect.saveTarget(ctx.client, { project: connectProject(ctx) }, body);
1323
- ctx.out.result(result, () => actedOn(result, `Saved the endpoint ${String(result.target?.base_url ?? '')}.`));
2679
+ ctx.out.result(result, () => actedOn(result, `Saved the connection: ${connect.targetAddress(result.target)}.`));
2680
+ }));
2681
+ connectCommand
2682
+ .command('limits')
2683
+ .description('Set how hard QualiLoop drives the saved endpoint: conversations at once, and the seconds one reply may take. With no flags, print the saved values.')
2684
+ .option('--parallel <n>', "the most conversations at once (0 removes the agent's own limit)")
2685
+ .option('--reply-timeout <seconds>', 'the most seconds one reply may take (1 to 600)')
2686
+ .action(run(async (ctx) => {
2687
+ const result = await connect.setLimits(ctx.client, { project: connectProject(ctx) }, {
2688
+ max_parallel_conversations: ctx.opts.parallel !== undefined ? intArg(String(ctx.opts.parallel)) : undefined,
2689
+ reply_timeout_seconds: ctx.opts.replyTimeout !== undefined ? intArg(String(ctx.opts.replyTimeout)) : undefined,
2690
+ });
2691
+ if (!result.target) {
2692
+ ctx.out.result(result, () => actedOn(result, 'No connection is saved for this project yet.'));
2693
+ return;
2694
+ }
2695
+ const target = result.target;
2696
+ const parallel = target.max_parallel_conversations;
2697
+ const fallback = target.default_max_parallel_conversations;
2698
+ const timeout = target.reply_timeout_seconds;
2699
+ const unset = fallback
2700
+ ? `no limit set, QualiLoop runs up to ${String(fallback)} at once`
2701
+ : 'no limit';
2702
+ ctx.out.result(result, () => actedOn(result, `Conversations at once: ${parallel ? String(parallel) : unset}. ` +
2703
+ `Reply timeout: ${timeout ? `${String(timeout)} seconds` : 'the default'}.`));
1324
2704
  }));
1325
2705
  connectCommand
1326
2706
  .command('knowledge')
@@ -1338,14 +2718,73 @@ connectCommand
1338
2718
  .action(run(async ({ out }) => {
1339
2719
  out.result({ status: 'no_longer_needed', detail: connect.TRACE_FIELDS_GONE }, () => connect.TRACE_FIELDS_GONE);
1340
2720
  }));
2721
+ const limitArg = (value) => (value.toLowerCase() === 'none' ? null : intArg(value));
2722
+ const PERIODS = ['day', 'week', 'month'];
1341
2723
  connectCommand
1342
2724
  .command('live <on|off>')
1343
- .description("Turn the project's live traffic on or off (admins). It sends real users' data.")
2725
+ .description("Turn the project's live traffic on or off (admins), and optionally how much is stored and scored. It sends real users' data.")
2726
+ .option('--collect-percent <n>', 'share of new live conversations stored, 0 to 100')
2727
+ .option('--scoring <on|off>', 'score stored live conversations')
2728
+ .option('--score-percent <n>', 'share of stored live conversations scored, 0 to 100')
2729
+ .option('--turn-limit <n|none>', 'the most live turns stored per period; none removes the limit')
2730
+ .addOption(new Option('--turn-limit-period <period>').choices(PERIODS))
2731
+ .option('--score-limit <n|none>', 'the most live conversations scored per period; none removes the limit')
2732
+ .addOption(new Option('--score-limit-period <period>').choices(PERIODS))
1344
2733
  .action(run(async (ctx, state) => {
1345
2734
  if (!['on', 'off'].includes(state))
1346
2735
  throw new ApiError('Say on or off.', 400, EXIT.usage);
1347
- const result = await connect.setLive(ctx.client, { project: connectProject(ctx) }, { enabled: state === 'on' });
1348
- ctx.out.result(result, () => actedOn(result, `Live traffic is ${result.live_data_enabled ? 'on' : 'off'}.`));
2736
+ const opts = ctx.opts;
2737
+ const result = await connect.setLive(ctx.client, { project: connectProject(ctx) }, {
2738
+ enabled: state === 'on',
2739
+ collect_percent: opts.collectPercent !== undefined ? intArg(String(opts.collectPercent)) : undefined,
2740
+ scoring_enabled: onOff(opts.scoring, '--scoring'),
2741
+ score_percent: opts.scorePercent !== undefined ? intArg(String(opts.scorePercent)) : undefined,
2742
+ turn_limit: opts.turnLimit !== undefined ? limitArg(String(opts.turnLimit)) : undefined,
2743
+ turn_limit_period: opts.turnLimitPeriod,
2744
+ score_limit: opts.scoreLimit !== undefined ? limitArg(String(opts.scoreLimit)) : undefined,
2745
+ score_limit_period: opts.scoreLimitPeriod,
2746
+ });
2747
+ const limit = (value, period) => value === null || value === undefined ? 'no limit' : `at most ${String(value)} a ${String(period)}`;
2748
+ ctx.out.result(result, () => actedOn(result, [
2749
+ `Live traffic is ${result.live_data_enabled ? 'on' : 'off'}.`,
2750
+ fields([
2751
+ [
2752
+ 'Stored',
2753
+ `${String(result.collect_percent)}% of new conversations, turns ${limit(result.turn_limit, result.turn_limit_period)}`,
2754
+ ],
2755
+ [
2756
+ 'Scored',
2757
+ result.scoring_enabled
2758
+ ? `${String(result.score_percent)}% of stored conversations, ${limit(result.score_limit, result.score_limit_period)}`
2759
+ : 'off',
2760
+ ],
2761
+ ]),
2762
+ ].join('\n')));
2763
+ }));
2764
+ connectCommand
2765
+ .command('traces [on|off]')
2766
+ .description("Whether scoring uses traces (on or off, admins), and how long QualiLoop waits for a conversation's traces once its last turn is done.")
2767
+ .option('--delay <seconds>', 'seconds before the first look, 0 to 120')
2768
+ .option('--interval <seconds>', 'seconds between looks, 1 to 60')
2769
+ .option('--max-wait <seconds>', 'seconds after which QualiLoop stops looking, 0 to 600')
2770
+ .action(run(async (ctx, state) => {
2771
+ const opts = ctx.opts;
2772
+ const result = await connect.setTraces(ctx.client, { project: connectProject(ctx) }, {
2773
+ enabled: onOff(state, 'traces'),
2774
+ delay_seconds: opts.delay !== undefined ? intArg(String(opts.delay)) : undefined,
2775
+ interval_seconds: opts.interval !== undefined ? intArg(String(opts.interval)) : undefined,
2776
+ max_wait_seconds: opts.maxWait !== undefined ? intArg(String(opts.maxWait)) : undefined,
2777
+ });
2778
+ const lines = [];
2779
+ if (result.traces_disabled !== undefined) {
2780
+ lines.push(result.traces_disabled ? 'Scoring without traces.' : 'Scoring with traces.');
2781
+ }
2782
+ if (result.target) {
2783
+ const target = result.target;
2784
+ lines.push(`Waiting for traces: first look after ${String(target.trace_fetch_delay_seconds)} s, then every ` +
2785
+ `${String(target.trace_fetch_interval_seconds)} s, at most ${String(target.trace_fetch_max_wait_seconds)} s.`);
2786
+ }
2787
+ ctx.out.result(result, () => actedOn(result, lines.join('\n')));
1349
2788
  }));
1350
2789
  const checkRender = (result) => {
1351
2790
  const items = (result.items ?? result.checks);
@@ -1433,6 +2872,7 @@ program
1433
2872
  .command('action <name>')
1434
2873
  .description('Run one action with JSON arguments, as the MCP server would: qualiloop action list_runs --args \'{"limit": 5}\'')
1435
2874
  .option('--args <json>', 'the arguments as a JSON object', '{}')
2875
+ .option('--yes', 'answer yes to the question an action that deletes asks first')
1436
2876
  .action(run(async ({ client, out, project, opts }, name) => {
1437
2877
  let args;
1438
2878
  try {
@@ -1446,6 +2886,9 @@ program
1446
2886
  const properties = (spec?.input_schema.properties ?? {});
1447
2887
  if ('project' in properties && args.project === undefined && project !== undefined)
1448
2888
  args.project = project;
2889
+ if (spec?.confirm === 'always' && !opts.yes && !(await confirm(`Run ${name}, which deletes?`))) {
2890
+ throw new ApiError('Not run.', 400, EXIT.usage);
2891
+ }
1449
2892
  const result = await client.action(name, args);
1450
2893
  out.result(result, () => JSON.stringify(result, null, 2));
1451
2894
  }));