From 8717f9398f8777ebafa9451750781a4972360feb Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:30:45 +0800 Subject: [PATCH] test(cli): verify process cleanup through owned scopes (#11893) --- src/cli/cliResources.ts | 8 --- src/cli/guidanceCommands.ts | 38 +++--------- src/cli/javascriptApplicationAnalysis.ts | 7 +-- .../cli/cliJavaScriptResourceClose.test.ts | 18 +++--- tests/boundary/cli/cliOwnedResources.test.ts | 9 --- tests/boundary/cli/cliResourceClose.test.ts | 62 +++++++++++++++---- tests/boundary/cli/dispatcher.test.ts | 2 +- 7 files changed, 72 insertions(+), 72 deletions(-) diff --git a/src/cli/cliResources.ts b/src/cli/cliResources.ts index 10b1a5f6f0..6735932426 100644 --- a/src/cli/cliResources.ts +++ b/src/cli/cliResources.ts @@ -7,10 +7,6 @@ export class CliResourceOwners { if (!this.#closers.has(name)) this.#closers.set(name, close); } - names(): readonly string[] { - return [...this.#closers.keys()]; - } - /** Settle every owner, then report each failure. */ async close(): Promise { const results = await Promise.allSettled( @@ -37,9 +33,5 @@ export const ownCliProcessResource = ( close: () => Promise, ): void => processOwners.own(name, close); -/** Owners registered in this process, in registration order. */ -export const cliProcessResourceOwners = (): readonly string[] => - processOwners.names(); - /** Close every process-owned resource used by CLI commands. */ export const closeCliResources = (): Promise => processOwners.close(); diff --git a/src/cli/guidanceCommands.ts b/src/cli/guidanceCommands.ts index 411dd35e42..7d95d7c9ba 100644 --- a/src/cli/guidanceCommands.ts +++ b/src/cli/guidanceCommands.ts @@ -18,39 +18,20 @@ import type { CliInstance } from "./types.js"; import { cliDecimalField } from "./options.js"; import { ownCliProcessResource } from "./cliResources.js"; -/** Guidance descriptors owned by one CLI host. */ -export class CliGuidanceResources { - #retained: ArtifactResourceScope | undefined; - - resources(): ArtifactResourceScope { - this.#retained ??= new ArtifactResourceScope(); - return this.#retained; - } - - /** Release this host's descriptors, retaining failed cleanup for retry. */ - async close(): Promise { - const resources = this.#retained; - if (resources === undefined) return; - await resources.close(); - if (this.#retained === resources) this.#retained = undefined; - } -} - -/** Process CLI host used when a caller does not pass its own resources. */ -const processGuidanceResources = new CliGuidanceResources(); +let retainedResources: ArtifactResourceScope | undefined; /** Release CLI-owned guidance descriptors, retaining failed cleanup for retry. */ -export const closeCliGuidanceResources = ( - resources: CliGuidanceResources = processGuidanceResources, -): Promise => resources.close(); - -ownCliProcessResource("guidance", () => closeCliGuidanceResources()); +ownCliProcessResource("guidance", async () => { + const resources = retainedResources; + if (resources === undefined) return; + await resources.close(); + if (retainedResources === resources) retainedResources = undefined; +}); /** Register offline search and retrieval for the installed REA guide bundle. */ export const registerGuidanceCommands = ( cli: CliInstance, logger: Logger, - resources: CliGuidanceResources = processGuidanceResources, ): void => { registerCliCommand( cli, @@ -114,6 +95,7 @@ export const registerGuidanceCommands = ( }), run: ({ options }) => logCliCommand(logger, CLI_COMMANDS.guidance, async () => { + const resources = (retainedResources ??= new ArtifactResourceScope()); const result = options.action === "search" ? await searchGuidance( @@ -128,13 +110,13 @@ export const registerGuidanceCommands = ( ? {} : { cursor: options.cursor }), }, - resources.resources(), + resources, ) : await readGuidanceSection( { locator: options.locator, }, - resources.resources(), + resources, ); return result.ok ? result.value : projectAnalysisError(result.error); }), diff --git a/src/cli/javascriptApplicationAnalysis.ts b/src/cli/javascriptApplicationAnalysis.ts index ff457ca9e9..0bac06f769 100644 --- a/src/cli/javascriptApplicationAnalysis.ts +++ b/src/cli/javascriptApplicationAnalysis.ts @@ -95,13 +95,8 @@ export class CliJavaScriptAnalysisHost { /** Process CLI host used when a caller does not pass its own host. */ const processJavaScriptAnalysis = new CliJavaScriptAnalysisHost(); -/** Stop the process-owned JavaScript worker. */ -export const closeCliJavaScriptResources = ( - host: CliJavaScriptAnalysisHost = processJavaScriptAnalysis, -): Promise => host.close(); - ownCliProcessResource("javascript-analysis", () => - closeCliJavaScriptResources(), + processJavaScriptAnalysis.close(), ); /** Execute the shared CLI boundary for static JavaScript analysis. */ diff --git a/tests/boundary/cli/cliJavaScriptResourceClose.test.ts b/tests/boundary/cli/cliJavaScriptResourceClose.test.ts index 3d4df5a4d3..7c0140992e 100644 --- a/tests/boundary/cli/cliJavaScriptResourceClose.test.ts +++ b/tests/boundary/cli/cliJavaScriptResourceClose.test.ts @@ -3,8 +3,8 @@ import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; +import { closeCliResources } from "../../../src/cli/cliResources.js"; import { - closeCliJavaScriptResources, CliJavaScriptAnalysisHost, runCliJavaScriptApplicationAnalysis, } from "../../../src/cli/javascriptApplicationAnalysis.js"; @@ -14,7 +14,7 @@ const originalClose = ArtifactResourceScope.prototype.close; afterEach(async () => { ArtifactResourceScope.prototype.close = originalClose; - await closeCliJavaScriptResources(); + await closeCliResources(); }); /** Create the process-owned scope without starting a worker. */ @@ -96,6 +96,7 @@ it("retains completed JavaScript Evidence when cancellation arrives during final }); it("retries JavaScript worker shutdown when the first close fails", async () => { + await closeCliResources(); let calls = 0; ArtifactResourceScope.prototype.close = function ( this: ArtifactResourceScope, @@ -106,17 +107,16 @@ it("retries JavaScript worker shutdown when the first close fails", async () => }; await openCliScope(); - await expect(closeCliJavaScriptResources()).rejects.toThrow( - "worker still owned", - ); + await expect(closeCliResources()).rejects.toThrow("worker still owned"); expect(calls).toBe(1); - await closeCliJavaScriptResources(); + await closeCliResources(); expect(calls).toBe(2); - await closeCliJavaScriptResources(); + await closeCliResources(); expect(calls).toBe(2); }); it("shares one in-flight JavaScript worker shutdown between callers", async () => { + await closeCliResources(); let calls = 0; let release = (): void => {}; const gate = new Promise((resolve) => { @@ -131,8 +131,8 @@ it("shares one in-flight JavaScript worker shutdown between callers", async () = try { await openCliScope(); - const first = closeCliJavaScriptResources(); - const second = closeCliJavaScriptResources(); + const first = closeCliResources(); + const second = closeCliResources(); let secondSettled = false; void second.then(() => { secondSettled = true; diff --git a/tests/boundary/cli/cliOwnedResources.test.ts b/tests/boundary/cli/cliOwnedResources.test.ts index 6fef10e49a..f94ed2cff1 100644 --- a/tests/boundary/cli/cliOwnedResources.test.ts +++ b/tests/boundary/cli/cliOwnedResources.test.ts @@ -1,7 +1,6 @@ import { afterEach, expect, it, vi } from "vitest"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; -import { CliGuidanceResources } from "../../../src/cli/guidanceCommands.js"; import { CliJavaScriptAnalysisHost } from "../../../src/cli/javascriptApplicationAnalysis.js"; const originalClose = ArtifactResourceScope.prototype.close; @@ -11,14 +10,6 @@ afterEach(() => { vi.restoreAllMocks(); }); -it("keeps guidance descriptors on the host that created them", () => { - const first = new CliGuidanceResources(); - const second = new CliGuidanceResources(); - expect(first.resources()).toBe(first.resources()); - expect(second.resources()).toBe(second.resources()); - expect(first.resources()).not.toBe(second.resources()); -}); - it("does not share a JavaScript worker scope or its in-flight close", async () => { let release = (): void => {}; const gate = new Promise((resolve) => { diff --git a/tests/boundary/cli/cliResourceClose.test.ts b/tests/boundary/cli/cliResourceClose.test.ts index 1c35d824e5..35def5425d 100644 --- a/tests/boundary/cli/cliResourceClose.test.ts +++ b/tests/boundary/cli/cliResourceClose.test.ts @@ -1,9 +1,13 @@ import { expect, it, vi } from "vitest"; -import "../../../src/cli.js"; +import { createCli } from "../../../src/cli.js"; import { CliResourceOwners, - cliProcessResourceOwners, + closeCliResources, } from "../../../src/cli/cliResources.js"; +import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { registrationEnvironment } from "../../support/cli/registrationEnvironment.js"; +import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js"; it.each([ [false, false], @@ -37,12 +41,48 @@ it.each([ }, ); -it("registers every process-owned CLI resource the complete CLI loads", () => { - expect(cliProcessResourceOwners()).toEqual( - expect.arrayContaining([ - "javascript-analysis", - "guidance", - "mcp-registration", - ]), - ); -}); +it.each([ + { + name: "guidance", + args: ["guidance", "--query", "qzxv"], + exitCode: 0, + }, + { + name: "MCP registration", + args: [ + "mcp", + "add", + "--agent", + "fixture-not-a-client", + "--command", + "fixture-mcp", + ], + exitCode: 1, + }, +])( + "closes the resource scope acquired by $name", + async ({ args, exitCode }) => { + await closeCliResources(); + const home = await createTestTempDirectory("rea-cli-resource-close-"); + const cli = createCli(await registrationEnvironment(home)); + const runs = vi.spyOn(ArtifactResourceScope.prototype, "run"); + try { + const result = await serveInProcessCli(cli, [...args, "--json"]); + expect(result.exitCode, result.stdout).toBe(exitCode); + const scope = runs.mock.contexts.find( + (value): value is ArtifactResourceScope => + value instanceof ArtifactResourceScope, + ); + if (scope === undefined) + throw new Error("Expected command to enter its resource scope"); + await expect(scope.run(async () => "open")).resolves.toBe("open"); + await closeCliResources(); + await expect(scope.run(async () => "closed")).rejects.toMatchObject({ + reason: "unavailable", + }); + } finally { + runs.mockRestore(); + await closeCliResources(); + } + }, +); diff --git a/tests/boundary/cli/dispatcher.test.ts b/tests/boundary/cli/dispatcher.test.ts index 3278092eb0..527733b38e 100644 --- a/tests/boundary/cli/dispatcher.test.ts +++ b/tests/boundary/cli/dispatcher.test.ts @@ -515,7 +515,7 @@ describe("project-scoped Amp registration dispatch", () => { const installGuardRuntime = async (workspace: TestWorkspace) => installCliRuntime( workspace, - `export const closeCliJavaScriptResources = () => {}; export const createCli = () => ({ serve: (_args, options) => { options.stdout(${JSON.stringify(runtimeReached)}); } });\n`, + `export const closeCliResources = () => {}; export const createCli = () => ({ serve: (_args, options) => { options.stdout(${JSON.stringify(runtimeReached)}); } });\n`, ); workspaceCliTest( "rejects a real project-scoped Amp registration before the CLI runtime loads",