From 4bbaf175121f101b319cd8aa0b4d47d3f40d5862 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:40:10 -0500 Subject: [PATCH] refactor: centralize owned finalization and configuration failures (#14071) * refactor(config): propagate typed configuration failures * refactor(lifecycle): centralize completion and cancellation * fix(config): preserve Hermes YAML edit refusal guidance --- docs/development/tool-design.md | 4 + .../baselines/cleanup-dependency-binding.json | 1 - .../completed-abort-reclassification.json | 17 - .../hand-caught-configuration-error.json | 9 - src/application/AnalysisInput.ts | 2 +- ...ientConfigurationDocument.capacity.test.ts | 42 +- ...onfigurationDocument.jsonRetention.test.ts | 11 +- ...figurationDocument.repeatedMembers.test.ts | 9 +- .../ClientConfigurationDocument.shape.test.ts | 44 +- ...ConfigurationDocument.tomlComments.test.ts | 24 +- .../ClientConfigurationDocument.ts | 80 +- .../ClientConfigurationFiles.test.ts | 17 +- src/application/ClientConfigurationFiles.ts | 33 +- .../ClientConfigurationPublication.ts | 32 +- src/application/ClientPrivateProfile.ts | 7 +- src/application/ClientRegistration.test.ts | 11 +- src/application/DshCordisPatch.ts | 40 +- src/application/DshCordisYaml.ts | 15 +- src/application/EvidenceInputResolver.ts | 5 +- src/application/GooseConfigurationYaml.ts | 24 +- .../HermesConfigurationYaml.test.ts | 7 +- src/application/HermesConfigurationYaml.ts | 13 +- src/application/KiloClientLocation.ts | 156 ++-- .../McpClientRegistration.layers.test.ts | 15 +- src/application/McpClientRegistration.ts | 127 +-- src/application/McpRegistrationCatalog.ts | 220 ++--- .../McpRegistrationConfiguration.ts | 235 ++++-- src/application/McpRegistrationGit.test.ts | 3 +- .../McpRegistrationKiloLocations.ts | 108 ++- src/application/McpRegistrationLocations.ts | 48 +- src/application/SetupClientConfiguration.ts | 413 +++++---- src/application/SetupClients.ts | 1 + src/application/SetupTypes.ts | 2 +- src/application/SupportedClientLocations.ts | 10 +- src/application/SupportedClients.ts | 4 +- src/application/Uninstall.ts | 149 ++-- src/application/WebScriptExportService.ts | 3 +- src/application/binary/BinarySession.ts | 34 +- src/browser/CdpBrowserProvider.ts | 230 +++-- src/browser/CdpElectronProvider.ts | 202 ++--- .../PlaywrightBrowserScenarioProvider.ts | 216 +++-- .../execution/CdpWebRuntimeProvider.ts | 97 +-- .../history/HistoricalCaptureDecoder.ts | 796 +++++++++--------- src/cli/cliJsonInput.ts | 30 +- src/config/mcpStartupPolicy.test.ts | 27 +- src/config/windowsChangeTimeSettle.ts | 10 +- src/domain/analysisErrorCleanup.ts | 17 +- src/evm/EvmoleInterfaceProvider.ts | 109 ++- src/ghidra/GhidraClient.ts | 27 +- src/ghidra/GhidraClientWire.test.ts | 1 + src/ghidra/GhidraClientWire.ts | 4 +- src/ghidra/GhidraProvider.behavior.test.ts | 2 +- src/ghidra/GhidraSessionError.ts | 13 +- src/ghidra/GhidraSessionErrorProjection.ts | 3 +- src/hopper/HopperClient.ts | 23 +- src/hopper/HopperMachOImage.ts | 133 +-- src/ida/IdaConfiguration.test.ts | 57 +- src/ida/IdaConfiguration.ts | 26 +- src/native/pwntools/PwntoolsDecoder.ts | 38 +- src/process/AbortablePromise.ts | 11 + src/process/ProviderDeadline.test.ts | 24 + src/process/ProviderDeadline.ts | 11 + src/providers/runOwned.ts | 95 ++- src/reference/ReferenceSourceReaderEntries.ts | 17 +- src/sqlite/SqliteDatabaseProvider.ts | 171 ++-- .../registrationRuntimeEnvironmentCli.test.ts | 30 +- .../setup/selectedClientHomePaths.test.ts | 6 +- .../browser/cdpElectronProvider.test.ts | 5 +- .../evm/evmoleInterfaceProvider.test.ts | 3 + .../filesystem/clientConfigurationBom.test.ts | 26 +- .../clientConfigurationEnvironment.test.ts | 173 ++-- ...entConfigurationLayeredEnvironment.test.ts | 41 +- .../clientRegistrationRefresh.test.ts | 4 +- .../hermesClientConfiguration.test.ts | 4 +- .../filesystem/mcpAddClientLifecycle.test.ts | 13 +- .../opencodeLayeredUninstall.test.ts | 9 +- .../filesystem/piClientConfiguration.test.ts | 22 +- .../referenceSourceCleanupOwnership.test.ts | 15 +- .../sqlite/sqliteDatabaseProvider.test.ts | 6 + .../setupPolicySnapshot.test.ts | 37 + tests/support/expectResultValue.ts | 10 + 81 files changed, 2667 insertions(+), 2102 deletions(-) delete mode 100644 scripts/verify/baselines/completed-abort-reclassification.json delete mode 100644 scripts/verify/baselines/hand-caught-configuration-error.json create mode 100644 tests/support/expectResultValue.ts diff --git a/docs/development/tool-design.md b/docs/development/tool-design.md index 4d70199b9e3..0a8710e1835 100644 --- a/docs/development/tool-design.md +++ b/docs/development/tool-design.md @@ -594,6 +594,10 @@ failed request's physical, cancellation and cleanup facts. cancellation before commit keeps the completed value as a partial observation, cancellation after commit keeps the value, and unconfirmed cleanup reports `cleanup_incomplete` while keeping the completed value. + SQLite keeps a failed close primary when cancellation arrives during that + close, and retains the caller's cancellation as a secondary failure. + Startup deadlines own the readiness cutoff for sessions that remain open + after a successful handshake. - Give descriptor-backed reads an owner before opening the file. A rejected close must retain the exact handle and preserve any earlier failure. Carry [`openRegularFile`](https://github.com/morluto/rea/blob/main/src/filesystem/RegularFile.ts)'s diff --git a/scripts/verify/baselines/cleanup-dependency-binding.json b/scripts/verify/baselines/cleanup-dependency-binding.json index fd88932bf8e..355a8434c24 100644 --- a/scripts/verify/baselines/cleanup-dependency-binding.json +++ b/scripts/verify/baselines/cleanup-dependency-binding.json @@ -5,7 +5,6 @@ "src/application/binary/CompositeProvider.ts": 1, "src/application/desktop/DesktopApplicationExport.ts": 2, "src/application/frida/FridaInstrumentationService.ts": 2, - "src/browser/PlaywrightBrowserScenarioProvider.ts": 1, "src/browser/WebSourceMapFetcher.ts": 2, "src/domain/explicitSensitiveFailure.ts": 1, "src/evm/EvmoleInterfaceProvider.ts": 3, diff --git a/scripts/verify/baselines/completed-abort-reclassification.json b/scripts/verify/baselines/completed-abort-reclassification.json deleted file mode 100644 index 101973cfc48..00000000000 --- a/scripts/verify/baselines/completed-abort-reclassification.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "src/application/EvidenceInputResolver.ts": 1, - "src/application/binary/BinarySession.ts": 1, - "src/browser/CdpBrowserProvider.ts": 1, - "src/browser/CdpElectronProvider.ts": 1, - "src/browser/PlaywrightBrowserScenarioProvider.ts": 1, - "src/browser/execution/CdpWebRuntimeProvider.ts": 1, - "src/browser/history/HistoricalCaptureDecoder.ts": 1, - "src/cli/cliJsonInput.ts": 1, - "src/evm/EvmoleInterfaceProvider.ts": 1, - "src/ghidra/GhidraClient.ts": 1, - "src/hopper/HopperClient.ts": 2, - "src/hopper/HopperMachOImage.ts": 1, - "src/native/pwntools/PwntoolsDecoder.ts": 1, - "src/reference/ReferenceSourceReaderEntries.ts": 1, - "src/sqlite/SqliteDatabaseProvider.ts": 1 -} diff --git a/scripts/verify/baselines/hand-caught-configuration-error.json b/scripts/verify/baselines/hand-caught-configuration-error.json deleted file mode 100644 index 00b0ec50432..00000000000 --- a/scripts/verify/baselines/hand-caught-configuration-error.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "src/application/KiloClientLocation.ts": 1, - "src/application/McpClientRegistration.ts": 1, - "src/application/McpRegistrationCatalog.ts": 1, - "src/application/SetupClientConfiguration.ts": 5, - "src/application/Uninstall.ts": 2, - "src/application/WebScriptExportService.ts": 1, - "src/ghidra/GhidraSessionErrorProjection.ts": 1 -} diff --git a/src/application/AnalysisInput.ts b/src/application/AnalysisInput.ts index 24ddf4c4664..003bedb20c9 100644 --- a/src/application/AnalysisInput.ts +++ b/src/application/AnalysisInput.ts @@ -35,5 +35,5 @@ export const parseAnalysisInput = ( cause: input.error, }), ); - return ok(input.data); + return signal?.aborted ? err(cancelledBy(operation, signal)) : ok(input.data); }; diff --git a/src/application/ClientConfigurationDocument.capacity.test.ts b/src/application/ClientConfigurationDocument.capacity.test.ts index b873539c8f7..19676f7e2af 100644 --- a/src/application/ClientConfigurationDocument.capacity.test.ts +++ b/src/application/ClientConfigurationDocument.capacity.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { describe, expect, it } from "vitest"; @@ -33,7 +34,9 @@ describe("TOML configuration source capacity", () => { "\n", newline, ); - const parsed = parseClientConfiguration(original, "toml"); + const parsed = expectResultValue( + parseClientConfiguration(original, "toml"), + ); const desired = withClientServers( parsed, { @@ -46,9 +49,10 @@ describe("TOML configuration source capacity", () => { expect( configured.startsWith("\uFEFF" + prefix.replaceAll("\n", newline)), ).toBe(true); - expect(parseClientConfiguration(configured, "toml").document).toEqual( - desired, - ); + expect( + expectResultValue(parseClientConfiguration(configured, "toml")) + .document, + ).toEqual(desired); const removed = serializedText( withClientServers(parsed, {}, HOST_PLATFORM.platform), "toml", @@ -56,16 +60,18 @@ describe("TOML configuration source capacity", () => { ); const expectedForeignDocument = { ...parsed.document }; delete expectedForeignDocument.mcp_servers; - expect(parseClientConfiguration(removed, "toml").document).toEqual( - expectedForeignDocument, - ); + expect( + expectResultValue(parseClientConfiguration(removed, "toml")).document, + ).toEqual(expectedForeignDocument); }, ); it("retains a large multiline foreign value inside an inline server table", () => { const note = `first\n${"x\n".repeat(500_000)}last`; const original = `mcp_servers = { other = {command="other",env={NOTE="""${note}"""}}}\n`; - const parsed = parseClientConfiguration(original, "toml"); + const parsed = expectResultValue( + parseClientConfiguration(original, "toml"), + ); const desired = withClientServers( parsed, { @@ -76,14 +82,14 @@ describe("TOML configuration source capacity", () => { ); const configured = serializedText(desired, "toml", original); expect(configured).toContain(`NOTE="""${note}"""`); - expect(parseClientConfiguration(configured, "toml").document).toEqual( - desired, - ); + expect( + expectResultValue(parseClientConfiguration(configured, "toml")).document, + ).toEqual(desired); const removed = serializedText(parsed.document, "toml", configured); expect(removed).toContain(`NOTE="""${note}"""`); - expect(parseClientConfiguration(removed, "toml").document).toEqual( - parsed.document, - ); + expect( + expectResultValue(parseClientConfiguration(removed, "toml")).document, + ).toEqual(parsed.document); }); it("removes only REA from a large multiline Grok disabled-server list", () => { @@ -91,7 +97,9 @@ describe("TOML configuration source capacity", () => { const original = `disabled_mcp_servers = [\n"rea",\n${otherNames}]\n` + '[mcp_servers.other]\ncommand = "other"\n'; - const parsed = parseClientConfiguration(original, "grok"); + const parsed = expectResultValue( + parseClientConfiguration(original, "grok"), + ); const desired = withClientServers( parsed, { @@ -101,7 +109,9 @@ describe("TOML configuration source capacity", () => { HOST_PLATFORM.platform, ); const configured = serializedText(desired, "grok", original); - const result = parseClientConfiguration(configured, "grok"); + const result = expectResultValue( + parseClientConfiguration(configured, "grok"), + ); expect(result.document.disabled_mcp_servers).toEqual( Array(500_000).fill("other"), ); diff --git a/src/application/ClientConfigurationDocument.jsonRetention.test.ts b/src/application/ClientConfigurationDocument.jsonRetention.test.ts index 94a20e3e53d..2173ef93ab9 100644 --- a/src/application/ClientConfigurationDocument.jsonRetention.test.ts +++ b/src/application/ClientConfigurationDocument.jsonRetention.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { expect, it } from "vitest"; @@ -10,7 +11,7 @@ import { } from "./ClientConfigurationDocument.js"; const replaceLauncher = (source: string, format: ClientConfigurationFormat) => { - const parsed = parseClientConfiguration(source, format); + const parsed = expectResultValue(parseClientConfiguration(source, format)); const existing = parsed.servers.rea; if (typeof existing !== "object" || existing === null) throw new Error("fixture registration missing"); @@ -62,7 +63,7 @@ it("keeps the exact JSONC source outside the changed launcher value", () => { it("retains nested array tokens while changing siblings, shrinking and extending arrays", () => { const source = `{"mcpServers":{"rea":{"command":"rea","items":[{"opaque":9007199254740993,"label":"old"},2,3],"grow":[9007199254740993]}}}`; - const parsed = parseClientConfiguration(source, "json"); + const parsed = expectResultValue(parseClientConfiguration(source, "json")); const result = serializeClientConfiguration( withClientServers( parsed, @@ -89,7 +90,7 @@ it("retains nested array tokens while changing siblings, shrinking and extending it("retains source tokens when the caller supplies a whole edited document", () => { const source = `{"opaque":9007199254740993,"mcpServers":{"rea":{"command":"old"}}}`; - const parsed = parseClientConfiguration(source, "fx"); + const parsed = expectResultValue(parseClientConfiguration(source, "fx")); const result = serializeClientConfiguration( withClientServers( parsed, @@ -106,7 +107,7 @@ it("retains source tokens when the caller supplies a whole edited document", () it("removes all repeated nested fields without activating an earlier value", () => { const source = `{"mcpServers":{"rea":{"remove":1,"remove":2,"retain":9007199254740993,"command":"old"}}}`; - const parsed = parseClientConfiguration(source, "json"); + const parsed = expectResultValue(parseClientConfiguration(source, "json")); const result = serializeClientConfiguration( withClientServers( parsed, @@ -134,7 +135,7 @@ it("removes all repeated nested fields without activating an earlier value", () it("keeps native JSON separators valid across replaced and emptied collections", () => { const source = `{"mcpServers":{"rea":{"replace":{"old":1,},"empty":{"old":2,},"shrink":[1,2,],"clear":[3,4,],}}}`; - const parsed = parseClientConfiguration(source, "fx"); + const parsed = expectResultValue(parseClientConfiguration(source, "fx")); const rea = { replace: { replacement: true }, empty: {}, diff --git a/src/application/ClientConfigurationDocument.repeatedMembers.test.ts b/src/application/ClientConfigurationDocument.repeatedMembers.test.ts index 7b04c4b9389..685ca9d6047 100644 --- a/src/application/ClientConfigurationDocument.repeatedMembers.test.ts +++ b/src/application/ClientConfigurationDocument.repeatedMembers.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { describe, expect, it } from "vitest"; import { parse as parseJsonc, type ParseError } from "jsonc-parser"; @@ -19,7 +20,7 @@ const removeRea = ( format: ClientConfigurationFormat, options?: ClientConfigurationEditOptions, ) => { - const parsed = parseClientConfiguration(text, format); + const parsed = expectResultValue(parseClientConfiguration(text, format)); const { rea: _removed, ...remaining } = parsed.servers; return serializeClientConfiguration( withClientServers(parsed, remaining, HOST_PLATFORM.platform), @@ -51,7 +52,9 @@ describe("JSON client configuration repeated-member edits", () => { `"rea":${JSON.stringify(owned)},` + `"other":{"args":[1,2]},` + `"rea":${JSON.stringify(owned)}}}`; - const parsed = parseClientConfiguration(text, "claude_code"); + const parsed = expectResultValue( + parseClientConfiguration(text, "claude_code"), + ); const path = clientServerPath(parsed, "rea"); const result = removeRea(text, "claude_code", { removeShadowedMembersAt: [path], @@ -69,7 +72,7 @@ describe("JSON client configuration repeated-member edits", () => { it("does not apply repeat-removal authority to a different path", () => { const text = `{"mcpServers":{"rea":1,"rea":2,"peer":3,"peer":4}}`; - const parsed = parseClientConfiguration(text, "json"); + const parsed = expectResultValue(parseClientConfiguration(text, "json")); const document = withClientServers(parsed, {}, HOST_PLATFORM.platform); const result = serializeClientConfiguration( document, diff --git a/src/application/ClientConfigurationDocument.shape.test.ts b/src/application/ClientConfigurationDocument.shape.test.ts index 6e63867dd9b..7e4a5b6c596 100644 --- a/src/application/ClientConfigurationDocument.shape.test.ts +++ b/src/application/ClientConfigurationDocument.shape.test.ts @@ -1,7 +1,7 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { describe, expect, it } from "vitest"; import { - ClientConfigurationShapeError, clientConfigurationSyntaxName, parseClientConfiguration, shadowedClientServers, @@ -16,16 +16,11 @@ describe("parseClientConfiguration shape diagnostics", () => { ["array server table", '{"mcpServers":[],"keep":1}', "mcpServers"], ["string server table", '{"mcpServers":"x","keep":1}', "mcpServers"], ])("reports a non-object %s", (_label, text, location) => { - let error: unknown; - try { - parseClientConfiguration(text, "json"); - } catch (cause: unknown) { - error = cause; - } - expect(error).toBeInstanceOf(ClientConfigurationShapeError); - if (!(error instanceof Error)) throw new Error("Expected shape error"); - expect(error.message).toContain(location); - expect(error.message).toContain("object"); + const result = parseClientConfiguration(text, "json"); + expect(result).toMatchObject({ ok: false, error: { kind: "shape" } }); + if (result.ok) throw new Error("Expected shape error"); + expect(result.error.detail).toContain(location); + expect(result.error.detail).toContain("object"); }); // The diagnostic syntax name must describe what the reader actually admits. @@ -49,14 +44,8 @@ describe("parseClientConfiguration shape diagnostics", () => { ["hermes", "YAML"], ] as const)("names %s configuration syntax %s", (format, name) => { expect(clientConfigurationSyntaxName(format)).toBe(name); - const accepts = (text: string): boolean => { - try { - parseClientConfiguration(text, format); - return true; - } catch { - return false; - } - }; + const accepts = (text: string): boolean => + parseClientConfiguration(text, format).ok; if (name === "TOML") expect(accepts("keep = 1\n")).toBe(true); if (name === "YAML") expect(accepts("keep: 1\n")).toBe(true); if (name === "JSON" || name === "JSONC") { @@ -66,16 +55,19 @@ describe("parseClientConfiguration shape diagnostics", () => { } }); - it("still rejects unparsable JSON with SyntaxError", () => { - expect(() => parseClientConfiguration("not-json", "json")).toThrow( - SyntaxError, - ); + it("reports the syntax failure for unparsable JSON", () => { + expect(parseClientConfiguration("not-json", "json")).toMatchObject({ + ok: false, + error: { kind: "syntax", cause: expect.any(SyntaxError) }, + }); }); it("reports only duplicates in the effective server object", () => { const owned = '{"command":"rea","args":["mcp"]}'; const activeTable = `{"mcpServers":{"rea":null,"rea":${owned}}}`; - const active = parseClientConfiguration(activeTable, "json"); + const active = expectResultValue( + parseClientConfiguration(activeTable, "json"), + ); expect(shadowedClientServers(activeTable, active, "rea")).toEqual({ servers: [null], legacyServers: [], @@ -86,7 +78,9 @@ describe("parseClientConfiguration shape diagnostics", () => { const inactiveParent = `{"mcpServers":{"rea":{"command":"/usr/bin/false"}},` + `"mcpServers":{"rea":${owned}}}`; - const parsed = parseClientConfiguration(inactiveParent, "json"); + const parsed = expectResultValue( + parseClientConfiguration(inactiveParent, "json"), + ); expect(shadowedClientServers(inactiveParent, parsed, "rea")).toEqual({ servers: [], legacyServers: [], diff --git a/src/application/ClientConfigurationDocument.tomlComments.test.ts b/src/application/ClientConfigurationDocument.tomlComments.test.ts index 856689df051..891208655a7 100644 --- a/src/application/ClientConfigurationDocument.tomlComments.test.ts +++ b/src/application/ClientConfigurationDocument.tomlComments.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { expect, it } from "vitest"; @@ -34,7 +35,7 @@ it.each([ "keeps real comments through %s %j %s", (format, lineBreak, operation) => { const source = original.replaceAll("\n", lineBreak); - const parsed = parseClientConfiguration(source, format); + const parsed = expectResultValue(parseClientConfiguration(source, format)); const other = { command: "other" }; const servers = operation === "replace" @@ -64,7 +65,10 @@ it.each([ "literal # value token", ]) expect(result.value).not.toContain(stringContent); - expect(parseClientConfiguration(result.value, format).document).toEqual({ + expect( + expectResultValue(parseClientConfiguration(result.value, format)) + .document, + ).toEqual({ root: "retained # root string", mcp_servers: servers, }); @@ -78,7 +82,7 @@ it("retains comments from dotted REA assignments and nested inline values", () = 'mcp_servers.rea.command = "old # string token" # dotted note\n', 'mcp_servers = { rea = { args = ["old # string token", # inline value note\n] }, other = { command = "other" } }\n', ]) { - const parsed = parseClientConfiguration(source, "toml"); + const parsed = expectResultValue(parseClientConfiguration(source, "toml")); const { rea: removed, ...servers } = parsed.servers; expect(removed).toBeDefined(); const result = serializeClientConfiguration( @@ -95,9 +99,9 @@ it("retains comments from dotted REA assignments and nested inline values", () = expect(result.value).not.toContain("# string token"); if (source.includes("# inline value note")) expect(result.value.split("\n")[0]).not.toContain("# inline value note"); - expect(parseClientConfiguration(result.value, "toml").servers).toEqual( - servers, - ); + expect( + expectResultValue(parseClientConfiguration(result.value, "toml")).servers, + ).toEqual(servers); } }); @@ -106,7 +110,7 @@ it.each(["toml", "grok"] as const)( (format) => { const source = 'mcp_servers = { rea = { command = "old", large = 1e20, exact = 9007199254740992.0, limit = inf, floor = -inf, unknown = nan, zero = -0.0, date = 2026-11-10, clock = 12:34:56, local = 2026-11-10T12:34:56, offset = 2026-11-10T12:34:56-05:00 }, peer = { command = "peer" } } # retained\n'; - const parsed = parseClientConfiguration(source, format); + const parsed = expectResultValue(parseClientConfiguration(source, format)); const previous = parsed.servers.rea as Record; const servers = { ...parsed.servers, @@ -118,9 +122,9 @@ it.each(["toml", "grok"] as const)( source, ); if (!result.ok) throw new Error("TOML edit was refused"); - expect(parseClientConfiguration(result.value, format).servers).toEqual( - servers, - ); + expect( + expectResultValue(parseClientConfiguration(result.value, format)).servers, + ).toEqual(servers); expect(result.value).toContain("# retained"); }, ); diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts index b38b7c2dddb..0fce94d738a 100644 --- a/src/application/ClientConfigurationDocument.ts +++ b/src/application/ClientConfigurationDocument.ts @@ -1,9 +1,11 @@ +import { CordisDocumentError } from "./DshCordisYaml.js"; import { parseClientToml, serializeCodexConfiguration, serializeGrokConfiguration, } from "./ClientConfigurationToml.js"; import { + GooseConfigurationYamlError, parseGooseConfigurationYaml, stringifyGooseConfigurationYaml, editGooseConfigurationYaml, @@ -17,6 +19,7 @@ import { } from "./DshCordisPatch.js"; import { editHermesConfigurationYaml, + HermesConfigurationEditError, parseHermesConfigurationYaml, stringifyHermesConfigurationYaml, } from "./HermesConfigurationYaml.js"; @@ -35,6 +38,7 @@ import { import { z } from "zod"; import { err, ok, type Result } from "../domain/result.js"; +import { errorMessage } from "../kernel/errorMessage.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import type { SetupClient } from "./SupportedClients.js"; import { @@ -276,7 +280,7 @@ const parseDocument = ( }; /** A parsed configuration whose structure, not its syntax, cannot hold MCP servers. */ -export class ClientConfigurationShapeError extends TypeError {} +class ClientConfigurationShapeError extends TypeError {} /** Validate source mappings and copy their own properties without rewriting values. */ const requireObject = ( @@ -291,7 +295,7 @@ const requireObject = ( }; /** ZCode reads the same-scope fallback as strict JSON with a mcpServers table. */ -export const parseZcodeFallbackConfiguration = ( +const parseZcodeFallbackConfiguration = ( text: string, ): ClientConfigurationDocument => { const { document } = parseDocument( @@ -327,12 +331,10 @@ const fxConfigurationServersKey = ( return legacy ? "mcp" : "mcpServers"; }; -export const parseClientConfiguration = ( +const readClientDocument = ( text: string, - format: ClientConfigurationFormat | undefined, + format: Exclude, ): ClientConfigurationDocument => { - if (format === undefined || format === "unsupported") - throw new TypeError("client does not have a supported MCP config format"); // DeepSeek Harness stores a Cordis patch list, not a server table. if (format === "zcode_fallback") return parseZcodeFallbackConfiguration(text); if (format === "dsh") return parseDshCordisDocument(text); @@ -434,6 +436,53 @@ export const parseClientConfiguration = ( }; }; +type NativeDocumentError = + | CordisDocumentError + | GooseConfigurationYamlError + | HermesConfigurationEditError; + +interface NativeDocumentFailure { + readonly kind: "document"; + readonly detail: string; + readonly cause: NativeDocumentError; +} + +const isNativeDocumentError = (cause: unknown): cause is NativeDocumentError => + cause instanceof CordisDocumentError || + cause instanceof GooseConfigurationYamlError || + cause instanceof HermesConfigurationEditError; + +export type ClientConfigurationParseFailure = + | NativeDocumentFailure + | { + readonly kind: "unsupported" | "syntax" | "shape"; + readonly detail: string; + readonly cause?: unknown; + }; + +/** Parse one native client document and retain its failure at the format boundary. */ +export const parseClientConfiguration = ( + text: string, + format: ClientConfigurationFormat | undefined, +): Result => { + if (format === undefined || format === "unsupported") + return err({ + kind: "unsupported", + detail: "client does not have a supported MCP config format", + }); + try { + return ok(readClientDocument(text, format)); + } catch (cause: unknown) { + if (isNativeDocumentError(cause)) + return err({ kind: "document", detail: cause.message, cause }); + return err({ + kind: cause instanceof ClientConfigurationShapeError ? "shape" : "syntax", + detail: errorMessage(cause), + cause, + }); + } +}; + /** Interpret activation in the authored dialect and preserve malformed values. */ export const openCodeDisabled = ( { enabled, disabled }: Record, @@ -951,7 +1000,7 @@ export interface ClientConfigurationEditOptions { * Serialize a validated client document, retaining JSONC and TOML comments. * JSON edits fail only when they would activate a shadowed duplicate member. */ -export const serializeClientConfiguration = ( +const editClientDocument = ( document: Record, format: ClientConfigurationFormat | undefined, originalText?: string, @@ -1010,6 +1059,23 @@ export const serializeClientConfiguration = ( ); }; +export type ClientConfigurationEditFailure = + | ClientConfigurationShadowedMember + | NativeDocumentFailure + | { readonly kind: "serialize"; readonly cause: unknown }; + +export const serializeClientConfiguration = ( + ...args: Parameters +): Result => { + try { + return editClientDocument(...args); + } catch (cause: unknown) { + return isNativeDocumentError(cause) + ? err({ kind: "document", detail: cause.message, cause }) + : err({ kind: "serialize", cause }); + } +}; + /** Key path of a named registration in the server table. */ export const clientServerPath = ( parsed: ClientConfigurationDocument, diff --git a/src/application/ClientConfigurationFiles.test.ts b/src/application/ClientConfigurationFiles.test.ts index 7c7d3d24d4b..e942bcfca39 100644 --- a/src/application/ClientConfigurationFiles.test.ts +++ b/src/application/ClientConfigurationFiles.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { describe, expect, it } from "vitest"; import { parseClientConfiguration } from "./ClientConfigurationDocument.js"; @@ -16,16 +17,20 @@ const sources = ( inline: Record, ) => [ { - ...parseClientConfiguration( - JSON.stringify({ mcp: { rea: kilo(file) } }), - "kilo", + ...expectResultValue( + parseClientConfiguration( + JSON.stringify({ mcp: { rea: kilo(file) } }), + "kilo", + ), ), sourcePath: client.configPath, }, { - ...parseClientConfiguration( - JSON.stringify({ mcp: { rea: { environment: inline } } }), - "kilo", + ...expectResultValue( + parseClientConfiguration( + JSON.stringify({ mcp: { rea: { environment: inline } } }), + "kilo", + ), ), inlineOrigin: "KILO_CONFIG_CONTENT" as const, }, diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index 5f948df7c19..6828409661a 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -18,7 +18,7 @@ import { clientRegistrationEnvironment, } from "./ClientRegistrationEnvironment.js"; import type { ArtifactResourceScope } from "../resources/index.js"; -import type { ConfigurationError } from "../domain/configurationErrors.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { isRecord } from "../kernel/isRecord.js"; @@ -177,15 +177,14 @@ export const readConfigurationFile = async ( if (!source.ok) return source; const content = source.value; if (content === undefined) return ok(undefined); - try { - return ok(parseClientConfiguration(content, format)); - } catch (cause: unknown) { - return err({ - kind: "malformed", - path, - detail: `Configuration ${path} is malformed: ${errorMessage(cause)}`, - }); - } + const parsed = parseClientConfiguration(content, format); + return parsed.ok + ? parsed + : err({ + kind: "malformed", + path, + detail: `Configuration ${path} is malformed: ${parsed.error.detail}`, + }); }; /** Read each layer; setup may validate its writable layer with proposed overrides. */ @@ -355,23 +354,25 @@ export const clientWriteDialect = ( export const clientConfigurationForWrite = ( parsed: ClientConfigurationDocument, sources: readonly ClientConfigurationDocument[], -): ClientConfigurationDocument => { +): Result => { if ( parsed.dialect !== "opencode" || clientWriteDialect(parsed.dialect, sources) !== "opencode_v2" ) - return parsed; + return ok(parsed); if (Object.hasOwn(parsed.servers, "servers")) - throw new TypeError( - "A legacy OpenCode server named servers conflicts with the effective native server table; repair this ambiguity before setup", + return err( + new ConfigurationError( + "A legacy OpenCode server named servers conflicts with the effective native server table. Repair this ambiguity before rerunning setup.", + ), ); - return { + return ok({ ...parsed, dialect: "opencode_v2", serversPath: ["mcp", "servers"], servers: {}, legacyServers: parsed.servers, - }; + }); }; /** Project a client's effective user registration without modifying its source files. */ diff --git a/src/application/ClientConfigurationPublication.ts b/src/application/ClientConfigurationPublication.ts index cac28aaf7b3..b0eaa34c829 100644 --- a/src/application/ClientConfigurationPublication.ts +++ b/src/application/ClientConfigurationPublication.ts @@ -1,3 +1,4 @@ +import { ok, type Result } from "../domain/result.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { constants, type Stats } from "node:fs"; import { link, lstat, mkdtemp, open, realpath, rename } from "node:fs/promises"; @@ -35,6 +36,9 @@ export interface ClientConfigurationWriteProblem { readonly requestedOwnership?: { readonly uid: number; readonly gid: number }; } +/** The selected path lost its admission before publication. */ +export class ClientConfigurationPathError extends ConfigurationError {} + /** Preserve the operation and original cause before publication cleanup runs. */ export class ClientConfigurationWriteError extends Error { readonly _tag = "ClientConfigurationWriteError"; @@ -179,15 +183,29 @@ export class ClientConfigurationPublication { /** Keep all publication resources owned through the complete operation. */ async verify(operation: () => Promise): Promise { - let outcome: RegularFileOperationOutcome; + const result = await this.verifyResult(async () => ok(await operation())); + if (!result.ok) throw result.error; + return result.value; + } + + async verifyResult( + operation: () => Promise>, + ): Promise> { + let result: Result; try { - outcome = { kind: "completed", value: await operation() }; + result = await operation(); } catch (cause: unknown) { - outcome = { kind: "failed", cause }; + await releaseStaging(this.path, this.staging, this.cleanup, { + kind: "failed", + cause, + }); + throw cause; } + const outcome: RegularFileOperationOutcome = result.ok + ? { kind: "completed", value: result.value } + : { kind: "failed", cause: result.error }; await releaseStaging(this.path, this.staging, this.cleanup, outcome); - if (outcome.kind === "failed") throw outcome.cause; - return outcome.value; + return result; } async assertCurrent(readback: string): Promise { @@ -287,7 +305,7 @@ const assertRequestedConfigurationPath = async ( ): Promise => { const current = await resolveClientConfigTransactionPath(requestedPath); if (current === undefined) - throw new ConfigurationError( + throw new ClientConfigurationPathError( `Client configuration path could not be safely verified: ${requestedPath}`, ); if (resolve(current) === resolve(path)) return; @@ -310,7 +328,7 @@ const isParentAliasRetarget = async ( requestedStats = await lstat(requestedPath); } catch (cause: unknown) { if (isNodeErrorCode(cause, "ENOENT")) return false; - throw new ConfigurationError( + throw new ClientConfigurationPathError( `Client configuration path could not be safely verified: ${requestedPath}`, ); } diff --git a/src/application/ClientPrivateProfile.ts b/src/application/ClientPrivateProfile.ts index d76a317938f..593e528572d 100644 --- a/src/application/ClientPrivateProfile.ts +++ b/src/application/ClientPrivateProfile.ts @@ -56,6 +56,9 @@ export const privateProfileModesCurrent = async ( ); }; +/** A refusal or retained cleanup from the private directory owner. */ +export class ClientPrivateProfileError extends ConfigurationError {} + /** Apply the private folder mode through the selected directory descriptor. */ export const securePrivateDirectory = async ( path: string, @@ -89,7 +92,7 @@ export const securePrivateDirectory = async ( // A linked parent can make a profile path name the home folder itself. const homeFolder = await stat(home); if (homeFolder.dev === before.dev && homeFolder.ino === before.ino) - throw new ConfigurationError( + throw new ClientPrivateProfileError( `The private profile folder ${path} is the home folder; REA will not make the home folder private. Point the client at its own profile folder; no settings were written.`, ); changed = (before.mode & 0o777) !== PRIVATE_PROFILE_MODES.directory; @@ -111,7 +114,7 @@ export const securePrivateDirectory = async ( try { await lease.release(); } catch (cause: unknown) { - const error = new ConfigurationError( + const error = new ClientPrivateProfileError( `Private client directory cleanup failed at ${path}`, { cause: diff --git a/src/application/ClientRegistration.test.ts b/src/application/ClientRegistration.test.ts index 66c03d9a40b..fdf5094e7c1 100644 --- a/src/application/ClientRegistration.test.ts +++ b/src/application/ClientRegistration.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { expect, it } from "vitest"; @@ -135,9 +136,11 @@ it.each([{ envs: { KEEP: "1" } }, {}])( ); it("keeps a native Goose leading-zero string when normalizing the env alias", () => { - const parsed = parseClientConfiguration( - "extensions:\n rea:\n cmd: old\n env:\n VALUE: 0123\n", - "goose", + const parsed = expectResultValue( + parseClientConfiguration( + "extensions:\n rea:\n cmd: old\n env:\n VALUE: 0123\n", + "goose", + ), ); const result = replaceClientRegistrationLauncher( gooseTarget, @@ -202,7 +205,7 @@ it.each([ "reads a null Goose env alias as a malformed environment, not an empty one: %j", (text) => { const result = clientRegistrationEnvironment( - parseClientConfiguration(text, "goose"), + expectResultValue(parseClientConfiguration(text, "goose")), { name: "goose", registrationProfile: supportedClientRegistrationProfile("goose"), diff --git a/src/application/DshCordisPatch.ts b/src/application/DshCordisPatch.ts index 6d5f78c94e4..6be95799039 100644 --- a/src/application/DshCordisPatch.ts +++ b/src/application/DshCordisPatch.ts @@ -15,7 +15,11 @@ import { import { ConfigurationError } from "../domain/configurationErrors.js"; import { err, ok, type Result } from "../domain/result.js"; import type { ClientConfigurationDocument } from "./ClientConfigurationDocument.js"; -import { CordisExpression, DshCordisYaml } from "./DshCordisYaml.js"; +import { + CordisDocumentError, + CordisExpression, + DshCordisYaml, +} from "./DshCordisYaml.js"; import { mergeRegistrationEnvironment } from "./UserConfigurationLocation.js"; import { isRecord } from "../kernel/isRecord.js"; @@ -63,7 +67,7 @@ export class DshCordisDocument { this.#yaml = new DshCordisYaml(text); const root = this.#yaml.document.contents; if (!isSeq(root)) - throw new ConfigurationError("Cordis patches must be a list"); + throw new CordisDocumentError("Cordis patches must be a list"); const operations: PatchOperation[] = []; let insertions = 0; let groupOwnership: string | undefined; @@ -121,19 +125,19 @@ export class DshCordisDocument { this.#operations = operations; this.#insertions = insertions; this.#editabilityError = this.#unknownStructure - ? new ConfigurationError( + ? new CordisDocumentError( "Expression-backed Cordis patches have unknown structure; use literal patches before setup", ) : this.#malformedStructure - ? new ConfigurationError( + ? new CordisDocumentError( "Malformed Cordis patches cannot be edited safely; use mapping entries and insert lists before setup", ) : groupOwnership !== undefined - ? new ConfigurationError( + ? new CordisDocumentError( `Cordis REA insertion ${groupOwnership}; use a direct insertion before setup`, ) : this.#unknownSelector - ? new ConfigurationError( + ? new CordisDocumentError( "Expression-backed Cordis name selectors have unknown applicability; use literal selectors before setup", { settings: [ @@ -212,7 +216,7 @@ export class DshCordisDocument { #id(map: YAMLMap | undefined): unknown { const id = this.#yaml.value(this.#yaml.field(map, "id")); if (id instanceof CordisExpression) - throw new ConfigurationError( + throw new CordisDocumentError( "Expression-backed Cordis IDs have unknown ownership; use literal IDs before changing registrations", ); return id; @@ -364,7 +368,7 @@ export class DshCordisDocument { throw this.#editabilityError; const root = this.#yaml.document.contents; if (!isSeq(root)) - throw new ConfigurationError("Cordis patches must be a list"); + throw new CordisDocumentError("Cordis patches must be a list"); const replacements = new Map(); const invalidated = new Set( this.#operations.flatMap((op) => @@ -382,10 +386,10 @@ export class DshCordisDocument { if (op.insertion === undefined) continue; const copy = this.#detachContainer(op.source, invalidated); if (!isMap(copy)) - throw new ConfigurationError("Cordis operation is not a mapping"); + throw new CordisDocumentError("Cordis operation is not a mapping"); const inserted = this.#detachContainer(op.insertion.source, invalidated); if (!isSeq(inserted)) - throw new ConfigurationError("Cordis insertion is not a list"); + throw new CordisDocumentError("Cordis insertion is not a list"); copy.set("insert", inserted); this.#editInsertion(inserted, op.insertion, invalidated, () => { if (carried || edit === undefined) return undefined; @@ -405,7 +409,7 @@ export class DshCordisDocument { const output = this.#yaml.document.clone(); const outputRoot = output.contents; if (!isSeq(outputRoot)) - throw new ConfigurationError("Cordis patches must be a list"); + throw new CordisDocumentError("Cordis patches must be a list"); outputRoot.items = root.items.flatMap((source) => { const copy = replacements.has(source) ? replacements.get(source) @@ -457,10 +461,10 @@ export class DshCordisDocument { ? this.#detachContainer(source, invalidated) : entry; if (!isMap(group)) - throw new ConfigurationError("Cordis group is not a mapping"); + throw new CordisDocumentError("Cordis group is not a mapping"); const config = this.#detachContainer(nested.source, invalidated); if (!isSeq(config)) - throw new ConfigurationError("Cordis group config is not a list"); + throw new CordisDocumentError("Cordis group config is not a list"); this.#editInsertion(config, nested, invalidated); group.set("config", config); return [group]; @@ -474,7 +478,7 @@ export class DshCordisDocument { ): YAMLMap { const entry = this.#yaml.detach(this.#entryNode, invalidated); if (!isMap(entry)) - throw new ConfigurationError("Cordis entry is not a mapping"); + throw new CordisDocumentError("Cordis entry is not a mapping"); this.#yaml.setValue(entry, "id", DSH_ENTRY_ID); this.#yaml.setValue(entry, "name", DSH_CLIENT_PACKAGE); entry.delete("disabled"); @@ -488,7 +492,7 @@ export class DshCordisDocument { ? this.#yaml.document.createNode({}) : this.#yaml.detach(sourceConfig, invalidated); if (!isMap(config)) - throw new ConfigurationError( + throw new CordisDocumentError( "Cordis registration config is not a mapping", ); // Caller nodes keep their tags and spelling; only literal launcher values change. @@ -508,7 +512,7 @@ export class DshCordisDocument { ? this.#yaml.document.createNode({}) : this.#yaml.detach(env, invalidated); if (!isMap(nextEnv)) - throw new ConfigurationError("Cordis environment is not a mapping"); + throw new CordisDocumentError("Cordis environment is not a mapping"); for (const pair of [...nextEnv.items]) { const key = this.#yaml.key(pair.key); if (Object.hasOwn(desiredEnv, key)) { @@ -552,7 +556,7 @@ export const dshDocument = ( document: Record, ): DshCordisDocument => { if (!(document.cordis instanceof DshCordisDocument)) - throw new ConfigurationError("Missing Cordis document owner"); + throw new CordisDocumentError("Missing Cordis document owner"); return document.cordis; }; export const parseDshCordisDocument = ( @@ -578,7 +582,7 @@ export const serializeDshDocument = ( document: Record, ): string => { if (!(document.cordis instanceof DshCordisEdit)) - throw new ConfigurationError("Missing Cordis edit plan"); + throw new CordisDocumentError("Missing Cordis edit plan"); return document.cordis.source.serialize(document.cordis.registration); }; /** Read a positive literal deadline or null for a caller-owned expression of unknown value. */ diff --git a/src/application/DshCordisYaml.ts b/src/application/DshCordisYaml.ts index 47512550e6b..bb2dcca6ecd 100644 --- a/src/application/DshCordisYaml.ts +++ b/src/application/DshCordisYaml.ts @@ -15,6 +15,9 @@ import { } from "yaml"; import { ConfigurationError } from "../domain/configurationErrors.js"; +/** A native Cordis document cannot be admitted or edited. */ +export class CordisDocumentError extends ConfigurationError {} + /** Expression source is never a literal value and is never evaluated by REA. */ export class CordisExpression { readonly kind = "cordis-expression"; @@ -35,13 +38,13 @@ export class DshCordisYaml { logLevel: "error", }); if (this.document.errors.length > 0 || this.document.warnings.length > 0) - throw new ConfigurationError("Invalid or unsupported Cordis YAML", { + throw new CordisDocumentError("Invalid or unsupported Cordis YAML", { cause: this.document.errors[0] ?? this.document.warnings[0], }); if (this.document.contents === null) this.document.contents = this.document.createNode([]); if (!isSeq(this.document.contents)) - throw new ConfigurationError( + throw new CordisDocumentError( "Cordis patches must be a YAML operation list", ); this.value(this.document.contents); @@ -50,7 +53,7 @@ export class DshCordisYaml { // This value is discarded; source nodes own every Cordis interpretation. this.document.toJS(); } catch (cause) { - throw new ConfigurationError("Unsafe Cordis YAML alias expansion", { + throw new CordisDocumentError("Unsafe Cordis YAML alias expansion", { cause, }); } @@ -60,7 +63,7 @@ export class DshCordisYaml { if (!isAlias(node)) return node; const resolved = node.resolve(this.document); if (resolved === undefined) - throw new ConfigurationError("Cordis YAML contains an unresolved alias"); + throw new CordisDocumentError("Cordis YAML contains an unresolved alias"); return resolved; } @@ -69,7 +72,7 @@ export class DshCordisYaml { if (!isNode(resolved)) return resolved; if (this.#values.has(resolved)) return this.#values.get(resolved); if (this.#visiting.has(resolved)) - throw new ConfigurationError( + throw new CordisDocumentError( "Cyclic Cordis YAML cannot be safely edited", ); this.#visiting.add(resolved); @@ -96,7 +99,7 @@ export class DshCordisYaml { key(node: unknown): string { const key = this.value(node); if (typeof key === "object" && key !== null) - throw new ConfigurationError( + throw new CordisDocumentError( "Cordis YAML mapping keys must be literal scalars", ); // Match YAML's JS object projection while retaining the original key node. diff --git a/src/application/EvidenceInputResolver.ts b/src/application/EvidenceInputResolver.ts index fa4f824002f..cf694bfe229 100644 --- a/src/application/EvidenceInputResolver.ts +++ b/src/application/EvidenceInputResolver.ts @@ -138,12 +138,13 @@ export function resolveEvidenceRequest( } selected = admitted.value; } + // A synchronous lookup or format admission can initiate cancellation. + if (options.signal?.aborted) + return err(cancelledBy(operation, options.signal)); sources.add(selected); return ok(selected); }, ); - if (result.ok && options.signal?.aborted) - return err(cancelledBy(operation, options.signal)); return result.ok ? ok({ input: result.value, diff --git a/src/application/GooseConfigurationYaml.ts b/src/application/GooseConfigurationYaml.ts index 2f77b3704ed..2fbfc821645 100644 --- a/src/application/GooseConfigurationYaml.ts +++ b/src/application/GooseConfigurationYaml.ts @@ -145,8 +145,11 @@ const gooseYamlOptions = { customTags: gooseScalarTags, } as const; +/** A diagnostic from Goose's native YAML reader or editor. */ +export class GooseConfigurationYamlError extends ConfigurationError {} + /** A duplicate YAML member cannot establish one selected configuration value. */ -class GooseConfigurationYamlError extends ConfigurationError { +class GooseDuplicateMemberError extends GooseConfigurationYamlError { readonly kind = "shadowed_member"; constructor( readonly path: readonly string[], @@ -194,12 +197,12 @@ const parseGooseDocument = (text: string): Document => { const document = parseDocument(text, gooseYamlOptions); const failure = document.errors[0] ?? document.warnings[0]; if (failure?.code === "DUPLICATE_KEY") - throw new GooseConfigurationYamlError( + throw new GooseDuplicateMemberError( duplicatePath(document.contents, failure.pos[0]) ?? [], failure, ); if (failure !== undefined) - throw new ConfigurationError("Invalid or unsupported Goose YAML", { + throw new GooseConfigurationYamlError("Invalid or unsupported Goose YAML", { cause: failure, }); return document; @@ -217,9 +220,12 @@ const gooseDocumentValue = (document: Document): unknown => { : value, }); } catch (cause: unknown) { - throw new ConfigurationError("Goose YAML values could not be resolved", { - cause, - }); + throw new GooseConfigurationYamlError( + "Goose YAML values could not be resolved", + { + cause, + }, + ); } }; @@ -252,7 +258,9 @@ export const editGooseConfigurationYaml = ( document.contents = map; } if (!isMap(document.contents)) - throw new ConfigurationError("Goose configuration root must be a mapping"); + throw new GooseConfigurationYamlError( + "Goose configuration root must be a mapping", + ); for (let length = 1; length < path.length; length++) { const parent = resolveYamlEditPath(document, path.slice(0, length)); let previous = document.getIn(parent, true); @@ -264,7 +272,7 @@ export const editGooseConfigurationYaml = ( if (value === undefined) return text; document.setIn(parent, document.createNode({})); } else if (!isMap(previous)) - throw new ConfigurationError( + throw new GooseConfigurationYamlError( `Goose configuration ${path.slice(0, length).join(".")} must be a mapping`, ); } diff --git a/src/application/HermesConfigurationYaml.test.ts b/src/application/HermesConfigurationYaml.test.ts index 794fa7b2db5..20f9677c10c 100644 --- a/src/application/HermesConfigurationYaml.test.ts +++ b/src/application/HermesConfigurationYaml.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { describe, expect, it } from "vitest"; import { parse } from "yaml"; @@ -604,7 +605,7 @@ describe("Hermes configuration YAML", () => { it("retains exact integer settings through a parsed Hermes launcher refresh", () => { const source = "mcp_servers:\n rea:\n command: old\n identifier: 9007199254740993 # caller identifier\n negative: -9007199254740993\n safe: 9007199254740991\n mode: 0600\n"; - const parsed = parseClientConfiguration(source, "hermes"); + const parsed = expectResultValue(parseClientConfiguration(source, "hermes")); const previous = parsed.servers.rea as Record; const result = serializeClientConfiguration( withClientServers( @@ -801,7 +802,9 @@ describe("Hermes registration refresh through inherited merges", () => { "/home/rea-test", HOST_PLATFORM.platform, ).find(({ name }) => name === "hermes")!; - const parsed = parseClientConfiguration(source, "hermes"); + const parsed = expectResultValue( + parseClientConfiguration(source, "hermes"), + ); const registration = refreshClientRegistration( client, "hermes", diff --git a/src/application/HermesConfigurationYaml.ts b/src/application/HermesConfigurationYaml.ts index e565e5532b2..670235882f8 100644 --- a/src/application/HermesConfigurationYaml.ts +++ b/src/application/HermesConfigurationYaml.ts @@ -299,8 +299,11 @@ const projectedYamlPathExists = ( path: readonly string[], ): boolean => projectedYamlValue(document, path) !== "absent"; +/** A refused Hermes YAML edit with repair guidance from the document owner. */ +export class HermesConfigurationEditError extends ConfigurationError {} + const inheritedRegistrationRemovalError = () => - new ConfigurationError( + new HermesConfigurationEditError( "The registration is inherited from a YAML merge. Remove it at the shared source before rerunning uninstall", ); @@ -320,7 +323,7 @@ const inheritedYamlValue = ( return isScalar(key) && key.value === name; }); if (matches.length > 1) - throw new ConfigurationError( + throw new HermesConfigurationEditError( `YAML mapping contains more than one key resolving to ${JSON.stringify(name)}`, ); if (matches[0] !== undefined) return matches[0].value; @@ -359,7 +362,7 @@ const inheritedYamlMapOverride = ( let inherited = inheritedYamlValue(document, owner, name); if (isAlias(inherited)) inherited = inherited.resolve(document); if (!isMap(inherited)) - throw new ConfigurationError( + throw new HermesConfigurationEditError( `Inherited YAML setting ${JSON.stringify(name)} is not a mapping`, ); const mergeDocument = parseHermesDocument("<<: {}\n"); @@ -367,13 +370,13 @@ const inheritedYamlMapOverride = ( !isMap(mergeDocument.contents) || mergeDocument.contents.items[0] === undefined ) - throw new ConfigurationError("Cannot create a YAML merge key"); + throw new HermesConfigurationEditError("Cannot create a YAML merge key"); const alias = document.createAlias(inherited, "rea_inherited"); const override = new YAMLMap(document.schema); override.items.push(new Pair(mergeDocument.contents.items[0].key, alias)); document.setIn(parent, override); if (alias.resolve(document) !== inherited) - throw new ConfigurationError( + throw new HermesConfigurationEditError( "The inherited YAML anchor is shadowed; edit its shared source before rerunning setup", ); }; diff --git a/src/application/KiloClientLocation.ts b/src/application/KiloClientLocation.ts index af29b94deba..58a5f622cea 100644 --- a/src/application/KiloClientLocation.ts +++ b/src/application/KiloClientLocation.ts @@ -4,8 +4,8 @@ import { type ClientRootContext, } from "./ClientConfigRoots.js"; import { present } from "./McpRegistrationLocations.js"; -import { ConfigurationError } from "../domain/configurationErrors.js"; import { err, ok, type Result } from "../domain/result.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { parseClientConfiguration, type ClientInlineConfiguration, @@ -49,13 +49,15 @@ export const observedFiles = async ( directory: string, names: readonly string[], authority: KiloFileLayer["authority"], -): Promise => { +): Promise> => { const files: KiloFileLayer[] = []; for (const name of names) { const path = join(directory, name); - if (await present(path)) files.push({ path, authority }); + const exists = await present(path); + if (!exists.ok) return exists; + if (exists.value) files.push({ path, authority }); } - return files; + return ok(files); }; /** Kilo's Global.Path.config: xdg-basedir's config home joined with "kilo". */ @@ -80,20 +82,22 @@ const kiloHomePaths = ({ /** Kilo's legacy and current home folders, when present. */ export const kiloHomeDirectories = async ( context: KiloLocationContext, -): Promise => { +): Promise> => { const directories: KiloConfigDirectory[] = []; for (const directory of kiloHomePaths(context)) { - if (await present(directory)) + const exists = await present(directory); + if (!exists.ok) return exists; + if (exists.value) directories.push({ path: directory, authority: "global" }); } - return directories; + return ok(directories); }; export const directoryFiles = async ( directories: readonly KiloConfigDirectory[], custom: string | undefined, planned?: KiloFileLayer, -): Promise => { +): Promise> => { const seen = new Set(); const layers: KiloFileLayer[] = []; for (const directory of directories) { @@ -107,15 +111,15 @@ export const directoryFiles = async ( continue; if (planned !== undefined && dirname(planned.path) === directory.path) layers.push(planned); - layers.push( - ...(await observedFiles( - directory.path, - KILO_DIRECTORY_FILES, - directory.authority, - )), + const files = await observedFiles( + directory.path, + KILO_DIRECTORY_FILES, + directory.authority, ); + if (!files.ok) return files; + layers.push(...files.value); } - return layers; + return ok(layers); }; export const kiloExplicitFile = ({ @@ -139,19 +143,15 @@ export const kiloInlineConfiguration = ( ): Result => { const text = root.env.KILO_CONFIG_CONTENT; if (!text) return ok(undefined); - try { - return ok({ - origin: "KILO_CONFIG_CONTENT", - parsed: parseClientConfiguration(text, "kilo"), - }); - } catch (cause: unknown) { - return err( - new ConfigurationError( - "KILO_CONFIG_CONTENT cannot be admitted as Kilo configuration. Repair that selected inline configuration; no settings were written.", - { cause }, - ), - ); - } + const parsed = parseClientConfiguration(text, "kilo"); + return parsed.ok + ? ok({ origin: "KILO_CONFIG_CONTENT", parsed: parsed.value }) + : err( + new ConfigurationError( + "KILO_CONFIG_CONTENT cannot be admitted as Kilo configuration. Repair that selected inline configuration; no settings were written.", + { cause: parsed.error.cause }, + ), + ); }; /** Kilo's user-scope write target, its file layers in load order, and evidence. */ @@ -206,60 +206,58 @@ export const kiloDefaultLocation = ( /** * Kilo's user-scope layers as Kilo v7.8.27 loads them, and the file it writes: * the last present layer, or `kilo.json` in KILO_CONFIG_DIR when that folder - * holds none yet. File-probe and inline-configuration failures are returned - * as `ConfigurationError` so one unreadable Kilo folder stays a Kilo row - * failure instead of rejecting the whole client table. + * holds none yet. */ export const kiloGlobalLocation = async ( context: KiloLocationContext, ): Promise> => { - try { - const root = kiloRoot(context); - const layers = await observedFiles(root, KILO_GLOBAL_FILES, "global"); - const explicit = kiloExplicitFile(context); - if (explicit !== undefined) { - await present(explicit); - layers.push({ path: explicit, authority: "global" }); - } - const custom = kiloExplicitDirectory(context); - const directories: KiloConfigDirectory[] = [ - { path: root, authority: "global" }, - ...(await kiloHomeDirectories(context)), - ]; - if (custom !== undefined) - directories.push({ path: custom, authority: "global" }); - const observed = await directoryFiles(directories, custom); - let configPath = observed.at(-1)?.path ?? layers.at(-1)?.path; - if ( - custom !== undefined && - ![...layers, ...observed].some((layer) => dirname(layer.path) === custom) - ) { - await present(custom); - configPath = join(custom, "kilo.json"); - layers.push( - ...(await directoryFiles(directories, custom, { - path: configPath, - authority: "global", - })), - ); - } else layers.push(...observed); - configPath ??= join(root, "kilo.json"); - const inlineConfiguration = kiloInlineConfiguration(context.root); - if (!inlineConfiguration.ok) return inlineConfiguration; - return ok({ - configPath, - configPaths: - layers.length === 0 ? [configPath] : layers.map((layer) => layer.path), - ...(inlineConfiguration.value === undefined - ? {} - : { inlineConfiguration: inlineConfiguration.value }), - markerPath: root, - discoveryPaths: [kiloExtensionStorage(context.root)], - }); - } catch (cause: unknown) { - // The shared probe keeps throwing for the registration path; this - // boundary owns the Result contract the client table consumes. - if (cause instanceof ConfigurationError) return err(cause); - throw cause; + const root = kiloRoot(context); + const global = await observedFiles(root, KILO_GLOBAL_FILES, "global"); + if (!global.ok) return global; + const layers = global.value; + const explicit = kiloExplicitFile(context); + if (explicit !== undefined) { + const exists = await present(explicit); + if (!exists.ok) return exists; + layers.push({ path: explicit, authority: "global" }); } + const custom = kiloExplicitDirectory(context); + const homes = await kiloHomeDirectories(context); + if (!homes.ok) return homes; + const directories: KiloConfigDirectory[] = [ + { path: root, authority: "global" }, + ...homes.value, + ]; + if (custom !== undefined) + directories.push({ path: custom, authority: "global" }); + const files = await directoryFiles(directories, custom); + if (!files.ok) return files; + const observed = files.value; + let configPath = observed.at(-1)?.path ?? layers.at(-1)?.path; + if ( + custom !== undefined && + ![...layers, ...observed].some((layer) => dirname(layer.path) === custom) + ) { + const exists = await present(custom); + if (!exists.ok) return exists; + configPath = join(custom, "kilo.json"); + const planned = await directoryFiles(directories, custom, { + path: configPath, + authority: "global", + }); + if (!planned.ok) return planned; + layers.push(...planned.value); + } else layers.push(...observed); + configPath ??= join(root, "kilo.json"); + const inline = kiloInlineConfiguration(context.root); + if (!inline.ok) return inline; + const inlineConfiguration = inline.value; + return ok({ + configPath, + configPaths: + layers.length === 0 ? [configPath] : layers.map((layer) => layer.path), + ...(inlineConfiguration === undefined ? {} : { inlineConfiguration }), + markerPath: root, + discoveryPaths: [kiloExtensionStorage(context.root)], + }); }; diff --git a/src/application/McpClientRegistration.layers.test.ts b/src/application/McpClientRegistration.layers.test.ts index f935a5d2041..f8cafebe124 100644 --- a/src/application/McpClientRegistration.layers.test.ts +++ b/src/application/McpClientRegistration.layers.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { registerMcpClientOnHost } from "../../tests/fixtures/mcpRegistration.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { lstat, mkdir, readFile, writeFile } from "node:fs/promises"; @@ -54,7 +55,9 @@ const effective = ( format: "kilo" | "opencode" = "kilo", ) => { const parsed = mergeClientConfigurationDocuments( - texts.map((text) => parseClientConfiguration(text, format)), + texts.map((text) => + expectResultValue(parseClientConfiguration(text, format)), + ), HOST_PLATFORM.platform, ); if (parsed === undefined) @@ -226,9 +229,11 @@ it("refuses a conflicting KILO_CONFIG_CONTENT launcher without mutating the inli const target = join(root, "project", "kilo.json"); const inline = { origin: "KILO_CONFIG_CONTENT", - parsed: parseClientConfiguration( - '{"mcp":{"rea":{"type":"local","command":["inline-server"]}}}', - "kilo", + parsed: expectResultValue( + parseClientConfiguration( + '{"mcp":{"rea":{"type":"local","command":["inline-server"]}}}', + "kilo", + ), ), } as const; const beforeInline = structuredClone(inline); @@ -283,7 +288,7 @@ it("retains harmless higher file and inline metadata as read-only inherited fact '{"mcp":{"rea":{"environment":{"INLINE":"1"},"custom":{"inline":true}}}}'; const inline = { origin: "KILO_CONFIG_CONTENT", - parsed: parseClientConfiguration(inlineText, "kilo"), + parsed: expectResultValue(parseClientConfiguration(inlineText, "kilo")), } as const; const beforeInline = structuredClone(inline); const client = { diff --git a/src/application/McpClientRegistration.ts b/src/application/McpClientRegistration.ts index f296519fd7e..32273ef566a 100644 --- a/src/application/McpClientRegistration.ts +++ b/src/application/McpClientRegistration.ts @@ -21,6 +21,7 @@ import { import { writeClientRegistrationBackup } from "./ClientRegistrationBackup.js"; import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js"; import { + ClientPrivateProfileError, privateProfilePermissions, PRIVATE_PROFILE_MODES, type PrivateProfilePermissions, @@ -32,10 +33,14 @@ import { retryClientConfigurationCleanup, } from "./ClientConfigurationCleanup.js"; import { clientConfigurationValuesEqual } from "./ClientConfigurationValues.js"; -import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js"; +import { + ClientConfigurationPathError, + ClientConfigurationPublication, +} from "./ClientConfigurationPublication.js"; import { withClientConfigurationTransaction } from "./ClientConfigurationTransaction.js"; import { prepareRegistration, + type PreparedRegistration, verifyEffectiveRegistration, } from "./McpRegistrationConfiguration.js"; import type { McpRegistrationClient } from "./McpRegistrationCatalog.js"; @@ -144,26 +149,40 @@ export const registerMcpClient = async ( }, }); }; + const retainFailure = (failure: McpClientRegistrationFailure) => { + if (backupPath !== undefined) + failure.retainPrimaryDiagnostics({ backup_path: backupPath }); + if (signal?.aborted === true) + analysisErrorWithCancellation( + failure, + cancelledBy("MCP registration", signal), + ); + return err(failure); + }; try { checkCancellation(); - // The caller supplies canonical argv, not a native client-shaped entry. + // The caller supplies canonical argv rather than a native client-shaped entry. if (launcher.command.length === 0) - throw new ConfigurationError( - "The registration needs a nonempty executable.", + return retainFailure( + new ConfigurationError("The registration needs a nonempty executable."), ); const path = await resolveClientConfigTransactionPath(settingsPath); if (path === undefined) - throw new ConfigurationError( - `Client settings path could not be verified: ${settingsPath}`, + return retainFailure( + new ConfigurationError( + `Client settings path could not be verified: ${settingsPath}`, + ), ); return await withClientConfigurationTransaction(path, async () => { checkCancellation(); - const prepared = await prepareRegistration( + const preparation = await prepareRegistration( path, client, launcher, platform, ); + if (!preparation.ok) return retainFailure(preparation.error); + const prepared = preparation.value; const { snapshot, original, contents } = prepared; checkCancellation(); const unchanged = await unchangedRegistration( @@ -171,17 +190,20 @@ export const registerMcpClient = async ( checkCancellation, resources, ); + if (!unchanged.ok) return retainFailure(unchanged.error); checkCancellation(); - if (unchanged !== undefined) return ok(unchanged); + if (unchanged.value !== undefined) return ok(unchanged.value); if (original !== undefined) { const backup = await writeClientRegistrationBackup(path, original); if (!backup.ok) - throw new ConfigurationError(backup.error.detail, { - diagnostics: { - settings_path: settingsPath, - backup_path: backup.error.path, - }, - }); + return retainFailure( + new ConfigurationError(backup.error.detail, { + diagnostics: { + settings_path: settingsPath, + backup_path: backup.error.path, + }, + }), + ); backupPath = backup.value; } checkCancellation(); @@ -216,7 +238,13 @@ export const registerMcpClient = async ( }, ); // Cancellation cannot abandon published bytes, verification or retained cleanup. - await verifyRegistration(publication, prepared, backupPath, resources); + const verified = await verifyRegistration( + publication, + prepared, + backupPath, + resources, + ); + if (!verified.ok) return retainFailure(verified.error); configured = true; checkCancellation(); return ok({ @@ -236,12 +264,7 @@ export const registerMcpClient = async ( backupPath, configured, }); - if (signal?.aborted === true) - analysisErrorWithCancellation( - failure, - cancelledBy("MCP registration", signal), - ); - return err(failure); + return retainFailure(failure); } }; @@ -255,11 +278,11 @@ const registrationFailure = async ( }, ): Promise => { const { backupPath, configured } = progress; - if (cause instanceof ConfigurationError) { - if (backupPath !== undefined) - cause.retainPrimaryDiagnostics({ backup_path: backupPath }); + if ( + cause instanceof ClientPrivateProfileError || + cause instanceof ClientConfigurationPathError + ) return cause; - } const cleanup = isClientConfigurationCleanupFailure(cause) ? await retryClientConfigurationCleanup(cause, resources) : undefined; @@ -284,10 +307,12 @@ const registrationFailure = async ( /** A semantic no-op is usable only while the admitted physical snapshot remains current. */ const unchangedRegistration = async ( - prepared: Awaited>, + prepared: PreparedRegistration, checkCancellation: () => void, resources: ArtifactResourceScope, -): Promise => { +): Promise< + Result +> => { const { client, path, snapshot, parsed, updated } = prepared; if ( parsed.requiresRewrite === true || @@ -296,7 +321,7 @@ const unchangedRegistration = async ( HOST_PLATFORM.platform !== "win32" && ((snapshot?.state.mode ?? 0) & 0o777) !== PRIVATE_PROFILE_MODES.file) ) - return undefined; + return ok(undefined); const current = await readRegularFileTextSnapshot(path, { symlinks: "reject", }); @@ -307,7 +332,8 @@ const unchangedRegistration = async ( ) throw new RegularFileChangedError(path); checkCancellation(); - await verifyEffectiveRegistration(prepared, current.text); + const verified = await verifyEffectiveRegistration(prepared, current.text); + if (!verified.ok) return verified; const permissionsChanged = client.privateProfile !== undefined && HOST_PLATFORM.platform !== "win32" ? await securePrivateDirectory( @@ -317,42 +343,49 @@ const unchangedRegistration = async ( resources, ) : false; - return { + return ok({ status: permissionsChanged ? "configured" : "unchanged", ...(client.privateProfile !== undefined ? { permissions: privateProfilePermissions(HOST_PLATFORM.platform) } : {}), - }; + }); }; const verifyRegistration = async ( publication: ClientConfigurationPublication, - prepared: Awaited>, + prepared: PreparedRegistration, backupPath: string | undefined, resources: ArtifactResourceScope, -): Promise => { +): Promise> => { const { original, client } = prepared; const settingsPath = client.configPath; - await publication.verify(async () => { + return publication.verifyResult(async () => { + let verified: Result; try { const readback = await readRegularFileText(publication.path, { symlinks: "reject", }); await publication.assertCurrent(readback); - await verifyEffectiveRegistration(prepared, readback); + verified = await verifyEffectiveRegistration(prepared, readback); } catch (cause: unknown) { if (cause instanceof RegularFileChangedError || isMissing(cause)) throw cause; - const failure = await registrationFailure( - cause, - settingsPath, - resources, - { backupPath, configured: false }, + verified = err( + await registrationFailure(cause, settingsPath, resources, { + backupPath, + configured: false, + }), ); - try { - await publication.restore(original); - } catch (rollbackCause: unknown) { - throw new ConfigurationError( + } + if (verified.ok) return verified; + const failure = verified.error; + if (backupPath !== undefined) + failure.retainPrimaryDiagnostics({ backup_path: backupPath }); + try { + await publication.restore(original); + } catch (rollbackCause: unknown) { + return err( + new ConfigurationError( "Client settings verification failed and restoration could not be verified", { cause: rollbackCause, @@ -362,9 +395,9 @@ const verifyRegistration = async ( ...(backupPath === undefined ? {} : { backup_path: backupPath }), }, }, - ); - } - throw failure; + ), + ); } + return verified; }); }; diff --git a/src/application/McpRegistrationCatalog.ts b/src/application/McpRegistrationCatalog.ts index e9f47aed7a6..484fb2ad51b 100644 --- a/src/application/McpRegistrationCatalog.ts +++ b/src/application/McpRegistrationCatalog.ts @@ -29,7 +29,7 @@ import { present, fixedProjectLocation, type McpRegistrationLocationContext, - type McpRegistrationLocation, + type McpRegistrationLocationResult, } from "./McpRegistrationLocations.js"; /** The facts registration needs, from the client's single owner. */ @@ -39,7 +39,7 @@ interface ClientDescriptor { readonly aliases: readonly string[]; readonly projectLocation?: ( context: McpRegistrationLocationContext, - ) => Promise; + ) => Promise; readonly projectFormat?: ClientConfigurationFormat; readonly registrationProfile: ClientRegistrationProfile; readonly setupName: SupportedClientName; @@ -159,17 +159,21 @@ const checkCancellation = (signal: AbortSignal | undefined): void => { if (signal?.aborted) throw cancelledBy("MCP registration selection", signal); }; -const selectedIds = (agents: readonly string[]): McpRegistrationClientId[] => { +const selectedIds = ( + agents: readonly string[], +): Result => { const ids: McpRegistrationClientId[] = []; for (const agent of agents) { const id = resolveMcpRegistrationClientId(agent); if (id === undefined) - throw new ConfigurationError( - `Unknown MCP client ${agent}. Select a supported --agent value.`, + return err( + new ConfigurationError( + `Unknown MCP client ${agent}. Select a supported --agent value.`, + ), ); if (!ids.includes(id)) ids.push(id); } - return ids; + return ok(ids); }; /** Each agent registers with its table row's exact profile. */ @@ -180,13 +184,16 @@ export const mcpClientRegistrationProfile = ( const projectTarget = async ( id: McpRegistrationClientId, context: McpRegistrationLocationContext, -): Promise => { +): Promise> => { const descriptor = clientDescriptor(id); if (descriptor.projectLocation === undefined) - throw new ConfigurationError( - `${descriptor.displayName} has no project-scoped registration. Remove --no-global or select a project-capable client; no settings were written.`, + return err( + new ConfigurationError( + `${descriptor.displayName} has no project-scoped registration. Remove --no-global or select a project-capable client; no settings were written.`, + ), ); const resolved = await descriptor.projectLocation(context); + if (!resolved.ok) return resolved; const [userClient] = id === "opencode" ? supportedClients( @@ -198,41 +205,48 @@ const projectTarget = async ( ) : []; if (id === "opencode" && userClient === undefined) - throw new ConfigurationError( - "OpenCode's user configuration could not be located for project registration.", + return err( + new ConfigurationError( + "OpenCode's user configuration could not be located for project registration.", + ), ); - return { + return ok({ id, displayName: descriptor.displayName, registrationProfile: mcpClientRegistrationProfile(id), - ...resolved, + ...resolved.value, scope: "project", ...(userClient === undefined ? {} : { projectConfiguration: { directory: context.cwd, userClient } }), format: descriptor.projectFormat ?? descriptor.format, - }; + }); }; /** The user-scope target is the client's resolved table row. */ const globalTarget = ( id: McpRegistrationClientId, context: McpRegistrationLocationContext, -): { client: McpRegistrationClient; markers: readonly string[] } => { +): Result< + { client: McpRegistrationClient; markers: readonly string[] }, + ConfigurationError +> => { const descriptor = clientDescriptor(id); const setupClient = context.setup.find( ({ name }) => name === descriptor.setupName, ); if (setupClient === undefined) - throw new ConfigurationError( - `The registration catalog has no path owner for ${descriptor.setupName}.`, + return err( + new ConfigurationError( + `The registration catalog has no path owner for ${descriptor.setupName}.`, + ), ); if (setupClient.configPathError !== undefined) - throw ( + return err( setupClient.configPathFailure ?? - new ConfigurationError(setupClient.configPathError) + new ConfigurationError(setupClient.configPathError), ); - return { + return ok({ client: { id, displayName: descriptor.displayName, @@ -259,7 +273,7 @@ const globalTarget = ( markers: clientEvidencePaths(setupClient).map((path) => selectedPath(path, context), ), - }; + }); }; /** @@ -284,14 +298,81 @@ const msixWriteBlocker = ( ); }; -/** User-scope read-scope rules that must hold before any target is written. */ -const admitGlobalTargets = async ( - clients: readonly McpRegistrationClient[], - context: McpRegistrationLocationContext, -): Promise => { +const selectRegistrationClients = async ( + selection: McpRegistrationSelection, + resources: ArtifactResourceScope, +): Promise> => { + checkCancellation(selection.signal); + const selectedIdsResult = selectedIds(selection.agents); + if (!selectedIdsResult.ok) return selectedIdsResult; + const ids = selectedIdsResult.value; + const context: McpRegistrationLocationContext = { + ...selection, + resources, + setup: selection.global + ? await resolveSupportedClients( + selection.home, + selection.platform, + selection.environment, + selection.systemPaths, + ) + : [], + }; + const clients: McpRegistrationClient[] = []; + if (!selection.global) { + // Default selection includes global-only Amp and cannot become project writes. + if (ids.length === 0) + return err( + new ConfigurationError( + "Default MCP registration includes global-only Amp. Select project-capable --agent values or remove --no-global; no settings were written.", + ), + ); + for (const id of ids) { + checkCancellation(selection.signal); + const target = await projectTarget(id, context); + if (!target.ok) return target; + clients.push(target.value); + } + checkCancellation(selection.signal); + return ok(clients); + } + if (ids.length > 0) { + for (const id of ids) { + // The table already resolved this target before the signal was read. + const target = globalTarget(id, context); + if (!target.ok) return target; + checkCancellation(selection.signal); + clients.push(target.value.client); + } + } else { + const all: McpRegistrationClient[] = []; + for (const id of Object.keys(MCP_REGISTRATION_CLIENTS).filter(isClientId)) { + checkCancellation(selection.signal); + if (id === "amp") continue; + const target = globalTarget(id, context); + if (!target.ok) return target; + const { client, markers } = target.value; + all.push(client); + // Examine every marker: unreadability cannot turn a partial observation into absence. + let detected = false; + for (const marker of markers) { + const exists = await present(marker); + if (!exists.ok) return exists; + detected ||= exists.value; + } + if (detected) clients.push(client); + } + const amp = globalTarget("amp", context); + if (!amp.ok) return amp; + checkCancellation(selection.signal); + if (clients.length === 0) clients.push(...all); + clients.push(amp.value.client); + } const blocker = msixWriteBlocker(clients, context); if (blocker !== undefined) - throw new ConfigurationError(`${blocker} No settings were written.`); + return err(new ConfigurationError(`${blocker} No settings were written.`)); + checkCancellation(selection.signal); + return ok(clients); }; /** Resolve all selected paths before any registration writer receives authority. */ @@ -299,72 +380,21 @@ export const resolveMcpRegistrationClients = async ( selection: McpRegistrationSelection, resources: ArtifactResourceScope, ): Promise> => { - try { - checkCancellation(selection.signal); - const ids = selectedIds(selection.agents); - const context: McpRegistrationLocationContext = { - ...selection, - resources, - setup: selection.global - ? await resolveSupportedClients( - selection.home, - selection.platform, - selection.environment, - selection.systemPaths, - ) - : [], - }; - // Default selection includes global-only Amp and cannot become project writes. - if (!selection.global && ids.length === 0) - throw new ConfigurationError( - "Default MCP registration includes global-only Amp. Select project-capable --agent values or remove --no-global; no settings were written.", - ); - if (ids.length > 0) { - const clients: McpRegistrationClient[] = []; - for (const id of ids) { - // A user-scope target is already resolved with the table, so its - // failure is reported before a cancellation that followed it. - if (selection.global) clients.push(globalTarget(id, context).client); - checkCancellation(selection.signal); - if (!selection.global) clients.push(await projectTarget(id, context)); - } - if (selection.global) await admitGlobalTargets(clients, context); - checkCancellation(selection.signal); - return ok(clients); - } - const all: McpRegistrationClient[] = []; - const detected: McpRegistrationClient[] = []; - for (const id of Object.keys(MCP_REGISTRATION_CLIENTS).filter(isClientId)) { - checkCancellation(selection.signal); - if (id === "amp") continue; - const { client, markers } = globalTarget(id, context); - all.push(client); - // Examine every marker: unreadability cannot turn a partial observation into absence. - const statuses: boolean[] = []; - for (const marker of markers) statuses.push(await present(marker)); - if (statuses.some(Boolean)) detected.push(client); - } - const amp = globalTarget("amp", context).client; - checkCancellation(selection.signal); - const selected = [...(detected.length === 0 ? all : detected), amp]; - await admitGlobalTargets(selected, context); - return ok(selected); - } catch (cause: unknown) { - const failure = - cause instanceof ConfigurationError || - cause instanceof AnalysisCancelledError - ? cause - : new ConfigurationError( - "Could not resolve MCP registration locations.", - { - cause, - }, - ); - if (selection.signal?.aborted === true) - analysisErrorWithCancellation( - failure, - cancelledBy("MCP registration selection", selection.signal), - ); - return err(failure); - } + const result = await selectRegistrationClients(selection, resources).catch( + (cause: unknown) => + err( + cause instanceof AnalysisCancelledError + ? cause + : new ConfigurationError( + "Could not resolve MCP registration locations.", + { cause }, + ), + ), + ); + if (!result.ok && selection.signal?.aborted === true) + analysisErrorWithCancellation( + result.error, + cancelledBy("MCP registration selection", selection.signal), + ); + return result; }; diff --git a/src/application/McpRegistrationConfiguration.ts b/src/application/McpRegistrationConfiguration.ts index 9dc4fb7164f..e041af92776 100644 --- a/src/application/McpRegistrationConfiguration.ts +++ b/src/application/McpRegistrationConfiguration.ts @@ -1,7 +1,8 @@ import { ConfigurationError } from "../domain/configurationErrors.js"; import type { ClientRegistrationCommand } from "../domain/clientRegistrationCommand.js"; +import { errorMessage } from "../kernel/errorMessage.js"; import { PRODUCT_IDENTITY } from "../identity.js"; -import type { Result } from "../domain/result.js"; +import { err, ok, type Result } from "../domain/result.js"; import { clientServerPath, clientServerForEdit, @@ -11,6 +12,8 @@ import { serializeClientConfiguration, withClientServers, type ClientConfigurationDocument, + type ClientConfigurationEditFailure, + type ClientConfigurationParseFailure, } from "./ClientConfigurationDocument.js"; import { clientConfigurationValuesEqual } from "./ClientConfigurationValues.js"; import { @@ -37,16 +40,37 @@ const registrationLocation = (client: McpRegistrationClient) => ({ name: client.setupClient?.name ?? client.id, }); -const requireAdmittedConfiguration = ( - result: Result, -): T => { - if (!result.ok) - throw ( - result.error.cleanupFailure ?? new ConfigurationError(result.error.detail) - ); - return result.value; +const configurationLayerFailure = ( + error: ClientConfigurationFileError, +): Result => { + if (error.cleanupFailure !== undefined) throw error.cleanupFailure; + return err(new ConfigurationError(error.detail)); }; +const registrationDocumentFailure = ( + client: McpRegistrationClient, + error: + | ClientConfigurationParseFailure + | Exclude< + ClientConfigurationEditFailure, + { readonly kind: "shadowed_member" } + >, +): Result => + error.kind === "document" + ? err(error.cause) + : err( + new ConfigurationError( + `Could not register MCP settings at ${client.configPath}: ${error.kind === "serialize" ? errorMessage(error.cause) : error.detail}`, + { + cause: error.cause, + diagnostics: { + settings_path: client.configPath, + configured: false, + }, + }, + ), + ); + /** * Merge REA's entry into one selected client document. `platform` is the host * the catalog resolved the client for; it decides the document's environment @@ -67,20 +91,30 @@ export const prepareRegistration = async ( const original = snapshot?.text; const empty = serializeClientConfiguration({}, client.format); if (!empty.ok) - throw new ConfigurationError( - "An empty client configuration could not be serialized.", + return err( + new ConfigurationError( + "An empty client configuration could not be serialized.", + ), ); const target = parseClientConfiguration( original ?? empty.value, client.format, ); + if (!target.ok) return registrationDocumentFailure(client, target.error); const location = registrationLocation(client); - const layers = requireAdmittedConfiguration( - await readClientConfigurationFiles(location, undefined, platform, { - targetDocument: target, - }), + const read = await readClientConfigurationFiles( + location, + undefined, + platform, + { + targetDocument: target.value, + }, ); - const parsed = clientConfigurationForWrite(target, layers); + if (!read.ok) return configurationLayerFailure(read.error); + const layers = read.value; + const writeDocument = clientConfigurationForWrite(target.value, layers); + if (!writeDocument.ok) return writeDocument; + const parsed = writeDocument.value; const targetIndex = layers.findLastIndex( ({ sourcePath }) => sourcePath === client.configPath, ); @@ -96,7 +130,7 @@ export const prepareRegistration = async ( ? undefined : effectiveClientServer(inherited, PRODUCT_IDENTITY.mcpServerKey), ); - if (!desired.ok) throw desired.error; + if (!desired.ok) return desired; // The client's own settings policy can exclude or override this entry. if (client.setupClient !== undefined) { const policy = await readClientPolicyBlock( @@ -104,13 +138,11 @@ export const prepareRegistration = async ( parsed, desired.value, ); - if (!policy.ok) - throw ( - policy.error.cleanupFailure ?? - new ConfigurationError(policy.error.detail) - ); + if (!policy.ok) return configurationLayerFailure(policy.error); if (policy.value !== undefined) - throw new ConfigurationError(`${policy.value} No settings were written.`); + return err( + new ConfigurationError(`${policy.value} No settings were written.`), + ); } const updated = withClientServers( parsed, @@ -133,21 +165,43 @@ export const prepareRegistration = async ( { removeShadowedMembersAt: legacy === undefined ? [] : [legacy] }, ); if (!serialized.ok) - throw new ConfigurationError( - `Client configuration member is shadowed at ${serialized.error.path.join(".")}.`, - ); + return serialized.error.kind === "shadowed_member" + ? err( + new ConfigurationError( + `Client configuration member is shadowed at ${serialized.error.path.join(".")}.`, + ), + ) + : registrationDocumentFailure(client, serialized.error); const candidate = parseClientConfiguration(serialized.value, client.format); - const effective = requireAdmittedConfiguration( - admitClientConfigurationCandidate(location, layers, candidate, platform), + if (!candidate.ok) + return registrationDocumentFailure(client, candidate.error); + const effective = admitClientConfigurationCandidate( + location, + layers, + candidate.value, + platform, ); - assertEffectiveLauncher(client, effective, launcher); - await verifyProjectLauncher(client, launcher, platform, path, { - candidates: [ - { path: client.configPath, original: target, replacement: candidate }, - ], - allowMissing: snapshot === undefined, - }); - return { + if (!effective.ok) return configurationLayerFailure(effective.error); + const admitted = admitEffectiveLauncher(client, effective.value, launcher); + if (!admitted.ok) return admitted; + const project = await verifyProjectLauncher( + client, + launcher, + platform, + path, + { + candidates: [ + { + path: client.configPath, + original: target.value, + replacement: candidate.value, + }, + ], + allowMissing: snapshot === undefined, + }, + ); + if (!project.ok) return project; + return ok({ path, client, launcher, @@ -157,15 +211,15 @@ export const prepareRegistration = async ( parsed, updated, contents: serialized.value, - }; + }); }; -const assertEffectiveLauncher = ( +const admitEffectiveLauncher = ( client: McpRegistrationClient, effective: ClientConfigurationDocument | undefined, launcher: ClientRegistrationCommand, overridePath?: string, -): void => { +): Result => { const admitted = admitClientStdioConnection( effective === undefined ? undefined @@ -180,23 +234,26 @@ const assertEffectiveLauncher = ( admitted.value.command !== launcher.command || !clientConfigurationValuesEqual(admitted.value.args, launcher.args) ) - throw new ConfigurationError( - admitted.ok - ? `A higher-priority configuration${overridePath === undefined ? "" : ` at ${overridePath}`} overrides the selected stdio launcher. Update that source before registering this command.` - : admitted.error.cause.message, - { - ...(admitted.ok ? {} : { cause: admitted.error.cause }), - diagnostics: { - settings_path: client.configPath, - ...(overridePath === undefined - ? {} - : { override_path: overridePath }), - ...(client.inlineConfiguration === undefined - ? {} - : { inline_origin: client.inlineConfiguration.origin }), + return err( + new ConfigurationError( + admitted.ok + ? `A higher-priority configuration${overridePath === undefined ? "" : ` at ${overridePath}`} overrides the selected stdio launcher. Update that source before registering this command.` + : admitted.error.cause.message, + { + ...(admitted.ok ? {} : { cause: admitted.error.cause }), + diagnostics: { + settings_path: client.configPath, + ...(overridePath === undefined + ? {} + : { override_path: overridePath }), + ...(client.inlineConfiguration === undefined + ? {} + : { inline_origin: client.inlineConfiguration.origin }), + }, }, - }, + ), ); + return ok(undefined); }; const verifyProjectLauncher = async ( @@ -207,28 +264,28 @@ const verifyProjectLauncher = async ( proposed?: Pick & { readonly allowMissing: boolean; }, -): Promise => { +): Promise> => { const project = client.projectConfiguration; - if (project === undefined) return; - const { document, launcherConfigPath } = requireAdmittedConfiguration( - await readEffectiveClientRegistrationConfiguration( - project.userClient, - undefined, - platform, - { - projectDirectory: project.directory, - writeTarget: { - path: client.configPath, - transactionPath, - allowMissing: proposed?.allowMissing ?? false, - }, - ...(proposed?.candidates === undefined - ? {} - : { candidates: proposed.candidates }), + if (project === undefined) return ok(undefined); + const effective = await readEffectiveClientRegistrationConfiguration( + project.userClient, + undefined, + platform, + { + projectDirectory: project.directory, + writeTarget: { + path: client.configPath, + transactionPath, + allowMissing: proposed?.allowMissing ?? false, }, - ), + ...(proposed?.candidates === undefined + ? {} + : { candidates: proposed.candidates }), + }, ); - assertEffectiveLauncher( + if (!effective.ok) return configurationLayerFailure(effective.error); + const { document, launcherConfigPath } = effective.value; + return admitEffectiveLauncher( client, document, launcher, @@ -236,24 +293,32 @@ const verifyProjectLauncher = async ( ); }; +export type PreparedRegistration = Extract< + Awaited>, + { readonly ok: true } +>["value"]; + /** Re-admit native layers around the caller's identity-verified target snapshot. */ export const verifyEffectiveRegistration = async ( - prepared: Awaited>, + prepared: PreparedRegistration, targetText: string, -): Promise => { +): Promise> => { const { client, launcher, platform } = prepared; - const layers = requireAdmittedConfiguration( - await readClientConfigurationFiles( - registrationLocation(client), - undefined, - platform, - { targetDocument: parseClientConfiguration(targetText, client.format) }, - ), + const parsed = parseClientConfiguration(targetText, client.format); + if (!parsed.ok) return registrationDocumentFailure(client, parsed.error); + const layers = await readClientConfigurationFiles( + registrationLocation(client), + undefined, + platform, + { targetDocument: parsed.value }, ); - assertEffectiveLauncher( + if (!layers.ok) return configurationLayerFailure(layers.error); + const admitted = admitEffectiveLauncher( client, - mergeClientConfigurationDocuments(layers, platform), + mergeClientConfigurationDocuments(layers.value, platform), launcher, ); - await verifyProjectLauncher(client, launcher, platform, prepared.path); + return admitted.ok + ? verifyProjectLauncher(client, launcher, platform, prepared.path) + : admitted; }; diff --git a/src/application/McpRegistrationGit.test.ts b/src/application/McpRegistrationGit.test.ts index 95e35bd636e..22e38abaa6a 100644 --- a/src/application/McpRegistrationGit.test.ts +++ b/src/application/McpRegistrationGit.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { err } from "../domain/result.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import * as exec from "../process/ExecFileOutput.js"; import { resolveKiloRegistrationWorktree } from "./McpRegistrationGit.js"; @@ -201,7 +202,7 @@ it("preserves a native location access failure and late cancellation through sel .spyOn(locations, "present") .mockImplementationOnce(async () => { controller.abort(reason); - throw failure; + return err(failure); }); try { const selected = await context(controller.signal); diff --git a/src/application/McpRegistrationKiloLocations.ts b/src/application/McpRegistrationKiloLocations.ts index 18389fec8d3..5ae7abb5cd0 100644 --- a/src/application/McpRegistrationKiloLocations.ts +++ b/src/application/McpRegistrationKiloLocations.ts @@ -1,4 +1,5 @@ import { dirname, join, relative } from "node:path"; +import { err, ok, type Result } from "../domain/result.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { directoryFiles, @@ -22,7 +23,7 @@ import { rootContext, present, type McpRegistrationLocationContext, - type McpRegistrationLocation, + type McpRegistrationLocationResult, } from "./McpRegistrationLocations.js"; /** `rea mcp add` resolves configured paths against its working directory. */ @@ -33,16 +34,21 @@ const kiloContext = ( path: (path) => selectedPath(path, context), }); -const ancestorsThrough = (directory: string, root: string): string[] => { +const ancestorsThrough = ( + directory: string, + root: string, +): Result => { const directories: string[] = []; let current = directory; while (true) { directories.push(current); - if (current === root) return directories; + if (current === root) return ok(directories); const parent = dirname(current); if (parent === current) - throw new ConfigurationError( - "Kilo worktree boundary is not an ancestor; no project settings were written.", + return err( + new ConfigurationError( + "Kilo worktree boundary is not an ancestor; no project settings were written.", + ), ); current = parent; } @@ -50,38 +56,46 @@ const ancestorsThrough = (directory: string, root: string): string[] => { const projectDirectories = async ( directories: readonly string[], authority: KiloFileLayer["authority"], -): Promise => { +): Promise> => { const found: KiloConfigDirectory[] = []; for (const directory of directories) for (const name of [".kilocode", ".kilo"]) { const path = join(directory, name); - if (await present(path)) found.push({ path, authority }); + const exists = await present(path); + if (!exists.ok) return exists; + if (exists.value) found.push({ path, authority }); } - return found; + return ok(found); }; /** Native project read order, with global/primary authorities retained read-only. */ export const kiloProjectLocation = async ( context: McpRegistrationLocationContext, -): Promise => { +): Promise => { if ( ["true", "1"].includes( context.environment.KILO_DISABLE_PROJECT_CONFIG?.toLowerCase() ?? "", ) ) - throw new ConfigurationError( - "KILO_DISABLE_PROJECT_CONFIG disables project configuration. Remove that selected override or register globally; no project settings were written.", + return err( + new ConfigurationError( + "KILO_DISABLE_PROJECT_CONFIG disables project configuration. Remove that selected override or register globally; no project settings were written.", + ), ); - const worktreeResult = await resolveKiloRegistrationWorktree(context); - if (!worktreeResult.ok) throw worktreeResult.error; - const worktree = worktreeResult.value; + const resolved = await resolveKiloRegistrationWorktree(context); + if (!resolved.ok) return resolved; + const worktree = resolved.value; const active = ancestorsThrough(worktree.activeDirectory, worktree.root); + if (!active.ok) return active; const kilo = kiloContext(context); const root = kiloRoot(kilo); - const layers = await observedFiles(root, KILO_GLOBAL_FILES, "readonly"); + const global = await observedFiles(root, KILO_GLOBAL_FILES, "readonly"); + if (!global.ok) return global; + const layers = global.value; const explicit = kiloExplicitFile(kilo); if (explicit !== undefined) { - await present(explicit); + const exists = await present(explicit); + if (!exists.ok) return exists; layers.push({ path: explicit, authority: pathWithin(worktree.root, explicit) ? "project" : "readonly", @@ -89,14 +103,15 @@ export const kiloProjectLocation = async ( } // ConfigPaths.files reverses nearest-first [jsonc,json] matches, first Kilo then OpenCode. for (const name of ["kilo", "opencode"]) - for (const directory of [...active].reverse()) - layers.push( - ...(await observedFiles( - directory, - [`${name}.json`, `${name}.jsonc`], - "project", - )), + for (const directory of [...active.value].reverse()) { + const files = await observedFiles( + directory, + [`${name}.json`, `${name}.jsonc`], + "project", ); + if (!files.ok) return files; + layers.push(...files.value); + } const primary: KiloConfigDirectory[] = []; const { primaryRoot } = worktree; if (primaryRoot !== undefined && primaryRoot !== worktree.root) { @@ -104,22 +119,25 @@ export const kiloProjectLocation = async ( primaryRoot, relative(worktree.root, worktree.activeDirectory), ); - primary.push( - ...(await projectDirectories( - ancestorsThrough(mirrored, primaryRoot), - "readonly", - )), + const primaryAncestors = ancestorsThrough(mirrored, primaryRoot); + if (!primaryAncestors.ok) return primaryAncestors; + const observed = await projectDirectories( + primaryAncestors.value, + "readonly", ); + if (!observed.ok) return observed; + primary.push(...observed.value); } - const nativeProject = await projectDirectories(active, "project"); + const nativeProject = await projectDirectories(active.value, "project"); + if (!nativeProject.ok) return nativeProject; const custom = kiloExplicitDirectory(kilo); + const homes = await kiloHomeDirectories(kilo); + if (!homes.ok) return homes; const directories: KiloConfigDirectory[] = [ { path: root, authority: "readonly" }, ...primary, - ...nativeProject, - ...(await kiloHomeDirectories(kilo).then((items) => - items.map((item) => ({ ...item, authority: "readonly" as const })), - )), + ...nativeProject.value, + ...homes.value.map((item) => ({ ...item, authority: "readonly" as const })), ]; if (custom !== undefined) directories.push({ @@ -127,7 +145,8 @@ export const kiloProjectLocation = async ( authority: pathWithin(worktree.root, custom) ? "project" : "readonly", }); const directoryLayers = await directoryFiles(directories, custom); - const writable = [...layers, ...directoryLayers].filter( + if (!directoryLayers.ok) return directoryLayers; + const writable = [...layers, ...directoryLayers.value].filter( (layer) => layer.authority === "project", ); let configPath = writable.at(-1)?.path; @@ -149,17 +168,20 @@ export const kiloProjectLocation = async ( seen.add(directory.path); if (directory.path === planned) ordered.push({ path: configPath, authority: "project" }); - else ordered.push(...(await directoryFiles([directory], custom))); + else { + const files = await directoryFiles([directory], custom); + if (!files.ok) return files; + ordered.push(...files.value); + } } layers.push(...ordered); - } else layers.push(...directoryLayers); - const inlineConfiguration = kiloInlineConfiguration(kilo.root); - if (!inlineConfiguration.ok) throw inlineConfiguration.error; - return { + } else layers.push(...directoryLayers.value); + const inline = kiloInlineConfiguration(kilo.root); + if (!inline.ok) return inline; + const inlineConfiguration = inline.value; + return ok({ configPath, configPaths: layers.map((layer) => layer.path), - ...(inlineConfiguration.value === undefined - ? {} - : { inlineConfiguration: inlineConfiguration.value }), - }; + ...(inlineConfiguration === undefined ? {} : { inlineConfiguration }), + }); }; diff --git a/src/application/McpRegistrationLocations.ts b/src/application/McpRegistrationLocations.ts index 7a33d7d6aff..5bcfb0b38f4 100644 --- a/src/application/McpRegistrationLocations.ts +++ b/src/application/McpRegistrationLocations.ts @@ -1,6 +1,8 @@ import { lstat } from "node:fs/promises"; import { ConfigurationError } from "../domain/configurationErrors.js"; +import type { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { err, ok, type Result } from "../domain/result.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import type { ClientRootContext } from "./ClientConfigRoots.js"; // Type-only: the client table imports project-location owners from here. @@ -25,6 +27,11 @@ export interface McpRegistrationLocation { readonly inlineConfiguration?: ClientInlineConfiguration; } +export type McpRegistrationLocationResult = Result< + McpRegistrationLocation, + ConfigurationError | AnalysisCancelledError +>; + export const selectedPath = ( path: string, context: McpRegistrationLocationContext, @@ -42,40 +49,35 @@ export const rootContext = ({ env: environment, }); -export const present = async (path: string): Promise => { +export const present = async ( + path: string, +): Promise> => { try { await lstat(path); - return true; + return ok(true); } catch (cause: unknown) { if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") - return false; - throw new ConfigurationError( - `Cannot determine the registration location at ${path}. Repair its access or path before registering.`, - { cause }, + return ok(false); + return err( + new ConfigurationError( + `Cannot determine the registration location at ${path}. Repair its access or path before registering.`, + { cause }, + ), ); } }; -export const firstExisting = async ( - candidates: readonly string[], - fallback: string, -): Promise => { - for (const candidate of candidates) - if (await present(candidate)) return candidate; - return fallback; -}; - /** Fixed relative target precedence used by clients with a single project document. */ export const fixedProjectLocation = (candidates: readonly [string, ...string[]]) => async ( context: McpRegistrationLocationContext, - ): Promise => { - const paths = candidates.map((path) => selectedPath(path, context)); - return { - configPath: await firstExisting( - paths, - selectedPath(candidates[0], context), - ), - }; + ): Promise => { + for (const candidate of candidates) { + const configPath = selectedPath(candidate, context); + const exists = await present(configPath); + if (!exists.ok) return exists; + if (exists.value) return ok({ configPath }); + } + return ok({ configPath: selectedPath(candidates[0], context) }); }; diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index 283bc358376..f774a4e051b 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -14,7 +14,7 @@ import { type ClientConfigurationFileError, } from "./ClientConfigurationFiles.js"; import { err, ok, type Result } from "../domain/result.js"; -import { ConfigurationError } from "../domain/configurationErrors.js"; +import type { ConfigurationError } from "../domain/configurationErrors.js"; import { effectiveClientServer, clientServerListedDisabled, @@ -23,7 +23,6 @@ import { shadowedClientServers, OMP_DISABLED_SERVERS_KEY, parseClientConfiguration, - parseZcodeFallbackConfiguration, serializeClientConfiguration, withClientServers, type ClientConfigurationDocument, @@ -38,6 +37,7 @@ import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js"; import { mkdir } from "node:fs/promises"; import { dirname } from "node:path"; import { + ClientPrivateProfileError, PRIVATE_PROFILE_MODES, privateProfileModesCurrent, securePrivateDirectory, @@ -131,25 +131,20 @@ export const configureClientConfiguration = async ( ); if (transactionPath === undefined) return { status: "failed", reason: "path" }; - try { - return await withClientConfigurationTransaction(transactionPath, () => - configureClientDocument( - { client, transactionPath, platform, launcherEnvironment }, - environment, - command, - resolveProviderRequestBudget, - ), - ); - } catch (cause: unknown) { - if (cause instanceof ConfigurationError && !cause.cleanupIncomplete) - return { status: "failed", reason: "readback" }; - throw cause; - } + return withClientConfigurationTransaction(transactionPath, () => + configureClientDocument( + { client, transactionPath, platform, launcherEnvironment }, + environment, + command, + resolveProviderRequestBudget, + ), + ); }; -/** An error that still owns an unreleased resource must reach the caller. */ -const cleanupIncomplete = (cause: unknown): boolean => - cause instanceof ConfigurationError && cause.cleanupIncomplete; +const configurationRemediation = (error: ConfigurationError): string => + error.settings.length === 0 + ? error.message + : `${error.message}: ${error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`; const configureClientDocument = async ( { @@ -203,55 +198,54 @@ const configureClientDocument = async ( if (!isMissing(cause)) return { status: "failed", reason: "readback" }; } const original = snapshot?.text; - let parsed: ClientConfigurationDocument; - try { - parsed = parseClientConfiguration( - original ?? - (format === "toml" || format === "grok" || format === "dsh" - ? "" - : "{}"), - format, - ); - parsed = clientConfigurationForWrite(parsed, files.value); - const ownershipBlocker = registrationOwnershipBlocker( - client, - parsed, - original ?? "", - files.value, - platform, - ); - if (ownershipBlocker !== undefined) - return { - status: "failed", - reason: "registration_ownership", - detail: ownershipBlocker, - }; - const policy = await readClientPolicyBlock( - client, - parsed, - await clientConfigurationDesired( - client, - environment, - command, - parsed, - files.value, - platform, - launcherEnvironment, - resolveProviderRequestBudget, - ), - ); - if (!policy.ok) { - throwCleanupFailure(policy.error); - return { status: "failed", reason: "readback" }; - } - if (policy.value !== undefined) - return { status: "failed", reason: "readback" }; - } catch (cause: unknown) { - if (cause instanceof RegularFileCleanupFailure) throw cause; - // Malformed existing configuration fails the readback gate. - void cause; + const document = parseClientConfiguration( + original ?? + (format === "toml" || format === "grok" || format === "dsh" ? "" : "{}"), + format, + ); + if (!document.ok) return { status: "failed", reason: "readback" }; + const writeDocument = clientConfigurationForWrite( + document.value, + files.value, + ); + if (!writeDocument.ok) + return { + status: "failed", + reason: "invalid_configuration", + detail: configurationRemediation(writeDocument.error), + }; + const parsed = writeDocument.value; + const ownershipBlocker = registrationOwnershipBlocker( + client, + parsed, + original ?? "", + files.value, + platform, + ); + if (ownershipBlocker !== undefined) + return { + status: "failed", + reason: "registration_ownership", + detail: ownershipBlocker, + }; + const policyEntry = await clientConfigurationDesired( + client, + environment, + command, + parsed, + files.value, + platform, + launcherEnvironment, + resolveProviderRequestBudget, + ); + if (!policyEntry.ok) return desiredReadbackFailure(policyEntry.error); + const policy = await readClientPolicyBlock(client, parsed, policyEntry.value); + if (!policy.ok) { + throwCleanupFailure(policy.error); return { status: "failed", reason: "readback" }; } + if (policy.value !== undefined) + return { status: "failed", reason: "readback" }; const fallback = await readZcodeFallbackServers(client, platform, parsed); if (!fallback.ok) { if (fallback.error.kind !== "registration_ownership") @@ -264,7 +258,7 @@ const configureClientDocument = async ( } : { status: "failed", reason: "readback" }; } - const desired = await clientConfigurationDesired( + const desiredResult = await clientConfigurationDesired( client, environment, command, @@ -277,6 +271,8 @@ const configureClientDocument = async ( launcherEnvironment, resolveProviderRequestBudget, ); + if (!desiredResult.ok) return desiredReadbackFailure(desiredResult.error); + const desired = desiredResult.value; // The settings written now can differ from the ones inspection admitted, // for example a Hopper path set by an installation earlier in this setup. const override = inlineOverrideBlocker( @@ -305,6 +301,13 @@ const configureClientDocument = async ( }); }; +const desiredReadbackFailure = ( + error: ConfigurationError, +): ClientConfigurationResult => { + if (error.cleanupIncomplete) throw error; + return { status: "failed", reason: "readback" }; +}; + interface ClientConfigurationUpdate { readonly client: SetupClient; readonly transactionPath: string; @@ -382,41 +385,37 @@ const persistClientConfiguration = async ({ ), } : registered; - let serialized: ReturnType; - try { - serialized = serializeClientConfiguration( - document, - format, - original, - [ - ...Object.keys(fallbackServers) - .filter((name) => name !== PRODUCT_IDENTITY.mcpServerKey) - .map((name) => clientServerPath(parsed, name)), - clientServerPath(parsed, PRODUCT_IDENTITY.mcpServerKey), - ...(legacyPath === undefined ? [] : [legacyPath]), - ...(enableOmp ? [[OMP_DISABLED_SERVERS_KEY]] : []), - ], - // Ownership admission above covers every legacy member removed here. - { removeShadowedMembersAt: legacyPath === undefined ? [] : [legacyPath] }, - ); - } catch (cause: unknown) { - // An unserializable edit is reported before any file is written. - return { - status: "failed", - reason: "write", - failure: new ClientConfigurationWriteError( - client.configPath, - "serialize", - cause, - ).problem, - }; - } + const serialized = serializeClientConfiguration( + document, + format, + original, + [ + ...Object.keys(fallbackServers) + .filter((name) => name !== PRODUCT_IDENTITY.mcpServerKey) + .map((name) => clientServerPath(parsed, name)), + clientServerPath(parsed, PRODUCT_IDENTITY.mcpServerKey), + ...(legacyPath === undefined ? [] : [legacyPath]), + ...(enableOmp ? [[OMP_DISABLED_SERVERS_KEY]] : []), + ], + // Ownership admission above covers every legacy member removed here. + { removeShadowedMembersAt: legacyPath === undefined ? [] : [legacyPath] }, + ); if (!serialized.ok) - return { - status: "failed", - reason: "shadowed_member", - path: serialized.error.path, - }; + return serialized.error.kind === "shadowed_member" + ? { + status: "failed", + reason: "shadowed_member", + path: serialized.error.path, + } + : { + status: "failed", + reason: "write", + failure: new ClientConfigurationWriteError( + client.configPath, + "serialize", + serialized.error.cause, + ).problem, + }; let recoveryBackupPath: string | undefined; if (original !== undefined) { // A private profile's backup stays owner-only even when it sits beside @@ -461,7 +460,8 @@ const persistClientConfiguration = async ({ }, ); } catch (cause: unknown) { - if (isClientConfigurationCleanupFailure(cause) || cleanupIncomplete(cause)) + if (isClientConfigurationCleanupFailure(cause)) throw cause; + if (cause instanceof ClientPrivateProfileError && cause.cleanupIncomplete) throw cause; if (isConfigurationConflict(cause)) return conflictFailure(recoveryBackupPath); @@ -483,11 +483,15 @@ const persistClientConfiguration = async ({ await publication.assertCurrent(text); const readback = parseClientConfiguration(text, format); if ( - !registrationCurrent(readback, desired) || + !readback.ok || + !registrationCurrent(readback.value, desired) || Object.entries(fallbackServers).some( ([name, entry]) => name !== PRODUCT_IDENTITY.mcpServerKey && - !clientConfigurationValuesEqual(readback.servers[name], entry), + !clientConfigurationValuesEqual( + readback.value.servers[name], + entry, + ), ) ) { return await rollbackOrReadbackFailure( @@ -581,14 +585,28 @@ const readClientRefresh = async ( } catch (cause: unknown) { if (!isMissing(cause)) throw cause; } - const parsed = + const document = original === undefined ? undefined - : clientConfigurationForWrite( - parseClientConfiguration(original, client.format), - files.value, - ); - const desired = await clientConfigurationDesired( + : parseClientConfiguration(original, client.format); + if (document?.ok === false) + return err({ + kind: "malformed", + path: client.configPath, + detail: document.error.detail, + }); + const writeDocument = + document === undefined + ? undefined + : clientConfigurationForWrite(document.value, files.value); + if (writeDocument?.ok === false) + return err({ + kind: "malformed", + path: client.configPath, + detail: configurationRemediation(writeDocument.error), + }); + const parsed = writeDocument?.value; + const desiredResult = await clientConfigurationDesired( client, providerEnvironment, command, @@ -598,6 +616,13 @@ const readClientRefresh = async ( launcherEnvironment, resolveProviderRequestBudget, ); + if (!desiredResult.ok) + return err({ + kind: "malformed", + path: client.configPath, + detail: configurationRemediation(desiredResult.error), + }); + const desired = desiredResult.value; const target = dshEditabilityBlocker(client, files.value) ?? writeTargetOwnershipBlocker( @@ -748,7 +773,7 @@ export const clientRefreshRefusal = async ( // An unreadable or malformed layer is a refusal too: setup's preflight // reports it the same way. if (!refresh.ok) return refused(refresh.error.detail); - const discovered = await discoveredInlineSettings( + const discoveredResult = await discoveredInlineSettings( client, providerEnvironment, command, @@ -756,6 +781,9 @@ export const clientRefreshRefusal = async ( platform, launcherEnvironment, ); + if (!discoveredResult.ok) + return refused(configurationRemediation(discoveredResult.error)); + const discovered = discoveredResult.value; if (discovered !== undefined) return { alignment: "unknown", @@ -766,10 +794,6 @@ export const clientRefreshRefusal = async ( : refused(refresh.value.refusal); } catch (cause: unknown) { if (cause instanceof RegularFileCleanupFailure) throw cause; - if (cause instanceof ConfigurationError) - return refused( - `${cause.message}: ${cause.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, - ); return refused( `The configuration could not be read. Check its permissions before rerunning setup. ${errorMessage(cause)}`, ); @@ -793,16 +817,19 @@ const discoveredInlineSettings = async ( platform: NodeJS.Platform, launcherEnvironment: Readonly, ): Promise< - | { - readonly origin: ClientInlineConfiguration["origin"]; - readonly settings: readonly string[]; - } - | undefined + Result< + | { + readonly origin: ClientInlineConfiguration["origin"]; + readonly settings: readonly string[]; + } + | undefined, + ConfigurationError + > > => { const [origin] = inlineRegistrationOrigins(client); - if (origin === undefined) return undefined; + if (origin === undefined) return ok(undefined); if (refresh.refusal !== undefined && refresh.overrideOrigin === undefined) - return undefined; + return ok(undefined); // Setting names are matched by the platform's environment identity, so a // Windows layer's `Java_Home` is the discovered `JAVA_HOME`. const declared = snapshotEnvironment( @@ -819,8 +846,8 @@ const discoveredInlineSettings = async ( }), ); const settings = Object.keys(adopted); - if (settings.length === 0) return undefined; - if (refresh.overrideOrigin === undefined) return { origin, settings }; + if (settings.length === 0) return ok(undefined); + if (refresh.overrideOrigin === undefined) return ok({ origin, settings }); const desired = await clientConfigurationDesired( client, { ...providerEnvironment, ...adopted }, @@ -830,14 +857,17 @@ const discoveredInlineSettings = async ( platform, launcherEnvironment, ); - return inlineRegistrationOverride( - client, - refresh.sources, - desired, - platform, - ) === undefined - ? { origin, settings } - : undefined; + if (!desired.ok) return desired; + return ok( + inlineRegistrationOverride( + client, + refresh.sources, + desired.value, + platform, + ) === undefined + ? { origin, settings } + : undefined, + ); }; /** Preflight one client configuration before setup presents any mutations. */ @@ -850,23 +880,14 @@ export const inspectClientConfiguration = async ( platform: NodeJS.Platform = HOST_PLATFORM.platform, launcherEnvironment: Readonly = process.env, ): Promise => { - let inspection: ClientConfigurationInspection; - try { - inspection = await inspectClientDocument( - client, - providerEnvironment, - command, - platform, - launcherEnvironment, - resolveProviderRequestBudget, - ); - } catch (cause: unknown) { - if (!(cause instanceof ConfigurationError)) throw cause; - return { - status: "invalid", - remediation: `${cause.message}: ${cause.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, - }; - } + const inspection = await inspectClientDocument( + client, + providerEnvironment, + command, + platform, + launcherEnvironment, + resolveProviderRequestBudget, + ); if (inspection.status !== "create" && inspection.status !== "update") return inspection; // A change the running client would overwrite is not a persisted registration. @@ -937,16 +958,25 @@ const inspectClientDocument = async ( launcherEnvironment, resolveProviderRequestBudget, ); + if (!desired.ok) + return { + status: "invalid", + remediation: configurationRemediation(desired.error), + }; const override = inlineOverrideBlocker( client, files.value, - desired, + desired.value, platform, ); if (override !== undefined) return { status: "invalid", remediation: override }; // This read establishes absence; do not reuse an earlier user-file policy. - const policy = await readClientPolicyBlock(client, undefined, desired); + const policy = await readClientPolicyBlock( + client, + undefined, + desired.value, + ); if (!policy.ok) { throwCleanupFailure(policy.error); return { @@ -970,10 +1000,25 @@ const inspectClientDocument = async ( }; } try { - const parsed = clientConfigurationForWrite( - parseClientConfiguration(original, client.format), + const document = parseClientConfiguration(original, client.format); + if (!document.ok) + return { + status: "invalid", + remediation: + document.error.kind === "document" + ? configurationRemediation(document.error.cause) + : "The existing configuration is malformed. Repair it before setup applies any other changes.", + }; + const writeDocument = clientConfigurationForWrite( + document.value, files.value, ); + if (!writeDocument.ok) + return { + status: "invalid", + remediation: configurationRemediation(writeDocument.error), + }; + const parsed = writeDocument.value; const ownershipBlocker = writeTargetOwnershipBlocker( client, files.value, @@ -993,15 +1038,20 @@ const inspectClientDocument = async ( launcherEnvironment, resolveProviderRequestBudget, ); + if (!desired.ok) + return { + status: "invalid", + remediation: configurationRemediation(desired.error), + }; const override = inlineOverrideBlocker( client, files.value, - desired, + desired.value, platform, ); if (override !== undefined) return { status: "invalid", remediation: override }; - const policy = await readClientPolicyBlock(client, parsed, desired); + const policy = await readClientPolicyBlock(client, parsed, desired.value); if (!policy.ok) { throwCleanupFailure(policy.error); return { @@ -1012,7 +1062,7 @@ const inspectClientDocument = async ( if (policy.value !== undefined) return { status: "invalid", remediation: policy.value }; if ( - registrationCurrent(parsed, desired) && + registrationCurrent(parsed, desired.value) && (await privateProfileCurrent(client, original)) ) return { status: "already_current" }; @@ -1023,11 +1073,7 @@ const inspectClientDocument = async ( return { status: "invalid", remediation: fallback.error.detail }; } } catch (cause: unknown) { - if ( - cause instanceof RegularFileCleanupFailure || - cause instanceof ConfigurationError - ) - throw cause; + if (cause instanceof RegularFileCleanupFailure) throw cause; // Malformed configuration is reported with the invalid remediation. void cause; return { @@ -1219,11 +1265,18 @@ const readZcodeFallbackServers = async ( if (!source.ok) return err({ ...source.error, detail: `${detail} ${source.error.detail}` }); if (source.value === undefined) return ok({}); + const document = parseClientConfiguration(source.value, "zcode_fallback"); + if (!document.ok) + return err({ + kind: "malformed", + path, + detail: `${detail} ${document.error.detail}`, + }); + const fallback = document.value; try { - const parsed = parseZcodeFallbackConfiguration(source.value); const ownershipBlocker = registrationOwnershipBlocker( { ...client, configPath: path, format: "zcode_fallback" }, - parsed, + fallback, source.value, [], platform, @@ -1234,14 +1287,18 @@ const readZcodeFallbackServers = async ( path, detail: ownershipBlocker, }); - const environment = clientRegistrationEnvironment(parsed, client, platform); + const environment = clientRegistrationEnvironment( + fallback, + client, + platform, + ); if (!environment.ok) return err({ kind: "malformed", path, detail: `${detail} ${environment.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, }); - return ok(parsed.servers); + return ok(fallback.servers); } catch (cause: unknown) { return err({ kind: "malformed", @@ -1356,7 +1413,7 @@ const clientConfigurationDesired = async ( platform: NodeJS.Platform, launcherEnvironment: Readonly, resolveProviderRequestBudget?: ProviderRequestBudgetResolver, -): Promise => { +): Promise> => { const effective = effectiveClientConfiguration( sources, { client, document: parsed }, @@ -1380,7 +1437,7 @@ const clientConfigurationDesired = async ( resolveProviderRequestBudget, platform, ); - if (!validated.ok) throw validated.error; + if (!validated.ok) return validated; const desired = ( parsed === undefined ? new DshCordisDocument("") @@ -1391,8 +1448,7 @@ const clientConfigurationDesired = async ( platform, recommendedMcpToolTimeoutMs(validated.value.timeoutInputs), ); - if (!desired.ok) throw desired.error; - return desired.value; + return desired; } const validated = await clientRegistrationEnvironmentDetailsWithBudget( effective, @@ -1404,7 +1460,7 @@ const clientConfigurationDesired = async ( : undefined, platform, ); - if (!validated.ok) throw validated.error; + if (!validated.ok) return validated; // Decide the fallback from the effective layers, then edit only the target. // A lower layer's locator still applies when the target has no value of its own. const writeEnvironment = @@ -1421,7 +1477,7 @@ const clientConfigurationDesired = async ( writeEnvironment, "fragment", ); - if (!environment.ok) throw environment.error; + if (!environment.ok) return environment; const registration = refreshClientRegistration( client, format, @@ -1434,7 +1490,7 @@ const clientConfigurationDesired = async ( launcherEnvironment, platform, ); - if (!registration.ok) throw registration.error; + if (!registration.ok) return registration; return withInheritedGooseSettings( registration.value, format, @@ -1470,8 +1526,8 @@ const withInheritedGooseSettings = ( effective: ClientConfigurationDocument | undefined, providerEnvironment: SetupProviderEnvironment, platform: NodeJS.Platform, -): Record => { - if (format !== "goose") return withoutInherited; +): Result, ConfigurationError> => { + if (format !== "goose") return ok(withoutInherited); // The layers below the user file, which the user entry overlays field by field. const lower = effectiveClientConfiguration( sources, @@ -1516,9 +1572,9 @@ const withInheritedGooseSettings = ( ); const environmentKeys = ["envs", "env"]; if (userDeclares(environmentKeys) || !declares(lower, environmentKeys)) - return spelled(registration); + return ok(spelled(registration)); const { envs: _generated, ...rest } = registration; - if (Object.keys(providerEnvironment).length === 0) return rest; + if (Object.keys(providerEnvironment).length === 0) return ok(rest); const inherited = clientRegistrationEnvironment( effective, client, @@ -1526,6 +1582,7 @@ const withInheritedGooseSettings = ( providerEnvironment, "fragment", ); - if (!inherited.ok) throw inherited.error; - return spelled({ ...rest, envs: { ...inherited.value } }); + return inherited.ok + ? ok(spelled({ ...rest, envs: { ...inherited.value } })) + : inherited; }; diff --git a/src/application/SetupClients.ts b/src/application/SetupClients.ts index 5c90058d1ce..3620308e677 100644 --- a/src/application/SetupClients.ts +++ b/src/application/SetupClients.ts @@ -12,6 +12,7 @@ export const failedConfigurationMessage = ( result: Extract, ): string => { switch (result.reason) { + case "invalid_configuration": case "registration_ownership": case "read_only_override": return result.detail; diff --git a/src/application/SetupTypes.ts b/src/application/SetupTypes.ts index 6d1756f9b3b..9e1e3180240 100644 --- a/src/application/SetupTypes.ts +++ b/src/application/SetupTypes.ts @@ -39,7 +39,7 @@ export interface SetupInitialState { export type ClientConfigurationResult = | { readonly status: "failed"; - readonly reason: "registration_ownership"; + readonly reason: "registration_ownership" | "invalid_configuration"; readonly detail: string; } | { diff --git a/src/application/SupportedClientLocations.ts b/src/application/SupportedClientLocations.ts index 5077b439332..6e9880a00f8 100644 --- a/src/application/SupportedClientLocations.ts +++ b/src/application/SupportedClientLocations.ts @@ -746,14 +746,14 @@ export const kiloLayeredLocation = async ( ): Promise> => { const kilo = kiloTableContext(context); try { - const located = await kiloGlobalLocation(kilo); - if (!located.ok) + const location = await kiloGlobalLocation(kilo); + if (!location.ok) return err({ path: kiloDefaultLocation(kilo).markerPath, - message: located.error.message, - failure: located.error, + message: location.error.message, + failure: location.error, }); - const { configPath, configPaths, inlineConfiguration } = located.value; + const { configPath, configPaths, inlineConfiguration } = location.value; return ok({ configPath, configPaths, diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index ea9fc2727fb..f39520e4e14 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -29,7 +29,7 @@ import { } from "./MsixPackageStorage.js"; import { kiloProjectLocation } from "./McpRegistrationKiloLocations.js"; import type { - McpRegistrationLocation, + McpRegistrationLocationResult, McpRegistrationLocationContext, } from "./McpRegistrationLocations.js"; import { errorMessage } from "../kernel/errorMessage.js"; @@ -234,7 +234,7 @@ type McpAddExposure = { /** A project location only an asynchronous probe can decide. */ readonly projectLocation: ( context: McpRegistrationLocationContext, - ) => Promise; + ) => Promise; readonly projectPaths?: undefined; } ); diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index 8a80c03915c..fb603f075d5 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -27,7 +27,6 @@ import { retryClientConfigurationCleanup, } from "./ClientConfigurationCleanup.js"; import { - ClientConfigurationShapeError, clientConfigurationServersKey, clientConfigurationSyntaxName, parseClientConfiguration, @@ -340,14 +339,10 @@ const hasOwnershipEvidence = async ( if (typeof completed !== "string") continue; original = completed; } - let parsed: ClientConfigurationDocument; - try { - parsed = parseClientConfiguration(original, client.format); - } catch { - // Malformed shared data is retained, never ownership evidence. - continue; - } - const removal = clientRegistrationRemoval(parsed, original, client); + const parsed = parseClientConfiguration(original, client.format); + // Malformed shared data is retained and cannot prove ownership. + if (!parsed.ok) continue; + const removal = clientRegistrationRemoval(parsed.value, original, client); // Refusing the edit never retracts the owned-row fact: an effective // REA-owned row shadowed by a foreign duplicate still proves ownership, // so later read failures stay blocking instead of softening to retained. @@ -626,10 +621,11 @@ export const systemUninstallHost = ( redirection = appDataRedirection(supported); if (projectDirectory !== undefined) { const directory = - await requireProjectUninstallDirectory(projectDirectory); + await resolveProjectUninstallDirectory(projectDirectory); + if (!directory.ok) throw directory.error; return resolveProjectUninstallClients( supported, - directory, + directory.value, projectTargets, fileSystem, resources, @@ -1072,19 +1068,21 @@ const readClientConfiguration = async ( configurationFailure, }); if (typeof original !== "string") return original; - try { - const parsed = parseClientConfiguration(original, format); - return { kind: "configuration", transactionPath, original, parsed }; - } catch (cause: unknown) { - return configurationFailure( - cause instanceof ClientConfigurationShapeError || - cause instanceof ConfigurationError - ? `Configuration was not changed: ${cause.message}. Repair it, then rerun uninstall.` - : format === undefined - ? "This client's configuration syntax is unknown, so its configuration was not changed." - : `Configuration is not valid ${clientConfigurationSyntaxName(format)} and was not changed. Repair it, then rerun uninstall.`, - ); - } + const parsed = parseClientConfiguration(original, format); + if (parsed.ok) + return { + kind: "configuration", + transactionPath, + original, + parsed: parsed.value, + }; + return configurationFailure( + parsed.error.kind === "shape" || parsed.error.kind === "document" + ? `Configuration was not changed: ${parsed.error.detail}. Repair it, then rerun uninstall.` + : format === undefined + ? "This client's configuration syntax is unknown, so its configuration was not changed." + : `Configuration is not valid ${clientConfigurationSyntaxName(format)} and was not changed. Repair it, then rerun uninstall.`, + ); }; const itemRead = (result: UninstallItem): ClientConfigurationRead => ({ @@ -1116,20 +1114,22 @@ interface ProjectUninstallPlan { readonly pending: Map; } -const requireProjectUninstallDirectory = async ( +const resolveProjectUninstallDirectory = async ( path: string, -): Promise => { +): Promise> => { try { const directory = await realpath(path); - if ((await lstat(directory)).isDirectory()) return directory; + if ((await lstat(directory)).isDirectory()) return ok(directory); } catch (cause: unknown) { - throw new ConfigurationError( - `Could not resolve the selected project directory ${path}. Select an existing directory before running uninstall.`, - { cause }, + return err( + new ConfigurationError( + `Could not resolve the selected project directory ${path}. Select an existing directory before running uninstall.`, + { cause }, + ), ); } - throw new ConfigurationError( - `The selected project ${path} is not a directory.`, + return err( + new ConfigurationError(`The selected project ${path} is not a directory.`), ); }; @@ -1537,31 +1537,26 @@ const removeClient = async ( ...(removeNative ? [clientServerPath(parsed, name)] : []), ...(legacyPath === undefined ? [] : [legacyPath]), ]; - let serialized: ReturnType; - try { - serialized = serializeClientConfiguration( - candidate.document, - client.format, - original, - editedPaths, - // clientRegistrationRemoval admitted only names whose repeats REA owns. - { removeShadowedMembersAt: editedPaths }, - ); - } catch (cause: unknown) { + const serialized = serializeClientConfiguration( + candidate.document, + client.format, + original, + editedPaths, + // clientRegistrationRemoval admitted only names whose repeats REA owns. + { removeShadowedMembersAt: editedPaths }, + ); + if (!serialized.ok) { + const failure = serialized.error; return item( client.name, "failed", - cause instanceof ConfigurationError - ? `Configuration could not be updated, so no change was made. ${cause.message}.` - : "Configuration could not be updated, so no change was made. Repair the configuration, then rerun uninstall.", + failure.kind === "shadowed_member" + ? `Configuration repeats the member at ${JSON.stringify(failure.path)}; removing the registration the client reads would activate an earlier duplicate, so no change was made. Remove the duplicate members manually, then rerun uninstall.` + : failure.kind === "document" + ? `Configuration could not be updated, so no change was made. ${failure.detail}.` + : "Configuration could not be updated, so no change was made. Repair the configuration, then rerun uninstall.", ); } - if (!serialized.ok) - return item( - client.name, - "failed", - `Configuration repeats the member at ${JSON.stringify(serialized.error.path)}; removing the registration the client reads would activate an earlier duplicate, so no change was made. Remove the duplicate members manually, then rerun uninstall.`, - ); const backupPath = await backupClientConfiguration( client, transactionPath, @@ -1596,33 +1591,37 @@ const removeClient = async ( try { const text = await fileSystem.readText(publication.path); await publication.assertCurrent(text); - const readback = parseClientConfiguration(text, client.format); - if ( - (removeNative && Object.hasOwn(readback.servers, name)) || - (readback.dialect === "dsh" && - dshDocument(readback.document).carriesEntry) || - (removeLegacy && Object.hasOwn(readback.legacyServers, name)) - ) - throw new Error("registration readback mismatch"); - return item( - client.name, - "removed", - `Removed registration from ${client.configPath}.`, - ); + const parsed = parseClientConfiguration(text, client.format); + if (parsed.ok) { + const readback = parsed.value; + if ( + !(removeNative && Object.hasOwn(readback.servers, name)) && + !( + readback.dialect === "dsh" && + dshDocument(readback.document).carriesEntry + ) && + !(removeLegacy && Object.hasOwn(readback.legacyServers, name)) + ) + return item( + client.name, + "removed", + `Removed registration from ${client.configPath}.`, + ); + } } catch (cause: unknown) { if (isClientConfigurationCleanupFailure(cause)) await retryClientConfigurationCleanup(cause, resources); - try { - await publication.restore(original); - } catch { - return manualRecovery(); - } - return item( - client.name, - "failed", - `Configuration could not be updated. The original was restored and its backup at ${backupPath} was retained. Repair the configuration or restore that backup, then rerun uninstall.`, - ); } + try { + await publication.restore(original); + } catch { + return manualRecovery(); + } + return item( + client.name, + "failed", + `Configuration could not be updated. The original was restored and its backup at ${backupPath} was retained. Repair the configuration or restore that backup, then rerun uninstall.`, + ); }; let completed: UninstallItem | undefined; try { diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index e4d97c720a8..9b3368e070b 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -20,6 +20,7 @@ import { } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; +import { WindowsChangeTimeConfigurationError } from "../config/windowsChangeTimeSettle.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; import { createEvidence, type Evidence } from "../domain/evidence.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; @@ -335,7 +336,7 @@ const captureReadFailure = ( "Capture read and file-handle close both failed", { cause }, ); - if (cause instanceof ConfigurationError) { + if (cause instanceof WindowsChangeTimeConfigurationError) { if (closeFailure === undefined) return cause; return new ConfigurationError(cause.message, { cause: causeWithClose, diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index 36f3ac50fc4..766dd33a8d2 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../../providers/runOwned.js"; import { bindSessionEvidenceExecution } from "./SessionEvidenceReuse.js"; import { admitCompletedAnalysis } from "../investigation/admitCompletedAnalysis.js"; import { randomUUID } from "node:crypto"; @@ -437,23 +438,30 @@ export class BinarySession } /** Resolve a target and provider profile without creating a provider client. */ - previewTarget( + async previewTarget( target: BinaryTarget, options: BinarySessionOpenOptions = {}, ): Promise> { if (isAborted(options.signal)) - return Promise.resolve(err(cancelledBy("open_binary", options.signal))); - return resolveSessionTarget({ - router: this.#providerRouter, - current: this.#active, - target, - options, - stagedSnapshotMismatch: (target, profile) => - this.snapshotMismatch(target, profile), - }).then((resolved) => - resolved.ok && isAborted(options.signal) - ? err(cancelledBy("open_binary", options.signal)) - : resolved, + return err(cancelledBy("open_binary", options.signal)); + return finalizedResult( + await runOwned( + () => + resolveSessionTarget({ + router: this.#providerRouter, + current: this.#active, + target, + options, + stagedSnapshotMismatch: (target, profile) => + this.snapshotMismatch(target, profile), + }), + { + providerId: "rea", + operation: "open_binary", + signal: options.signal, + diagnostics: () => undefined, + }, + ), ); } diff --git a/src/browser/CdpBrowserProvider.ts b/src/browser/CdpBrowserProvider.ts index 1b228e6f438..6b05482c19a 100644 --- a/src/browser/CdpBrowserProvider.ts +++ b/src/browser/CdpBrowserProvider.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import type { ConfigurationError } from "../domain/configurationErrors.js"; import { DEFAULT_JAVASCRIPT_MEMBER_MUTATION_ALLOWANCE, @@ -57,10 +58,7 @@ import { AnalysisError, type AnalysisPartialObservation, } from "../domain/analysisErrorBase.js"; -import { - analysisErrorWithCleanupFailure, - providerCleanupErrorFromFailures, -} from "../domain/analysisErrorCleanup.js"; +import { providerCleanupErrorFromFailures } from "../domain/analysisErrorCleanup.js"; import { AnalysisInputError, cancelledBy, @@ -560,134 +558,106 @@ const withTargetSession = async < ); let targetSession: CdpTargetSession | undefined; let attachAttempted = false; - let outcome: Result; - let cleanupFailure: AnalysisError | undefined; - try { - const { target, allowedOrigins } = authorizeCdpTarget( - endpoint.discovery, - input, - operation, - ); - // The authorization owner already derived the target origin scope. - const scopedInput = - input.allowed_origins.length > 0 - ? input - : { ...input, allowed_origins: [...allowedOrigins] }; - if (endpoint.connection === undefined) { - targetSession = await openCdpTargetSession( - endpoint.discovery, - target, - operation, - options.signal, - { commandTimeoutMs }, - owner, - ); - } else { - attachAttempted = true; - targetSession = await attachCdpTargetSession( - endpoint.connection, - target, - operation, - options.signal, - owner, - ); - } - outcome = ok( - await work({ - connection: targetSession.connection, - sessionId: targetSession.sessionId, - discovery: endpoint.discovery, - target, - input: scopedInput, - ...(options.signal === undefined ? {} : { signal: options.signal }), - ...(options.progress === undefined - ? {} - : { progress: options.progress }), - }), - ); - } catch (cause: unknown) { - outcome = err(cause); - } - try { - if (targetSession !== undefined) - await closeCdpTargetSession( - targetSession, - CLEANUP_DOMAINS, - options.signal, - owner, - endpoint.reusableBrowserSocket === true, - ); - if ( - endpoint.connection !== undefined && - endpoint.connection !== targetSession?.connection - ) { - if (endpoint.reusableBrowserSocket === true) { - // A correlated rejection confirms this attach created no session. - // A lost or unusable reply can leave an attachment on the socket. - const rejected = - !outcome.ok && outcome.error instanceof CdpCommandRejection; - if (attachAttempted && !rejected) - await owner.evictBrowserSocket(endpoint.connection); - else await owner.releaseBrowserSocket(endpoint.connection); - } else { - await owner.finish(endpoint.connection); - } - } - } catch (cause: unknown) { - cleanupFailure = - cause instanceof AnalysisError - ? cause - : new ProviderCleanupError( - "rea-cdp-browser", - [input.target_id], - { reason: errorMessage(cause) }, - { operation, cause }, + let attachRejected = false; + const finalized = await runOwned( + async () => { + try { + const { target, allowedOrigins } = authorizeCdpTarget( + endpoint.discovery, + input, + operation, + ); + // The authorization owner already derived the target origin scope. + const scopedInput = + input.allowed_origins.length > 0 + ? input + : { ...input, allowed_origins: [...allowedOrigins] }; + if (endpoint.connection === undefined) { + targetSession = await openCdpTargetSession( + endpoint.discovery, + target, + operation, + options.signal, + { commandTimeoutMs }, + owner, ); - } - - if (outcome.ok && options.signal?.aborted === true) - outcome = err( - partialObservation === undefined - ? cancelledBy(operation, options.signal) - : cancelledBy(operation, options.signal, { - partialObservation: partialObservation(outcome.value), + } else { + attachAttempted = true; + targetSession = await attachCdpTargetSession( + endpoint.connection, + target, + operation, + options.signal, + owner, + ); + } + return ok( + await work({ + connection: targetSession.connection, + sessionId: targetSession.sessionId, + discovery: endpoint.discovery, + target, + input: scopedInput, + ...(options.signal === undefined ? {} : { signal: options.signal }), + ...(options.progress === undefined + ? {} + : { progress: options.progress }), }), - ); - - if (cleanupFailure !== undefined) { - if (!outcome.ok && outcome.error instanceof AnalysisError) - throw bindCdpTransportCleanup( - cleanupFailure, - analysisErrorWithCleanupFailure( - outcome.error, - cleanupFailure, - operation, - ), - ); - if (!outcome.ok) - throw new AggregateError( - [outcome.error, cleanupFailure], - `CDP operation ${operation} failed and cleanup remains incomplete.`, - { cause: outcome.error }, - ); - throw bindCdpTransportCleanup( - cleanupFailure, - new ProviderCleanupError( - "rea-cdp-browser", - cleanupFailure.cleanupResources, - { cleanup_error: cleanupFailure.message }, - { - operation, - cause: cleanupFailure, - ...(partialObservation === undefined - ? {} - : { partialObservation: partialObservation(outcome.value) }), - }, - ), - ); - } - if (!outcome.ok) throw outcome.error; - return outcome.value; + ); + } catch (cause: unknown) { + attachRejected = cause instanceof CdpCommandRejection; + return err(providerError(cause, operation)); + } + }, + { + providerId: CDP_BROWSER_PROVIDER_IDENTITY.id, + operation, + signal: options.signal, + ...(partialObservation === undefined + ? { diagnostics: () => undefined } + : { partial: partialObservation }), + close: async () => { + try { + if (targetSession !== undefined) + await closeCdpTargetSession( + targetSession, + CLEANUP_DOMAINS, + options.signal, + owner, + endpoint.reusableBrowserSocket === true, + ); + if ( + endpoint.connection !== undefined && + endpoint.connection !== targetSession?.connection + ) { + if (endpoint.reusableBrowserSocket === true) { + // A correlated rejection confirms this attach created no session. + // A lost or unusable reply can leave an attachment on the socket. + if (attachAttempted && !attachRejected) + await owner.evictBrowserSocket(endpoint.connection); + else await owner.releaseBrowserSocket(endpoint.connection); + } else { + await owner.finish(endpoint.connection); + } + } + } catch (cause: unknown) { + const failure = cause instanceof AnalysisError ? cause : undefined; + throw bindCdpTransportCleanup( + cause, + new ProviderCleanupError( + CDP_BROWSER_PROVIDER_IDENTITY.id, + failure?.cleanupResources ?? [input.target_id], + { cleanup_error: failure?.message ?? errorMessage(cause) }, + { operation, cause }, + ), + ); + } + }, + }, + ); + const result = finalizedResult(finalized); + if (!result.ok) throw result.error; + return result.value; }; const selectTargets = ( diff --git a/src/browser/CdpElectronProvider.ts b/src/browser/CdpElectronProvider.ts index 6cac2aa4944..505396c42ff 100644 --- a/src/browser/CdpElectronProvider.ts +++ b/src/browser/CdpElectronProvider.ts @@ -42,10 +42,8 @@ import { import { CDP_ELECTRON_PROVIDER_IDENTITY } from "./providerIdentities.js"; import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js"; -import { - analysisErrorWithCleanupFailure, - providerCleanupErrorFromFailures, -} from "../domain/analysisErrorCleanup.js"; +import { providerCleanupErrorFromFailures } from "../domain/analysisErrorCleanup.js"; +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { CdpTargetSessionOwner, @@ -264,132 +262,92 @@ export class CdpElectronProvider implements ElectronObservationPort { options: ExecutionOptions, ): Promise> { let targetSession: CdpTargetSession | undefined; - let cleanupFailure: AnalysisError | undefined; - let result: Result; - try { - const discovery = await discoverCdpEndpoint( - input.cdp_endpoint, - "inspect_electron_page", - options.signal, - ); - const target = await authorizeTarget( - discovery, - input.target_id, - this.#asarHeaderAdmission, - options.signal, - ); - targetSession = await openCdpTargetSession( - discovery, - target, - "inspect_electron_page", - options.signal, - { - commandTimeoutMs: selectedCdpCommandTimeoutMs( - input.command_timeout_ms, - ), - }, - this.#owner, - ); - result = ok( - electronPageInspectionSchema.parse( - await inspectCdpElectronPage({ - connection: targetSession.connection, - sessionId: targetSession.sessionId, + const operation = "inspect_electron_page"; + let cleanupIncomplete = false; + const result = await runOwned( + async () => { + try { + const discovery = await discoverCdpEndpoint( + input.cdp_endpoint, + operation, + options.signal, + ); + const target = await authorizeTarget( + discovery, + input.target_id, + this.#asarHeaderAdmission, + options.signal, + ); + targetSession = await openCdpTargetSession( discovery, target, - input, - asarHeaderAdmission: this.#asarHeaderAdmission, - ...(options.signal === undefined ? {} : { signal: options.signal }), - ...(options.progress === undefined - ? {} - : { progress: options.progress }), - }), - ), - ); - } catch (cause: unknown) { - result = err(providerError(cause, "inspect_electron_page")); - } finally { - if (targetSession !== undefined) - try { - await closeCdpTargetSession( - targetSession, - ["Debugger", "Runtime", "Page"], + operation, options.signal, + { + commandTimeoutMs: selectedCdpCommandTimeoutMs( + input.command_timeout_ms, + ), + }, this.#owner, ); + return ok( + electronPageInspectionSchema.parse( + await inspectCdpElectronPage({ + connection: targetSession.connection, + sessionId: targetSession.sessionId, + discovery, + target, + input, + asarHeaderAdmission: this.#asarHeaderAdmission, + ...(options.signal === undefined + ? {} + : { signal: options.signal }), + ...(options.progress === undefined + ? {} + : { progress: options.progress }), + }), + ), + ); } catch (cause: unknown) { - cleanupFailure = - cause instanceof AnalysisError - ? cause - : new ProviderCleanupError( - CDP_ELECTRON_PROVIDER_IDENTITY.id, - [input.target_id], - { - reason: errorMessage(cause), - }, - { operation: "inspect_electron_page", cause }, - ); + return err(providerError(cause, operation)); } - } - const finalCancellation = - result.ok && options.signal?.aborted === true - ? cancelledBy("inspect_electron_page", options.signal, { - partialObservation: { - kind: "electron-page-observation", - inspection: result.value, - cleanup: - cleanupFailure === undefined - ? "transport-closed" - : "incomplete", - }, - }) - : undefined; - if (cleanupFailure !== undefined) { - if (finalCancellation !== undefined) - return err( - bindCdpTransportCleanup( - cleanupFailure, - analysisErrorWithCleanupFailure( - finalCancellation, - cleanupFailure, - "inspect_electron_page", - ), - ), - ); - if (!result.ok) - return err( - bindCdpTransportCleanup( - cleanupFailure, - analysisErrorWithCleanupFailure( - result.error, - cleanupFailure, - "inspect_electron_page", - ), - ), - ); - return err( - bindCdpTransportCleanup( - cleanupFailure, - new ProviderCleanupError( - CDP_ELECTRON_PROVIDER_IDENTITY.id, - cleanupFailure.cleanupResources, - { cleanup_error: cleanupFailure.message }, - { - operation: "inspect_electron_page", - cause: cleanupFailure, - partialObservation: { - kind: "electron-page-observation", - inspection: result.value, - cleanup: "incomplete", + }, + { + operation, + providerId: CDP_ELECTRON_PROVIDER_IDENTITY.id, + signal: options.signal, + partial: (inspection) => ({ + kind: "electron-page-observation", + inspection, + cleanup: cleanupIncomplete ? "incomplete" : "transport-closed", + }), + close: async () => { + if (targetSession === undefined) return; + try { + await closeCdpTargetSession( + targetSession, + ["Debugger", "Runtime", "Page"], + options.signal, + this.#owner, + ); + } catch (cause: unknown) { + cleanupIncomplete = true; + const cleanupFailure = + cause instanceof AnalysisError ? cause : undefined; + const failure = new ProviderCleanupError( + CDP_ELECTRON_PROVIDER_IDENTITY.id, + cleanupFailure?.cleanupResources ?? [input.target_id], + { + cleanup_error: cleanupFailure?.message ?? errorMessage(cause), }, - }, - ), - ), - ); - } - if (!result.ok) return result; - if (finalCancellation !== undefined) return err(finalCancellation); - return result; + { operation, cause }, + ); + throw bindCdpTransportCleanup(cause, failure); + } + }, + }, + ); + return finalizedResult(result); } async #withAdmission( diff --git a/src/browser/PlaywrightBrowserScenarioProvider.ts b/src/browser/PlaywrightBrowserScenarioProvider.ts index b075057db1e..57ceee9bb92 100644 --- a/src/browser/PlaywrightBrowserScenarioProvider.ts +++ b/src/browser/PlaywrightBrowserScenarioProvider.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { withPlaywrightExecutionBoundary, PLAYWRIGHT_CLEANUP_CONFIRMATION_TIMEOUT_MS, @@ -38,8 +39,6 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisCancelledError, AnalysisCapabilityUnavailableError, - isAborted, - cancelledBy, } from "../domain/analysisErrorCore.js"; import { BrowserObservationError, @@ -56,10 +55,7 @@ import { notExecutedActionError, type ScenarioActionStop, } from "./ScenarioActionSequence.js"; -import { - browserScenarioOperationFailure, - browserScenarioCaptureData, -} from "./BrowserScenarioPartialObservation.js"; +import { browserScenarioCaptureData } from "./BrowserScenarioPartialObservation.js"; const OPERATION = "capture_browser_scenario" as const; import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js"; @@ -275,134 +271,112 @@ const runScenario = async ( retainCleanup, }); const steps: BrowserScenarioStep[] = []; - let operationOutcome: - | { readonly ok: true } - | { - readonly ok: false; - readonly cause: unknown; - } = { ok: true }; - try { - steps.push( - await initialStep({ - session, - scenario, - elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)), - signal: options.signal, - }), - ); - let stoppedBy: ScenarioActionStop | undefined; - for (const [offset, action] of scenario.actions.entries()) { - const step = await executeStep({ - session, - scenario, - action, - stepIndex: offset + 1, - stoppedBy, - signal: options.signal, - }); - steps.push(step); - if (stoppedBy === undefined && step.status !== "completed") - stoppedBy = step.status; - } - } catch (cause: unknown) { - operationOutcome = { ok: false, cause }; - } - let cleanupOutcome: - | { - readonly ok: true; - readonly cleanup: "terminated-owned-process" | "disconnected-external"; - } - | { readonly ok: false; readonly cause: unknown }; - try { - cleanupOutcome = { ok: true, cleanup: await session.close() }; - } catch (cause: unknown) { - const cleanup = browserCleanupObservation(cause); - const failure = new BrowserObservationError(OPERATION, "cleanup_failed", { - cause, - cleanup, - }); - retainCleanup(session.cleanupLease); - new AnalysisCleanupLeaseGroup(failure, [session.cleanupLease]); - cleanupOutcome = { ok: false, cause: failure }; - } - if (!cleanupOutcome.ok) { - if (operationOutcome.ok && options.signal?.aborted) - operationOutcome = { - ok: false, - cause: cancelledBy(OPERATION, options.signal), - }; - const cleanup = browserCleanupObservation(cleanupOutcome.cause); - const partialObservation: BrowserScenarioPartialObservation = { - kind: "browser-scenario-observation", - capture: browserScenarioCaptureData({ + let cleanup: BrowserScenarioPartialObservation["capture"]["browser"]["cleanup"] = + "incomplete"; + let primary: AnalysisError | undefined; + const completeCapture = (): BrowserScenarioCapture => { + const completeness = globalCompleteness(scenario, session, steps); + return browserScenarioCaptureSchema.parse({ + ...browserScenarioCaptureData({ session, scenario, startedAt, steps, - cleanup: "incomplete", - limitations: [ - "Scenario observations are partial because browser cleanup could not be confirmed.", - ], + cleanup, }), - }; - if (!operationOutcome.ok) - throw browserScenarioOperationFailure( - operationOutcome.cause, - partialObservation, - { cause: cleanupOutcome.cause }, - ); - const failure = new BrowserObservationError(OPERATION, "cleanup_failed", { - cause: cleanupOutcome.cause, - cleanup, - partialObservation, - detail: `Browser scenario cleanup could not be confirmed: ${cleanup.reason}. Collected steps and events are retained in partial_observation. Review the reported resources before retrying.`, + completeness, }); - if ( - cleanupOutcome.cause instanceof AnalysisError && - cleanupOutcome.cause.cleanupIncomplete - ) - failure.bindCleanupDependencies([cleanupOutcome.cause]); - throw failure; - } - if (!operationOutcome.ok) - throw browserScenarioOperationFailure(operationOutcome.cause, { - kind: "browser-scenario-observation", - capture: browserScenarioCaptureData({ - session, - scenario, - startedAt, - steps, - cleanup: cleanupOutcome.cleanup, - limitations: [ - "Scenario capture ended after an operation failed; uncollected steps are not represented.", - ], - }), - }); - const completeness = globalCompleteness(scenario, session, steps); - const capture = browserScenarioCaptureSchema.parse({ - ...browserScenarioCaptureData({ + }; + const partial = (limitation: string): BrowserScenarioPartialObservation => ({ + kind: "browser-scenario-observation", + capture: browserScenarioCaptureData({ session, scenario, startedAt, steps, - cleanup: cleanupOutcome.cleanup, + cleanup, + limitations: [limitation], }), - completeness, }); - if (isAborted(options.signal)) - throw cancelledBy(OPERATION, options.signal, { - partialObservation: { - kind: "browser-scenario-observation", - capture: { - ...capture, - limitations: [ - ...capture.limitations, - "Scenario capture was cancelled; collected steps, observations, and cleanup state are retained.", - ], - }, + const cleanupLimitation = + "Scenario observations are partial because browser cleanup could not be confirmed."; + const finalized = await runOwned( + async () => { + steps.push( + await initialStep({ + session, + scenario, + elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)), + signal: options.signal, + }), + ); + let stoppedBy: ScenarioActionStop | undefined; + for (const [offset, action] of scenario.actions.entries()) { + const step = await executeStep({ + session, + scenario, + action, + stepIndex: offset + 1, + stoppedBy, + signal: options.signal, + }); + steps.push(step); + if (stoppedBy === undefined && step.status !== "completed") + stoppedBy = step.status; + } + return ok(undefined); + }, + { + providerId: PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id, + operation: OPERATION, + signal: options.signal, + inspectPrimary: (result) => { + if (!result.ok) primary = result.error; }, - }); - return capture; + close: async () => { + try { + cleanup = await session.close(); + } catch (cause: unknown) { + primary?.retainPartialObservation(partial(cleanupLimitation)); + const observation = browserCleanupObservation(cause); + const failure = new BrowserObservationError( + OPERATION, + "cleanup_failed", + { + cause, + cleanup: observation, + detail: `Browser scenario cleanup could not be confirmed: ${observation.reason}. Collected steps and events are retained in partial_observation. Review the reported resources before retrying.`, + }, + ); + retainCleanup(session.cleanupLease); + new AnalysisCleanupLeaseGroup(failure, [session.cleanupLease]); + throw failure; + } + primary?.retainPartialObservation( + partial( + "Scenario capture ended after an operation failed; uncollected steps are not represented.", + ), + ); + }, + partial: () => { + if (cleanup === "incomplete") return partial(cleanupLimitation); + const capture = completeCapture(); + return { + kind: "browser-scenario-observation", + capture: { + ...capture, + limitations: [ + ...capture.limitations, + "Scenario capture was cancelled; collected steps, observations, and cleanup state are retained.", + ], + }, + }; + }, + }, + ); + const result = finalizedResult(finalized); + if (!result.ok) throw result.error; + return completeCapture(); }; /** Controlled Playwright/CDP scenario driver with exact process ownership. */ diff --git a/src/browser/execution/CdpWebRuntimeProvider.ts b/src/browser/execution/CdpWebRuntimeProvider.ts index 77bf507ac0e..c85b8346f3d 100644 --- a/src/browser/execution/CdpWebRuntimeProvider.ts +++ b/src/browser/execution/CdpWebRuntimeProvider.ts @@ -5,13 +5,10 @@ import { AnalysisError, type AnalysisPartialObservation, } from "../../domain/analysisErrorBase.js"; -import { - AnalysisOutputError, - cancelledBy, -} from "../../domain/analysisErrorCore.js"; +import { AnalysisOutputError } from "../../domain/analysisErrorCore.js"; import type { BrowserObservationOperation } from "../../domain/browserObservationErrors.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { finalizedResult, runOwned } from "../../providers/runOwned.js"; import { err, ok, type Result } from "../../domain/result.js"; import { webExecutionObservationSchema, @@ -93,53 +90,49 @@ export class CdpWebRuntimeProvider implements WebRuntimePort { group?: string, ): Promise> { let session: CdpRuntimeSession | undefined; - let result: Result; - try { - session = await CdpRuntimeSession.open( - input, - operation, - options, - this.#owner, - ); - result = ok(schema.parse(await capture(new CdpRuntimeSources(session)))); - } catch (cause: unknown) { - result = err( - cause instanceof AnalysisError - ? cause - : cause instanceof z.ZodError - ? new AnalysisOutputError(operation, cause.message) - : new ProviderAdapterError(this.identity().id, operation, { - cause, - }), - ); - } - if (session !== undefined) { - const failure = await session.close( - result.ok ? undefined : result.error, - group, - ); - if (failure !== undefined) - return err( - result.ok - ? options.signal?.aborted === true - ? analysisErrorWithCleanupFailure( - cancelledBy(operation, options.signal, { - partialObservation: result.value, + let primary: AnalysisError | undefined; + let cleanupConfirmed = false; + const outcome = await runOwned( + async () => { + try { + session = await CdpRuntimeSession.open( + input, + operation, + options, + this.#owner, + ); + return ok( + schema.parse(await capture(new CdpRuntimeSources(session))), + ); + } catch (cause: unknown) { + return err( + cause instanceof AnalysisError + ? cause + : cause instanceof z.ZodError + ? new AnalysisOutputError(operation, cause.message) + : new ProviderAdapterError(this.identity().id, operation, { + cause, }), - failure, - operation, - ) - : failure.retainPartialObservation(result.value) - : analysisErrorWithCleanupFailure(result.error, failure, operation), - ); - } - const completed = result.ok ? ok(confirmCleanup(result.value)) : result; - if (completed.ok && options.signal?.aborted === true) - return err( - cancelledBy(operation, options.signal, { - partialObservation: completed.value, - }), - ); - return completed; + ); + } + }, + { + providerId: this.identity().id, + operation, + signal: options.signal, + inspectPrimary: (result) => { + if (!result.ok) primary = result.error; + }, + close: async () => { + const failure = await session?.close(primary, group); + if (failure !== undefined) throw failure; + cleanupConfirmed = true; + }, + partial: (observation) => + cleanupConfirmed ? confirmCleanup(observation) : observation, + }, + ); + const result = finalizedResult(outcome); + return result.ok ? ok(confirmCleanup(result.value)) : result; } } diff --git a/src/browser/history/HistoricalCaptureDecoder.ts b/src/browser/history/HistoricalCaptureDecoder.ts index d4c718eeb08..8f03de084fa 100644 --- a/src/browser/history/HistoricalCaptureDecoder.ts +++ b/src/browser/history/HistoricalCaptureDecoder.ts @@ -35,7 +35,6 @@ import { completedStableArtifactObservation, type ArtifactReaderFailure, ArtifactResourceScope, - type ArtifactCleanupAttempt, AnalysisCleanupLease, AnalysisCleanupLeaseGroup, } from "../../resources/index.js"; @@ -46,12 +45,11 @@ import { AnalysisInputError, AnalysisOutputError, AnalysisResourceConstraintError, - cancelledBy, fixedCeilingConstraint, } from "../../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; +import { finalizedResult, runOwned } from "../../providers/runOwned.js"; import { err, ok, type Result } from "../../domain/result.js"; import { WEB_NETWORK_CAPTURE_LIMITS, @@ -156,419 +154,413 @@ export class HistoricalCaptureDecoder { const runtimeResources = new ArtifactResourceScope(); let processLease: AnalysisCleanupLease | undefined; let sourceObservation: FileSnapshotPartialObservation | undefined; - let result: Result; let phase: "capture-read" | "decoder" = "capture-read"; let encodedReplyBytes = 0; let reportedHeap = this.#heap; let replyFinalization: ArtifactReaderFailure | undefined; - try { - const selectedAdapter = this.adapters.find( - (candidate) => candidate.format === input.format, - ); - const adapter = - selectedAdapter?.snapshotConfiguration?.() ?? selectedAdapter; - reportedHeap = this.#reportedHeap(adapter); - if (adapter === undefined) - throw new AnalysisCapabilityUnavailableError( - input.format, - OPERATION, - "No adapter is configured for the selected capture format.", - ); - const snapshot = await readStableArtifact( - input.capture_path, - captureBudgets().inputBytes, - options?.signal, - undefined, - this.#resources, - ); - sourceObservation = { - kind: "file-snapshot-hash", - path: input.capture_path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, - }; - phase = "decoder"; - runtime = await this.createRuntime(); - const snapshotPath = join(runtime.path, "capture.snapshot"); - const requestPath = join(runtime.path, "request.json"); - const replyPath = join(runtime.path, "reply.json"); - await writeFile(snapshotPath, snapshot.bytes, { - mode: 0o600, - flag: "wx", - ...(options?.signal === undefined ? {} : { signal: options.signal }), - }); - await writeFile( - requestPath, - JSON.stringify({ - snapshot_path: snapshotPath, - reply_path: replyPath, - sensitive_values: input.sensitive_values, - budgets: captureBudgets(), - }), - { mode: 0o600, flag: "wx" }, - ); - const command = await adapter.command(requestPath, runtime.path); - const environment: NodeJS.ProcessEnv = { - ...selectedEnvironment, - UV_THREADPOOL_SIZE: "1", - }; - delete environment.NODE_OPTIONS; - const completed = await runOwnedCommand( - { - ...command, - runId: `rea-web-capture-${randomUUID()}`, - cwd: runtime.path, - hostEnvironment: environment, - }, - { - timeoutMs: selectedWebNetworkCaptureTimeoutMs( - input.capture_timeout_ms, - ), - diagnosticBytes: 1024 * 1024, - // Node adapters declare their V8 heap; the mitmproxy decoder is Python. - ...(adapter.heap === undefined ? {} : { runtime: "v8" as const }), - }, - options?.signal === undefined ? {} : { signal: options.signal }, - ); - // A decoder that survived a failed allocation may still reply; its - // reply is not trusted as complete once the limit was reached. - if (completed.memoryLimitReached === true) - throw captureMemoryFailure( - input, - CAPTURE_PROCESS_MEMORY_LIMIT_REASON, - undefined, - reportedHeap, - ); - const decodedReply = await readHistoricalCaptureReply( - replyPath, - input.capture_path, - runtimeResources, - options?.signal, - input.sensitive_values, - ); - const reply = decodedReply.value; - encodedReplyBytes = decodedReply.bytes; - replyFinalization = decodedReply.finalization; - if (!reply.ok) { - if (reply.reason === "format") - throw new AnalysisInputError(OPERATION, undefined, [ - { - path: ["capture_path", reply.pointer], - reason: "invalid_format", - message: reply.message, - }, - ]); - // No capture budget raises a ceiling the decoder's reader named. - if (reply.reason === "fixed-limit") - throw fixedCeilingConstraint( - OPERATION, - reply.boundary, - reply.message, - reply.ceiling, + let closeFailed = false; + const finalized = await runOwned( + async () => { + let result: Result; + try { + const selectedAdapter = this.adapters.find( + (candidate) => candidate.format === input.format, ); - const limit = captureLimitForReply(reply.reason); - if (limit !== undefined) { - const { parameter, expected } = CAPTURE_LIMITS[limit]; - const budget = webNetworkCaptureBudgetFacts(input, parameter); - throw new AnalysisInputError( - OPERATION, + const adapter = + selectedAdapter?.snapshotConfiguration?.() ?? selectedAdapter; + reportedHeap = this.#reportedHeap(adapter); + if (adapter === undefined) + throw new AnalysisCapabilityUnavailableError( + input.format, + OPERATION, + "No adapter is configured for the selected capture format.", + ); + const snapshot = await readStableArtifact( + input.capture_path, + captureBudgets().inputBytes, + options?.signal, + undefined, + this.#resources, + ); + sourceObservation = { + kind: "file-snapshot-hash", + path: input.capture_path, + sha256: snapshot.sha256, + bytes: snapshot.bytes.length, + }; + phase = "decoder"; + runtime = await this.createRuntime(); + const snapshotPath = join(runtime.path, "capture.snapshot"); + const requestPath = join(runtime.path, "request.json"); + const replyPath = join(runtime.path, "reply.json"); + await writeFile(snapshotPath, snapshot.bytes, { + mode: 0o600, + flag: "wx", + ...(options?.signal === undefined + ? {} + : { signal: options.signal }), + }); + await writeFile( + requestPath, + JSON.stringify({ + snapshot_path: snapshotPath, + reply_path: replyPath, + sensitive_values: input.sensitive_values, + budgets: captureBudgets(), + }), + { mode: 0o600, flag: "wx" }, + ); + const command = await adapter.command(requestPath, runtime.path); + const environment: NodeJS.ProcessEnv = { + ...selectedEnvironment, + UV_THREADPOOL_SIZE: "1", + }; + delete environment.NODE_OPTIONS; + const completed = await runOwnedCommand( { - diagnostics: { budget }, + ...command, + runId: `rea-web-capture-${randomUUID()}`, + cwd: runtime.path, + hostEnvironment: environment, + }, + { + timeoutMs: selectedWebNetworkCaptureTimeoutMs( + input.capture_timeout_ms, + ), + diagnosticBytes: 1024 * 1024, + // Node adapters declare their V8 heap; the mitmproxy decoder is Python. + ...(adapter.heap === undefined ? {} : { runtime: "v8" as const }), + }, + options?.signal === undefined ? {} : { signal: options.signal }, + ); + // A decoder that survived a failed allocation may still reply; its + // reply is not trusted as complete once the limit was reached. + if (completed.memoryLimitReached === true) + throw captureMemoryFailure( + input, + CAPTURE_PROCESS_MEMORY_LIMIT_REASON, + undefined, + reportedHeap, + ); + const decodedReply = await readHistoricalCaptureReply( + replyPath, + input.capture_path, + runtimeResources, + options?.signal, + input.sensitive_values, + ); + const reply = decodedReply.value; + encodedReplyBytes = decodedReply.bytes; + replyFinalization = decodedReply.finalization; + if (!reply.ok) { + if (reply.reason === "format") + throw new AnalysisInputError(OPERATION, undefined, [ + { + path: ["capture_path", reply.pointer], + reason: "invalid_format", + message: reply.message, + }, + ]); + // No capture budget raises a ceiling the decoder's reader named. + if (reply.reason === "fixed-limit") + throw fixedCeilingConstraint( + OPERATION, + reply.boundary, + reply.message, + reply.ceiling, + ); + const limit = captureLimitForReply(reply.reason); + if (limit !== undefined) { + const { parameter, expected } = CAPTURE_LIMITS[limit]; + const budget = webNetworkCaptureBudgetFacts(input, parameter); + throw new AnalysisInputError( + OPERATION, + { + diagnostics: { budget }, + remediationAction: webNetworkCaptureBudgetRecovery( + input, + parameter, + ), + }, + [ + { + path: ["capture_path", reply.pointer], + reason: "out_of_range", + message: reply.message, + expected: { [expected]: budget.effective_value }, + }, + ], + ); + } + if (reply.reason === "resource-limit") + throw captureMemoryFailure( + input, + reply.message, + undefined, + reportedHeap, + ); + if (reply.reason === "decoder") + throw new ProviderAdapterError(input.format, OPERATION, { + diagnostics: { + phase: "decoder", + failure_kind: reply.reason, + reason: reply.message, + pointer: reply.pointer, + }, + }); + if (reply.reason === "unsupported") + throw new AnalysisCapabilityUnavailableError( + input.format, + OPERATION, + reply.message, + { + userMessage: reply.message, + remediationAction: + "Meet the reported capture format or decoder requirement before retrying.", + ...(reply.pointer === "" + ? {} + : { diagnostics: { pointer: reply.pointer } }), + }, + ); + throw new AnalysisOutputError(OPERATION, reply.message, { + userMessage: `The capture decoder refused a complete reply exceeding ${String(captureBudgets().outputBytes)} bytes: ${reply.message}`, remediationAction: webNetworkCaptureBudgetRecovery( input, - parameter, + "max_reply_bytes", ), - }, - [ - { - path: ["capture_path", reply.pointer], - reason: "out_of_range", - message: reply.message, - expected: { [expected]: budget.effective_value }, + diagnostics: { + maximum_reply_bytes: captureBudgets().outputBytes, + boundary: "historical-capture-reply", + budget: webNetworkCaptureBudgetFacts(input, "max_reply_bytes"), }, - ], - ); - } - if (reply.reason === "resource-limit") - throw captureMemoryFailure( - input, - reply.message, - undefined, - reportedHeap, - ); - if (reply.reason === "decoder") - throw new ProviderAdapterError(input.format, OPERATION, { - diagnostics: { - phase: "decoder", - failure_kind: reply.reason, - reason: reply.message, - pointer: reply.pointer, - }, - }); - if (reply.reason === "unsupported") - throw new AnalysisCapabilityUnavailableError( - input.format, - OPERATION, - reply.message, - { - userMessage: reply.message, - remediationAction: - "Meet the reported capture format or decoder requirement before retrying.", - ...(reply.pointer === "" - ? {} - : { diagnostics: { pointer: reply.pointer } }), - }, - ); - throw new AnalysisOutputError(OPERATION, reply.message, { - userMessage: `The capture decoder refused a complete reply exceeding ${String(captureBudgets().outputBytes)} bytes: ${reply.message}`, - remediationAction: webNetworkCaptureBudgetRecovery( - input, - "max_reply_bytes", - ), - diagnostics: { - maximum_reply_bytes: captureBudgets().outputBytes, - boundary: "historical-capture-reply", - budget: webNetworkCaptureBudgetFacts(input, "max_reply_bytes"), - }, - }); - } - if ( - reply.value.decoder.id !== adapter.identity.id || - reply.value.decoder.name !== adapter.identity.name || - reply.value.decoder.version !== adapter.identity.version - ) - throw new AnalysisOutputError( - OPERATION, - "Capture decoder changed the selected upstream profile identity.", - ); - const common = { - artifact: { - path: input.capture_path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, - }, - - runtime_attribution: "unknown" as const, - limitations: [ - ...(adapter.limitations ?? []), - "This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.", - "Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.", - "Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.", - `Complete evidence is bounded by a ${String(captureBudgets().inputBytes)}-byte input budget, a ${String(captureBudgets().outputBytes)}-byte reply budget, and a ${String(captureBudgets().depth)}-level nesting cap. Set max_input_bytes, max_reply_bytes or max_nesting_depth explicitly for the next call to change those budgets without restarting REA. capture_timeout_ms is ${String(selectedWebNetworkCaptureTimeoutMs(input.capture_timeout_ms))} ms (omitted means ${String(WEB_NETWORK_CAPTURE_LIMITS.timeoutMs)}). ${nodeMemoryLimitation(reportedHeap)} Mitmproxy decoding uses a 768 MiB Linux address-space limit.`, - ], - }; - if (input.format === "qlog") { - if (!("qlog" in reply.value)) - throw new AnalysisOutputError( - OPERATION, - "Capture decoder omitted qlog transport facts.", - ); - result = ok({ ...reply.value, ...common, format: "qlog" }); - } else { - if ("qlog" in reply.value) - throw new AnalysisOutputError( - OPERATION, - "Capture decoder supplied inapplicable qlog transport facts.", - ); - result = ok({ ...reply.value, ...common, format: input.format }); - } - if (result.ok) { - let safePartialSource = false; - try { - const prepared = await prepareCaptureProtobuf( - result.value, - input, - options?.signal, - ); - safePartialSource = true; - await decodeCaptureProtobuf( - result.value, - input, - this.#resources, - prepared, - options?.signal, - encodedReplyBytes + Buffer.byteLength(JSON.stringify(common)) + 16, - ); - } catch (cause) { - const error = - cause instanceof CaptureFormatError - ? protobufCaptureFailure(input, cause) - : historicalCaptureFailure( - input, - cause, - phase, - options, - reportedHeap, - ); - if (safePartialSource) error.retainPartialObservation(result.value); - throw error; - } - if (replyFinalization !== undefined) { - const error = historicalCaptureFailure( - input, - replyFinalization, - phase, - options, - reportedHeap, - ); - error.retainPartialObservation(result.value); - throw error; - } - } - } catch (cause: unknown) { - if ( - cause instanceof OwnedCommandFailure && - cause.cleanupOwner !== undefined - ) { - const supervisor = cause.cleanupOwner; - processLease = new AnalysisCleanupLease(async () => { - const stopped = await supervisor.stop(); - if (stopped.status === "incomplete") - throw new ProviderCleanupError( - input.format, - cause.resources, - { - reason: stopped.reason, - }, - { operation: OPERATION, cause: stopped }, + }); + } + if ( + reply.value.decoder.id !== adapter.identity.id || + reply.value.decoder.name !== adapter.identity.name || + reply.value.decoder.version !== adapter.identity.version + ) + throw new AnalysisOutputError( + OPERATION, + "Capture decoder changed the selected upstream profile identity.", ); - }, cause.resources); - runtimeResources.retain({ - kind: "lease", - resource: runtime?.path ?? input.capture_path, - lease: processLease, - }); - } - // Preparation transfers independent helper/descriptor owners. Keep that - // typed stage separate from the decoder supervisor lease above: its - // historical error already follows the post-launch completion owner. - const effectiveCpuSeconds = await recordedDecoderCpuSeconds( - runtime?.path, - cause, - runtimeResources, - ); - const error = retainProcessInspectionCleanup( - processInspectionFailure(cause), - historicalCaptureFailure( - input, - cause, - phase, - options, - reportedHeap, - processLease, - effectiveCpuSeconds, - ), - runtimeResources, - OPERATION, - ); - if ( - replyFinalization?.reason === "cancelled" && - !(error instanceof AnalysisCancelledError) - ) { - const cancellation = historicalCaptureFailure( - input, - replyFinalization, - phase, - options, - reportedHeap, - ); - error.retainSecondaryFailure(cancellation, { - reply_finalization_error: projectAnalysisError(cancellation), - }); - } - const failure = withCaptureReaderCleanup( - error, - replyFinalization ?? cause, - ); - if (processLease !== undefined) - new AnalysisCleanupLeaseGroup(failure, [processLease]); - if (phase === "capture-read") { - const snapshot = completedStableArtifactObservation( - cause, - input.capture_path, - ); - if (snapshot !== undefined) failure.retainPartialObservation(snapshot); - } - if ( - failure.partialObservation === undefined && - sourceObservation !== undefined - ) - failure.retainPartialObservation(sourceObservation); - result = err(redactExplicitFailure(failure, input.sensitive_values)); - } - const completedCapture = result.ok ? result.value : undefined; - let cleanupFailure: - | Extract - | undefined; - if (runtime !== undefined) { - const root = runtime; - const lease = new AnalysisCleanupLease( - async () => { - await runtimeResources.close(); - await root.close(); - }, - { - get cleanupResources() { - return [ - ...new Set([root.path, ...runtimeResources.cleanupResources]), - ]; - }, - }, - ); - const owner = { kind: "lease" as const, resource: root.path, lease }; - if (runtimeResources.hasPending) { - // Failed child cleanup is retried by the service owner, after active peers settle. - this.#resources.retain(owner); - cleanupFailure = { - kind: "failed", - owner, - lease, - cause: new ProviderCleanupError( - input.format, - lease.cleanupResources ?? [root.path], - { - reason: - "Capture decoder resources must be released before runtime removal.", + const common = { + artifact: { + path: input.capture_path, + sha256: snapshot.sha256, + bytes: snapshot.bytes.length, }, - { operation: OPERATION }, - ), - }; - } else { - const cleanup = await this.#resources.release(owner); - if (cleanup.kind === "failed") cleanupFailure = cleanup; - } - } - if (result.ok && options?.signal?.aborted) - result = err(cancelledBy(OPERATION, options.signal)); - if (cleanupFailure !== undefined) { - const cleanupError = new ProviderCleanupError( - input.format, - [cleanupFailure.owner.resource], - { - capture_path: input.capture_path, - reason: errorMessage(cleanupFailure.cause), - }, - { - operation: OPERATION, - cause: cleanupFailure.cause, - }, - ); - const failure = result.ok - ? cleanupError - : analysisErrorWithCleanupDependencies( - result.error, - cleanupError, + + runtime_attribution: "unknown" as const, + limitations: [ + ...(adapter.limitations ?? []), + "This is retained producer evidence, without live browser transaction IDs, scenario provenance, execution attribution or deployment authenticity. Recorded URLs are never fetched.", + "Every record is decoded before selection; no partial success is returned on malformed input or a resource limit.", + "Known authentication headers/cookies and explicitly marked literal values are excluded. Unknown extension names do not establish sensitivity.", + `Complete evidence is bounded by a ${String(captureBudgets().inputBytes)}-byte input budget, a ${String(captureBudgets().outputBytes)}-byte reply budget, and a ${String(captureBudgets().depth)}-level nesting cap. Set max_input_bytes, max_reply_bytes or max_nesting_depth explicitly for the next call to change those budgets without restarting REA. capture_timeout_ms is ${String(selectedWebNetworkCaptureTimeoutMs(input.capture_timeout_ms))} ms (omitted means ${String(WEB_NETWORK_CAPTURE_LIMITS.timeoutMs)}). ${nodeMemoryLimitation(reportedHeap)} Mitmproxy decoding uses a 768 MiB Linux address-space limit.`, + ], + }; + if (input.format === "qlog") { + if (!("qlog" in reply.value)) + throw new AnalysisOutputError( + OPERATION, + "Capture decoder omitted qlog transport facts.", + ); + result = ok({ ...reply.value, ...common, format: "qlog" }); + } else { + if ("qlog" in reply.value) + throw new AnalysisOutputError( + OPERATION, + "Capture decoder supplied inapplicable qlog transport facts.", + ); + result = ok({ ...reply.value, ...common, format: input.format }); + } + if (result.ok) { + let safePartialSource = false; + try { + const prepared = await prepareCaptureProtobuf( + result.value, + input, + options?.signal, + ); + safePartialSource = true; + await decodeCaptureProtobuf( + result.value, + input, + this.#resources, + prepared, + options?.signal, + encodedReplyBytes + + Buffer.byteLength(JSON.stringify(common)) + + 16, + ); + } catch (cause) { + const error = + cause instanceof CaptureFormatError + ? protobufCaptureFailure(input, cause) + : historicalCaptureFailure( + input, + cause, + phase, + options, + reportedHeap, + ); + if (safePartialSource) + error.retainPartialObservation(result.value); + throw error; + } + if (replyFinalization !== undefined) { + const error = historicalCaptureFailure( + input, + replyFinalization, + phase, + options, + reportedHeap, + ); + error.retainPartialObservation(result.value); + throw error; + } + } + } catch (cause: unknown) { + if ( + cause instanceof OwnedCommandFailure && + cause.cleanupOwner !== undefined + ) { + const supervisor = cause.cleanupOwner; + processLease = new AnalysisCleanupLease(async () => { + const stopped = await supervisor.stop(); + if (stopped.status === "incomplete") + throw new ProviderCleanupError( + input.format, + cause.resources, + { + reason: stopped.reason, + }, + { operation: OPERATION, cause: stopped }, + ); + }, cause.resources); + runtimeResources.retain({ + kind: "lease", + resource: runtime?.path ?? input.capture_path, + lease: processLease, + }); + } + // Preparation transfers independent helper/descriptor owners. Keep that + // typed stage separate from the decoder supervisor lease above: its + // historical error already follows the post-launch completion owner. + const effectiveCpuSeconds = await recordedDecoderCpuSeconds( + runtime?.path, + cause, + runtimeResources, + ); + const error = retainProcessInspectionCleanup( + processInspectionFailure(cause), + historicalCaptureFailure( + input, + cause, + phase, + options, + reportedHeap, + processLease, + effectiveCpuSeconds, + ), + runtimeResources, OPERATION, ); - if (completedCapture !== undefined) - failure.retainPartialObservation(completedCapture); - new AnalysisCleanupLeaseGroup(cleanupError, [cleanupFailure.lease]); - new AnalysisCleanupLeaseGroup(failure, [cleanupFailure.lease]); - return err(redactExplicitFailure(failure, input.sensitive_values)); - } - if (!result.ok && completedCapture !== undefined) - result.error.retainPartialObservation(completedCapture); - return result; + if ( + replyFinalization?.reason === "cancelled" && + !(error instanceof AnalysisCancelledError) + ) { + const cancellation = historicalCaptureFailure( + input, + replyFinalization, + phase, + options, + reportedHeap, + ); + error.retainSecondaryFailure(cancellation, { + reply_finalization_error: projectAnalysisError(cancellation), + }); + } + const failure = withCaptureReaderCleanup( + error, + replyFinalization ?? cause, + ); + if (processLease !== undefined) + new AnalysisCleanupLeaseGroup(failure, [processLease]); + if (phase === "capture-read") { + const snapshot = completedStableArtifactObservation( + cause, + input.capture_path, + ); + if (snapshot !== undefined) + failure.retainPartialObservation(snapshot); + } + if ( + failure.partialObservation === undefined && + sourceObservation !== undefined + ) + failure.retainPartialObservation(sourceObservation); + result = err(redactExplicitFailure(failure, input.sensitive_values)); + } + return result; + }, + { + providerId: input.format, + operation: OPERATION, + signal: options?.signal, + partial: (capture) => capture, + close: async () => { + if (runtime === undefined) return; + const root = runtime; + const lease = new AnalysisCleanupLease( + async () => { + await runtimeResources.close(); + await root.close(); + }, + { + get cleanupResources() { + return [ + ...new Set([root.path, ...runtimeResources.cleanupResources]), + ]; + }, + }, + ); + const owner = { kind: "lease" as const, resource: root.path, lease }; + let cause: unknown; + if (runtimeResources.hasPending) { + // Failed child cleanup is retried by the service owner, after active peers settle. + this.#resources.retain(owner); + cause = new ProviderCleanupError( + input.format, + lease.cleanupResources ?? [root.path], + { + reason: + "Capture decoder resources must be released before runtime removal.", + }, + { operation: OPERATION }, + ); + } else { + const cleanup = await this.#resources.release(owner); + if (cleanup.kind !== "failed") return; + cause = cleanup.cause; + } + const failure = new ProviderCleanupError( + input.format, + [root.path], + { capture_path: input.capture_path, reason: errorMessage(cause) }, + { operation: OPERATION, cause }, + ); + new AnalysisCleanupLeaseGroup(failure, [lease]); + closeFailed = true; + throw failure; + }, + }, + ); + const result = finalizedResult(finalized); + return !result.ok && closeFailed + ? err(redactExplicitFailure(result.error, input.sensitive_values)) + : result; } } diff --git a/src/cli/cliJsonInput.ts b/src/cli/cliJsonInput.ts index 1cbe646f67f..ff0966b5ad9 100644 --- a/src/cli/cliJsonInput.ts +++ b/src/cli/cliJsonInput.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { addAbortListener } from "node:events"; import { isAbortOf } from "../process/SignalAbort.js"; import type { Readable } from "node:stream"; @@ -108,19 +109,30 @@ export const parseCliJsonInput = async ( resources, options?.snapshot ?? false, ); - if (parsed.ok && signal?.aborted) return cancelled(signal.reason); - return parsed.ok - ? { ok: true, value: parsed.value } + const finalized = finalizedResult( + await runOwned(async () => parsed, { + providerId: "rea", + operation, + signal, + diagnostics: () => undefined, + }), + ); + return finalized.ok + ? { ok: true, value: finalized.value } : { ok: false, error: { error: "Application workflow failed", - ...projectAnalysisError(parsed.error), - input_path: value, - input_reason: - parsed.error._tag === "AnalysisInputError" - ? "invalid-json" - : "too-large", + ...projectAnalysisError(finalized.error), + ...(parsed.ok + ? {} + : { + input_path: value, + input_reason: + parsed.error._tag === "AnalysisInputError" + ? "invalid-json" + : "too-large", + }), }, }; } catch (cause: unknown) { diff --git a/src/config/mcpStartupPolicy.test.ts b/src/config/mcpStartupPolicy.test.ts index 7726eed2043..690ff12c408 100644 --- a/src/config/mcpStartupPolicy.test.ts +++ b/src/config/mcpStartupPolicy.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../tests/support/expectResultValue.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { describe, expect, it } from "vitest"; @@ -40,20 +41,22 @@ describe("MCP tool deadline allowance for a Ghidra decompile limit", () => { it("derives the registration allowance from REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS", () => { const details = clientRegistrationEnvironmentDetails( - parseClientConfiguration( - JSON.stringify({ - mcpServers: { - rea: { - command: "rea", - args: ["mcp"], - env: { - REA_ANALYSIS_PROVIDER: "ghidra", - REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS: "600", + expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { + rea: { + command: "rea", + args: ["mcp"], + env: { + REA_ANALYSIS_PROVIDER: "ghidra", + REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS: "600", + }, }, }, - }, - }), - "json", + }), + "json", + ), ), undefined, HOST_PLATFORM.platform, diff --git a/src/config/windowsChangeTimeSettle.ts b/src/config/windowsChangeTimeSettle.ts index 1766e23b773..5cd0ce20dc8 100644 --- a/src/config/windowsChangeTimeSettle.ts +++ b/src/config/windowsChangeTimeSettle.ts @@ -155,10 +155,16 @@ const readBound = ( return undefined; }; +/** A rejected ChangeTime admission budget, carried through descriptor cleanup. */ +export class WindowsChangeTimeConfigurationError extends ConfigurationError {} + /** Resolve the settle budget from one environment. Invalid values are refused. */ export const resolveWindowsChangeTimeSettle = ( environment: Readonly>, -): Result => { +): Result< + WindowsChangeTimeSettleLimits, + WindowsChangeTimeConfigurationError +> => { const failures: WindowsChangeTimeSettingFailure[] = []; const driftMs = readBound( WINDOWS_CHANGE_TIME_DRIFT_MS, @@ -177,7 +183,7 @@ export const resolveWindowsChangeTimeSettle = ( ); if (failures.length > 0) return err( - new ConfigurationError( + new WindowsChangeTimeConfigurationError( failures.map(windowsChangeTimeSettingMessage).join(" "), { settings: failures.map((failure) => ({ diff --git a/src/domain/analysisErrorCleanup.ts b/src/domain/analysisErrorCleanup.ts index 00171e69c0a..6f3c59fb29a 100644 --- a/src/domain/analysisErrorCleanup.ts +++ b/src/domain/analysisErrorCleanup.ts @@ -69,12 +69,17 @@ export const analysisErrorWithCleanupDependencies = ( primary: AnalysisError, cleanup: AnalysisError, operation = "close_binary", -): AnalysisError => - analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]); + compose?: (primary: AnalysisError, cleanup: AnalysisError) => AnalysisError, +): AnalysisError => { + const failure = + compose?.(primary, cleanup) ?? + analysisErrorWithCleanupFailure(primary, cleanup, operation); + // An existing envelope already owns its dependencies. New projections + // must follow both source errors without acquiring either owner again. + return failure === cleanup || failure === primary + ? failure + : failure.bindCleanupDependencies([primary, cleanup]); +}; /** * Compose a failure with a close rejection whose completion may be unknown. A diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index cacc1935f58..8a4fcdfabae 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { capturedProviderOutput, providerResultDiagnostics, @@ -946,18 +947,69 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { ); } } - const retainCancellation = (outcome: EvmOutcome): EvmOutcome => - outcome.ok && options?.signal?.aborted - ? err( - cancelledBy(OPERATION, options.signal, { - partialObservation: evmInterfaceEvidence(input, outcome.value), - ...(retainedOutput === undefined - ? {} - : { capturedOutput: retainedOutput }), - }), - ) - : outcome; - result = retainCancellation(result); + let rootCleanup: + | { readonly owner: EvmRuntimeRoot; readonly lease: AnalysisCleanupLease } + | undefined; + const finalized = await runOwned(async () => result, { + providerId: EVMOLE_PROVIDER_IDENTITY.id, + operation: OPERATION, + signal: options?.signal, + partial: (execution) => evmInterfaceEvidence(input, execution), + capturedOutput: (_execution, replacement) => + replacement === "cancellation" ? retainedOutput : undefined, + close: async () => { + if (root === undefined || processOwner !== undefined) return; + const lease = rootLeaseFor(root); + try { + await lease.release(); + } catch (cause: unknown) { + rootCleanup = { owner: root, lease }; + const failure = result.ok + ? evmCleanupFailure( + input, + result, + [root.path], + errorMessage(cause), + retainedOutput, + cause, + ) + : new ProviderCleanupError( + EVMOLE_PROVIDER_IDENTITY.id, + [root.path], + { reason: errorMessage(cause) }, + { operation: OPERATION, cause }, + ); + bindEvmCleanupOwners(failure, [lease]); + throw failure; + } + }, + composeCleanupFailure: (primary, cleanup) => + evmCleanupFailure( + input, + err(primary), + cleanup.cleanupResources, + errorMessage(cleanup.cause), + retainedOutput, + cleanup.cause, + ), + }); + if (rootCleanup !== undefined) { + const cleanup = rootCleanup; + const primary = + finalized.kind === "completed-cleanup-retained" + ? ok(finalized.value) + : finalized.kind === "failed" || finalized.kind === "cancelled" + ? err(finalized.error.cleanupPrimary ?? finalized.error) + : result; + this.#pendingCleanup = { + input, + result: primary, + output: retainedOutput, + root: cleanup, + process: undefined, + }; + } + result = finalizedResult(finalized); if (processOwner !== undefined) { const lease = processLeaseFor(processOwner); const rootOwnerLease = @@ -1022,38 +1074,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { ); return err(failure); } - if (root !== undefined) { - try { - await rootLeaseFor(root).release(); - } catch (cause: unknown) { - const retainedRoot = root; - const lease = rootLeaseFor(retainedRoot); - const cleanupResult = retainCancellation(result); - this.#pendingCleanup = { - input, - result: cleanupResult, - output: retainedOutput, - root: { owner: retainedRoot, lease }, - process: undefined, - }; - root = undefined; - const failure = evmCleanupFailure( - input, - cleanupResult, - [retainedRoot.path], - errorMessage(cause), - retainedOutput, - cause, - ); - bindEvmCleanupOwners( - failure, - [lease], - cleanupResult.ok ? undefined : cleanupResult.error, - ); - return err(failure); - } - } - return retainCancellation(result); + return result; } async close(): Promise { diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 62afaef8e81..ff5d2500db6 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -45,7 +45,11 @@ import { JsonLineBridgeReader, type JsonLineBridgeFailure, } from "../process/JsonLineBridgeReader.js"; -import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; +import { + AbortedWait, + waitForAbortable, + waitForRetainedResult, +} from "../process/AbortablePromise.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { ProviderStartupDeadline } from "../process/ProviderDeadline.js"; @@ -392,10 +396,10 @@ export class GhidraClient { attempt: GhidraStartupAttempt, signal: AbortSignal | undefined, ): Promise { - const signalAborted = (): boolean => signal?.aborted === true; - if (signalAborted()) return err(this.#startupWaitCancellation(signal)); - const waited = await waitForAbortable(attempt.promise, signal); - if (waited instanceof AbortedWait || (waited.ok && signalAborted())) + if (signal?.aborted === true) + return err(this.#startupWaitCancellation(signal)); + const waited = await waitForRetainedResult(attempt.promise, signal); + if (waited instanceof AbortedWait) return err(this.#startupWaitCancellation(signal)); if (waited.ok || waited.error.cleanupFailure !== undefined) return waited; return this.start(signal); @@ -928,7 +932,7 @@ export class GhidraClient { async #startupFailure( primary: GhidraSessionError, deadline?: ProviderStartupDeadline, - ): Promise { + ): Promise> { const finalization = deadline?.finalize(); await this.#drainOutputBounded( finalization?.signal, @@ -1057,16 +1061,17 @@ export class GhidraClient { "admission", startupTimeout.error.message, startupTimeout.error, + { configurationFailure: startupTimeout.error }, ), ); const deadline = new ProviderStartupDeadline(startupTimeout.value, signal, { finalizeMs: OUTPUT_DRAIN_MS, }); try { - const result = await this.#startWithin(deadline); - return result.ok && deadline.signal.aborted - ? await this.#startupInterrupted(deadline) - : result; + return await deadline.finishStartup( + () => this.#startWithin(deadline), + () => this.#startupInterrupted(deadline), + ); } catch (cause: unknown) { if (cause instanceof GhidraSessionError) return err(cause); throw cause; @@ -1705,7 +1710,7 @@ export class GhidraClient { async #startupInterrupted( deadline: ProviderStartupDeadline, - ): Promise { + ): Promise> { const failure = this.#interruptionFailure(deadline); return this.#startupFailure(failure, deadline); } diff --git a/src/ghidra/GhidraClientWire.test.ts b/src/ghidra/GhidraClientWire.test.ts index 177ccb0f7b7..478e66e3a9f 100644 --- a/src/ghidra/GhidraClientWire.test.ts +++ b/src/ghidra/GhidraClientWire.test.ts @@ -209,6 +209,7 @@ it("refuses an invalid request seed without sending or leaving a pending reply", const result = await request; if (result.ok) throw new Error("Expected a configuration refusal"); expect(result.error.kind).toBe("admission"); + expect(result.error.configurationFailure).toBe(refusal); expect(result.error.cause).toBe(refusal); } finally { pending.failAll(() => ok(null)); diff --git a/src/ghidra/GhidraClientWire.ts b/src/ghidra/GhidraClientWire.ts index e57d154b68a..746076f220e 100644 --- a/src/ghidra/GhidraClientWire.ts +++ b/src/ghidra/GhidraClientWire.ts @@ -93,7 +93,9 @@ export class GhidraWire { } #refused(cause: ConfigurationError): GhidraSessionError { - return this.#options.failure("admission", cause.message, cause); + return this.#options.failure("admission", cause.message, cause, { + configurationFailure: cause, + }); } /** Write one authenticated request and return its correlated reply. */ diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index 75e46642e5d..885bf5cfdae 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -4955,7 +4955,7 @@ it("keeps a refused setting's configuration error through the provider boundary" "admission", refusal.message, {}, - { cause: refusal }, + { cause: refusal, configurationFailure: refusal }, ); const ghidra = provider(installationHost(), () => ({ start: async () => err(failure), diff --git a/src/ghidra/GhidraSessionError.ts b/src/ghidra/GhidraSessionError.ts index d09703eb606..173713140ae 100644 --- a/src/ghidra/GhidraSessionError.ts +++ b/src/ghidra/GhidraSessionError.ts @@ -1,3 +1,4 @@ +import type { ConfigurationError } from "../domain/configurationErrors.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisError, @@ -41,6 +42,7 @@ export const GHIDRA_STARTUP_DEADLINE_ELAPSED = /** Additional structured context for a Ghidra session failure. */ export interface GhidraSessionErrorOptions extends ErrorOptions { readonly cancellation?: { readonly reason: unknown }; + readonly configurationFailure?: ConfigurationError; readonly partialObservation?: AnalysisPartialObservation; readonly timeoutMs?: number; readonly remoteCode?: string; @@ -56,6 +58,7 @@ export class GhidraSessionError extends Error { readonly remoteCode: string | undefined; readonly cleanupFailure: AnalysisError | undefined; readonly cancellation: { readonly reason: unknown } | undefined; + readonly configurationFailure: ConfigurationError | undefined; readonly partialObservation: AnalysisPartialObservation | undefined; readonly concurrentCancellation: { readonly reason: unknown } | undefined; @@ -72,6 +75,7 @@ export class GhidraSessionError extends Error { this.remoteCode = options.remoteCode; this.cleanupFailure = options.cleanupFailure; this.cancellation = options.cancellation; + this.configurationFailure = options.configurationFailure; this.partialObservation = options.partialObservation; this.concurrentCancellation = options.concurrentCancellation; } @@ -136,6 +140,9 @@ export class GhidraSessionError extends Error { ...(this.cancellation === undefined ? {} : { cancellation: this.cancellation }), + ...(this.configurationFailure === undefined + ? {} + : { configurationFailure: this.configurationFailure }), ...(this.timeoutMs === undefined ? {} : { timeoutMs: this.timeoutMs }), ...(this.remoteCode === undefined ? {} : { remoteCode: this.remoteCode }), ...(cleanupFailure === undefined ? {} : { cleanupFailure }), @@ -156,6 +163,7 @@ const createGhidraSessionError = (failure: { readonly timeoutMs?: number; readonly remoteCode?: string; readonly cancellation?: { readonly reason: unknown }; + readonly configurationFailure?: ConfigurationError; readonly redact: (value: string, incomplete?: boolean) => string; }): GhidraSessionError => new GhidraSessionError( @@ -177,6 +185,9 @@ const createGhidraSessionError = (failure: { ? {} : { cancellation: failure.cancellation }), ...(failure.cause === undefined ? {} : { cause: failure.cause }), + ...(failure.configurationFailure === undefined + ? {} + : { configurationFailure: failure.configurationFailure }), ...(failure.timeoutMs === undefined ? {} : { timeoutMs: failure.timeoutMs }), @@ -211,7 +222,7 @@ export const bindGhidraSessionFailure = cause?: unknown, options: Pick< GhidraSessionErrorOptions, - "timeoutMs" | "remoteCode" | "cancellation" + "timeoutMs" | "remoteCode" | "cancellation" | "configurationFailure" > = {}, ): GhidraSessionError => { const failure = createGhidraSessionError({ diff --git a/src/ghidra/GhidraSessionErrorProjection.ts b/src/ghidra/GhidraSessionErrorProjection.ts index 4cb03e2e53a..f7adcb6bb0b 100644 --- a/src/ghidra/GhidraSessionErrorProjection.ts +++ b/src/ghidra/GhidraSessionErrorProjection.ts @@ -112,7 +112,8 @@ const projectPrimarySessionError = ( }; // A refused setting (for example the reply ceiling admitted before launch) // is already the caller-facing refusal with its setting and allowed values. - if (failure.cause instanceof ConfigurationError) return failure.cause; + if (failure.configurationFailure !== undefined) + return failure.configurationFailure; if (failure.kind === "checkpoint") { if (failure.cause instanceof AnalysisError) return analysisClientFailureForOperation( diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index 7064bcbe842..22dbb7036a9 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -35,7 +35,7 @@ import { import { hopperAppleEventsAuthorizationRejection, hopperCancelledBySignal, - type HopperCancelledError, + HopperCancelledError, type HopperError, type HopperLauncherOutcome, HopperProcessError, @@ -70,7 +70,11 @@ import { } from "../process/ProviderDeadline.js"; import { redactExplicitOutput } from "../domain/explicitSensitiveValues.js"; import { ProviderRunLineage } from "../process/ProviderRunLineage.js"; -import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; +import { + AbortedWait, + waitForAbortable, + waitForRetainedResult, +} from "../process/AbortablePromise.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { type ProviderProcessDiagnostic, @@ -501,9 +505,9 @@ export class HopperClient< attempt: HopperStartupAttempt, signal?: AbortSignal, ): Promise { - const waited = await waitForAbortable(attempt.promise, signal); - if (waited instanceof AbortedWait || (waited.ok && isAborted(signal))) - return err(hopperCancelledBySignal(signal)); + const waited = await waitForRetainedResult(attempt.promise, signal); + if (waited instanceof AbortedWait) + return err(new HopperCancelledError(waited.carried)); if (waited.ok || waited.error.cleanupIncomplete) return waited; return this.start(signal); } @@ -543,10 +547,11 @@ export class HopperClient< }; deadline.signal.addEventListener("abort", onStartupAbort, { once: true }); try { - const result = await this.#startWithin(deadline); - return result.ok && deadline.signal.aborted - ? await this.#startupFailure(await this.#interruptionFailure(deadline)) - : result; + return await deadline.finishStartup( + () => this.#startWithin(deadline), + async () => + this.#startupFailure(await this.#interruptionFailure(deadline)), + ); } finally { deadline.signal.removeEventListener("abort", onStartupAbort); if (this.#startupSignal === deadline.signal) diff --git a/src/hopper/HopperMachOImage.ts b/src/hopper/HopperMachOImage.ts index 972578b09ce..260f20b47eb 100644 --- a/src/hopper/HopperMachOImage.ts +++ b/src/hopper/HopperMachOImage.ts @@ -1,3 +1,9 @@ +import { + withOwnedFileHandle, + RegularFileCancelled, + RegularFileCleanupFailure, +} from "../filesystem/OwnedRegularFile.js"; +import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js"; import { createHash } from "node:crypto"; import { open, type FileHandle } from "node:fs/promises"; import { z } from "zod"; @@ -124,57 +130,63 @@ const inspectAndFinalizeHopperMachOImage = async ( owner: OwnedFileHandle, options: HopperMachOImageResolutionOptions, ): Promise> => { - let result: Result; - try { - result = await inspectHopperMachOImage( - target, - owner.handle, - options.signal, - ); - } catch (cause: unknown) { - result = - cause instanceof BinaryTargetError || - cause instanceof AnalysisCancelledError - ? err(cause) - : err( - new BinaryTargetError( - target.path, - `Cannot validate Mach-O image: ${errorMessage(cause)}`, - { cause }, - ), + let cancellationBeforeClose = false; + const readFailure = (cause: unknown): HopperMachOImageResolutionError => + cause instanceof BinaryTargetError || + cause instanceof AnalysisCancelledError + ? cause + : cause instanceof RegularFileOperationCancelled + ? cancelledBy("open_binary", carriedReason(cause.reason)) + : new BinaryTargetError( + target.path, + `Cannot validate Mach-O image: ${errorMessage(cause)}`, + { cause }, ); - } - const cancellationBeforeClose = options.signal?.aborted === true; - let closeOutcome: - | { readonly kind: "closed" } - | { readonly kind: "failed"; readonly cause: unknown }; try { - await owner.close(); - closeOutcome = { kind: "closed" }; + const image = await withOwnedFileHandle( + target.path, + owner, + options.signal === undefined ? {} : { signal: options.signal }, + async (handle) => { + try { + const inspected = await inspectHopperMachOImage( + target, + handle, + options.signal, + ); + if (!inspected.ok) throw inspected.error; + return inspected.value; + } finally { + cancellationBeforeClose = options.signal?.aborted === true; + } + }, + ); + return ok(image); } catch (cause: unknown) { - closeOutcome = { kind: "failed", cause }; + if (cause instanceof RegularFileCancelled) + return err(cancelledBy("open_binary", carriedReason(cause.reason))); + if (!(cause instanceof RegularFileCleanupFailure)) + return err(readFailure(cause)); + return retainHopperPreflightCloseFailure({ + target, + owner: cause.owner, + resourceScope: options.resourceScope, + failure: + cause.outcome.kind === "failed" + ? readFailure(cause.outcome.cause) + : undefined, + cancellationBeforeClose, + signal: options.signal, + closeFailure: cause.cleanupCause, + }); } - if (closeOutcome.kind === "closed") { - if (result.ok && options.signal?.aborted) - return err(cancelledBy("open_binary", options.signal)); - return result; - } - return retainHopperPreflightCloseFailure({ - target, - owner, - resourceScope: options.resourceScope, - result, - cancellationBeforeClose, - signal: options.signal, - closeFailure: closeOutcome.cause, - }); }; const retainHopperPreflightCloseFailure = (options: { readonly target: BinaryTarget & { readonly kind: "executable" }; readonly owner: OwnedFileHandle; readonly resourceScope: RetainedResourceScope; - readonly result: Result; + readonly failure: HopperMachOImageResolutionError | undefined; readonly cancellationBeforeClose: boolean; readonly signal: AbortSignal | undefined; readonly closeFailure: unknown; @@ -195,32 +207,25 @@ const retainHopperPreflightCloseFailure = (options: { resources: [resource], }; const cancellationIsPrimary = - (!options.result.ok && - options.result.error instanceof AnalysisCancelledError) || - (options.result.ok && options.cancellationBeforeClose); + options.failure instanceof AnalysisCancelledError || + (options.failure === undefined && options.cancellationBeforeClose); let failure: AnalysisError; let closeIsPrimary = false; - if (!options.result.ok) { + if (options.failure !== undefined) { failure = - options.result.error instanceof BinaryTargetError - ? new BinaryTargetError( - options.result.error.path, - options.result.error.reason, - { - ...(options.result.error.cause === undefined - ? {} - : { cause: options.result.error.cause }), - ...(options.result.error.constraint === undefined - ? {} - : { constraint: options.result.error.constraint }), - cleanup, - }, - ) - : cancelledBy( - "open_binary", - carriedReason(options.result.error.cause), - { cleanup }, - ); + options.failure instanceof BinaryTargetError + ? new BinaryTargetError(options.failure.path, options.failure.reason, { + ...(options.failure.cause === undefined + ? {} + : { cause: options.failure.cause }), + ...(options.failure.constraint === undefined + ? {} + : { constraint: options.failure.constraint }), + cleanup, + }) + : cancelledBy("open_binary", carriedReason(options.failure.cause), { + cleanup, + }); } else if (options.cancellationBeforeClose) { // cancellationBeforeClose records that the caller's signal had aborted. failure = cancelledBy( diff --git a/src/ida/IdaConfiguration.test.ts b/src/ida/IdaConfiguration.test.ts index 6fe69c6957b..028b41fbcf7 100644 --- a/src/ida/IdaConfiguration.test.ts +++ b/src/ida/IdaConfiguration.test.ts @@ -125,9 +125,14 @@ it("rejects registration growth beyond the byte limit after descriptor admission } }); -it.each(["admission", "growth"] as const)( - "keeps the 64 KiB rejection when the %s size check meets a denied close", - async (branch) => { +it.each([ + ["admission", "denied"], + ["growth", "denied"], + ["admission", "cancelled"], + ["admission", "cancelled-and-denied"], +] as const)( + "keeps the 64 KiB rejection from the %s size check through a %s close", + async (branch, closeOutcome) => { const root = await createTestTempDirectory("rea-ida-config-"); const path = join(root, "mcp.json"); await writeFile( @@ -152,33 +157,47 @@ it.each(["admission", "growth"] as const)( return source; }) : undefined; + const controller = new AbortController(); + const reason = new Error("cancel while closing the oversized registration"); const close = OwnedFileHandle.prototype.close; - let denied = false; const denial = new Error("descriptor close denied"); const closeSpy = vi .spyOn(OwnedFileHandle.prototype, "close") - .mockImplementation(function (this: OwnedFileHandle) { - if (!denied) { - denied = true; - return Promise.reject(denial); - } - return close.call(this); + .mockImplementationOnce(function (this: OwnedFileHandle) { + if (closeOutcome !== "denied") controller.abort(reason); + return closeOutcome === "cancelled" + ? close.call(this) + : Promise.reject(denial); }); try { const result = await readIdaConfiguration(path, { resourceScope: owner, + signal: controller.signal, }); if (result.ok) throw new Error("expected the size rejection"); expect(result.error.message).toContain("64 KiB"); - expect(result.error.cleanup).toMatchObject({ - reason: expect.stringContaining("descriptor close denied"), - resources: [path], - }); - expect(result.error.cleanupIncomplete).toBe(true); - expect(retained).toHaveLength(1); - await rm(path); - await retained[0]!.close(); - expect(result.error.cleanupIncomplete).toBe(false); + if (closeOutcome !== "denied") { + expect(result.error.secondaryFailures).toEqual([ + expect.objectContaining({ + _tag: "AnalysisCancelledError", + cause: reason, + }), + ]); + } + if (closeOutcome === "cancelled") { + expect(result.error.cleanupIncomplete).toBe(false); + expect(retained).toHaveLength(0); + } else { + expect(result.error.cleanup).toMatchObject({ + reason: expect.stringContaining("descriptor close denied"), + resources: [path], + }); + expect(result.error.cleanupIncomplete).toBe(true); + expect(retained).toHaveLength(1); + await rm(path); + await retained[0]!.close(); + expect(result.error.cleanupIncomplete).toBe(false); + } } finally { admission?.mockRestore(); closeSpy.mockRestore(); diff --git a/src/ida/IdaConfiguration.ts b/src/ida/IdaConfiguration.ts index 07958db317c..b0c7cac0a0d 100644 --- a/src/ida/IdaConfiguration.ts +++ b/src/ida/IdaConfiguration.ts @@ -1,3 +1,4 @@ +import { WindowsChangeTimeConfigurationError } from "../config/windowsChangeTimeSettle.js"; import { MAX_NODE_TIMER_DELAY_MS } from "../domain/analysisResourceLimits.js"; import { isAbsolute } from "node:path"; import { z } from "zod"; @@ -16,6 +17,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { withOwnedRegularFile, regularFileCancellation, + RegularFileCancelled, RegularFileCleanupFailure, type RegularFileOperationOutcome, } from "../filesystem/OwnedRegularFile.js"; @@ -261,6 +263,20 @@ export const readIdaConfiguration = ( ), ); } catch (cause: unknown) { + if (cause instanceof WindowsChangeTimeConfigurationError) + return err(cause); + const rejection = + cause instanceof RegularFileCancelled || + cause instanceof RegularFileCleanupFailure + ? completedRegistrationRejection(cause.outcome) + : undefined; + const cancellation = regularFileCancellation(cause); + if (cause instanceof RegularFileCancelled && rejection !== undefined) + return err( + rejection.retainSecondaryFailure( + cancelledBy("ida:registration", carriedReason(cause.reason)), + ), + ); if (cause instanceof NonRegularFileReadError) return err( idaConfigurationError( @@ -269,8 +285,7 @@ export const readIdaConfiguration = ( ), ); if (cause instanceof AnalysisCancelledError) throw cause; - const cancellation = regularFileCancellation(cause); - if (cancellation !== undefined) { + if (cancellation !== undefined && rejection === undefined) { if (cause instanceof RegularFileCleanupFailure) { const error = cancelledBy( "ida:registration", @@ -296,8 +311,7 @@ export const readIdaConfiguration = ( const primary = cause.outcome.kind === "failed" ? cause.outcome.cause - : (completedRegistrationRejection(cause.outcome) ?? - cause.cleanupCause); + : (rejection ?? cause.cleanupCause); const primaryMessage = primary instanceof ConfigurationError ? primary.message @@ -319,6 +333,10 @@ export const readIdaConfiguration = ( }, ], }); + if (cancellation !== undefined) + error.retainSecondaryFailure( + cancelledBy("ida:registration", carriedReason(cancellation.reason)), + ); closeLease?.bindCleanupError(error); return err(error); } diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index 5125d123a53..da1b6156285 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../../providers/runOwned.js"; import { capturedProviderOutput, providerResultDiagnostics, @@ -705,27 +706,22 @@ export class PwntoolsDecoder< ? result.value.diagnostics : result.error.capturedOutput; } - const cleanup = await this.#completeCleanup(() => this.#retire()); - if (result.ok && options?.signal?.aborted) - result = err( - cancelledBy(OPERATION, options.signal, { - partialObservation: result.value, - capturedOutput: result.value.diagnostics, - }), - ); - if (cleanup !== undefined) { - const failure = result.ok - ? cleanup - : analysisErrorWithCleanupDependencies( - result.error, - cleanup, - OPERATION, - ); - if (this.#pendingCleanup !== undefined) - this.#pendingCleanup.failure = failure; - return err(failure); - } - return result; + const finalized = await runOwned(async () => result, { + providerId: this.identity.id, + operation: OPERATION, + signal: options?.signal, + partial: (report) => report, + capturedOutput: (report, replacement) => + replacement === "cancellation" ? report.diagnostics : undefined, + close: async () => { + const cleanup = await this.#completeCleanup(() => this.#retire()); + if (cleanup !== undefined) throw cleanup; + }, + }); + const completed = finalizedResult(finalized); + if (!completed.ok && this.#pendingCleanup !== undefined) + this.#pendingCleanup.failure = completed.error; + return completed; } async #runCommand( diff --git a/src/process/AbortablePromise.ts b/src/process/AbortablePromise.ts index 07e79ce289e..e99210590cc 100644 --- a/src/process/AbortablePromise.ts +++ b/src/process/AbortablePromise.ts @@ -1,3 +1,4 @@ +import type { Result } from "../domain/result.js"; import { cancelledBy, type CarriedCancellationReason, @@ -39,6 +40,16 @@ export const waitForAbortable = async ( } }; +/** Join a retiring owner, preserving a reported failure even if the waiter has since aborted. */ +export const waitForRetainedResult = async ( + pending: Promise>, + signal: AbortSignal | undefined, +): Promise | AbortedWait> => { + const observed = await waitForAbortable(pending, signal); + if (observed instanceof AbortedWait || !observed.ok) return observed; + return signal?.aborted ? new AbortedWait(signal.reason) : observed; +}; + /** * Await the previous holder of a serialized command turn. A caller abort that * wins the wait becomes `operation`'s cancellation with the caller's reason. diff --git a/src/process/ProviderDeadline.test.ts b/src/process/ProviderDeadline.test.ts index 15065448242..72e1801e214 100644 --- a/src/process/ProviderDeadline.test.ts +++ b/src/process/ProviderDeadline.test.ts @@ -1,3 +1,4 @@ +import { err, ok } from "../domain/result.js"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { ProviderStartupDeadline } from "./ProviderDeadline.js"; @@ -86,6 +87,29 @@ it("classifies elapsed time before a delayed timer callback and a later abort", } }); +it.each([true, false])( + "uses the final monotonic cutoff for startup readiness (successful reply: %s)", + async (succeeded) => { + const now = vi.spyOn(performance, "now").mockReturnValue(0); + const deadline = new ProviderStartupDeadline(1000); + const refusal = err(new Error("startup refusal already observed")); + const interrupted = err(new Error("startup deadline elapsed")); + const interrupt = vi.fn(async () => interrupted); + try { + const result = await deadline.finishStartup(async () => { + // The handshake settles before the timer callback can observe expiry. + now.mockReturnValue(1001); + return succeeded ? ok("ready") : refusal; + }, interrupt); + expect(deadline.signal.aborted).toBe(false); + expect(result).toBe(succeeded ? interrupted : refusal); + expect(interrupt).toHaveBeenCalledTimes(succeeded ? 1 : 0); + } finally { + deadline.dispose(); + } + }, +); + it("keeps remaining milliseconds integral for downstream request budgets", () => { const now = vi.spyOn(performance, "now").mockReturnValue(10.25); const deadline = new ProviderStartupDeadline(1000); diff --git a/src/process/ProviderDeadline.ts b/src/process/ProviderDeadline.ts index cc7edb501c3..9dead878294 100644 --- a/src/process/ProviderDeadline.ts +++ b/src/process/ProviderDeadline.ts @@ -1,3 +1,4 @@ +import type { Result } from "../domain/result.js"; import { Deadline } from "../domain/deadline.js"; /** Result of an abort-aware interval wait. */ @@ -125,6 +126,16 @@ export class ProviderStartupDeadline { return poll(); } + /** Settle readiness under this deadline while leaving failed startup primary. */ + async finishStartup( + start: () => Promise>, + interrupt: () => Promise>, + ): Promise> { + const outcome = await start(); + if (!outcome.ok) return outcome; + return this.interruption === undefined ? outcome : interrupt(); + } + /** * Begin finalizing a failed or interrupted startup. The finalize budget * starts now and only the caller's signal interrupts it, so work that diff --git a/src/providers/runOwned.ts b/src/providers/runOwned.ts index 6c00a2c6323..2dc5eda5227 100644 --- a/src/providers/runOwned.ts +++ b/src/providers/runOwned.ts @@ -7,6 +7,8 @@ import { AnalysisError, primaryAnalysisError, type AnalysisPartialObservation, + type AnalysisCapturedOutput, + type AnalysisErrorOptions, } from "../domain/analysisErrorBase.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; @@ -94,13 +96,14 @@ export type CompletedValueRecord = readonly diagnostics: ( value: Value, replacedBy: CompletedValueReplacement, - ) => Readonly>; + ) => Readonly> | undefined; readonly partial?: never; }; -type KeptCompletion = - | { readonly partialObservation: AnalysisPartialObservation } - | { readonly diagnostics: Readonly> }; +type KeptCompletion = Pick< + AnalysisErrorOptions, + "partialObservation" | "diagnostics" | "capturedOutput" +>; export type RunOwnedOptions = RunOwnedBaseOptions & CompletedValueRecord; @@ -126,8 +129,20 @@ interface RunOwnedBaseOptions { * the operation and its work budget. */ readonly timeoutRecovery?: AnalysisTimeoutRecovery | undefined; - /** Releases everything the work acquired; awaited before the signal is read. */ - readonly close: () => Promise; + /** Releases everything the work acquired before reporting completion. */ + readonly close?: () => Promise; + /** Existing contracts can keep a failed close primary over cancellation of completed work. */ + readonly cleanupFailureBeforeCancellation?: true; + /** Preserve a provider's published cleanup envelope. The finalizer binds both owners. */ + readonly composeCleanupFailure?: ( + primary: AnalysisError, + cleanup: AnalysisError, + ) => AnalysisError; + /** Retain separately bounded command output alongside the observation on cancellation. */ + readonly capturedOutput?: ( + value: Value, + replacedBy: CompletedValueReplacement, + ) => AnalysisCapturedOutput | undefined; /** Names the owned resources when a non-REA close failure names none. */ readonly fallbackResource?: string; /** @@ -156,21 +171,36 @@ interface RunOwnedBaseOptions { } const keepCompleted = ( - record: CompletedValueRecord, + record: RunOwnedOptions, value: Value, replacedBy: CompletedValueReplacement, -): KeptCompletion => - record.partial === undefined - ? { diagnostics: record.diagnostics(value, replacedBy) } - : { partialObservation: record.partial(value, replacedBy) }; + priorDiagnostics?: Readonly>, +): KeptCompletion => { + const capturedOutput = record.capturedOutput?.(value, replacedBy); + const observation = record.partial?.(value, replacedBy); + const recorded = record.diagnostics?.(value, replacedBy); + const diagnostics = + priorDiagnostics === undefined + ? recorded + : { ...priorDiagnostics, ...recorded }; + return { + ...(observation === undefined ? {} : { partialObservation: observation }), + ...(diagnostics === undefined ? {} : { diagnostics }), + ...(capturedOutput === undefined ? {} : { capturedOutput }), + }; +}; const retainCompleted = ( error: AnalysisError, kept: KeptCompletion, -): AnalysisError => - "partialObservation" in kept - ? error.retainPartialObservation(kept.partialObservation) - : error.retainDiagnostics(kept.diagnostics); +): AnalysisError => { + if (kept.partialObservation !== undefined) + error.retainPartialObservation(kept.partialObservation); + if (kept.diagnostics !== undefined) error.retainDiagnostics(kept.diagnostics); + if (kept.capturedOutput !== undefined) + error.retainCapturedOutput(kept.capturedOutput); + return error; +}; const closeFailure = ( cause: unknown, @@ -245,6 +275,7 @@ const closeWithin = async ( | "fallbackResource" >, ): Promise => { + if (options.close === undefined) return undefined; const closing = options.close(); const deadline = options.deadline; if (deadline === undefined) { @@ -385,7 +416,8 @@ export const runOwned = async ( try { // Owners may resolve the primary's retained cleanup during close; only // they can confirm it, so its status is read again afterwards. - const unfinished = await closeWithin(options); + const unfinished = + options.close === undefined ? undefined : await closeWithin(options); if (unfinished !== undefined) cleanup = { kind: "retained", failure: unfinished }; } catch (cause) { @@ -530,13 +562,10 @@ export const runOwned = async ( }; if (outcome.ok && !committed) { // The value arrived after the budget elapsed and was not published. - const kept = keepCompleted(options, outcome.value, "failure"); outcome = { ok: false, error: timeout( - "partialObservation" in kept - ? { partialObservation: kept.partialObservation } - : { diagnostics: { ...outcome.diagnostics, ...kept.diagnostics } }, + keepCompleted(options, outcome.value, "failure", outcome.diagnostics), ), }; } else if (!outcome.ok && budgetCancellation(outcome.error)) @@ -566,22 +595,27 @@ export const runOwned = async ( value: outcome.value, lateCancellation: signal.reason, }; - if (!committed) { + if ( + cleanup.kind === "retained" && + options.cleanupFailureBeforeCancellation === true + ) { + analysisErrorWithCancellation( + cleanup.failure, + cancelledBy(options.operation, signal), + ); + } else if (!committed) { cancelled = true; - const kept = keepCompleted(options, outcome.value, "cancellation"); outcome = { ok: false, error: cancelledBy( options.operation, signal, - "partialObservation" in kept - ? { - partialObservation: kept.partialObservation, - ...(outcome.diagnostics === undefined - ? {} - : { diagnostics: outcome.diagnostics }), - } - : { diagnostics: { ...outcome.diagnostics, ...kept.diagnostics } }, + keepCompleted( + options, + outcome.value, + "cancellation", + outcome.diagnostics, + ), ), }; } @@ -605,6 +639,7 @@ export const runOwned = async ( outcome.error, cleanup.failure, options.operation, + options.composeCleanupFailure, ), cleanup, }; diff --git a/src/reference/ReferenceSourceReaderEntries.ts b/src/reference/ReferenceSourceReaderEntries.ts index a269013cb29..128d6be8b93 100644 --- a/src/reference/ReferenceSourceReaderEntries.ts +++ b/src/reference/ReferenceSourceReaderEntries.ts @@ -188,10 +188,12 @@ export const traverseDirectory = async ( : ((await state.beforeDirectory?.( pathFromRoot(state.root, current.path), )) ?? ok(undefined)); - if (result.ok && isAborted(state.signal)) - result = err(cancelled(state.signal)); - while (result.ok) { - while (!listingComplete && listed.length < OBSERVATION_WINDOW) { + while (result.ok && !isAborted(state.signal)) { + while ( + !listingComplete && + listed.length < OBSERVATION_WINDOW && + !isAborted(state.signal) + ) { let child: Dirent | null; try { child = await handle.read(); @@ -237,7 +239,12 @@ export const traverseDirectory = async ( directories, ); } - if (result.ok && listingFailure !== undefined) { + if ( + listingFailure !== undefined && + (result.ok || result.error.code === "cancelled") + ) { + // A later cancellation cannot replace a completed directory read failure. + result = ok(undefined); readFailureCause = listingFailure.cause; if (current.path === state.root && readFailureCause !== undefined) state.rootFailureCause = readFailureCause; diff --git a/src/sqlite/SqliteDatabaseProvider.ts b/src/sqlite/SqliteDatabaseProvider.ts index b9c4f2e8150..531bbfbd83f 100644 --- a/src/sqlite/SqliteDatabaseProvider.ts +++ b/src/sqlite/SqliteDatabaseProvider.ts @@ -1,3 +1,4 @@ +import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { providerCleanupErrorFromFailures } from "../domain/analysisErrorCleanup.js"; import { createAnalysisExecution, @@ -353,91 +354,98 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { retainedOutput ??= failure.capturedOutput; result = err(failure); } - if (root !== undefined) { - if (processOwner !== undefined) { - const ownership = processOwner.launch.ownership; - const rootRelease = new AnalysisCleanupRelease(); - const rootFailure = rootRelease.bind(sqliteRootFailure(root)); - const processReason = - processCleanup?.reason ?? "SQLite worker cleanup remains unresolved."; - const processRelease = new AnalysisCleanupRelease(); - const processFailure = processRelease.bind( - new ProviderCleanupError( - SQLITE_PROVIDER_IDENTITY.id, - ownership === undefined - ? ["owned-sqlite-worker"] - : ownedCommandResources(ownership), - { reason: processReason }, - { operation }, - ), - ); - this.#pendingCleanup.set(root, { - input, - result, - output: retainedOutput, - rootFailure, - rootRelease, - processFailure, - processRelease, - process: processOwner, - }); - if (processCleanup !== undefined) { - const failure = sqliteCleanupFailure( - ownership === undefined - ? ["owned-sqlite-worker", root.path] - : ownedCommandResources(ownership, root.path), - processCleanup.reason, - result, - input, - retainedOutput, - processCleanup.cleanupResult === undefined - ? undefined - : { - ...(processCleanup.cleanupResult.failures === undefined - ? {} - : { - failures: processCleanup.cleanupResult.failures.map( - (failure) => ({ ...failure }), - ), - }), - ...(processCleanup.cleanupResult.unverified === undefined - ? {} - : { - unverified: processCleanup.cleanupResult.unverified.map( - (process) => ({ ...process }), - ), - }), - }, - ); - failure.bindCleanupDependencies([processFailure, rootFailure]); - return err(failure); - } - if (!result.ok) { - result.error.bindCleanupDependencies([processFailure, rootFailure]); - return result; - } + if (root !== undefined && processOwner !== undefined) { + const ownership = processOwner.launch.ownership; + const rootRelease = new AnalysisCleanupRelease(); + const rootFailure = rootRelease.bind(sqliteRootFailure(root)); + const processReason = + processCleanup?.reason ?? "SQLite worker cleanup remains unresolved."; + const processRelease = new AnalysisCleanupRelease(); + const processFailure = processRelease.bind( + new ProviderCleanupError( + SQLITE_PROVIDER_IDENTITY.id, + ownership === undefined + ? ["owned-sqlite-worker"] + : ownedCommandResources(ownership), + { reason: processReason }, + { operation }, + ), + ); + this.#pendingCleanup.set(root, { + input, + result, + output: retainedOutput, + rootFailure, + rootRelease, + processFailure, + processRelease, + process: processOwner, + }); + if (processCleanup !== undefined) { const failure = sqliteCleanupFailure( - [ - ...(ownership === undefined - ? ["owned-sqlite-worker"] - : ownedCommandResources(ownership)), - root.path, - ], - processReason, + ownership === undefined + ? ["owned-sqlite-worker", root.path] + : ownedCommandResources(ownership, root.path), + processCleanup.reason, result, input, retainedOutput, + processCleanup.cleanupResult === undefined + ? undefined + : { + ...(processCleanup.cleanupResult.failures === undefined + ? {} + : { + failures: processCleanup.cleanupResult.failures.map( + (failure) => ({ ...failure }), + ), + }), + ...(processCleanup.cleanupResult.unverified === undefined + ? {} + : { + unverified: processCleanup.cleanupResult.unverified.map( + (process) => ({ ...process }), + ), + }), + }, ); failure.bindCleanupDependencies([processFailure, rootFailure]); return err(failure); } - const cleaned = await cleanupSqliteRoot( - root, + if (!result.ok) { + result.error.bindCleanupDependencies([processFailure, rootFailure]); + return result; + } + const failure = sqliteCleanupFailure( + [ + ...(ownership === undefined + ? ["owned-sqlite-worker"] + : ownedCommandResources(ownership)), + root.path, + ], + processReason, result, input, retainedOutput, ); - if (!cleaned.ok) { + failure.bindCleanupDependencies([processFailure, rootFailure]); + return err(failure); + } + const finalized = await runOwned(async () => result, { + providerId: SQLITE_PROVIDER_IDENTITY.id, + operation, + signal: options?.signal, + partial: (execution) => completedSqliteEvidence(input, execution), + cleanupFailureBeforeCancellation: true, + close: async () => { + if (root === undefined) return; + const cleaned = await cleanupSqliteRoot( + root, + result, + input, + retainedOutput, + ); + if (cleaned.ok) return; const rootRelease = new AnalysisCleanupRelease(); const rootFailure = rootRelease.bind(sqliteRootFailure(root)); cleaned.error.bindCleanupDependencies([rootFailure]); @@ -451,16 +459,13 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { processRelease: new AnalysisCleanupRelease(), process: undefined, }); - return cleaned; - } - } - if (result.ok && options?.signal?.aborted) - return err( - cancelledBy(operation, options.signal, { - partialObservation: completedSqliteEvidence(input, result.value), - }), - ); - return result; + throw cleaned.error; + }, + // The SQLite adapter already owns a compact cleanup envelope with its + // primary diagnostic and exact root release claim. + composeCleanupFailure: (_primary, cleanup) => cleanup, + }); + return finalizedResult(finalized); } } diff --git a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts index bfbb93f871e..0a1a6a3620e 100644 --- a/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts +++ b/tests/acceptance/setup/registrationRuntimeEnvironmentCli.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { access, mkdir, @@ -141,7 +142,7 @@ cliTest( expect(configured).not.toContain("do not copy"); expect( effectiveClientServer( - parseClientConfiguration(configured, "json"), + expectResultValue(parseClientConfiguration(configured, "json")), "rea", ), ).toHaveProperty("env", selected); @@ -168,7 +169,7 @@ cliTest( expect(updated.exitCode, updated.stdout).toBe(0); const saved = await readFile(config, "utf8"); expect(saved).not.toContain("do not copy"); - const parsed = parseClientConfiguration(saved, "json"); + const parsed = expectResultValue(parseClientConfiguration(saved, "json")); expect(effectiveClientServer(parsed, "foreign")).toEqual(foreign); expect(effectiveClientServer(parsed, "rea")).toHaveProperty("env", { ...changed, @@ -532,7 +533,9 @@ for (const scenario of scenarios) ]); expect(configured.exitCode, configured.stdout).toBe(0); const text = await readFile(config, "utf8"); - const parsed = parseClientConfiguration(text, scenario.format); + const parsed = expectResultValue( + parseClientConfiguration(text, scenario.format), + ); expect(effectiveClientServer(parsed, "rea")).toMatchObject({ env: { CALLER_SETTING: "keep exactly", @@ -729,7 +732,7 @@ cliTest( const text = await readFile(config, "utf8"); expect(text).not.toContain("REA_UNRELATED_MARKER"); const registration = effectiveClientServer( - parseClientConfiguration(text, format), + expectResultValue(parseClientConfiguration(text, format)), "rea", ); expect(registration).toMatchObject(timeout); @@ -927,7 +930,9 @@ XDG_CONFIG_HOME = ${JSON.stringify(clientRoot)} ], }); const registration = effectiveClientServer( - parseClientConfiguration(await readFile(codex, "utf8"), "toml"), + expectResultValue( + parseClientConfiguration(await readFile(codex, "utf8"), "toml"), + ), "rea", ); expect(registration).toMatchObject({ @@ -993,9 +998,11 @@ cliTest( const setup = await run(["setup", "--yes"], configHome); expect(setup.exitCode, setup.stdout).toBe(0); const registration = effectiveClientServer( - parseClientConfiguration( - await readFile(join(codexHome, "config.toml"), "utf8"), - "toml", + expectResultValue( + parseClientConfiguration( + await readFile(join(codexHome, "config.toml"), "utf8"), + "toml", + ), ), "rea", ); @@ -1127,7 +1134,12 @@ for (const [client, provider] of [ const text = await readFile(config, "utf8"); expect( effectiveClientServer( - parseClientConfiguration(text, client === "codex" ? "toml" : "kimi"), + expectResultValue( + parseClientConfiguration( + text, + client === "codex" ? "toml" : "kimi", + ), + ), "rea", ), ).toMatchObject({ diff --git a/tests/acceptance/setup/selectedClientHomePaths.test.ts b/tests/acceptance/setup/selectedClientHomePaths.test.ts index 46bc514aaf9..19f8aaf568d 100644 --- a/tests/acceptance/setup/selectedClientHomePaths.test.ts +++ b/tests/acceptance/setup/selectedClientHomePaths.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { access, mkdir, @@ -71,9 +72,8 @@ cliTest.skipIf(process.platform === "win32")( }); const configured = await run(); expect(configured.exitCode, configured.stdout + configured.stderr).toBe(0); - const registered = parseClientConfiguration( - await readFile(config, "utf8"), - "toml", + const registered = expectResultValue( + parseClientConfiguration(await readFile(config, "utf8"), "toml"), ); expect(registered.document.model).toBe("selected-model"); expect(registered.servers.other).toMatchObject({ command: "other-server" }); diff --git a/tests/boundary/browser/cdpElectronProvider.test.ts b/tests/boundary/browser/cdpElectronProvider.test.ts index 70b4912cc92..7b886501048 100644 --- a/tests/boundary/browser/cdpElectronProvider.test.ts +++ b/tests/boundary/browser/cdpElectronProvider.test.ts @@ -481,10 +481,11 @@ describe("CdpElectronProvider target access", () => { it("retains a completed page observation when cancellation arrives during final detach", async () => { const root = await electronFixture(); const controller = new AbortController(); + const reason = { request: "cancel during Electron detach" }; const browser = await startFakeCdpBrowser({ electronFileUrl: pathToFileURL(join(root, "index.html")).href, commandEvents: ({ method }) => { - if (method === "Target.detachFromTarget") controller.abort(); + if (method === "Target.detachFromTarget") controller.abort(reason); return undefined; }, }); @@ -503,6 +504,7 @@ describe("CdpElectronProvider target access", () => { if (result.ok) throw new Error("Expected late cancellation"); expect(result.error).toBeInstanceOf(AnalysisCancelledError); + expect(result.error.cause).toBe(reason); expect(result.error.partialObservation).toMatchObject({ kind: "electron-page-observation", cleanup: "transport-closed", @@ -642,6 +644,7 @@ describe("CdpElectronProvider transport lifecycle", () => { expect(first.error.cleanupIncomplete).toBe(true); expect(first.error.partialObservation).toMatchObject({ kind: "electron-page-observation", + cleanup: "incomplete", inspection: { target: { file_path: join(root, "index.html") } }, }); const failedCloses = closes; diff --git a/tests/boundary/evm/evmoleInterfaceProvider.test.ts b/tests/boundary/evm/evmoleInterfaceProvider.test.ts index 99b6a48d75f..2a0f0f3fd21 100644 --- a/tests/boundary/evm/evmoleInterfaceProvider.test.ts +++ b/tests/boundary/evm/evmoleInterfaceProvider.test.ts @@ -938,6 +938,9 @@ it expect(result.error.cause).toBe(reason); else expect(result.error.cleanupIncomplete).toBe(true); if (scenario === "cancelled-cleanup-failure") { + expect(result.error.diagnostics?.["reason"]).toBe( + "reported cleanup failure", + ); expect(result.error.cleanupPrimary?.cause).toBe(reason); denyClose = false; await provider.close(); diff --git a/tests/boundary/filesystem/clientConfigurationBom.test.ts b/tests/boundary/filesystem/clientConfigurationBom.test.ts index b36cad1796d..88d62e702c2 100644 --- a/tests/boundary/filesystem/clientConfigurationBom.test.ts +++ b/tests/boundary/filesystem/clientConfigurationBom.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; @@ -70,7 +71,8 @@ describe.each(["vscode", "copilot_cli", "opencode", "commandcode"])( ).toBe(true); } expect( - parseClientConfiguration(updated, client.format).document, + expectResultValue(parseClientConfiguration(updated, client.format)) + .document, ).toEqual({ label: "left\uFEFFright", [serversKey]: { @@ -137,9 +139,13 @@ it.each(['\uFEFF{"servers": {"rea": @}}', '\uFEFF{"setting":\uFEFFtrue}'])( } as const; await writeFile(configPath, original); const invalidOffset = original.includes("@") ? original.indexOf("@") : 12; - expect(() => parseClientConfiguration(original, client.format)).toThrow( - `Invalid JSON/JSONC at offset ${invalidOffset}: InvalidSymbol`, - ); + expect(parseClientConfiguration(original, client.format)).toMatchObject({ + ok: false, + error: { + kind: "syntax", + detail: `Invalid JSON/JSONC at offset ${invalidOffset}: InvalidSymbol`, + }, + }); expect( await inspectClientConfiguration(client, {}, ["rea", "mcp"]), @@ -178,7 +184,9 @@ it("preserves BOM-prefixed JSONC values and comments through update and removal" await configureClientConfiguration(client, {}, updatedCommand), ).toMatchObject({ status: "configured" }); const updated = await readFile(client.configPath, "utf8"); - expect(parseClientConfiguration(updated, client.format).servers).toEqual({ + expect( + expectResultValue(parseClientConfiguration(updated, client.format)).servers, + ).toEqual({ other: { command: "other\uFEFFtool" }, rea: clientRegistrationEntry(client.format, updatedCommand, {}), }); @@ -192,8 +200,12 @@ it("preserves BOM-prefixed JSONC values and comments through update and removal" expect(removed).toContain("\r\n // Keep prefix \uFEFF comment.\r\n"); expect(removed).toContain("\r\n // Keep suffix comment.\r\n"); expect(removed).toContain("// Keep this unrelated registration."); - expect(parseClientConfiguration(removed, client.format).document).toEqual( - parseClientConfiguration(original, client.format).document, + expect( + expectResultValue(parseClientConfiguration(removed, client.format)) + .document, + ).toEqual( + expectResultValue(parseClientConfiguration(original, client.format)) + .document, ); expect( Buffer.compare( diff --git a/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts b/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts index f1fcf077c7c..57dfbd382b8 100644 --- a/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts +++ b/tests/boundary/filesystem/clientConfigurationEnvironment.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { access, mkdir, readFile, writeFile } from "node:fs/promises"; @@ -92,9 +93,8 @@ it.each([ status: "configured", backupPath: `${configPath}.rea.backup`, }); - const current = parseClientConfiguration( - await readFile(configPath, "utf8"), - "kimi", + const current = expectResultValue( + parseClientConfiguration(await readFile(configPath, "utf8"), "kimi"), ); expect(current.servers.rea).toMatchObject({ toolTimeoutMs: deadline }); expect(current.servers.rea).toHaveProperty("env", env); @@ -235,7 +235,7 @@ it.skipIf(process.platform !== "win32").each([ if (duplicate) expect(text).toContain("# retain winning rationale"); expect(text).toContain("!!js caller.custom"); const env = clientRegistrationEnvironmentDetails( - parseClientConfiguration(text, "dsh"), + expectResultValue(parseClientConfiguration(text, "dsh")), undefined, HOST_PLATFORM.platform, ); @@ -282,9 +282,8 @@ it("preserves a lowercase explicit Kimi schema profile instead of inserting a co expect(await configureClientConfiguration(client, {}, command)).toMatchObject( { status: "configured" }, ); - const parsed = parseClientConfiguration( - await readFile(configPath, "utf8"), - "kimi", + const parsed = expectResultValue( + parseClientConfiguration(await readFile(configPath, "utf8"), "kimi"), ); expect(effectiveClientServer(parsed, "rea")).toHaveProperty("env", { rea_mcp_input_schema_profile: "compact", @@ -326,7 +325,7 @@ it expect(text).toContain("REA_ANALYSIS_PROVIDER: ghidra"); expect(text).toContain("!!js caller.custom"); const details = clientRegistrationEnvironmentDetails( - parseClientConfiguration(text, "dsh"), + expectResultValue(parseClientConfiguration(text, "dsh")), undefined, HOST_PLATFORM.platform, ); @@ -352,11 +351,13 @@ it.skipIf(process.platform !== "win32").each([ ])( "keeps Windows override precedence consistent with the launched environment: $expected", ({ existing, overrides, expected }) => { - const parsed = parseClientConfiguration( - JSON.stringify({ - mcpServers: { rea: { command: "rea", args: ["mcp"], env: existing } }, - }), - "json", + const parsed = expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { rea: { command: "rea", args: ["mcp"], env: existing } }, + }), + "json", + ), ); const result = clientRegistrationEnvironmentDetails( parsed, @@ -464,7 +465,9 @@ it.each([ ); if (!serialized.ok) throw new Error("fixture serialization failed"); const original = serialized.value; - const originalParsed = parseClientConfiguration(original, format); + const originalParsed = expectResultValue( + parseClientConfiguration(original, format), + ); await writeFile(configPath, original); const providers = { GHIDRA_INSTALL_DIR: join(root, "new-ghidra") }; const command = ["rea", "mcp"]; @@ -475,7 +478,9 @@ it.each([ await configureClientConfiguration(client, providers, command), ).toMatchObject({ status: "configured" }); const configured = await readFile(configPath, "utf8"); - const parsed = parseClientConfiguration(configured, format); + const parsed = expectResultValue( + parseClientConfiguration(configured, format), + ); expect(Object.hasOwn(parsed.document, "__proto__")).toBe(true); expect(parsed.document["__proto__"]).toEqual({ caller: "retain root value", @@ -522,7 +527,7 @@ it.each(["linux", "win32"] as const)( CUSTOM: !!js caller.custom `; const details = clientRegistrationEnvironmentDetails( - parseClientConfiguration(source, "dsh"), + expectResultValue(parseClientConfiguration(source, "dsh")), undefined, platform, {}, @@ -539,15 +544,17 @@ it.each(["linux", "win32"] as const)( ); it("retains an unresolved JEB endpoint expression until a selected literal replaces it", async () => { - const parsed = parseClientConfiguration( - `- insert: + const parsed = expectResultValue( + parseClientConfiguration( + `- insert: - id: rea-mcp name: "@deepseek-ai/dsh-mcp-client" config: env: REA_JEB_MCP_URL: !!js caller.endpoint `, - "dsh", + "dsh", + ), ); const unresolved = await clientRegistrationEnvironmentDetailsWithBudget( parsed, @@ -588,8 +595,9 @@ it.each( )( "keeps expression-backed $setting unknown on $platform when deriving timeout guidance", async ({ setting, platform }) => { - const parsed = parseClientConfiguration( - `- insert: + const parsed = expectResultValue( + parseClientConfiguration( + `- insert: - id: rea-mcp name: "@deepseek-ai/dsh-mcp-client" config: @@ -597,7 +605,8 @@ it.each( ${platform === "win32" ? setting.toLowerCase() : setting}: !!js caller.setting CALLER_SETTING: retained `, - "dsh", + "dsh", + ), ); const values = clientRegistrationEnvironment( parsed, @@ -654,8 +663,9 @@ it.each( ); it("retains an unknown companion while deriving unrelated literal timeout facts", () => { - const parsed = parseClientConfiguration( - `- insert: + const parsed = expectResultValue( + parseClientConfiguration( + `- insert: - id: rea-mcp name: "@deepseek-ai/dsh-mcp-client" config: @@ -664,7 +674,8 @@ it("retains an unknown companion while deriving unrelated literal timeout facts" REA_GHIDRA_COMPILER_SPEC_ID: borlandcpp REA_GHIDRA_STARTUP_TIMEOUT_MS: "17000" `, - "dsh", + "dsh", + ), ); const details = clientRegistrationEnvironmentDetails( parsed, @@ -679,8 +690,9 @@ it("retains an unknown companion while deriving unrelated literal timeout facts" }); it("does not resolve a provider budget from an expression omitted from literal values", async () => { - const parsed = parseClientConfiguration( - `- insert: + const parsed = expectResultValue( + parseClientConfiguration( + `- insert: - id: rea-mcp name: "@deepseek-ai/dsh-mcp-client" config: @@ -688,7 +700,8 @@ it("does not resolve a provider budget from an expression omitted from literal v REA_ANALYSIS_PROVIDER: ida REA_IDA_MCP_CONFIG: !!js caller.idaConfig `, - "dsh", + "dsh", + ), ); const observations: string[] = []; const resolveBudget = async ( @@ -801,9 +814,8 @@ it("retains legacy OpenCode environment when migrating into a native server tabl expect( await configureClientConfiguration(client, {}, ["rea", "mcp"]), ).toMatchObject({ status: "configured" }); - const parsed = parseClientConfiguration( - await readFile(configPath, "utf8"), - "opencode", + const parsed = expectResultValue( + parseClientConfiguration(await readFile(configPath, "utf8"), "opencode"), ); expect(parsed.legacyServers).toEqual({}); expect(parsed.servers.rea).toEqual( @@ -945,9 +957,8 @@ it.each([ ] as const)( "identifies the malformed registration setting for %s", (_name, env, setting) => { - const parsed = parseClientConfiguration( - registrationWithEnvironment(env), - "json", + const parsed = expectResultValue( + parseClientConfiguration(registrationWithEnvironment(env), "json"), ); expect( clientRegistrationEnvironmentDetails( @@ -1050,17 +1061,19 @@ it("refuses an unidentified launch command before creating a client configuratio }); it("treats a variable-expanding client's recorded expression as unresolved", () => { - const parsed = parseClientConfiguration( - JSON.stringify({ - mcpServers: { - rea: { - command: "rea", - args: ["mcp"], - env: { PATH: "${PATH}:/opt/jdk/bin", JAVA_HOME: "/opt/jdk" }, + const parsed = expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { + rea: { + command: "rea", + args: ["mcp"], + env: { PATH: "${PATH}:/opt/jdk/bin", JAVA_HOME: "/opt/jdk" }, + }, }, - }, - }), - "json", + }), + "json", + ), ); const qwen = clientRegistrationEnvironmentDetails( parsed, @@ -1091,17 +1104,19 @@ it("treats a variable-expanding client's recorded expression as unresolved", () }); it("keeps a typed Qwen setting unresolved without discarding its recorded expression", () => { - const parsed = parseClientConfiguration( - JSON.stringify({ - mcpServers: { - rea: { - command: "rea", - args: ["mcp"], - env: { REA_GHIDRA_STARTUP_TIMEOUT_MS: "${JOBS}" }, + const parsed = expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { + rea: { + command: "rea", + args: ["mcp"], + env: { REA_GHIDRA_STARTUP_TIMEOUT_MS: "${JOBS}" }, + }, }, - }, - }), - "json", + }), + "json", + ), ); const details = clientRegistrationEnvironmentDetails( parsed, @@ -1120,17 +1135,19 @@ it("keeps a typed Qwen setting unresolved without discarding its recorded expres }); it("keeps a differently cased Qwen expression unresolved on Windows", () => { - const parsed = parseClientConfiguration( - JSON.stringify({ - mcpServers: { - rea: { - command: "rea", - args: ["mcp"], - env: { rea_ghidra_startup_timeout_ms: "${JOBS}" }, + const parsed = expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { + rea: { + command: "rea", + args: ["mcp"], + env: { rea_ghidra_startup_timeout_ms: "${JOBS}" }, + }, }, - }, - }), - "json", + }), + "json", + ), ); const details = clientRegistrationEnvironmentDetails( parsed, @@ -1157,21 +1174,23 @@ it.each([ ] as const)( "reads only the profile-selected %s environment with nested value %j", (name, value) => { - const parsed = parseClientConfiguration( - JSON.stringify({ - mcpServers: { - rea: { - command: "outer", - env: { SELECTED: "outer" }, - transport: { - type: "stdio", - command: "nested", - env: { SELECTED: value }, + const parsed = expectResultValue( + parseClientConfiguration( + JSON.stringify({ + mcpServers: { + rea: { + command: "outer", + env: { SELECTED: "outer" }, + transport: { + type: "stdio", + command: "nested", + env: { SELECTED: value }, + }, }, }, - }, - }), - "json", + }), + "json", + ), ); const details = clientRegistrationEnvironmentDetails( parsed, diff --git a/tests/boundary/filesystem/clientConfigurationLayeredEnvironment.test.ts b/tests/boundary/filesystem/clientConfigurationLayeredEnvironment.test.ts index 79a79e26b65..b9889682979 100644 --- a/tests/boundary/filesystem/clientConfigurationLayeredEnvironment.test.ts +++ b/tests/boundary/filesystem/clientConfigurationLayeredEnvironment.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises"; @@ -271,9 +272,11 @@ it("keeps higher-priority values and does not copy inherited settings into the w ), ).toMatchObject({ status: "configured" }); expect(await readFile(fixture.paths[0]!, "utf8")).toBe(fixture.sources[0]); - const configured = parseClientConfiguration( - await readFile(fixture.client.configPath, "utf8"), - "opencode", + const configured = expectResultValue( + parseClientConfiguration( + await readFile(fixture.client.configPath, "utf8"), + "opencode", + ), ); expect(effectiveClientServer(configured, "rea")).toHaveProperty( "environment", @@ -297,13 +300,17 @@ it("keeps higher-priority values and does not copy inherited settings into the w }); it("merges caller server names as own keys without inventing absent registrations", () => { - const lower = parseClientConfiguration( - '{"mcp":{"__proto__":{"type":"local","command":["peer"],"environment":{"LOWER":"retained"}}}}', - "opencode", + const lower = expectResultValue( + parseClientConfiguration( + '{"mcp":{"__proto__":{"type":"local","command":["peer"],"environment":{"LOWER":"retained"}}}}', + "opencode", + ), ); - const upper = parseClientConfiguration( - '{"mcp":{"__proto__":{"environment":{"UPPER":"selected"}}}}', - "opencode", + const upper = expectResultValue( + parseClientConfiguration( + '{"mcp":{"__proto__":{"environment":{"UPPER":"selected"}}}}', + "opencode", + ), ); expect(effectiveClientServer(lower, "constructor")).toBeUndefined(); const effective = effectiveClientConfiguration( @@ -358,9 +365,11 @@ it("uses inherited settings when creating a missing write layer", async () => { expect( await configureClientConfiguration(fixture.client, overrides, command), ).toMatchObject({ status: "configured" }); - const parsed = parseClientConfiguration( - await readFile(fixture.client.configPath, "utf8"), - "opencode", + const parsed = expectResultValue( + parseClientConfiguration( + await readFile(fixture.client.configPath, "utf8"), + "opencode", + ), ); expect(effectiveClientServer(parsed, "rea")).toHaveProperty( "environment", @@ -386,9 +395,11 @@ it("replaces the selected write layer rather than the last loaded layer", async expect( await configureClientConfiguration(client, overrides, command), ).toMatchObject({ status: "configured" }); - const parsed = parseClientConfiguration( - await readFile(client.configPath, "utf8"), - "opencode", + const parsed = expectResultValue( + parseClientConfiguration( + await readFile(client.configPath, "utf8"), + "opencode", + ), ); expect(effectiveClientServer(parsed, "rea")).toHaveProperty("environment", { REA_GHIDRA_LANGUAGE_ID: language, diff --git a/tests/boundary/filesystem/clientRegistrationRefresh.test.ts b/tests/boundary/filesystem/clientRegistrationRefresh.test.ts index 8d84c88b7f6..270d7cbe511 100644 --- a/tests/boundary/filesystem/clientRegistrationRefresh.test.ts +++ b/tests/boundary/filesystem/clientRegistrationRefresh.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; @@ -24,7 +25,8 @@ it.each([90, 120])( ).toMatchObject({ status: "configured" }); const refreshed = await readFile(configPath, "utf8"); expect( - parseClientConfiguration(refreshed, "grok").servers.rea, + expectResultValue(parseClientConfiguration(refreshed, "grok")).servers + .rea, ).toMatchObject({ command: "rea", args: ["mcp"], diff --git a/tests/boundary/filesystem/hermesClientConfiguration.test.ts b/tests/boundary/filesystem/hermesClientConfiguration.test.ts index ba5693dd9eb..34159cd18e6 100644 --- a/tests/boundary/filesystem/hermesClientConfiguration.test.ts +++ b/tests/boundary/filesystem/hermesClientConfiguration.test.ts @@ -139,7 +139,9 @@ describe("Hermes inherited registration removal", () => { const configured = await readFile(path, "utf8"); expect(await systemUninstallHost(home).removeClient(client)).toMatchObject({ status: "failed", - detail: expect.stringContaining("inherited from a YAML merge"), + detail: expect.stringContaining( + "Remove it at the shared source before rerunning uninstall", + ), }); expect(await readFile(path, "utf8")).toBe(configured); }); diff --git a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts index 206c9182a95..f61a14303b3 100644 --- a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts +++ b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { registerMcpClientsOnHost } from "../../fixtures/mcpRegistration.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { @@ -149,9 +150,11 @@ it.each([ expect(uninstall.items).toContainEqual( expect.objectContaining({ name: client, status: "removed" }), ); - const remaining = parseClientConfiguration( - await readFile(row.configPath, "utf8"), - row.format, + const remaining = expectResultValue( + parseClientConfiguration( + await readFile(row.configPath, "utf8"), + row.format, + ), ); expect(remaining.servers).not.toHaveProperty("rea"); if (row.privateProfile !== undefined && platform !== "win32") @@ -187,7 +190,9 @@ it("registers Amp in settings.jsonc when that is Amp's only settings file", asyn ); const text = await readFile(jsonc, "utf8"); expect(text).toContain("// keep"); - expect(parseClientConfiguration(text, "amp").servers).toHaveProperty("rea"); + expect( + expectResultValue(parseClientConfiguration(text, "amp")).servers, + ).toHaveProperty("rea"); // With both files present, which one Amp reads is unknown. await writeFile(join(directory, "settings.json"), "{}\n"); diff --git a/tests/boundary/filesystem/opencodeLayeredUninstall.test.ts b/tests/boundary/filesystem/opencodeLayeredUninstall.test.ts index 39258a879ee..8ec911e7377 100644 --- a/tests/boundary/filesystem/opencodeLayeredUninstall.test.ts +++ b/tests/boundary/filesystem/opencodeLayeredUninstall.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { access, mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -53,9 +54,11 @@ it.each([ effectiveClientConfiguration( await Promise.all( [lower, upper].map(async (sourcePath) => ({ - ...parseClientConfiguration( - await readFile(sourcePath, "utf8"), - "opencode", + ...expectResultValue( + parseClientConfiguration( + await readFile(sourcePath, "utf8"), + "opencode", + ), ), sourcePath, })), diff --git a/tests/boundary/filesystem/piClientConfiguration.test.ts b/tests/boundary/filesystem/piClientConfiguration.test.ts index 6f89b76f5e9..a80eaa7e5b8 100644 --- a/tests/boundary/filesystem/piClientConfiguration.test.ts +++ b/tests/boundary/filesystem/piClientConfiguration.test.ts @@ -1,3 +1,4 @@ +import { expectResultValue } from "../../support/expectResultValue.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { mkdir, readFile, writeFile } from "node:fs/promises"; @@ -256,7 +257,7 @@ describe("Pi strict JSON parsing", () => { async (_description, original) => { const { home, client } = await piClient(); await writeFile(client.configPath, original); - expect(() => parseClientConfiguration(original, "pi")).toThrow(); + expect(parseClientConfiguration(original, "pi").ok).toBe(false); expect( await inspectClientConfiguration(client, {}, command), ).toMatchObject({ status: "invalid" }); @@ -338,14 +339,21 @@ describe("Pi strict JSON parsing", () => { it("keeps JSONC tolerance for other dialects while Pi rejects the same text", () => { const jsonc = `\uFEFF{\n // A comment Pi rejects but OpenCode keeps.\n "mcp": { "other": { "type": "local" }, },\n}\n`; - expect(parseClientConfiguration(jsonc, "opencode").servers).toEqual({ + expect( + expectResultValue(parseClientConfiguration(jsonc, "opencode")).servers, + ).toEqual({ other: { type: "local" }, }); - expect(parseClientConfiguration("", "opencode").document).toEqual({}); - expect(parseClientConfiguration("\uFEFF", "opencode").document).toEqual({}); - expect(() => parseClientConfiguration(jsonc, "pi")).toThrow(); - expect(() => parseClientConfiguration("", "pi")).toThrow(); - expect(() => parseClientConfiguration("\uFEFF", "pi")).toThrow(); + expect( + expectResultValue(parseClientConfiguration("", "opencode")).document, + ).toEqual({}); + expect( + expectResultValue(parseClientConfiguration("\uFEFF", "opencode")) + .document, + ).toEqual({}); + expect(parseClientConfiguration(jsonc, "pi").ok).toBe(false); + expect(parseClientConfiguration("", "pi").ok).toBe(false); + expect(parseClientConfiguration("\uFEFF", "pi").ok).toBe(false); }); }); diff --git a/tests/boundary/filesystem/referenceSourceCleanupOwnership.test.ts b/tests/boundary/filesystem/referenceSourceCleanupOwnership.test.ts index 2ad8ec1c065..6472b5cb195 100644 --- a/tests/boundary/filesystem/referenceSourceCleanupOwnership.test.ts +++ b/tests/boundary/filesystem/referenceSourceCleanupOwnership.test.ts @@ -374,6 +374,7 @@ it.each([ [true, true, "reader"], [true, false, "import"], [true, true, "import"], + ["file-close", false, "reader"], ] as const)( "preserves directory EIO through close (late cancellation=%s, close fails=%s, surface=%s)", async (lateCancellation, closeFails, surface) => { @@ -396,6 +397,18 @@ it.each([ let readCalls = 0; let closeCalls = 0; + if (lateCancellation === "file-close") + openMock.mockImplementation(async (...args) => { + const handle = await actual.open(...args); + if (String(args[0]) === file) { + const close = handle.close.bind(handle); + vi.spyOn(handle, "close").mockImplementation(async () => { + controller.abort(reason); + await close(); + }); + } + return handle; + }); opendirMock.mockImplementation(async (...args) => { const directory = await actual.opendir(...args); const operations: DirectoryOperations = directory; @@ -407,7 +420,7 @@ it.each([ const close = operations.close.bind(directory); vi.spyOn(operations, "close").mockImplementation(async () => { closeCalls += 1; - if (lateCancellation) controller.abort(reason); + if (lateCancellation === true) controller.abort(reason); await close(); if (closeFails) throw closeFailure; }); diff --git a/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts b/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts index d0218846d6d..1b1e7ac9362 100644 --- a/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts +++ b/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts @@ -544,6 +544,12 @@ it.each(["late-cancellation", "cleanup-failure", "cancelled cleanup-failure"])( expect(result.ok ? undefined : result.error).toBeInstanceOf( ProviderCleanupError, ); + if (result.ok) throw new Error("Expected an unresolved cleanup"); + if (scenario === "cancelled cleanup-failure") { + const [cancellation] = result.error.secondaryFailures; + expect(cancellation?._tag).toBe("AnalysisCancelledError"); + expect(cancellation?.cause).toBe(cancellationReason); + } expect(result).toMatchObject({ ok: false, error: { diff --git a/tests/process-global/setupPolicySnapshot.test.ts b/tests/process-global/setupPolicySnapshot.test.ts index bc6e87544fa..6e2da3e05ee 100644 --- a/tests/process-global/setupPolicySnapshot.test.ts +++ b/tests/process-global/setupPolicySnapshot.test.ts @@ -195,3 +195,40 @@ it.each(["other", "rea"])( } }, ); + +it("reports an OpenCode layer conflict introduced before the transaction snapshot", async () => { + const home = await createTestTempDirectory("rea-setup-opencode-snapshot-"); + const nativePath = join(home, "opencode.json"); + const configPath = join(home, "opencode.jsonc"); + const client: SetupClient = { + name: "opencode", + registrationProfile: supportedClientRegistrationProfile("opencode"), + configPath, + configPaths: [nativePath, configPath], + format: "opencode", + }; + const native = + '{"mcp":{"servers":{"peer":{"type":"local","command":["peer"]}}}}'; + const conflict = + '{"mcp":{"servers":{"type":"local","command":["legacy-peer"]}}}'; + await writeFile(nativePath, native); + await writeFile(configPath, "{}"); + expect( + await inspectClientConfiguration(client, {}, ["rea", "mcp"]), + ).toMatchObject({ + status: "update", + }); + refresh.afterDiscovery = () => writeFile(configPath, conflict); + expect( + await configureClientConfiguration(client, {}, ["rea", "mcp"]), + ).toEqual({ + status: "failed", + reason: "invalid_configuration", + detail: expect.stringContaining("legacy OpenCode server named servers"), + }); + expect(await readFile(configPath, "utf8")).toBe(conflict); + expect(await readFile(nativePath, "utf8")).toBe(native); + await expect(readFile(`${configPath}.rea.backup`)).rejects.toMatchObject({ + code: "ENOENT", + }); +}); diff --git a/tests/support/expectResultValue.ts b/tests/support/expectResultValue.ts new file mode 100644 index 00000000000..b19ebe7264a --- /dev/null +++ b/tests/support/expectResultValue.ts @@ -0,0 +1,10 @@ +import type { Result } from "../../src/domain/result.js"; + +/** Unwrap successful fixture operations while preserving the cause of a failed test. */ +export const expectResultValue = ( + result: Result, +): Value => { + if (!result.ok) + throw new Error("Expected a successful result", { cause: result.error }); + return result.value; +};