Skip to content

fix: return botVersionId when publish fails after the BotVersion commit @W-24949433@ - #398

Closed
nhalko-sf wants to merge 4 commits into
mainfrom
nh/W-24949433-publish-post-commit-error
Closed

nhalko-sf wants to merge 4 commits into
mainfrom
nh/W-24949433-publish-post-commit-error

Conversation

@nhalko-sf

@nhalko-sf nhalko-sf commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Follow-up to #350 (W-23735101).

publishAgentJson commits the new BotVersion in its first step (the POST to ai-agent/v1.1/authoring/agents[/<botId>/versions]). The steps after that can still throw: getBotVersion, retrieveAgentMetadata (agentRetrievalError) and deployAuthoringBundle (authoringBundleDeploymentError). When one does, sf agent publish authoring-bundle fails, and the error has no botId or botVersionId. Callers, including CI loops and coding agents, can't tell the version actually landed. They retry, and each retry creates another BotVersion.

Changes:

  • publishAgentJson: wraps the post-commit steps in a try/catch and rethrows through a new toPublishedAgentError. The rethrown error:
    • keeps the original error name, message and actions;
    • adds data.publishedAgent = { developerName, botId, botVersionId, versionNumber?, target?, failedStep }, where failedStep is botVersionLookup, retrieve or bundleDeploy;
    • puts an action first saying the agent is already published as version N and should not be republished. When the version is known, it names the <target> (<agent>.<version>) the bundle-meta.xml needs for a manual deploy, and it only mentions the retrieve step when retrieve wasn't skipped;
    • logs a debug line and sends agent_publish_post_commit_failed telemetry, both including failedStep.
  • deployAuthoringBundle: the <target> cleanup in the bundle-meta now runs in a finally. It no longer stays in local source when the deploy poll or listener throws. A failed cleanup write is logged at debug level and doesn't replace the deploy error.
  • New exported type PublishedAgentInfo. This is additive only. Its JSDoc notes that a missing data.publishedAgent doesn't prove nothing was committed, since a POST timeout can still follow a commit.

Nothing changes on the success path. Error names are the same, and with sf … --json, data and actions show up in the output automatically. plugin-agent and vscode-agents don't key on these error names, actions or data, so the change is non-breaking for them. (vscode-agents shows only .message, so VS Code users won't see the don't-republish action. Surfacing it there is a small follow-up, to be filed separately.)

Testing

  • yarn build and lint are clean.
  • mocha: 477 passing, 1 pending. That includes 6 new cases in test/agentPublisher.test.ts:
    • a retrieve failure after the commit keeps its name, message and actions, and gains data.publishedAgent, the don't-republish action and telemetry;
    • a getBotVersion failure reports the BotVersion Id without a versionNumber;
    • a bundle-deploy failure merges publishedAgent into the error's existing data;
    • a failure of the publish POST itself is left unannotated, because nothing was committed;
    • <target> is removed from the local bundle-meta even when the deploy poll throws;
    • a publish POST that rejects (4xx/5xx) is left unannotated and emits no telemetry.

The recovery action also names the target and skips the retrieve clause under skipRetrieve, both asserted in the existing cases. The cleanup-write failure path has no unit test, because the ESM writeFile import isn't practical to stub.

  • yarn test fails only in link-check, on external 403/429 responses for README and CODE_OF_CONDUCT links. That's unrelated to this change.

What issues does this PR fix or reference?

@W-24949433@ (child of W-23735101)

@nhalko-sf
nhalko-sf requested review from a team as code owners November 18, 2026 19:57
@salesforce-cla

Copy link
Copy Markdown

Thanks for the contribution! Unfortunately we can't verify the commit author(s): Nathan Halko <n***@s***.com>. One possible solution is to add that email to your GitHub account. Alternatively you can change your commits to another email and force push the change. After getting your commits associated with your GitHub account, refresh the status of this Pull Request.

@salesforce-cla

Copy link
Copy Markdown

Thanks for the contribution! Unfortunately we can't verify the commit author(s): Nathan Halko <n***@g***.com>. One possible solution is to add that email to your GitHub account. Alternatively you can change your commits to another email and force push the change. After getting your commits associated with your GitHub account, sign the Salesforce Inc. Contributor License Agreement and this Pull Request will be revalidated.

@nhalko-sf
nhalko-sf force-pushed the nh/W-24949433-publish-post-commit-error branch from 616a862 to 2150031 Compare November 18, 2026 22:39
@nhalko-sf
nhalko-sf force-pushed the nh/W-24949433-publish-post-commit-error branch from 2150031 to 8a625f7 Compare November 18, 2026 22:44
@salesforce-cla

Copy link
Copy Markdown

Thanks for the contribution! Before we can merge this, we need @nhalko-sf to sign the Salesforce Inc. Contributor License Agreement.

@nhalko-sf nhalko-sf left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pre-review, round 1 of 2 (an extra pair of eyes, not a gate). Verdict: approve with nits, no blockers.

The approach is sound. The try/catch covers exactly the steps after the commit (getBotVersion → retrieve → bundle deploy). That includes the plugin-agent scopedPostRetrieve/scopedPostDeploy listeners that throw from inside pollStatus, so those come back annotated too. A failure of the POST itself, or a response without ids, is correctly left alone. Error names and messages are unchanged, PublishedAgentInfo is additive, and the tests assert real behavior, including a failing telemetry listener. No secrets or tokens show up in logs or telemetry.

Main ask: make the recovery path actionable (inline 1). The <target> that the bundle deploy needs isn't surfaced anywhere, and the finally now strips it from local source.

General (no line anchor)

  1. Warning: an ambiguous POST failure is still unannotated. If the POST times out or gets a gateway 5xx after Core committed the BotVersion, a retry can still create a duplicate. Fixing that is out of scope, but please say in the PublishedAgentInfo JSDoc that a missing data.publishedAgent does not prove nothing was committed, or file a follow-up (e.g. re-query the latest BotVersion for botId after a POST timeout).
  2. Suggestion: how callers surface the error. plugin-agent rethrows unchanged, so data and actions should flow into --json output and under "Try this". Worth a quick NUT or manual check that data.publishedAgent really appears in sf agent publish authoring-bundle --json. vscode-agents (src/commands/publishAgent.ts L133-140) shows only sfError.message, so VS Code users won't see the don't-republish guidance. Please file and link the follow-up the PR body mentions.
  3. Backwards compatibility: OK. Names and messages are unchanged, and actions are only prepended. A non-object data moving under originalData is technically a shape change, but no post-commit error sets one today.

What's good: the commit boundary is exactly right; telemetry is guarded and that's tested; the <target> cleanup in finally fixes a real local-source pollution bug; and the tests assert the exact data, the action order and the telemetry payload.


# publishedBeforeFailureActions

The agent was already published to the org as %s before this step failed. Don't run the publish command again, because that creates another, duplicate version. Fix the cause of the error, then finish the step that failed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1. Warning: the recovery action isn't actionable on its own. "Fix the cause of the error, then finish the step that failed" doesn't say how. If the retrieve failed, the bundle deploy never ran. If the deploy failed, the new finally (scriptAgentPublisher.ts L340-345) has already removed <target> from the local bundle-meta. Either way, a manual sf project deploy start would deploy the bundle without <target>developerName.vN</target>, so it wouldn't be linked to the committed version. The user (or a coding agent) is likely to give up and republish, which is the duplicate this PR prevents.

Suggest naming the target in the action, and adding it to PublishedAgentInfo (e.g. target?: string, set once botVersion resolves) so --json callers can finish the job programmatically:

Suggested change
The agent was already published to the org as %s before this step failed. Don't run the publish command again, because that creates another, duplicate version. Fix the cause of the error, then finish the step that failed.
The agent was already published to the org as %s before this step failed. Don't run the publish command again, because that creates another, duplicate version. Fix the cause of the error, then finish the remaining steps: retrieve the agent metadata if that step failed, then deploy the authoring bundle with `<target>%s</target>` set in its bundle-meta.xml.

(This needs a second %s argument from toPublishedAgentError. Fall back to generic phrasing when botVersion is unresolved.)

Comment on lines +153 to 162
let botVersion: { developerName: string; versionNumber: number } | undefined;
try {
botVersion = await this.getBotVersion(response.botVersionId);
if (!this.skipRetrieve) {
await this.retrieveAgentMetadata(botVersion);
}
await this.deployAuthoringBundle(botVersion.developerName);
} catch (error) {
throw await this.toPublishedAgentError(error, response, botVersion);
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2. Suggestion: record which step failed. errName alone doesn't identify the stage. Deployment Failed can come from the plugin-agent scopedPostDeploy listener or from SDR, and getBotVersion reuses the deploy action text. Tracking a step ('botVersionLookup' | 'retrieve' | 'bundleDeploy') inside the try, and passing it to toPublishedAgentError for the telemetry event, the debug log and optionally data.publishedAgent.failedStep, would make agent_publish_post_commit_failed diagnosable. It would also let the action in comment 1 name the remaining steps exactly.

Comment on lines +340 to +345
} finally {
// 3.remove the target from the local authoring bundle meta.xml file, even if the deploy threw
// (poll timeout, a scopedPostDeploy listener), so it never lingers in local source
delete authoringBundle.AiAuthoringBundle.target;
await writeFile(this.bundleMetaPath, xmlBuilder.build(authoringBundle));
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3. Suggestion: a write failure in finally masks the deploy error. If writeFile throws here (EACCES, or the file is locked by an editor), it replaces the deploy/poll error. The replacement still gets the published annotation, but the root cause is lost. Consider a nested try/catch with a debug log:

Suggested change
} finally {
// 3.remove the target from the local authoring bundle meta.xml file, even if the deploy threw
// (poll timeout, a scopedPostDeploy listener), so it never lingers in local source
delete authoringBundle.AiAuthoringBundle.target;
await writeFile(this.bundleMetaPath, xmlBuilder.build(authoringBundle));
}
} finally {
// 3.remove the target from the local authoring bundle meta.xml file, even if the deploy threw
// (poll timeout, a scopedPostDeploy listener), so it never lingers in local source
delete authoringBundle.AiAuthoringBundle.target;
try {
await writeFile(this.bundleMetaPath, xmlBuilder.build(authoringBundle));
} catch (cleanupError) {
getLogger().debug('Failed to remove target from authoring bundle meta.xml', {
bundleMetaPath: this.bundleMetaPath,
errMsg: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
});
}
}

(Trade-off: swallowing the error means a <target> can still linger silently. A debug log plus an appended action may be the better balance.)

Comment on lines +394 to +408
it('should not annotate errors when the publish POST itself fails', async () => {
process.env.SF_MOCK_DIR = join('test', 'mocks', 'publishAgentJson-Error');
$$.SANDBOX.stub(connection, 'singleRecordQuery')
.withArgs("SELECT Id FROM BotDefinition WHERE DeveloperName='test_agent'")
.throws(new SfError('No record found', 'SingleRecordQuery_NoRecords'));
const telemetryStub = $$.SANDBOX.stub(Lifecycle.getInstance(), 'emitTelemetry').resolves();

publisher = new ScriptAgentPublisher(connection, sfProject, agentJson, false);

const error = await expectPublishError();

expect(error.name).to.equal('CreateAgentJsonError');
expect(error.data).to.not.have.property('publishedAgent');
expect(telemetryStub.called).to.be.false;
});

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4. Suggestion: this test covers a response without ids, not a POST that throws. The publishAgentJson-Error mock returns a body without botId/botVersionId, so it exercises the CreateAgentJsonError branch. Please add a case where the request rejects (HTTP 4xx/5xx thrown by MaybeMock.request) and assert there's no publishedAgent and no telemetry, so both pre-commit shapes are pinned down.

…e failed step @W-24949433@

Address pre-review round 1: add target and failedStep to PublishedAgentInfo, name the
<target> in the recovery action, tolerate a failed bundle-meta cleanup, document that a
missing publishedAgent is not proof nothing was committed, and test a rejecting POST.

@nhalko-sf nhalko-sf left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pre-review, round 2 of 2 (an extra pair of eyes, not a gate). Verdict: approve. There are no blockers and one optional nit (inline).

84ef183 fixes all round-1 findings. The <target> value matches deployAuthoringBundle (${developerName}.${botVersionName}).

# Round-1 finding Status
1 The recovery action wasn't actionable (name <target>) Fixed: target is now on PublishedAgentInfo, there's a target-specific message plus a generic fallback, and both are tested
2 Record which step failed Fixed: failedStep is in the data, the debug log and telemetry, and is tested for all three steps
3 writeFile in finally masks the deploy error Fixed: it's now in a nested try/catch, and a test covers the poll throwing
4 No test for a rejecting POST Fixed
5 Ambiguous POST failure not annotated Fixed: JSDoc says to re-query the latest BotVersion before retrying
6 How callers surface the error Out of scope here. The vscode-agents UI still shows only sfError.message, so it needs its own follow-up item

General (no line anchor)

  • Cleanup failure: if the cleanup writeFile itself fails, <target> stays in local source with only a debug log. That's acceptable, since the recovery action tells the user to set it anyway, but that branch has no test.
  • --json output: whether data.publishedAgent reaches sf agent publish --json output can only be checked in plugin-agent.
  • CI: the unit-test jobs were still running at review time. The other checks, including CLA, pass.


# publishedBeforeFailureTargetActions

The agent was already published to the org as %s before this step failed. Don't run the publish command again, because that creates another, duplicate version. Fix the cause of the error, then finish the remaining steps: retrieve the agent metadata if that step failed, then deploy the authoring bundle with `<target>%s</target>` set in its bundle-meta.xml. Without the target, the bundle isn't linked to the version that was already published.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): this message always says "retrieve the agent metadata if that step failed", even when the publisher ran with skipRetrieve and no retrieve happened. failedStep already tells callers which step failed, so it's only wording. Consider dropping the retrieve clause when the retrieve was skipped.

@nhalko-sf

Copy link
Copy Markdown
Collaborator Author

Moved to a fork so it can be merged: replaced by #403 (same commits, head 21979f2). Closing this one.

@nhalko-sf nhalko-sf closed this Nov 20, 2026
@nhalko-sf
nhalko-sf deleted the nh/W-24949433-publish-post-commit-error branch November 20, 2026 20:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants