From 4f8b4dc8e0da112dd23a7ed889204359fd06d4b2 Mon Sep 17 00:00:00 2001 From: Balaji Srinivasan Date: Mon, 23 Nov 2026 00:50:01 -0800 Subject: [PATCH 1/5] feat: run conversation-level test specs with agent test run --spec (W-24861403) `sf agent test run --spec ` reads a YAML spec with `testScope: CONVERSATION_LEVEL`, validates it for a run without saving, resolves `subjectName` (plus optional `subjectVersion`) to agent IDs or sends `project` as-is, runs it with ConversationTester.runEphemeral and prints results through the shared human/JSON/JUnit/TAP formatters. - --spec is exclusive with --api-name, --wait and --test-runner. - Exit 1: invalid spec, server rejected the input, or an execution error (run Failed or a scorer ERROR). Scorer FAILs don't change the exit code, matching saved runs. Exit 2: spec file, agent or version not found. Exit 4: API or network failure. Depends on @salesforce/agents with ConversationTester (forcedotcom/agents #401 and #406). Co-Authored-By: Claude Opus 5.5 --- command-snapshot.json | 3 +- messages/agent.test.run.md | 43 ++++++ schemas/agent-test-run.json | 191 ++++++++++++++++-------- src/commands/agent/test/run.ts | 88 ++++++++++- src/conversationTestRun.ts | 150 +++++++++++++++++++ test/commands/agent/test/run.test.ts | 177 ++++++++++++++++++++++ test/conversationTestRun.test.ts | 212 +++++++++++++++++++++++++++ 7 files changed, 792 insertions(+), 72 deletions(-) create mode 100644 src/conversationTestRun.ts create mode 100644 test/commands/agent/test/run.test.ts create mode 100644 test/conversationTestRun.test.ts diff --git a/command-snapshot.json b/command-snapshot.json index 9e281d50..6ac4dd58 100644 --- a/command-snapshot.json +++ b/command-snapshot.json @@ -540,7 +540,7 @@ "alias": [], "command": "agent:test:run", "flagAliases": [], - "flagChars": ["d", "n", "o", "w"], + "flagChars": ["d", "n", "o", "s", "w"], "flags": [ "api-name", "api-version", @@ -548,6 +548,7 @@ "json", "output-dir", "result-format", + "spec", "target-org", "test-runner", "verbose", diff --git a/messages/agent.test.run.md b/messages/agent.test.run.md index 09adc433..165d2690 100644 --- a/messages/agent.test.run.md +++ b/messages/agent.test.run.md @@ -10,6 +10,8 @@ By default, this command starts the agent test in your org, but it doesn't wait By default, this command outputs test results in human-readable tables for each test case, if the test completes in time. The tables show whether the test case passed, the expected and actual values, the test score, how long the test took, and more. Use the --result-format to display the test results in JSON or Junit format. Use the --output-dir flag to write the results to a file rather than to the terminal. +To run a conversation-level test without saving it to your org, use the --spec flag instead of --api-name, and specify a YAML test spec that has `testScope: CONVERSATION_LEVEL`. A simulated user holds a multi-turn conversation with the agent for each test case's `conversationGoal`, and the scorers in the spec grade it. The command waits for the run to finish and displays the results; nothing is saved to the org. The --wait and --test-runner flags don't apply to --spec. + # flags.api-name.summary API name of the agent test to run; corresponds to the name of the AiEvaluationDefinition metadata component that implements the agent test. @@ -18,6 +20,14 @@ API name of the agent test to run; corresponds to the name of the AiEvaluationDe API name of the agent test to run +# flags.spec.summary + +Path to a conversation-level test spec (YAML) to run without saving it to the org. + +# flags.spec.description + +The spec must set `testScope: CONVERSATION_LEVEL`, and name the agent with `subjectName` (a published agent's API name, plus an optional `subjectVersion` such as v3; the latest version is used if omitted) or `project` (a draft agent's projectId and projectVersionId). Each test case needs a `conversationGoal`. Supported scorers when running without saving: task_resolution (the default), acceptance_criteria, topic_sequence_match and action_sequence_match. A run accepts up to 10 test cases (more if your org has a higher limit) and `maxTurns` from 1 to 30. + # flags.wait.summary Number of minutes to wait for the command to complete and display results to the terminal window. @@ -36,6 +46,39 @@ Number of minutes to wait for the command to complete and display results to the <%= config.bin %> <%= command.id %> --api-name Resort_Manager_Test --wait 10 --output-dir ./test-results --result-format json +- Run the conversation-level test spec in the file specs/order-status-clt.yaml without saving it, using the org with alias "my-org": + + <%= config.bin %> <%= command.id %> --spec specs/order-status-clt.yaml --target-org my-org + +- Run a conversation-level test spec and write the JUnit-formatted results into a directory called "test-results": + + <%= config.bin %> <%= command.id %> --spec specs/order-status-clt.yaml --output-dir ./test-results --result-format junit + +# progress.conversationRun + +Running conversation-level test "%s" (%s test cases) without saving + +# error.specFileNotFound + +Spec file not found: %s + +# error.specNotConversationLevel + +The spec %s isn't a conversation-level test spec. + +# error.specNotConversationLevel.actions + +- Add `testScope: CONVERSATION_LEVEL` to the spec to run it with --spec. +- To run a saved turn-level test, deploy it and use --api-name instead. + +# error.invalidSpec + +The spec %s isn't valid: %s + +# error.agentVersionNotFound + +Version '%s' of agent '%s' not found. Set `subjectVersion` to a BotVersion API name such as v1, or remove it to use the latest version. + # error.missingRequiredFlags When using --json, you must also specify the required flag(s): %s. diff --git a/schemas/agent-test-run.json b/schemas/agent-test-run.json index db4dd9d6..9c3355d1 100644 --- a/schemas/agent-test-run.json +++ b/schemas/agent-test-run.json @@ -1,7 +1,18 @@ { "$schema": "http://json-schema.org/draft-07/schema#", - "$ref": "#/definitions/AgentTestRunResult", + "$ref": "#/definitions/AgentTestRunCommandResult", "definitions": { + "AgentTestRunCommandResult": { + "anyOf": [ + { + "$ref": "#/definitions/AgentTestRunResult" + }, + { + "$ref": "#/definitions/ConversationTestRunResult" + } + ], + "description": "`--api-name` starts (and with `--wait`, polls) a saved test; `--spec` runs a conversation-level spec without saving." + }, "AgentTestRunResult": { "anyOf": [ { @@ -33,10 +44,7 @@ } } }, - "required": [ - "runId", - "status" - ] + "required": ["runId", "status"] }, { "type": "object", @@ -67,13 +75,7 @@ } } }, - "required": [ - "runId", - "startTime", - "status", - "subjectName", - "testCases" - ] + "required": ["runId", "startTime", "status", "subjectName", "testCases"] }, { "type": "object", @@ -93,23 +95,13 @@ } } }, - "required": [ - "runId", - "status", - "testCases" - ] + "required": ["runId", "status", "testCases"] } ] }, "TestStatus": { "type": "string", - "enum": [ - "NEW", - "IN_PROGRESS", - "COMPLETED", - "ERROR", - "TERMINATED" - ] + "enum": ["NEW", "IN_PROGRESS", "COMPLETED", "ERROR", "TERMINATED"] }, "TestCaseResult": { "type": "object", @@ -130,9 +122,7 @@ "type": "string" } }, - "required": [ - "utterance" - ], + "required": ["utterance"], "additionalProperties": false }, "generatedData": { @@ -157,13 +147,7 @@ "type": "string" } }, - "required": [ - "actionsSequence", - "invokedActions", - "sessionId", - "outcome", - "topic" - ], + "required": ["actionsSequence", "invokedActions", "sessionId", "outcome", "topic"], "additionalProperties": false }, "testResults": { @@ -184,22 +168,12 @@ "type": "number" }, "result": { - "type": [ - "null", - "string" - ], - "enum": [ - null, - "PASS", - "FAILURE" - ] + "type": ["null", "string"], + "enum": [null, "PASS", "FAILURE"] }, "metricLabel": { "type": "string", - "enum": [ - "Accuracy", - "Precision" - ] + "enum": ["Accuracy", "Precision"] }, "metricExplainability": { "type": "string" @@ -238,14 +212,7 @@ "type": "number" } }, - "required": [ - "status", - "startTime", - "inputs", - "generatedData", - "testResults", - "testNumber" - ], + "required": ["status", "startTime", "inputs", "generatedData", "testResults", "testNumber"], "additionalProperties": false }, "AgentforceStudioTestCaseResult": { @@ -264,11 +231,7 @@ } } }, - "required": [ - "subjectResponse", - "testNumber", - "testScorerResults" - ], + "required": ["subjectResponse", "testNumber", "testScorerResults"], "additionalProperties": false }, "TestScorerResult": { @@ -281,11 +244,109 @@ "type": "string" } }, - "required": [ - "scorerName", - "scorerResponse" - ], + "required": ["scorerName", "scorerResponse"], + "additionalProperties": false + }, + "ConversationTestRunResult": { + "type": "object", + "additionalProperties": false, + "properties": { + "status": { + "type": "string", + "const": "COMPLETED" + }, + "testScope": { + "type": "string", + "const": "CONVERSATION_LEVEL" + }, + "runStatus": { + "type": "string", + "description": "The server's run status: `Completed` or `Failed`." + }, + "errorRepresentation": { + "type": "object", + "properties": { + "errorCode": { + "type": "string" + }, + "errorMessage": { + "type": "string" + }, + "retryable": { + "type": "boolean" + } + }, + "additionalProperties": false + }, + "summary": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "not": {} + }, + { + "type": "number" + } + ] + }, + "properties": { + "totalNumberOfTestCases": { + "type": "number" + }, + "taskResolutionPassPercent": { + "type": "number" + }, + "acceptanceCriteriaPassPercent": { + "type": "number" + } + }, + "description": "Omitted until the run is complete." + }, + "testCases": { + "type": "array", + "items": { + "$ref": "#/definitions/ConversationTestCaseResult" + } + } + }, + "required": ["runStatus", "status", "testCases", "testScope"], + "description": "`agent test run --spec` result: a conversation-level run without saving a suite." + }, + "ConversationTestCaseResult": { + "type": "object", + "properties": { + "testNumber": { + "type": "number", + "description": "The 1-based `number` sent in the request." + }, + "testCaseId": { + "type": "string", + "description": "Saved suites only." + }, + "subjectResponse": { + "type": "string", + "description": "JSON string: the simulated conversation (turns, topics, actions, completion reason)." + }, + "testScorerResults": { + "type": "array", + "items": { + "type": "object", + "properties": { + "scorerName": { + "type": "string" + }, + "scorerResponse": { + "type": "string" + } + }, + "required": ["scorerName"], + "additionalProperties": false + } + } + }, + "required": ["testNumber"], "additionalProperties": false } } -} \ No newline at end of file +} diff --git a/src/commands/agent/test/run.ts b/src/commands/agent/test/run.ts index 2e3500ca..0f6937fe 100644 --- a/src/commands/agent/test/run.ts +++ b/src/commands/agent/test/run.ts @@ -15,8 +15,13 @@ */ import { SfCommand, Flags, toHelpSection } from '@salesforce/sf-plugins-core'; -import { EnvironmentVariable, Messages, SfError } from '@salesforce/core'; -import { AgentTestStartResponse, AgentforceStudioTestStartResponse } from '@salesforce/agents'; +import { EnvironmentVariable, Messages, Org, SfError } from '@salesforce/core'; +import { + AgentTestStartResponse, + AgentforceStudioTestStartResponse, + ConversationTester, + cltSpecToEphemeralInput, +} from '@salesforce/agents'; import { colorize } from '@oclif/core/ux'; import { CLIError } from '@oclif/core/errors'; import { @@ -34,6 +39,13 @@ import { AgentTestCache } from '../../../agentTestCache.js'; import { TestStages } from '../../../testStages.js'; import { handleTestResults } from '../../../handleTestResults.js'; import { createTestRunner } from '../../../testRunnerFactory.js'; +import { + type ConversationTestRunResult, + hasExecutionErrors, + readConversationSpec, + resolveConversationAgent, + toDisplayResults, +} from '../../../conversationTestRun.js'; Messages.importMessagesDirectoryFromMetaUrl(import.meta.url); const messages = Messages.loadMessages('@salesforce/plugin-agent', 'agent.test.run'); @@ -60,7 +72,10 @@ const FLAGGABLE_PROMPTS = { }, } satisfies Record; -export default class AgentTestRun extends SfCommand { +/** `--api-name` starts (and with `--wait`, polls) a saved test; `--spec` runs a conversation-level spec without saving. */ +export type AgentTestRunCommandResult = AgentTestRunResult | ConversationTestRunResult; + +export default class AgentTestRun extends SfCommand { public static readonly summary = messages.getMessage('summary'); public static readonly description = messages.getMessage('description'); public static readonly examples = messages.getMessages('examples'); @@ -72,8 +87,9 @@ export default class AgentTestRun extends SfCommand { public static readonly errorCodes = toHelpSection('ERROR CODES', { 'Succeeded (0)': 'Test started successfully (without --wait), or test completed successfully (with --wait).', - 'Failed (1)': 'Tests encountered execution errors (test cases with ERROR status when using --wait).', - 'NotFound (2)': 'Test definition not found or invalid test name.', + 'Failed (1)': + 'Tests encountered execution errors (test cases with ERROR status when using --wait), or the --spec file is invalid or was rejected.', + 'NotFound (2)': 'Test definition not found or invalid test name, or the --spec file or its agent not found.', 'OperationFailed (4)': 'Failed to start or poll test due to API or network errors.', }); @@ -81,6 +97,15 @@ export default class AgentTestRun extends SfCommand { 'target-org': Flags.requiredOrg(), 'api-version': Flags.orgApiVersion(), ...makeFlags(FLAGGABLE_PROMPTS), + spec: Flags.file({ + char: 's', + exists: true, + summary: messages.getMessage('flags.spec.summary'), + description: messages.getMessage('flags.spec.description'), + // api-name comes from makeFlags(FLAGGABLE_PROMPTS) above, which this rule can't see. + // eslint-disable-next-line sf-plugin/flag-cross-references + exclusive: ['api-name', 'wait', 'test-runner'], + }), // we want to pass `undefined` to the API // eslint-disable-next-line sf-plugin/flag-min-max-default wait: Flags.duration({ @@ -97,10 +122,14 @@ export default class AgentTestRun extends SfCommand { private mso: TestStages | undefined; - public async run(): Promise { + public async run(): Promise { const { flags } = await this.parse(AgentTestRun); const connection = flags['target-org'].getConnection(flags['api-version']); + if (flags.spec) { + return this.runConversationSpec(flags.spec, flags); + } + if (this.jsonEnabled() && !flags['api-name']) { throw messages.createError('error.missingRequiredFlags', ['api-name']); } @@ -224,4 +253,51 @@ export default class AgentTestRun extends SfCommand { this.mso?.error(); return super.catch(error); } + + private async runConversationSpec( + specPath: string, + flags: { + 'target-org': Org; + 'api-version'?: string; + 'result-format': 'json' | 'human' | 'junit' | 'tap'; + 'output-dir'?: string; + verbose: boolean; + } + ): Promise { + const spec = await readConversationSpec(specPath); + const org = flags['target-org']; + const agent = await resolveConversationAgent(org, spec); + + this.spinner.start(messages.getMessage('progress.conversationRun', [spec.name, spec.testCases.length])); + let results; + try { + results = await new ConversationTester(org.getConnection(flags['api-version'])).runEphemeral( + cltSpecToEphemeralInput(spec, agent) + ); + } catch (e) { + this.spinner.stop('failed'); + const wrapped = SfError.wrap(e); + if (wrapped.name === 'ConversationTestRejectedError') { + throw new SfError(wrapped.message, 'ConversationTestRejected', wrapped.actions, 1, wrapped); + } + throw new SfError(`Failed to run test: ${wrapped.message}`, 'TestRunFailed', [wrapped.message], 4, wrapped); + } + this.spinner.stop(); + + await handleTestResults({ + id: spec.name, + format: flags['result-format'], + results: toDisplayResults(spec, results), + jsonEnabled: this.jsonEnabled(), + outputDir: flags['output-dir'], + verbose: flags.verbose, + }); + + // Same rule as saved runs: execution errors set exit code 1, scorer FAILs don't. + if (hasExecutionErrors(results)) { + process.exitCode = 1; + } + + return { ...results, status: 'COMPLETED', testScope: 'CONVERSATION_LEVEL', runStatus: results.status }; + } } diff --git a/src/conversationTestRun.ts b/src/conversationTestRun.ts new file mode 100644 index 00000000..0f2eb204 --- /dev/null +++ b/src/conversationTestRun.ts @@ -0,0 +1,150 @@ +/* + * Copyright 2026, Salesforce, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { readFile } from 'node:fs/promises'; +import YAML from 'yaml'; +import { Messages, Org, SfError } from '@salesforce/core'; +import { + type AgentforceStudioTestCaseResult, + type AgentforceStudioTestResultsResponse, + type CltTestSpec, + type ConversationTestResultsResponse, + isCltSpec, + parseConversationScorerResponse, + resolveAgent, + validateCltSpec, +} from '@salesforce/agents'; + +Messages.importMessagesDirectoryFromMetaUrl(import.meta.url); +const messages = Messages.loadMessages('@salesforce/plugin-agent', 'agent.test.run'); + +/** `agent test run --spec` result: a conversation-level run without saving a suite. */ +export type ConversationTestRunResult = Omit & { + status: 'COMPLETED'; + testScope: 'CONVERSATION_LEVEL'; + /** The server's run status: `Completed` or `Failed`. */ + runStatus: string; +}; + +/** + * Reads a conversation-level test spec from a YAML file and validates it for a run without saving. + * Exit code 2 when the file can't be read, 1 when it isn't a valid conversation-level spec. + */ +export async function readConversationSpec(specPath: string): Promise { + let content: string; + try { + content = await readFile(specPath, 'utf-8'); + } catch (e) { + throw new SfError(messages.getMessage('error.specFileNotFound', [specPath]), 'SpecFileNotFound', [], 2, e); + } + + let spec: unknown; + try { + spec = YAML.parse(content); + } catch (e) { + throw messages.createError('error.invalidSpec', [specPath, SfError.wrap(e).message]); + } + + if (!isCltSpec(spec)) { + throw messages.createError('error.specNotConversationLevel', [specPath]); + } + try { + validateCltSpec(spec, { target: 'ephemeral' }); + } catch (e) { + throw messages.createError('error.invalidSpec', [specPath, SfError.wrap(e).message]); + } + return spec; +} + +/** + * Resolves the published agent a spec names (`subjectName`, optional `subjectVersion`) to IDs. + * Returns `undefined` for a draft agent (`project`), which the converter sends as-is. + */ +export async function resolveConversationAgent( + org: Org, + spec: CltTestSpec +): Promise<{ agentId: string; agentVersionId: string } | undefined> { + if (!spec.subjectName) { + return undefined; + } + + let agentId: string; + let versionId: string; + try { + ({ agentId, versionId } = await resolveAgent(org, spec.subjectName)); + } catch (e) { + throw new SfError(SfError.wrap(e).message, 'AgentNotFound', [], 2, e); + } + if (!spec.subjectVersion) { + return { agentId, agentVersionId: versionId }; + } + + const { records } = await org + .getConnection() + .query<{ Id: string }>( + `SELECT Id FROM BotVersion WHERE BotDefinitionId = '${agentId}' AND DeveloperName = '${escapeSoql( + spec.subjectVersion + )}'` + ); + if (records.length === 0) { + throw new SfError( + messages.getMessage('error.agentVersionNotFound', [spec.subjectVersion, spec.subjectName]), + 'AgentVersionNotFound', + [], + 2 + ); + } + return { agentId, agentVersionId: records[0].Id }; +} + +/** + * Shapes conversation-level results for the shared test-result formatters (human, JUnit, TAP). + * Each test case's conversation goal comes from the spec, by `testNumber`. + */ +export function toDisplayResults( + spec: CltTestSpec, + results: ConversationTestResultsResponse +): AgentforceStudioTestResultsResponse { + return { + status: results.status, + testCases: results.testCases.map((tc): AgentforceStudioTestCaseResult & { inputs: unknown } => ({ + testNumber: tc.testNumber, + subjectResponse: tc.subjectResponse ?? '', + testScorerResults: (tc.testScorerResults ?? []).map((s) => ({ + scorerName: s.scorerName, + scorerResponse: s.scorerResponse ?? '', + })), + inputs: [{ name: 'Conversation Goal', value: spec.testCases[tc.testNumber - 1]?.conversationGoal }], + })), + }; +} + +/** + * True when the run couldn't complete properly: the server reports `Failed` (for example, the agent + * failed mid-conversation), or a scorer returned `ERROR`. Scorer FAILs are test outcomes, not errors. + */ +export function hasExecutionErrors(results: ConversationTestResultsResponse): boolean { + return ( + results.status.toLowerCase() === 'failed' || + results.testCases.some((tc) => + (tc.testScorerResults ?? []).some( + (s) => parseConversationScorerResponse(s.scorerResponse)?.status?.toUpperCase() === 'ERROR' + ) + ) + ); +} + +const escapeSoql = (value: string): string => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'"); diff --git a/test/commands/agent/test/run.test.ts b/test/commands/agent/test/run.test.ts new file mode 100644 index 00000000..183ac950 --- /dev/null +++ b/test/commands/agent/test/run.test.ts @@ -0,0 +1,177 @@ +/* + * Copyright 2026, Salesforce, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */ + +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect } from 'chai'; +import sinon from 'sinon'; +import esmock from 'esmock'; +import { SfError } from '@salesforce/core'; +import { TestContext, MockTestOrgData } from '@salesforce/core/testSetup'; + +const SPEC = { + name: 'Order status', + testScope: 'CONVERSATION_LEVEL', + subjectName: 'Order_Agent', + testCases: [{ conversationGoal: 'Check the status of my order' }], +}; + +const RESULTS = { + status: 'Completed', + testCases: [ + { + testNumber: 1, + subjectResponse: '{}', + testScorerResults: [{ scorerName: 'task_resolution', scorerResponse: '{"status":"FAIL","reasoning":"no date"}' }], + }, + ], +}; + +describe('agent test run --spec', () => { + const $$ = new TestContext(); + let testOrg: MockTestOrgData; + let tmpDir: string; + let specFile: string; + + let readConversationSpecStub: sinon.SinonStub; + let resolveConversationAgentStub: sinon.SinonStub; + let runEphemeralStub: sinon.SinonStub; + let handleTestResultsStub: sinon.SinonStub; + let createTestRunnerStub: sinon.SinonStub; + + let AgentTestRun: any; + + beforeEach(async () => { + testOrg = new MockTestOrgData(); + await $$.stubAuths(testOrg); + tmpDir = mkdtempSync(join(tmpdir(), 'clt-run-cmd-')); + specFile = join(tmpDir, 'spec.yaml'); + writeFileSync(specFile, 'placeholder', 'utf-8'); + + readConversationSpecStub = $$.SANDBOX.stub().resolves(SPEC); + resolveConversationAgentStub = $$.SANDBOX.stub().resolves({ agentId: '0XxA', agentVersionId: '0X9A' }); + runEphemeralStub = $$.SANDBOX.stub().resolves(RESULTS); + handleTestResultsStub = $$.SANDBOX.stub().resolves(); + createTestRunnerStub = $$.SANDBOX.stub(); + + const mod = await esmock('../../../../src/commands/agent/test/run.js', { + '@salesforce/agents': { + ConversationTester: class { + public runEphemeral = runEphemeralStub; + }, + }, + '../../../../src/conversationTestRun.js': { + readConversationSpec: readConversationSpecStub, + resolveConversationAgent: resolveConversationAgentStub, + }, + '../../../../src/handleTestResults.js': { handleTestResults: handleTestResultsStub }, + '../../../../src/testRunnerFactory.js': { createTestRunner: createTestRunnerStub }, + }); + AgentTestRun = mod.default; + }); + + afterEach(() => { + $$.restore(); + rmSync(tmpDir, { recursive: true, force: true }); + process.exitCode = undefined; + }); + + const run = (...extra: string[]): Promise => + AgentTestRun.run(['--spec', specFile, '--target-org', testOrg.username, ...extra]); + + const expectError = async (promise: Promise): Promise => { + try { + await promise; + } catch (e) { + return e; + } + expect.fail('expected the command to throw'); + }; + + it('runs the spec without saving and returns the results', async () => { + const result = await run(); + + expect(readConversationSpecStub.calledOnceWith(specFile)).to.be.true; + expect(runEphemeralStub.firstCall.args[0]).to.deep.equal({ + agentId: '0XxA', + agentVersionId: '0X9A', + testCases: [{ number: 1, conversationGoal: 'Check the status of my order' }], + }); + expect(createTestRunnerStub.called).to.be.false; + expect(result).to.deep.equal({ + ...RESULTS, + status: 'COMPLETED', + testScope: 'CONVERSATION_LEVEL', + runStatus: 'Completed', + }); + }); + + it('passes results, format and output dir to the shared formatter', async () => { + await run('--result-format', 'junit', '--output-dir', tmpDir); + + const args = handleTestResultsStub.firstCall.args[0]; + expect(args).to.include({ id: 'Order status', format: 'junit', outputDir: tmpDir }); + expect(args.results.testCases[0].inputs).to.deep.equal([ + { name: 'Conversation Goal', value: 'Check the status of my order' }, + ]); + }); + + it('does not set an exit code for scorer FAILs', async () => { + await run(); + expect(process.exitCode).to.equal(undefined); + }); + + it('sets exit code 1 when the run has execution errors', async () => { + runEphemeralStub.resolves({ ...RESULTS, status: 'Failed' }); + await run(); + expect(process.exitCode).to.equal(1); + }); + + it('reports a rejected run as ConversationTestRejected (exit 1) with the server message', async () => { + runEphemeralStub.rejects( + new SfError('The conversation-level test run was rejected: bad maxTurns', 'ConversationTestRejectedError', [ + 'Fix the input the message names, then run again.', + ]) + ); + const err = await expectError(run()); + expect(err.name).to.equal('ConversationTestRejected'); + expect(err.exitCode).to.equal(1); + expect(err.message).to.equal('The conversation-level test run was rejected: bad maxTurns'); + expect(err.actions).to.deep.equal(['Fix the input the message names, then run again.']); + }); + + it('reports API failures as TestRunFailed (exit 4)', async () => { + runEphemeralStub.rejects(new Error('socket hang up')); + const err = await expectError(run()); + expect(err.name).to.equal('TestRunFailed'); + expect(err.exitCode).to.equal(4); + expect(err.message).to.equal('Failed to run test: socket hang up'); + }); + + it('rejects --spec together with --api-name', async () => { + const err = await expectError(run('--api-name', 'My_Test')); + expect(err.message).to.include('--api-name'); + expect(readConversationSpecStub.called).to.be.false; + }); + + it('rejects --spec together with --wait', async () => { + const err = await expectError(run('--wait', '5')); + expect(err.message).to.include('--wait'); + }); +}); diff --git a/test/conversationTestRun.test.ts b/test/conversationTestRun.test.ts new file mode 100644 index 00000000..01e807cf --- /dev/null +++ b/test/conversationTestRun.test.ts @@ -0,0 +1,212 @@ +/* + * Copyright 2026, Salesforce, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any */ + +import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect } from 'chai'; +import sinon from 'sinon'; +import esmock from 'esmock'; +import type { CltTestSpec, ConversationTestResultsResponse } from '@salesforce/agents'; +import { hasExecutionErrors, readConversationSpec, toDisplayResults } from '../src/conversationTestRun.js'; + +const CLT_YAML = ` +name: Order status +testScope: CONVERSATION_LEVEL +subjectName: Order_Agent +maxTurns: 5 +testCases: + - conversationGoal: Check the status of my order +`; + +const spec: CltTestSpec = { + name: 'Order status', + testScope: 'CONVERSATION_LEVEL', + subjectName: 'Order_Agent', + testCases: [{ conversationGoal: 'Check the status of my order' }, { conversationGoal: 'Cancel my order' }], +}; + +const expectError = async (promise: Promise): Promise => { + try { + await promise; + } catch (e) { + return e; + } + expect.fail('expected the call to throw'); +}; + +describe('conversationTestRun', () => { + let tmpDir: string; + const writeSpec = (content: string): string => { + const file = join(tmpDir, 'spec.yaml'); + writeFileSync(file, content, 'utf-8'); + return file; + }; + + beforeEach(() => { + tmpDir = mkdtempSync(join(tmpdir(), 'clt-run-test-')); + }); + + afterEach(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + describe('readConversationSpec', () => { + it('returns a valid conversation-level spec', async () => { + const result = await readConversationSpec(writeSpec(CLT_YAML)); + expect(result.name).to.equal('Order status'); + expect(result.testCases).to.have.length(1); + }); + + it('throws SpecFileNotFound (exit 2) for a missing file', async () => { + const err = await expectError(readConversationSpec(join(tmpDir, 'missing.yaml'))); + expect(err.name).to.equal('SpecFileNotFound'); + expect(err.exitCode).to.equal(2); + }); + + it('throws InvalidSpec for YAML that does not parse', async () => { + const file = writeSpec('name: [unclosed'); + const err = await expectError(readConversationSpec(file)); + expect(err.name).to.equal('InvalidSpecError'); + expect(err.message).to.include(`The spec ${file} isn't valid:`); + }); + + it('throws SpecNotConversationLevel for a turn-level spec', async () => { + const err = await expectError(readConversationSpec(writeSpec('name: x\nsubjectName: A\ntestCases: []\n'))); + expect(err.name).to.equal('SpecNotConversationLevelError'); + expect(err.actions[0]).to.include('testScope: CONVERSATION_LEVEL'); + }); + + it('throws InvalidSpec with the validation message for a spec the ephemeral run rejects', async () => { + const err = await expectError(readConversationSpec(writeSpec(CLT_YAML.replace('maxTurns: 5', 'maxTurns: 50')))); + expect(err.name).to.equal('InvalidSpecError'); + expect(err.message).to.include('maxTurns'); + expect(err.message).to.include('Saved suites allow up to 100'); + }); + }); + + describe('resolveConversationAgent', () => { + let resolveAgentStub: sinon.SinonStub; + let queryStub: sinon.SinonStub; + let resolveConversationAgent: any; + const org = (): any => ({ getConnection: () => ({ query: queryStub }) }); + + beforeEach(async () => { + resolveAgentStub = sinon.stub().resolves({ agentId: '0XxA', versionId: '0X9Latest' }); + queryStub = sinon.stub().resolves({ records: [{ Id: '0X9V3' }] }); + ({ resolveConversationAgent } = await esmock('../src/conversationTestRun.js', { + '@salesforce/agents': { resolveAgent: resolveAgentStub }, + })); + }); + + it('returns undefined for a draft agent (project)', async () => { + const result = await resolveConversationAgent(org(), { + ...spec, + subjectName: undefined, + project: { projectId: '1bY', projectVersionId: '1bZ' }, + }); + expect(result).to.equal(undefined); + expect(resolveAgentStub.called).to.be.false; + }); + + it('uses the latest version when subjectVersion is omitted', async () => { + expect(await resolveConversationAgent(org(), spec)).to.deep.equal({ + agentId: '0XxA', + agentVersionId: '0X9Latest', + }); + expect(queryStub.called).to.be.false; + }); + + it('looks up subjectVersion by BotVersion DeveloperName, escaping quotes', async () => { + const result = await resolveConversationAgent(org(), { ...spec, subjectVersion: "v3'" }); + expect(result).to.deep.equal({ agentId: '0XxA', agentVersionId: '0X9V3' }); + expect(queryStub.firstCall.args[0]).to.equal( + "SELECT Id FROM BotVersion WHERE BotDefinitionId = '0XxA' AND DeveloperName = 'v3\\''" + ); + }); + + it('throws AgentVersionNotFound (exit 2) for an unknown subjectVersion', async () => { + queryStub.resolves({ records: [] }); + const err = await expectError(resolveConversationAgent(org(), { ...spec, subjectVersion: 'v9' })); + expect(err.name).to.equal('AgentVersionNotFound'); + expect(err.exitCode).to.equal(2); + expect(err.message).to.include("Version 'v9' of agent 'Order_Agent' not found."); + }); + + it('throws AgentNotFound (exit 2) with the lookup message when the agent is unknown', async () => { + resolveAgentStub.rejects(new Error("Agent 'Order_Agent' not found.")); + const err = await expectError(resolveConversationAgent(org(), spec)); + expect(err.name).to.equal('AgentNotFound'); + expect(err.exitCode).to.equal(2); + expect(err.message).to.equal("Agent 'Order_Agent' not found."); + }); + }); + + describe('toDisplayResults', () => { + it('adds each case goal as an input and fills missing JSON strings', () => { + const results: ConversationTestResultsResponse = { + status: 'Completed', + testCases: [ + { + testNumber: 2, + subjectResponse: '{}', + testScorerResults: [{ scorerName: 'task_resolution', scorerResponse: '{"status":"PASS"}' }], + }, + { testNumber: 1, testScorerResults: [{ scorerName: 'task_resolution' }] }, + { testNumber: 9 }, + ], + }; + const display = toDisplayResults(spec, results); + expect(display.status).to.equal('Completed'); + expect(display.testCases[0]).to.deep.equal({ + testNumber: 2, + subjectResponse: '{}', + testScorerResults: [{ scorerName: 'task_resolution', scorerResponse: '{"status":"PASS"}' }], + inputs: [{ name: 'Conversation Goal', value: 'Cancel my order' }], + }); + expect(display.testCases[1].subjectResponse).to.equal(''); + expect(display.testCases[1].testScorerResults[0].scorerResponse).to.equal(''); + expect(display.testCases[2].testScorerResults).to.deep.equal([]); + expect((display.testCases[2] as any).inputs[0].value).to.equal(undefined); + }); + }); + + describe('hasExecutionErrors', () => { + const run = (status: string, scorerResponse?: string): ConversationTestResultsResponse => ({ + status, + testCases: [ + { testNumber: 1, testScorerResults: [{ scorerName: 'task_resolution', scorerResponse }] }, + { testNumber: 2 }, + ], + }); + + it('is false for a completed run with PASS and FAIL scores', () => { + expect(hasExecutionErrors(run('Completed', '{"status":"FAIL"}'))).to.be.false; + expect(hasExecutionErrors(run('Completed'))).to.be.false; + }); + + it('is true when the run status is Failed', () => { + expect(hasExecutionErrors(run('Failed', '{"status":"PASS"}'))).to.be.true; + }); + + it('is true when a scorer returned ERROR, in either response shape', () => { + expect(hasExecutionErrors(run('Completed', '{"status":"error"}'))).to.be.true; + expect(hasExecutionErrors(run('Completed', '{"content":{"status":"ERROR"}}'))).to.be.true; + }); + }); +}); From 524128d2e01d87ba9ed1d2799f1d2ed1bdaa52b6 Mon Sep 17 00:00:00 2001 From: Balaji Srinivasan Date: Mon, 23 Nov 2026 12:25:56 -0800 Subject: [PATCH 2/5] test: stringify warn args before join in express-context delete test Fixes @typescript-eslint/no-base-to-string on main, which fails the pre-commit and pre-push lint. Co-Authored-By: Claude Opus 5.5 --- test/commands/agent/express-context/readCommands.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/commands/agent/express-context/readCommands.test.ts b/test/commands/agent/express-context/readCommands.test.ts index c9ee23b6..911e327f 100644 --- a/test/commands/agent/express-context/readCommands.test.ts +++ b/test/commands/agent/express-context/readCommands.test.ts @@ -172,7 +172,7 @@ describe('agent express-context read/delete commands', () => { destroy.rejects(new Error('in use')); const result = await AgentExpressContextDelete.run(['--target-org', testOrg.username, '-i', LIB, '--no-prompt']); expect(result).to.deep.equal({ libraryId: LIB, deleted: true }); - expect(ux.warn.args.flat().join('\n')).to.include('FAQ_RetrieverAction').and.include('in use'); + expect(ux.warn.args.flat().map(String).join('\n')).to.include('FAQ_RetrieverAction').and.include('in use'); }); it('still deletes the library when the lookup fails', async () => { From 3f4a8e3cf5b92a4dfdd51640798bf8c638a8e75c Mon Sep 17 00:00:00 2001 From: Balaji Srinivasan Date: Mon, 23 Nov 2026 13:33:13 -0800 Subject: [PATCH 3/5] fix: read conversation scorer outcomes nested under content (W-24861403) Core returns task_resolution and acceptance_criteria verdicts under a content field. The shared formatters read status and reasoning at the top level, so passing scorers showed as Fail with no reasoning in the human and JUnit output. Found in an end-to-end run against a live org. Co-Authored-By: Claude Opus 5.5 --- src/conversationTestRun.ts | 9 +++++---- test/conversationTestRun.test.ts | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/conversationTestRun.ts b/src/conversationTestRun.ts index 0f2eb204..738284db 100644 --- a/src/conversationTestRun.ts +++ b/src/conversationTestRun.ts @@ -123,10 +123,11 @@ export function toDisplayResults( testCases: results.testCases.map((tc): AgentforceStudioTestCaseResult & { inputs: unknown } => ({ testNumber: tc.testNumber, subjectResponse: tc.subjectResponse ?? '', - testScorerResults: (tc.testScorerResults ?? []).map((s) => ({ - scorerName: s.scorerName, - scorerResponse: s.scorerResponse ?? '', - })), + // The formatters read `status` / `reasoning` at the top level; Core may nest them under `content`. + testScorerResults: (tc.testScorerResults ?? []).map((s) => { + const outcome = parseConversationScorerResponse(s.scorerResponse); + return { scorerName: s.scorerName, scorerResponse: outcome ? JSON.stringify(outcome) : s.scorerResponse ?? '' }; + }), inputs: [{ name: 'Conversation Goal', value: spec.testCases[tc.testNumber - 1]?.conversationGoal }], })), }; diff --git a/test/conversationTestRun.test.ts b/test/conversationTestRun.test.ts index 01e807cf..1b580fe9 100644 --- a/test/conversationTestRun.test.ts +++ b/test/conversationTestRun.test.ts @@ -184,6 +184,27 @@ describe('conversationTestRun', () => { expect(display.testCases[2].testScorerResults).to.deep.equal([]); expect((display.testCases[2] as any).inputs[0].value).to.equal(undefined); }); + + it('flattens scorer outcomes nested under content and keeps unparseable responses as sent', () => { + const results: ConversationTestResultsResponse = { + status: 'Completed', + testCases: [ + { + testNumber: 1, + testScorerResults: [ + { + scorerName: 'task_resolution', + scorerResponse: '{"content":{"status":"PASS","score":5.0,"reasoning":"Resolved."},"schema":{}}', + }, + { scorerName: 'acceptance_criteria', scorerResponse: 'not json' }, + ], + }, + ], + }; + const [scorer, unparsed] = toDisplayResults(spec, results).testCases[0].testScorerResults; + expect(JSON.parse(scorer.scorerResponse)).to.deep.equal({ status: 'PASS', score: 5, reasoning: 'Resolved.' }); + expect(unparsed.scorerResponse).to.equal('not json'); + }); }); describe('hasExecutionErrors', () => { From 6cae4f5b0900ba6d3a023ddb5d4577ca8d6c62b2 Mon Sep 17 00:00:00 2001 From: Balaji Srinivasan Date: Wed, 25 Nov 2026 13:03:45 -0800 Subject: [PATCH 4/5] fix: bump @salesforce/agents to 2.6.0 for conversation-level specs (W-24861403) agents 2.6.0 (forcedotcom/agents#401) ships ConversationTester, the CLT spec validator and converter. Core-owned values (scorer names, personas, evaluation modes, maxTurns and test-case limits) are now warnings, not errors; SfCommand prints them. Update the maxTurns test: 0 is still rejected, 50 on a run without saving now warns. Note in the --spec help that unrecognized values warn and the org makes the final check. Co-Authored-By: Claude Opus 5.5 --- messages/agent.test.run.md | 2 +- package.json | 2 +- test/conversationTestRun.test.ts | 17 +++++++++++++++-- yarn.lock | 8 ++++---- 4 files changed, 21 insertions(+), 8 deletions(-) diff --git a/messages/agent.test.run.md b/messages/agent.test.run.md index 165d2690..2786cc77 100644 --- a/messages/agent.test.run.md +++ b/messages/agent.test.run.md @@ -26,7 +26,7 @@ Path to a conversation-level test spec (YAML) to run without saving it to the or # flags.spec.description -The spec must set `testScope: CONVERSATION_LEVEL`, and name the agent with `subjectName` (a published agent's API name, plus an optional `subjectVersion` such as v3; the latest version is used if omitted) or `project` (a draft agent's projectId and projectVersionId). Each test case needs a `conversationGoal`. Supported scorers when running without saving: task_resolution (the default), acceptance_criteria, topic_sequence_match and action_sequence_match. A run accepts up to 10 test cases (more if your org has a higher limit) and `maxTurns` from 1 to 30. +The spec must set `testScope: CONVERSATION_LEVEL`, and name the agent with `subjectName` (a published agent's API name, plus an optional `subjectVersion` such as v3; the latest version is used if omitted) or `project` (a draft agent's projectId and projectVersionId). Each test case needs a `conversationGoal`. Supported scorers when running without saving: task_resolution (the default), acceptance_criteria, topic_sequence_match and action_sequence_match. A run accepts up to 10 test cases (more if your org has a higher limit) and `maxTurns` from 1 to 30. The command checks the spec's structure before calling the org; a scorer, persona or limit it doesn't recognize produces a warning, and the org makes the final check. # flags.wait.summary diff --git a/package.json b/package.json index 4d79d05d..e7e93134 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "@inquirer/prompts": "^7.10.1", "@oclif/core": "^5.0.0", "@oclif/multi-stage-output": "^1.0.0", - "@salesforce/agents": "^2.5.4", + "@salesforce/agents": "^2.6.0", "@salesforce/core": "^9.1.9", "@salesforce/kit": "^4.0.0", "@salesforce/sf-plugins-core": "^13.0.0", diff --git a/test/conversationTestRun.test.ts b/test/conversationTestRun.test.ts index 1b580fe9..84d1dc37 100644 --- a/test/conversationTestRun.test.ts +++ b/test/conversationTestRun.test.ts @@ -22,6 +22,7 @@ import { join } from 'node:path'; import { expect } from 'chai'; import sinon from 'sinon'; import esmock from 'esmock'; +import { Lifecycle } from '@salesforce/core'; import type { CltTestSpec, ConversationTestResultsResponse } from '@salesforce/agents'; import { hasExecutionErrors, readConversationSpec, toDisplayResults } from '../src/conversationTestRun.js'; @@ -93,10 +94,22 @@ describe('conversationTestRun', () => { }); it('throws InvalidSpec with the validation message for a spec the ephemeral run rejects', async () => { - const err = await expectError(readConversationSpec(writeSpec(CLT_YAML.replace('maxTurns: 5', 'maxTurns: 50')))); + const err = await expectError(readConversationSpec(writeSpec(CLT_YAML.replace('maxTurns: 5', 'maxTurns: 0')))); expect(err.name).to.equal('InvalidSpecError'); expect(err.message).to.include('maxTurns'); - expect(err.message).to.include('Saved suites allow up to 100'); + expect(err.message).to.include('whole number of at least 1'); + }); + + it('warns, without throwing, for a maxTurns over the limit for a run without saving', async () => { + const emitWarning = sinon.stub(Lifecycle.getInstance(), 'emitWarning').resolves(); + try { + const result = await readConversationSpec(writeSpec(CLT_YAML.replace('maxTurns: 5', 'maxTurns: 50'))); + expect(result.maxTurns).to.equal(50); + expect(emitWarning.calledOnce).to.be.true; + expect(emitWarning.firstCall.args[0]).to.include('maxTurns').and.include('save the suite'); + } finally { + emitWarning.restore(); + } }); }); diff --git a/yarn.lock b/yarn.lock index bfe7351c..c6bf4916 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1431,10 +1431,10 @@ "@pnpm/network.ca-file" "^1.0.1" config-chain "^1.1.11" -"@salesforce/agents@^2.5.4": - version "2.5.4" - resolved "https://registry.yarnpkg.com/@salesforce/agents/-/agents-2.5.4.tgz#a9e41880cdefa0821e58fb929afe1f4ae56f3ba7" - integrity sha512-zwSmTEXDc6prxvImJ1aycXCnyrJgxuLgp23/hyELzqLI3eyTMblyZNc0+kl8ZaChBYv5xdK47afqboFbmMulFg== +"@salesforce/agents@^2.6.0": + version "2.6.0" + resolved "https://registry.yarnpkg.com/@salesforce/agents/-/agents-2.6.0.tgz#52c7cede55a3d229bfe50b1a1d5b8cfc22f1a51d" + integrity sha512-OXICQWWefTf9ZpzXiY0xvJrQrz6bNdPdZ1yp0W1G1DyPTok8KAdFX00K0bu6V8RMZKZNlGZgpzvWAcU0LUx7Fw== dependencies: "@salesforce/core" "^9.0.0" "@salesforce/kit" "^4.0.0" From 886e19feecc9b9d0cea2558f0ce4e9c74e08a4aa Mon Sep 17 00:00:00 2001 From: Balaji Srinivasan Date: Wed, 25 Nov 2026 13:08:19 -0800 Subject: [PATCH 5/5] chore: regenerate agent test run schema for agents 2.6.0 (W-24861403) agents 2.6.0 dropped testCaseId from conversation test case results. Co-Authored-By: Claude Opus 5.5 --- schemas/agent-test-run.json | 4 ---- 1 file changed, 4 deletions(-) diff --git a/schemas/agent-test-run.json b/schemas/agent-test-run.json index 9c3355d1..25b02dd9 100644 --- a/schemas/agent-test-run.json +++ b/schemas/agent-test-run.json @@ -320,10 +320,6 @@ "type": "number", "description": "The 1-based `number` sent in the request." }, - "testCaseId": { - "type": "string", - "description": "Saved suites only." - }, "subjectResponse": { "type": "string", "description": "JSON string: the simulated conversation (turns, topics, actions, completion reason)."