diff --git a/docs/architecture/architecture.mermaid b/docs/architecture/architecture.mermaid index 4dbd0b05f5..3774bd7813 100644 --- a/docs/architecture/architecture.mermaid +++ b/docs/architecture/architecture.mermaid @@ -1,7 +1,8 @@ graph TD %% Selected layer owners and dependency/wiring paths, not a directory or import inventory. %% Current deep-provider candidates are wired in src/composition/binary.ts. - %% Layers, innermost first: domain, contracts, foundation, ports (src/ports/: + %% Layers, innermost first: kernel (src/kernel/: dependency-free helpers such as + %% errorMessage), domain, contracts, foundation, ports (src/ports/: %% interfaces providers implement), providerCore (src/providers/: the shared %% provider core), providers, application, composition, adapters. An import may point to the same or an %% inner layer. scripts/lib/module-layers.mjs declares the layer of every diff --git a/scripts/lib/module-boundaries.mjs b/scripts/lib/module-boundaries.mjs index e2102fe21e..249017db27 100644 --- a/scripts/lib/module-boundaries.mjs +++ b/scripts/lib/module-boundaries.mjs @@ -5,7 +5,7 @@ import { fileURLToPath, pathToFileURL } from "node:url"; import { readImportSpecifiers } from "./import-specifiers.mjs"; import { isLayerException } from "./module-layers.mjs"; -const PURE_LAYERS = new Set(["domain", "contracts"]); +const PURE_LAYERS = new Set(["kernel", "domain", "contracts"]); const MIGRATED_PROVIDER_ROOTS = new Set([ "sqlite", "evm", diff --git a/scripts/lib/module-layers.mjs b/scripts/lib/module-layers.mjs index 886411edc8..4ece67d960 100644 --- a/scripts/lib/module-layers.mjs +++ b/scripts/lib/module-layers.mjs @@ -4,7 +4,8 @@ * layer. An undeclared unit fails the check, so a new directory must choose * its layer when it is added. * - * The order follows docs/architecture/architecture.mermaid: domain and + * The order follows docs/architecture/architecture.mermaid: the dependency-free + * kernel helpers that every layer may use, domain and * contracts at the centre, the process/filesystem foundation, the ports * that providers implement and application consumes, the shared provider * core (src/providers), provider adapters, @@ -12,6 +13,7 @@ * MCP entry points. */ export const LAYER_ORDER = Object.freeze([ + "kernel", "domain", "contracts", "foundation", @@ -27,6 +29,7 @@ const units = (layer, names) => names.map((name) => [name, layer]); export const UNIT_LAYERS = Object.freeze( Object.fromEntries([ + ...units("kernel", ["kernel"]), ...units("domain", ["domain"]), ...units("contracts", ["contracts"]), ...units("foundation", [ diff --git a/scripts/lib/test-projects.mjs b/scripts/lib/test-projects.mjs index 572ce7c7e3..81d1c8018c 100644 --- a/scripts/lib/test-projects.mjs +++ b/scripts/lib/test-projects.mjs @@ -6,7 +6,7 @@ export const SOURCE_TEST_PROJECTS = [ name: "domain", group: "source", isolate: false, - include: ["src/{contracts,domain,ports}/**/*.test.ts"], + include: ["src/{contracts,domain,kernel,ports}/**/*.test.ts"], }, { name: "services", diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index fe6f607792..a3e9d25073 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -324,7 +324,7 @@ const checkCounted = (label, key, selected, pattern, owners) => { if (owners.includes(file.path)) continue; const count = typeof pattern === "function" - ? pattern(file.content) + ? pattern(file.content, file.path) : (file.content.match(pattern)?.length ?? 0); if (count > 0) counts.set(file.path, count); } @@ -484,6 +484,51 @@ checkCounted( ["src/pcap/TsharkJsonPackets.ts"], ); +// Text from an unknown caught value has one owner, src/kernel/errorMessage.ts. +// The pattern matches the inline copy with the same expression in all three +// places; a named local helper with this body is the same copy. +// Copies that run in another realm cannot import the owner and are excluded by +// name, so no slice rewrites them: the regex worker's source string and a +// fetch run inside the browser page through page.evaluate. +const ISOLATED_ERROR_MESSAGE_COPIES = new Map([ + ["src/browser/PlaywrightScenarioRequest.ts", 1], + ["src/process/RegexMatcher.ts", 1], +]); +const inlineErrorMessage = + /(? + Math.max( + 0, + (content.match(inlineErrorMessage)?.length ?? 0) - + (ISOLATED_ERROR_MESSAGE_COPIES.get(path) ?? 0), + ), + ["src/kernel/errorMessage.ts"], +); + +// Two hexadecimal digits for one byte have one owner, src/kernel/byteToHex.ts. +checkCounted( + "inline byte-to-hex formatting (use byteToHex from src/kernel/byteToHex)", + "inline-byte-hex", + files, + /\.toString\(16\)\s*\.padStart\(\s*2\s*,\s*"0"\s*\)/gu, + ["src/kernel/byteToHex.ts"], +); + +// A one-shot SHA-256 hex digest of an in-memory value has one owner, +// src/kernel/sha256Hex.ts. Incremental and streamed hashing (a Hash updated +// more than once) is not counted. +checkCounted( + "one-shot SHA-256 hex digest (use sha256Hex from src/kernel/sha256Hex)", + "inline-sha256-hex", + files, + /createHash\(\s*"sha256"\s*\)\s*\.update\((?:[^()]|\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\))*\)\s*\.digest\(\s*"hex"\s*\)/gu, + ["src/kernel/sha256Hex.ts"], +); + // Strict UTF-8 decoding has one owner, src/domain/strictUtf8.ts, which makes // each site state its byte-order-mark policy. A local fatal decoder silently // strips a leading BOM unless it remembers ignoreBOM. The pattern matches the diff --git a/scripts/verify/baselines/inline-sha256-hex.json b/scripts/verify/baselines/inline-sha256-hex.json new file mode 100644 index 0000000000..29fa33b87b --- /dev/null +++ b/scripts/verify/baselines/inline-sha256-hex.json @@ -0,0 +1,71 @@ +{ + "src/adb/AdbProvider.ts": 1, + "src/android/AndroidJniLibraries.ts": 2, + "src/apkSignature/apkCertificateFacts.ts": 1, + "src/application/GuidanceAccess.ts": 1, + "src/application/LinuxHopperPublisher.ts": 2, + "src/application/ReferenceSourceImportEntries.ts": 1, + "src/application/SetupRecoveryBackup.ts": 1, + "src/application/ValidateSelectedWebScript.ts": 1, + "src/application/WebScriptExportService.ts": 1, + "src/application/WebSourceLocationService.ts": 1, + "src/application/decompileDirectory/exportTree.ts": 2, + "src/application/desktop/DesktopBuildWitness.ts": 1, + "src/application/desktop/DesktopBuildWitnessRecord.ts": 1, + "src/application/desktop/DesktopExportFiles.ts": 1, + "src/application/desktop/DesktopExportWithheld.ts": 1, + "src/application/desktop/DesktopRetainedContent.ts": 1, + "src/application/environment/environmentBundleWrite.ts": 1, + "src/application/javascript/JavaScriptArtifactAnalysis.ts": 1, + "src/application/javascript/JavaScriptArtifactGraphFindings.ts": 1, + "src/artifacts/DesktopFileInspection.ts": 1, + "src/artifacts/apple/InterfaceBuilderAnalysis.ts": 1, + "src/artifacts/apple/KeyedArchiveReader.ts": 1, + "src/artifacts/javascript/JavaScriptArtifactFiles.ts": 1, + "src/artifacts/nodeSea/NodeSeaLocation.ts": 1, + "src/browser/CdpCaptureStorageFingerprints.ts": 1, + "src/browser/CdpWebMcpDiscovery.ts": 1, + "src/browser/PlaywrightElectronActiveProvider.ts": 1, + "src/browser/PlaywrightScenarioArtifacts.ts": 2, + "src/browser/WebSourceMapFetcher.ts": 1, + "src/browser/assets/PublishWebScripts.ts": 1, + "src/browser/history/HarCapture.ts": 1, + "src/browser/history/SazProjection.ts": 1, + "src/browser/history/protobuf/ProtobufCapture.ts": 1, + "src/browser/network/PlaywrightNetworkContent.ts": 1, + "src/cutter/CutterBridgeSource.ts": 1, + "src/desktop/AgentEnvComputer.ts": 1, + "src/desktop/BuildComputerController.ts": 1, + "src/desktop/DesktopContentStore.ts": 1, + "src/desktop/GpgvKeyCheck.ts": 1, + "src/dotnet/ManagedSnapshot.ts": 1, + "src/erlang/BeamParser.ts": 1, + "src/evm/EvmoleInterfaceProvider.ts": 1, + "src/evm/EvmoleInterfaceWorker.ts": 1, + "src/firmware/FirmwarePublication.ts": 1, + "src/frida/FridaInstrumentationManager.ts": 3, + "src/ghidra/GhidraAnalysisSeeds.ts": 1, + "src/ghidra/GhidraCheckpoint.ts": 1, + "src/ghidra/GhidraExecutableHeader.ts": 1, + "src/ghidra/GhidraInstallationProperties.ts": 1, + "src/ghidra/GhidraLoadImageValues.ts": 1, + "src/ghidra/extensions/GhidraExtensions.ts": 2, + "src/gpu/GpuSource.ts": 1, + "src/inspector/V8InspectorCaptureProjection.ts": 1, + "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 2, + "src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts": 2, + "src/javascript/recovery/RecoveryFiles.ts": 1, + "src/javascript/sourceMaps/TraceSourceMap.ts": 2, + "src/kuna/KunaProjectCache.ts": 1, + "src/kuna/KunaProjectExport.ts": 1, + "src/kuna/KunaReferenceFiles.ts": 1, + "src/main/deferredRuntime.ts": 1, + "src/native/AppleDispatchMetadata.ts": 1, + "src/native/elf/ElfNoteParser.ts": 1, + "src/native/elf/KernelModuleParser.ts": 1, + "src/native/pe/PeCertificateParser.ts": 1, + "src/native/windows/WindowsShortcutParser.ts": 1, + "src/python/PythonPycParser.ts": 1, + "src/v8/V8CodeCacheParser.ts": 1, + "src/wasm/WabtArtifactProvider.ts": 1 +} diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts index 936895ad62..1276969853 100644 --- a/src/adb/AdbProvider.ts +++ b/src/adb/AdbProvider.ts @@ -160,6 +160,7 @@ import { listAdbDevicesOperation, type AdbCommandContext, } from "./AdbDeviceOperations.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const SHELL_TIMEOUT_MS = 30_000; const PACKAGE_LIST_TIMEOUT_MS = 60_000; @@ -252,10 +253,7 @@ const adbDigestError = ( partialObservation, }); const resource = `${digestFailure.path} (ADB digest handle)`; - const reason = - digestFailure.cleanupCause instanceof Error - ? digestFailure.cleanupCause.message - : String(digestFailure.cleanupCause); + const reason = errorMessage(digestFailure.cleanupCause); const cleanup = new ProviderCleanupError( ADB_PROVIDER_IDENTITY.id, [resource], @@ -385,10 +383,7 @@ const syncStagedAdbFile = async ( ADB_PROVIDER_IDENTITY.id, [resource], { - reason: - released.cause instanceof Error - ? released.cause.message - : String(released.cause), + reason: errorMessage(released.cause), }, { operation, cause: released.cause }, ); @@ -466,9 +461,6 @@ const hardLinksUnsupported = (cause: unknown): boolean => String(cause.code), ); -const describeAdbFailure = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - interface ScreenPublicationCloseFailure { readonly cause: unknown; readonly resource: string; @@ -579,7 +571,7 @@ const publishScreenExclusively = async ( const error = new ProviderCleanupError( ADB_PROVIDER_IDENTITY.id, [outputPath], - { reason: describeAdbFailure(closeCause) }, + { reason: errorMessage(closeCause) }, { operation, cause: new AggregateError( @@ -601,7 +593,7 @@ const publishScreenExclusively = async ( const error = new ProviderCleanupError( ADB_PROVIDER_IDENTITY.id, [outputPath], - { reason: describeAdbFailure(removed.cause) }, + { reason: errorMessage(removed.cause) }, { operation, cause: new AggregateError( @@ -938,11 +930,7 @@ export class AdbProvider { ADB_PROVIDER_IDENTITY.id, [...new Set(resources)], { - reason: failures - .map((cause) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + reason: failures.map((cause) => errorMessage(cause)).join("; "), }, { operation: "close_binary", @@ -991,11 +979,7 @@ export class AdbProvider { ADB_PROVIDER_IDENTITY.id, resources, { - reason: causes - .map((cause) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + reason: causes.map((cause) => errorMessage(cause)).join("; "), }, { operation, @@ -1158,7 +1142,7 @@ export class AdbProvider { ADB_PROVIDER_IDENTITY.id, [owner.path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: owner.operation, cause }, ); @@ -1247,8 +1231,7 @@ export class AdbProvider { ({ path }) => path, ), { - reason: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: request.operation, cause }, ), @@ -1962,11 +1945,9 @@ export class AdbProvider { mode: created.mode, }; } catch (cause) { - const primary = new AnalysisOutputError( - operation, - cause instanceof Error ? cause.message : String(cause), - { cause }, - ); + const primary = new AnalysisOutputError(operation, errorMessage(cause), { + cause, + }); if (!packageDirectoryCreated) return err(primary); const owner = { operation, @@ -2007,7 +1988,7 @@ export class AdbProvider { const cleanup = new ProviderCleanupError( ADB_PROVIDER_IDENTITY.id, [packageDirectory], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation, cause }, ); return err(this.#retainOutputDirectoryCleanup(owner, cleanup)); @@ -2180,7 +2161,7 @@ export class AdbProvider { failures.push({ device_path: entry.device_path, stage: "digest", - message: `The pulled file could not be read back after pulling: ${localPath}: ${physicalCause instanceof Error ? physicalCause.message : String(physicalCause)}`, + message: `The pulled file could not be read back after pulling: ${localPath}: ${errorMessage(physicalCause)}`, cause, }); } @@ -3311,7 +3292,7 @@ export class AdbProvider { new ProviderCleanupError( ADB_PROVIDER_IDENTITY.id, [stagingDirectory], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation, cause }, ), ), diff --git a/src/android/AndroidJniLibraries.ts b/src/android/AndroidJniLibraries.ts index dc3326164d..311ae93e33 100644 --- a/src/android/AndroidJniLibraries.ts +++ b/src/android/AndroidJniLibraries.ts @@ -23,6 +23,7 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Bounds cover the live library buffer, completed scan work and retained JSON separately. */ export const ANDROID_JNI_LIBRARY_LIMITS = Object.freeze({ @@ -207,8 +208,7 @@ export const readAndroidJniLibraries = async (input: { cause instanceof ArtifactReaderFailure ? cause.reason : "io", - message: - cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), ...(cause instanceof ArtifactReaderFailure && cause.integrityCheck !== undefined ? { integrity_check: cause.integrityCheck } @@ -278,10 +278,7 @@ export const readAndroidJniLibraries = async (input: { "jadx", [owner.resource], { - reason: - released.cause instanceof Error - ? released.cause.message - : String(released.cause), + reason: errorMessage(released.cause), }, { operation, cause: released.cause }, ); diff --git a/src/android/AndroidMappingFile.ts b/src/android/AndroidMappingFile.ts index bd74284279..18911dd8a0 100644 --- a/src/android/AndroidMappingFile.ts +++ b/src/android/AndroidMappingFile.ts @@ -29,6 +29,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { isSelectedRegularFileError } from "../filesystem/RegularFile.js"; import { jadxOperationTimeoutGuidance } from "./JadxOperationTimeout.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface AndroidMappingReadDeadline { readonly timeout: AbortSignal; @@ -121,7 +122,7 @@ const readFailurePrimary = ( cause: primary, diagnostics: { mapping_path: read.path, - reason: primary instanceof Error ? primary.message : String(primary), + reason: errorMessage(primary), }, }); }; diff --git a/src/android/JadxConfiguration.ts b/src/android/JadxConfiguration.ts index d7e2b576a3..f7a063c54d 100644 --- a/src/android/JadxConfiguration.ts +++ b/src/android/JadxConfiguration.ts @@ -59,6 +59,7 @@ import { JADX_UNSUPPORTED_HOST_REMEDIATION, JADX_WINDOWS_NATIVE_REMEDIATION, } from "./JadxRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; // Bound ZIP metadata allocation during discovery. The audited 0.7.1 JAR's // central directory occupies 2,294,350 bytes; class bodies are not read here. @@ -450,7 +451,7 @@ const requireEngineArchive = async ( }; const archiveInspectionFailure = (jar: string, cause: unknown) => { - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); return configurationFailure( "version_unresolved", `Cannot inspect REA_JADX_MCP_JAR ${jar} as a Java archive: ${reason}. ${JADX_JAR_CONFIGURATION_REMEDIATION}`, @@ -585,7 +586,7 @@ const resolveJar = async ( if (cause instanceof JadxConfigurationFailure) throw cause; throw configurationFailure( "executable_missing", - `Cannot read REA_JADX_MCP_JAR ${jar}: ${cause instanceof Error ? cause.message : String(cause)}`, + `Cannot read REA_JADX_MCP_JAR ${jar}: ${errorMessage(cause)}`, { jar_path: jar }, "jar", cause, @@ -637,7 +638,7 @@ const resolveJava = async ( continue; throw configurationFailure( "runtime_missing", - `Cannot inspect selected Java executable ${candidate}: ${errorText(cause)}`, + `Cannot inspect selected Java executable ${candidate}: ${errorMessage(cause)}`, { java_executable: candidate }, "java_runtime", cause, @@ -684,7 +685,7 @@ const requireJavaHomeExecutable = async ( if (cause instanceof JadxConfigurationFailure) throw cause; throw configurationFailure( "runtime_missing", - `Cannot execute JAVA_HOME java ${java}: ${cause instanceof Error ? cause.message : String(cause)}`, + `Cannot execute JAVA_HOME java ${java}: ${errorMessage(cause)}`, { java_executable: java }, "java_runtime", cause, @@ -776,6 +777,3 @@ const configurationFailure = ( kind, cause === undefined ? undefined : { cause }, ); - -const errorText = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/android/JadxFailure.ts b/src/android/JadxFailure.ts index 96033989d6..cfa1d0b372 100644 --- a/src/android/JadxFailure.ts +++ b/src/android/JadxFailure.ts @@ -29,6 +29,7 @@ import type { JadxMcpTransport } from "./JadxMcpTransport.js"; import type { OwnedMcpTransportFailure } from "../process/OwnedMcpStdioTransport.js"; import { jadxHeapExhausted } from "./JadxProtocol.js"; import { JADX_HEAP_REMEDIATION } from "./JadxRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface FailureContext { readonly cause: unknown; @@ -127,10 +128,7 @@ const observeJadxFailure = ( }) : cancelledBy(request.operation, carriedReason(cancellation.reason)); if (cause instanceof RegularFileCleanupFailure) { - const reason = - cause.cleanupCause instanceof Error - ? cause.cleanupCause.message - : String(cause.cleanupCause); + const reason = errorMessage(cause.cleanupCause); // A finished copy or its cancellation can sit on this close or inside a // nested one when another descriptor also rejected close. Name every // descriptor that failed; the copied output path stays on the observation. @@ -187,10 +185,7 @@ const observeJadxFailure = ( ? primaryCause : new ProviderAdapterError("jadx", request.operation, { cause: primaryCause, - userMessage: - primaryCause instanceof Error - ? primaryCause.message - : String(primaryCause), + userMessage: errorMessage(primaryCause), })); const cleanup = new ProviderCleanupError( "jadx", @@ -379,7 +374,7 @@ const presentDiagnosticFailure = ( remediationAction: JADX_HEAP_REMEDIATION, }, ); - const reason = `Java could not start REA's Android bridge using ${failure.command}: ${failure.cause instanceof Error ? failure.cause.message : String(failure.cause)}. ${output === undefined || output.stderr.length === 0 ? "No launcher stderr was observed." : "Review the retained launcher diagnostics."}${output?.truncated === true ? " Diagnostics are incomplete." : ""} Review the selected Java/JADX configuration; for a JVM memory limit, review REA_JADX_HEAP_MIB and inherited JVM options such as JAVA_TOOL_OPTIONS.`; + const reason = `Java could not start REA's Android bridge using ${failure.command}: ${errorMessage(failure.cause)}. ${output === undefined || output.stderr.length === 0 ? "No launcher stderr was observed." : "Review the retained launcher diagnostics."}${output?.truncated === true ? " Diagnostics are incomplete." : ""} Review the selected Java/JADX configuration; for a JVM memory limit, review REA_JADX_HEAP_MIB and inherited JVM options such as JAVA_TOOL_OPTIONS.`; return new AnalysisCapabilityUnavailableError( "jadx", failure.operation, @@ -393,10 +388,7 @@ const presentDiagnosticFailure = ( return new ProviderAdapterError("jadx", failure.operation, { ...options, diagnostics: { - reason: - failure.cause instanceof Error - ? failure.cause.message - : String(failure.cause), + reason: errorMessage(failure.cause), }, }); }; diff --git a/src/android/JadxProvider.ts b/src/android/JadxProvider.ts index f81a9f83fe..06acc0368b 100644 --- a/src/android/JadxProvider.ts +++ b/src/android/JadxProvider.ts @@ -67,6 +67,7 @@ import { jadxBridgeIdentity, type JadxBridgeIdentity, } from "./JadxRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const BRIDGE_SOURCE = fileURLToPath(JADX_BRIDGE_SOURCE_URL); type Outcome = Awaited>; @@ -258,13 +259,9 @@ const cleanup = async ( cleanupResources(resources), { reason: cleanupCauses - .map((failure) => - failure instanceof Error ? failure.message : String(failure), - ) + .map((failure) => errorMessage(failure)) .join("; "), - cleanup_causes: cleanupCauses.map((failure) => - failure instanceof Error ? failure.message : String(failure), - ), + cleanup_causes: cleanupCauses.map((failure) => errorMessage(failure)), provider_cleanup: cleanupCauses.map((failure) => failure instanceof ProviderCleanupError ? (failure.diagnostics ?? null) @@ -291,7 +288,7 @@ const cleanup = async ( "jadx", cleanupResources(resources), { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: resources.operation, cause }, ); diff --git a/src/apkSignature/apkSignatureFailures.ts b/src/apkSignature/apkSignatureFailures.ts index 073e707c49..3b75501c3f 100644 --- a/src/apkSignature/apkSignatureFailures.ts +++ b/src/apkSignature/apkSignatureFailures.ts @@ -28,6 +28,7 @@ import { APK_SIGNATURE_LIMITS, APK_SIGNATURE_PROVIDER_IDENTITY, } from "./ApkSignatureRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_apk_signature"; @@ -249,6 +250,6 @@ const adapterFailure = (cause: unknown, path: string): AnalysisError => cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 92c83eca46..7c80d08ed0 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -132,6 +132,7 @@ import { import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { localPathStringSchema } from "../domain/localPath.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const XML_PLIST_PROBE_CHUNK_BYTES = 64 * 1024; @@ -607,10 +608,7 @@ const targetFileCleanupError = ( cause: failure, cleanupPrimary: primary, cleanup: { - reason: - failure.cleanupCause instanceof Error - ? failure.cleanupCause.message - : String(failure.cleanupCause), + reason: errorMessage(failure.cleanupCause), resources: [failure.path], }, ...childFailureDiagnostics( diff --git a/src/application/ClaudeDesktopConfigLocation.ts b/src/application/ClaudeDesktopConfigLocation.ts index bbee87fe29..7d2c590972 100644 --- a/src/application/ClaudeDesktopConfigLocation.ts +++ b/src/application/ClaudeDesktopConfigLocation.ts @@ -6,6 +6,7 @@ import { windowsAppDataRoots, type MsixPackageView, } from "./MsixPackageStorage.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const CONFIG_FILE = "claude_desktop_config.json"; @@ -377,6 +378,3 @@ const isMissing = (cause: unknown): boolean => cause instanceof Error && "code" in cause && (cause.code === "ENOENT" || cause.code === "ENOTDIR"); - -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/application/ClientConfigurationFiles.ts b/src/application/ClientConfigurationFiles.ts index b26021db77..dc7632735f 100644 --- a/src/application/ClientConfigurationFiles.ts +++ b/src/application/ClientConfigurationFiles.ts @@ -17,6 +17,7 @@ import type { ConfigurationError } from "../domain/configurationErrors.js"; import { mergeEnvironmentOverrides } from "../process/snapshotEnvironment.js"; import { PRODUCT_IDENTITY } from "../identity.js"; import { isRecord } from "../domain/isRecord.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * A parsed layer retains its path so rereading the write target replaces only @@ -89,7 +90,7 @@ export const readConfigurationText = async ( return err({ kind: "unreadable", path, - detail: `Configuration ${path} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Configuration ${path} could not be read: ${errorMessage(cause)}`, ...(cause instanceof RegularFileCleanupFailure ? { cleanupFailure: cause } : {}), @@ -115,7 +116,7 @@ export const readConfigurationFile = async ( return err({ kind: "malformed", path, - detail: `Configuration ${path} is malformed: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Configuration ${path} is malformed: ${errorMessage(cause)}`, }); } }; diff --git a/src/application/ClientConfigurationPublication.ts b/src/application/ClientConfigurationPublication.ts index 333bd9d1d2..aa56ea4cb6 100644 --- a/src/application/ClientConfigurationPublication.ts +++ b/src/application/ClientConfigurationPublication.ts @@ -17,6 +17,7 @@ import { readRegularFileTextSnapshot } from "../process/RegularFileRead.js"; import { ClientConfigurationPublicationFailure } from "./ClientConfigurationCleanup.js"; import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js"; import { ConfigurationError } from "../domain/configurationErrors.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Facts captured where a configuration write operation failed. */ export interface ClientConfigurationWriteProblem { @@ -43,7 +44,7 @@ export class ClientConfigurationWriteError extends Error { cause: unknown, requestedOwnership?: { readonly uid: number; readonly gid: number }, ) { - const detail = cause instanceof Error ? cause.message : String(cause); + const detail = errorMessage(cause); super(`Configuration ${operation} failed at ${path}: ${detail}`, { cause }); const code: unknown = cause instanceof Error ? Reflect.get(cause, "code") : undefined; diff --git a/src/application/ClientRegistrationBackup.ts b/src/application/ClientRegistrationBackup.ts index 8f621661bb..39715af077 100644 --- a/src/application/ClientRegistrationBackup.ts +++ b/src/application/ClientRegistrationBackup.ts @@ -7,9 +7,7 @@ import { type RecoveryBackupPreservationOptions, } from "./SetupRecoveryBackup.js"; import { err, ok, type Result } from "../domain/result.js"; - -const errorDetail = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); +import { errorMessage } from "../kernel/errorMessage.js"; const isMissing = (cause: unknown): boolean => typeof cause === "object" && @@ -28,7 +26,7 @@ const restrictExistingBackup = ( return err({ kind: "unreadable", path: backupPath, - detail: `The existing client configuration backup could not be checked: ${errorDetail(cause)}`, + detail: `The existing client configuration backup could not be checked: ${errorMessage(cause)}`, }); } if (!existing.isFile()) @@ -43,7 +41,7 @@ const restrictExistingBackup = ( return err({ kind: "unreadable", path: backupPath, - detail: `The existing client configuration backup permissions could not be secured: ${errorDetail(cause)}`, + detail: `The existing client configuration backup permissions could not be secured: ${errorMessage(cause)}`, }); } return ok(undefined); diff --git a/src/application/ClientRegistrationStatus.ts b/src/application/ClientRegistrationStatus.ts index 64a52c1c08..5669044590 100644 --- a/src/application/ClientRegistrationStatus.ts +++ b/src/application/ClientRegistrationStatus.ts @@ -55,6 +55,7 @@ import { type ClientRegistration, } from "./ClientRegistration.js"; import { admitClientStdioConnection } from "./ClientRegistrationConnection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface ClientRegistrationStatusBase { readonly client: string; @@ -720,7 +721,7 @@ const clientEvidencePresent = async ( if (!isMissing(cause)) unavailable ??= { path, - detail: `Client configuration evidence at ${path} could not be inspected: ${cause instanceof Error ? cause.message : String(cause)}. Check file permissions and rerun rea doctor.`, + detail: `Client configuration evidence at ${path} could not be inspected: ${errorMessage(cause)}. Check file permissions and rerun rea doctor.`, }; } } diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index d88236cf85..51d51a103d 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -85,6 +85,7 @@ import type { DesktopBuildFactsInput, OwnedProviderSetting, } from "../ports/DesktopBuildHost.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Read-only host capabilities required by diagnostics. */ export interface DoctorHost { @@ -411,7 +412,7 @@ const closeDoctorHost = async ( return await host.close?.(); } catch (cause: unknown) { if (cause instanceof AnalysisError) return cause; - return `Doctor host cleanup failed: ${cause instanceof Error ? cause.message : String(cause)}`; + return `Doctor host cleanup failed: ${errorMessage(cause)}`; } }; diff --git a/src/application/GeminiClientSettings.ts b/src/application/GeminiClientSettings.ts index f5d84e808e..8f97106d77 100644 --- a/src/application/GeminiClientSettings.ts +++ b/src/application/GeminiClientSettings.ts @@ -22,6 +22,7 @@ import { } from "./ClientConfigurationFiles.js"; import type { SetupClient } from "./SupportedClients.js"; import { readJunieLocationBlock } from "./JunieClientSettings.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type SettingsSource = { path: string; document: ClientConfigurationDocument }; const folderTrustSchema = z @@ -46,7 +47,7 @@ const sourceFailure = ( ): ClientConfigurationFileError => ({ kind: "malformed", path, - detail: `Gemini settings in ${path} are malformed: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Gemini settings in ${path} are malformed: ${errorMessage(cause)}`, }); // Gemini normalizes trust-file keys before replacement and rule precedence. @@ -173,7 +174,7 @@ export const readClientPolicyBlock = async ( : err({ kind: "unreadable" as const, path, - detail: `Configuration ${path} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Configuration ${path} could not be read: ${errorMessage(cause)}`, }), ); if (!present.ok) return present; diff --git a/src/application/JsonFiles.ts b/src/application/JsonFiles.ts index 2248d7be57..2950d9f659 100644 --- a/src/application/JsonFiles.ts +++ b/src/application/JsonFiles.ts @@ -33,6 +33,7 @@ import { fileAccessFailureReason, } from "../resources/index.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; +import { errorMessage } from "../kernel/errorMessage.js"; // The JSON read owner records the exact leases it binds; consumers never // infer cleanup ownership from matching resource labels. @@ -237,10 +238,7 @@ const jsonFileCleanupError = ( cause: failure, path, cleanup: { - reason: - failure.cleanupCause instanceof Error - ? failure.cleanupCause.message - : String(failure.cleanupCause), + reason: errorMessage(failure.cleanupCause), resources: [failure.path], }, }); diff --git a/src/application/JunieClientSettings.ts b/src/application/JunieClientSettings.ts index 7fb8b1db0e..5ba37dd949 100644 --- a/src/application/JunieClientSettings.ts +++ b/src/application/JunieClientSettings.ts @@ -5,6 +5,7 @@ import { readConfigurationText, type ClientConfigurationFileError, } from "./ClientConfigurationFiles.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Inputs that decide whether Junie loads its default user MCP location. They @@ -55,7 +56,7 @@ export const readJunieLocationBlock = async ( return err({ kind: "malformed", path: settings.userConfigPath, - detail: `Cannot parse Junie's user configuration as JSON to determine its MCP locations: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Cannot parse Junie's user configuration as JSON to determine its MCP locations: ${errorMessage(cause)}`, }); } const record = clientConfigurationRecordSchema.safeParse(parsed); diff --git a/src/application/LinuxHopper.ts b/src/application/LinuxHopper.ts index 2982de2def..c0b50b1a33 100644 --- a/src/application/LinuxHopper.ts +++ b/src/application/LinuxHopper.ts @@ -38,6 +38,7 @@ import { type VerifiedLinuxHopperLauncher, } from "./LinuxHopperPublisher.js"; import type { LinuxHopperLauncherVerification } from "../ports/LinuxHopperLauncherVerification.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Package-manager output retained per stream without stopping the command. */ const PACKAGE_MANAGER_OUTPUT_BYTES = 64 * 1024; @@ -208,7 +209,7 @@ const operationFailure = ( cause instanceof Error ? Reflect.get(cause, "code") : undefined; return { operation, - detail: cause instanceof Error ? cause.message : String(cause), + detail: errorMessage(cause), ...(path === undefined ? {} : { path }), ...(typeof code === "string" ? { systemCode: code } : {}), }; @@ -281,7 +282,7 @@ export class LinuxHopperTemporaryCleanupOwner { await cleanup(path); this.pending.delete(path); } catch (cause: unknown) { - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); failures.push( `Linux Hopper temporary cleanup failed for ${path}: ${reason}`, ); @@ -507,7 +508,7 @@ export const installLinuxHopper = async ( ...result, cleanupFailure: { path: temporary, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }; } diff --git a/src/application/McpClientRegistration.ts b/src/application/McpClientRegistration.ts index dcbee59365..92fbb513d4 100644 --- a/src/application/McpClientRegistration.ts +++ b/src/application/McpClientRegistration.ts @@ -43,6 +43,7 @@ import { readRegularFileText, readRegularFileTextSnapshot, } from "../process/RegularFileRead.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface McpClientRegistrationReceipt { readonly status: "configured" | "unchanged"; @@ -259,7 +260,7 @@ const registrationFailure = async ( ? await retryClientConfigurationCleanup(cause, resources) : undefined; const primary = cleanup?.primary ?? cause; - const detail = primary instanceof Error ? primary.message : String(primary); + const detail = errorMessage(primary); const error = new ConfigurationError( `Could not register MCP settings at ${path}: ${detail}`, { diff --git a/src/application/MsixPackageStorage.ts b/src/application/MsixPackageStorage.ts index 73d42b8524..00c8b24e05 100644 --- a/src/application/MsixPackageStorage.ts +++ b/src/application/MsixPackageStorage.ts @@ -2,6 +2,7 @@ import { lstat } from "node:fs/promises"; import { realpathSync } from "node:fs"; import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"; import { err, ok, type Result } from "../domain/result.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * How one MSIX-packaged client reads its AppData configuration. A package @@ -132,7 +133,7 @@ const canonicalDestination = ( } return err({ path, - detail: cause instanceof Error ? cause.message : String(cause), + detail: errorMessage(cause), }); } } @@ -195,7 +196,7 @@ export const packageReadTargetChanged = async ( return err({ _tag: "MsixReadTargetInspectionFailure", path: view.privateConfigPath, - detail: cause instanceof Error ? cause.message : String(cause), + detail: errorMessage(cause), cause, }); } diff --git a/src/application/ReferenceSourceImportPolicy.ts b/src/application/ReferenceSourceImportPolicy.ts index f2cf550225..e1a4ae1c97 100644 --- a/src/application/ReferenceSourceImportPolicy.ts +++ b/src/application/ReferenceSourceImportPolicy.ts @@ -30,6 +30,7 @@ import { RegularFileCleanupFailure, regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Validated inputs ready for filesystem traversal. */ export interface PreparedReferenceSourceImport { @@ -407,6 +408,3 @@ export const prepareReferenceSourceImport = async ( }); } }; - -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/application/ReferenceSourceVcsAdapter.ts b/src/application/ReferenceSourceVcsAdapter.ts index 21bcec7dc2..f527492bfd 100644 --- a/src/application/ReferenceSourceVcsAdapter.ts +++ b/src/application/ReferenceSourceVcsAdapter.ts @@ -21,6 +21,7 @@ import { } from "../process/RegularFileRead.js"; import { referenceSourceResourceFailure } from "../reference/ReferenceSourceReaderErrors.js"; import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export type ReferenceSourceVcsInfo = | { @@ -282,6 +283,3 @@ const errorCode = (cause: unknown): string | undefined => typeof cause === "object" && cause !== null && "code" in cause ? String(cause.code) : undefined; - -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/application/SetupClientConfiguration.ts b/src/application/SetupClientConfiguration.ts index cdca350ec3..47db19e6e7 100644 --- a/src/application/SetupClientConfiguration.ts +++ b/src/application/SetupClientConfiguration.ts @@ -84,6 +84,7 @@ import { registrationWriteBlocker, type SetupClient, } from "./SupportedClients.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure { constructor( @@ -754,7 +755,7 @@ export const clientRefreshRefusal = async ( `${cause.message}: ${cause.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`, ); return refused( - `The configuration could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`, + `The configuration could not be read. Check its permissions before rerunning setup. ${errorMessage(cause)}`, ); } }; @@ -943,7 +944,7 @@ const inspectClientDocument = async ( } return { status: "invalid", - remediation: `The configuration file could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`, + remediation: `The configuration file could not be read. Check its permissions before rerunning setup. ${errorMessage(cause)}`, }; } try { @@ -1224,7 +1225,7 @@ const readZcodeFallbackServers = async ( return err({ kind: "malformed", path, - detail: `${detail} ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `${detail} ${errorMessage(cause)}`, }); } }; @@ -1250,7 +1251,7 @@ const restoreConfig = async ( return err({ kind: "restore", path: publication.path, - detail: errorDetail(cause), + detail: errorMessage(cause), }); } }; @@ -1295,9 +1296,6 @@ const conflictFailure = ( ...(backupPath === undefined ? {} : { backupPath }), }); -const errorDetail = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Whether REA's entry matches, no legacy entry remains, and no client disable list suppresses it. */ const registrationCurrent = ( parsed: ClientConfigurationDocument, diff --git a/src/application/SetupHost.ts b/src/application/SetupHost.ts index 4df30e16d5..7c3ddfc0ee 100644 --- a/src/application/SetupHost.ts +++ b/src/application/SetupHost.ts @@ -71,6 +71,7 @@ import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js"; import { analysisProviderSelectorSchema } from "../domain/providerSelection.js"; import { systemDesktopBuildSetupHost } from "../desktop/DesktopBuildSetupHost.js"; import { clientEnvironment } from "./SetupPlan.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * The launcher setup registers, and why it must not be registered when it @@ -466,9 +467,6 @@ const configurationCleanupError = ( return error; }; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Detect supported agents from their config files or stable installation markers. */ export const detectClients = async ( home: string, diff --git a/src/application/SetupRecoveryBackup.ts b/src/application/SetupRecoveryBackup.ts index 543464949f..db4e679711 100644 --- a/src/application/SetupRecoveryBackup.ts +++ b/src/application/SetupRecoveryBackup.ts @@ -5,6 +5,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { readRegularFile } from "../process/RegularFileRead.js"; import type { ArtifactResourceScope } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface RecoveryBackupSelection { readonly backupPath: string; @@ -20,9 +21,6 @@ export interface RecoveryBackupSelectionFailure { const isMissing = (cause: unknown): boolean => cause instanceof Error && "code" in cause && cause.code === "ENOENT"; -const errorDetail = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Select a persistent snapshot only when its bytes match this transaction's original. */ export const selectCurrentRecoveryBackup = async ( firstBackupPath: string, @@ -46,7 +44,7 @@ export const selectCurrentRecoveryBackup = async ( return err({ kind: "unreadable", path: firstBackupPath, - detail: `The recovery backup could not be checked: ${errorDetail(cause)}`, + detail: `The recovery backup could not be checked: ${errorMessage(cause)}`, }); } if (firstBackup === undefined) @@ -65,7 +63,7 @@ export const selectCurrentRecoveryBackup = async ( return err({ kind: "unreadable", path: recoveryPath, - detail: `The recovery backup could not be checked: ${errorDetail(cause)}`, + detail: `The recovery backup could not be checked: ${errorMessage(cause)}`, }); } if (recovery !== undefined && !recovery.equals(expected)) @@ -121,7 +119,7 @@ export const preserveCurrentRecoveryBackup = async ( return err({ kind: "copy", path: backupPath, - detail: `The recovery backup could not be written: ${errorDetail(cause)}`, + detail: `The recovery backup could not be written: ${errorMessage(cause)}`, }); } } diff --git a/src/application/SetupSkill.ts b/src/application/SetupSkill.ts index 1759933849..4716bdc260 100644 --- a/src/application/SetupSkill.ts +++ b/src/application/SetupSkill.ts @@ -26,6 +26,7 @@ import { type SkillFileSnapshot, type SkillPublicationCleanupOwner, } from "./SkillFilePublication.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export const MANAGED_SKILL_FILES = [ "SKILL.md", @@ -303,7 +304,7 @@ export const existingSkillDestinations = async ( client: destination.client, path: destination.path, kind: "unreadable", - detail: causeReason(cause), + detail: errorMessage(cause), }); } } @@ -353,7 +354,7 @@ const inspectSkillDirectory = async ( return err({ path, kind: "unreadable", - detail: cause instanceof Error ? cause.message : String(cause), + detail: errorMessage(cause), }); } }; @@ -512,7 +513,7 @@ const inspectCanonicalSkill = async ( rootIssues.push({ path: destination, kind: "unreadable", - detail: causeReason(cause), + detail: errorMessage(cause), }); if (failureCause === undefined) failureCause = cause; rootCanonical = false; @@ -581,9 +582,6 @@ export const canonicalSkillNeedsInstall = async ( } }; -const causeReason = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const causePath = (cause: unknown): string | undefined => cause instanceof Error && "path" in cause && typeof cause.path === "string" ? cause.path @@ -605,7 +603,7 @@ const closeSkillPublications = async ( } catch (cause: unknown) { failures.push({ path: publication.resource, - reason: causeReason(cause), + reason: errorMessage(cause), }); } } @@ -700,7 +698,7 @@ export const installCanonicalSkill = async ( } catch (rollbackCause: unknown) { rollbackFailures.push({ path: publication.path, - reason: causeReason(rollbackCause), + reason: errorMessage(rollbackCause), }); } } @@ -714,7 +712,7 @@ export const installCanonicalSkill = async ( new SetupSkillInstallError({ path: failingPath, stage, - reason: causeReason(cause), + reason: errorMessage(cause), rollbackFailures, recoveryBackupPaths: [...recoveryPaths.values()], completed: verified, diff --git a/src/application/SkillFilePublication.ts b/src/application/SkillFilePublication.ts index a725f04b44..7439ece2c7 100644 --- a/src/application/SkillFilePublication.ts +++ b/src/application/SkillFilePublication.ts @@ -7,6 +7,7 @@ import { fileHandleMatchesBytes } from "../filesystem/fileHandleMatchesBytes.js" import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js"; import { sameRegularFileState } from "../filesystem/RegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The read owner's byte-exact original and selected identity. */ export interface SkillFileSnapshot { @@ -48,7 +49,7 @@ export class SkillFilePreparationFailure extends Error { readonly cleanupCause: unknown, ) { super( - `Skill staging cleanup failed for ${publication.path}: ${primary instanceof Error ? primary.message : String(primary)}; cleanup: ${cleanupCause instanceof Error ? cleanupCause.message : String(cleanupCause)}`, + `Skill staging cleanup failed for ${publication.path}: ${errorMessage(primary)}; cleanup: ${errorMessage(cleanupCause)}`, { cause: new AggregateError([primary, cleanupCause]), }, diff --git a/src/application/SupportedClients.ts b/src/application/SupportedClients.ts index 01d7efc881..7c90376c90 100644 --- a/src/application/SupportedClients.ts +++ b/src/application/SupportedClients.ts @@ -48,6 +48,7 @@ import type { McpRegistrationLocation, McpRegistrationLocationContext, } from "./McpRegistrationLocations.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** One supported client configuration location. */ export interface SetupClient { @@ -304,7 +305,7 @@ const lmStudioLocation = ({ if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) return err({ path: pointerPath, - message: `${pointerPath} could not be read, so REA cannot establish which LM Studio home holds mcp.json: ${cause instanceof Error ? cause.message : String(cause)}. Repair access to that file, then rerun.`, + message: `${pointerPath} could not be read, so REA cannot establish which LM Studio home holds mcp.json: ${errorMessage(cause)}. Repair access to that file, then rerun.`, }); const cache = join(home, ".cache", "lm-studio"); directory = existsSync(cache) ? cache : join(home, ".lmstudio"); @@ -669,7 +670,7 @@ const directoryPresent = (path: string): Result => { return ok(false); return err({ path, - message: `Cannot determine whether ${path} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring Zed.`, + message: `Cannot determine whether ${path} exists: ${errorMessage(cause)}. Repair its access before configuring Zed.`, }); } }; @@ -687,7 +688,7 @@ const sameDirectory = ( } catch (cause: unknown) { return err({ path, - message: `Cannot resolve ${path}: ${cause instanceof Error ? cause.message : String(cause)}. Repair it before configuring Zed.`, + message: `Cannot resolve ${path}: ${errorMessage(cause)}. Repair it before configuring Zed.`, }); } } @@ -757,7 +758,7 @@ const regularPathPresent = ( return ok(false); return err({ path, - message: `Cannot determine whether ${path} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring MCPorter.`, + message: `Cannot determine whether ${path} exists: ${errorMessage(cause)}. Repair its access before configuring MCPorter.`, }); } }; @@ -869,7 +870,7 @@ const ampLocation = ({ ) return err({ path: candidate, - message: `Cannot determine whether ${candidate} exists: ${cause instanceof Error ? cause.message : String(cause)}. Repair its access before configuring Amp.`, + message: `Cannot determine whether ${candidate} exists: ${errorMessage(cause)}. Repair its access before configuring Amp.`, }); } } @@ -2080,7 +2081,7 @@ export const supportedClients = ( displayName: definition.displayName, format: definition.format, configPath: env.PI_CODING_AGENT_DIR ?? "", - configPathError: `Invalid PI_CODING_AGENT_DIR: ${cause instanceof Error ? cause.message : String(cause)}. Repair the override before configuring Pi.`, + configPathError: `Invalid PI_CODING_AGENT_DIR: ${errorMessage(cause)}. Repair the override before configuring Pi.`, }; } }); diff --git a/src/application/Update.ts b/src/application/Update.ts index e4b923c30e..a1b1ca7c65 100644 --- a/src/application/Update.ts +++ b/src/application/Update.ts @@ -7,6 +7,7 @@ import { unresolvedMaintenanceRemediation, type IntegrationMaintenance, } from "./UpdateMaintenance.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Global npm installation that owns the running package and its entry point. */ export interface NpmInstallation { @@ -168,7 +169,7 @@ export const runUpdate = async ( try { cleanupFailure = await host.close?.(); } catch (cause: unknown) { - cleanupFailure = `Update resource cleanup failed: ${cause instanceof Error ? cause.message : String(cause)}`; + cleanupFailure = `Update resource cleanup failed: ${errorMessage(cause)}`; } if (failed) { if (cleanupFailure !== undefined) diff --git a/src/application/UpdateCommandRunner.ts b/src/application/UpdateCommandRunner.ts index c5339b9a72..28fff4f0c4 100644 --- a/src/application/UpdateCommandRunner.ts +++ b/src/application/UpdateCommandRunner.ts @@ -18,6 +18,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { UpdateCommandProgress } from "./UpdateCommandProgress.js"; import type { UpdateOutput } from "./Update.js"; import { withoutPackageRunnerIdentity } from "./ClientRegistrationIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const UPDATE_COMMAND_OUTPUT_BYTES = 4 * 1024 * 1024; const UPDATE_PROBE_TIMEOUT_MS = 10_000; @@ -65,9 +66,7 @@ export class UpdateCommandRunner { ), ); } catch (cause: unknown) { - return commandFailure( - cause instanceof Error ? cause.message : String(cause), - ); + return commandFailure(errorMessage(cause)); } finally { deadline.dispose(); } @@ -94,9 +93,7 @@ export class UpdateCommandRunner { ), ) .then((result) => (result.ok ? result : err(result.error.detail))) - .catch((cause: unknown) => - err(cause instanceof Error ? cause.message : String(cause)), - ); + .catch((cause: unknown) => err(errorMessage(cause))); } close(): Promise { @@ -187,10 +184,7 @@ const runUpdateProcess = async ( }, ); } catch (cause: unknown) { - return commandFailure( - cause instanceof Error ? cause.message : String(cause), - "launch", - ); + return commandFailure(errorMessage(cause), "launch"); } let spawned = false; child.once("spawn", () => { diff --git a/src/application/UpdateMaintenance.ts b/src/application/UpdateMaintenance.ts index c385274d61..d2acc0552d 100644 --- a/src/application/UpdateMaintenance.ts +++ b/src/application/UpdateMaintenance.ts @@ -16,6 +16,7 @@ import type { SetupAction } from "./SetupTypes.js"; import type { Result } from "../domain/result.js"; import type { ArtifactResourceScope } from "../resources/index.js"; import type { ClientSystemPaths } from "./SupportedClients.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * A client maintenance left alone: its registration as inspected, and why REA @@ -293,9 +294,6 @@ export const planIntegrationMaintenance = async ( // Without a supplied scope, the typed failure is the caller's cleanup capability. if (resources === undefined && cause instanceof RegularFileCleanupFailure) throw cause; - return unavailableMaintenance( - cause instanceof Error ? cause.message : String(cause), - scope, - ); + return unavailableMaintenance(errorMessage(cause), scope); } }; diff --git a/src/application/UpdateRuntime.ts b/src/application/UpdateRuntime.ts index 38f31dd600..2b40c955b7 100644 --- a/src/application/UpdateRuntime.ts +++ b/src/application/UpdateRuntime.ts @@ -20,6 +20,7 @@ import { } from "./Update.js"; import { planIntegrationMaintenance } from "./UpdateMaintenance.js"; import { UpdateCommandRunner } from "./UpdateCommandRunner.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** npm filesystem queries used to identify the installation being updated. */ export interface NpmInstallationHost { @@ -338,13 +339,7 @@ export const systemUpdateHost = ( resources.close(), ]); const failures = results.flatMap((result) => - result.status === "rejected" - ? [ - result.reason instanceof Error - ? result.reason.message - : String(result.reason), - ] - : [], + result.status === "rejected" ? [errorMessage(result.reason)] : [], ); return failures.length === 0 ? undefined diff --git a/src/application/WebScriptExportService.ts b/src/application/WebScriptExportService.ts index 26258635ae..3bd60bf1ee 100644 --- a/src/application/WebScriptExportService.ts +++ b/src/application/WebScriptExportService.ts @@ -49,6 +49,7 @@ import { RegularFileCleanupFailure, regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "export_web_scripts"; @@ -364,7 +365,7 @@ const captureReadFailure = ( diagnostics: { capture_path: path, error_name: cause instanceof Error ? cause.name : "UnknownError", - error_message: cause instanceof Error ? cause.message : String(cause), + error_message: errorMessage(cause), }, }); }; @@ -389,9 +390,6 @@ const incompleteCaptureCleanup = ( return error; }; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const parseCapture = ( bytes: Buffer, closeFailure?: { readonly cause: unknown }, diff --git a/src/application/closeOwnedWebResources.ts b/src/application/closeOwnedWebResources.ts index 6107bce400..10043a1ffa 100644 --- a/src/application/closeOwnedWebResources.ts +++ b/src/application/closeOwnedWebResources.ts @@ -1,6 +1,7 @@ import { AnalysisError } from "../domain/analysisErrorBase.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Attempt every web workflow cleanup owner and report all failures. */ export const closeOwnedWebResources = async ( @@ -21,7 +22,7 @@ export const closeOwnedWebResources = async ( throw new ProviderCleanupError( "web-workflow", [], - { reason: failure instanceof Error ? failure.message : String(failure) }, + { reason: errorMessage(failure) }, { cause: failure, operation: "close_web_workflow" }, ); } @@ -48,7 +49,7 @@ export const closeOwnedWebResources = async ( failures: normalized.map( ({ cause, projection }) => projection ?? { - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), }, ), }, diff --git a/src/application/desktop/DesktopBuildBundle.ts b/src/application/desktop/DesktopBuildBundle.ts index 4adb15a744..ccdc38b867 100644 --- a/src/application/desktop/DesktopBuildBundle.ts +++ b/src/application/desktop/DesktopBuildBundle.ts @@ -25,6 +25,7 @@ import { bindArtifactFileCleanup, } from "../../resources/index.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const START = "start_build_computer"; const MAX_KEY_BYTES = 1024 * 1024; @@ -120,7 +121,7 @@ const writeBuildBundle = async ( ]); const error = new ProviderAdapterError(AGENTENV_PROVIDER, START, { cause, - userMessage: cause instanceof Error ? cause.message : String(cause), + userMessage: errorMessage(cause), cleanup: cleanup.cleanup, }); bindArtifactFileCleanup(cleanup, error); @@ -161,7 +162,7 @@ export const seededLockFiles = async ( if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) unreadable.push({ path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); return []; }; diff --git a/src/application/desktop/DesktopBuildCapture.ts b/src/application/desktop/DesktopBuildCapture.ts index e3faec2309..380680c7f3 100644 --- a/src/application/desktop/DesktopBuildCapture.ts +++ b/src/application/desktop/DesktopBuildCapture.ts @@ -39,13 +39,7 @@ import { notAnswered, type CaptureStep, } from "./DesktopBuildCaptureFailure.js"; -import { - adapterError, - errorText, - refused, - runRea, - WORK, -} from "./DesktopBuildCommands.js"; +import { adapterError, refused, runRea, WORK } from "./DesktopBuildCommands.js"; import { exportBuild, type BuildExportRequest, @@ -56,6 +50,7 @@ import { secretDraftRefusal, type StoppedCapture, } from "./DesktopBuildSummary.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const START = "start_build_capture"; const MARK = "mark_build_checkpoint"; @@ -215,7 +210,7 @@ const checkExportRuntime = async ( return ok(undefined); } catch (cause: unknown) { if (signal.aborted) return err(cancelledBy(START, signal)); - const message = errorText(cause); + const message = errorMessage(cause); const redacted = computer.redacted(message); return err( adapterError( @@ -426,7 +421,7 @@ export class DesktopBuildCapture { failure: cause instanceof AnalysisError ? cause - : adapterError(START, errorText(cause), cause), + : adapterError(START, errorMessage(cause), cause), }); } if (answer.refused !== undefined) @@ -534,7 +529,7 @@ export class DesktopBuildCapture { return err( cause instanceof AnalysisError ? cause - : adapterError(MARK, errorText(cause), cause), + : adapterError(MARK, errorMessage(cause), cause), ); } } @@ -594,7 +589,7 @@ export class DesktopBuildCapture { return err( cause instanceof AnalysisError ? cause - : adapterError(STOP, errorText(cause), cause), + : adapterError(STOP, errorMessage(cause), cause), ); } } @@ -679,7 +674,7 @@ export class DesktopBuildCapture { ? cause : signal.aborted ? cancelledBy(EXPORT, signal) - : adapterError(EXPORT, errorText(cause), cause), + : adapterError(EXPORT, errorMessage(cause), cause), ); } return exportBuild( diff --git a/src/application/desktop/DesktopBuildCommands.ts b/src/application/desktop/DesktopBuildCommands.ts index 175670b6a1..c88aab7aff 100644 --- a/src/application/desktop/DesktopBuildCommands.ts +++ b/src/application/desktop/DesktopBuildCommands.ts @@ -50,9 +50,6 @@ export type CommandOutput = | { readonly kind: "result"; readonly result: unknown } | ({ readonly kind: "failure" } & CommandFailure); -export const errorText = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - export const adapterError = ( operation: string, userMessage: string, diff --git a/src/application/desktop/DesktopBuildComputers.ts b/src/application/desktop/DesktopBuildComputers.ts index eb6ef7e3b6..472b21558f 100644 --- a/src/application/desktop/DesktopBuildComputers.ts +++ b/src/application/desktop/DesktopBuildComputers.ts @@ -68,6 +68,7 @@ import type { BuildSettle } from "./DesktopBuildSettle.js"; import { DesktopBuildTurns } from "./DesktopBuildTurns.js"; import { DesktopBuildWitness } from "./DesktopBuildWitness.js"; import { ScreenJudgeProcess } from "../../desktop/ScreenJudgeProcess.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const START = "start_build_computer"; const ACT = "act_on_build_computer"; @@ -149,7 +150,7 @@ const failure = ( if (cause instanceof AnalysisError) return cause; if (signal.aborted) return cancelledBy(operation, signal); return new ProviderAdapterError(AGENTENV_PROVIDER, operation, { - userMessage: cause instanceof Error ? cause.message : String(cause), + userMessage: errorMessage(cause), cause, }); }; @@ -199,7 +200,7 @@ const reset = async ( .callTool("computer_screenshot", {}, signal) .catch((cause: unknown) => { if (signal.aborted) throw cause; - return cause instanceof Error ? cause.message : String(cause); + return errorMessage(cause); }); if (typeof shot === "string" || shot.isError) return { @@ -271,7 +272,7 @@ const liveComputer = ( } catch (cause: unknown) { return { verified: false, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: [], }; } @@ -397,7 +398,7 @@ const startFailure = ( kept.release.verified ? { remediationAction: cause.remediation } : {}), - userMessage: cause instanceof Error ? cause.message : String(cause), + userMessage: errorMessage(cause), ...options, cause, }); @@ -759,7 +760,7 @@ export class DesktopBuildComputers { } catch (cause: unknown) { return { verified: false, - reason: `the build bundle folder could not be removed: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `the build bundle folder could not be removed: ${errorMessage(cause)}`, resources: [held.workspace?.path ?? id], }; } diff --git a/src/application/desktop/DesktopBuildExport.ts b/src/application/desktop/DesktopBuildExport.ts index 439febec15..81a85b06e6 100644 --- a/src/application/desktop/DesktopBuildExport.ts +++ b/src/application/desktop/DesktopBuildExport.ts @@ -38,7 +38,6 @@ import { import { adapterError, ENDS, - errorText, readOutput, refused, reportedFailure, @@ -51,6 +50,7 @@ import { desktopOutputFailure, type DesktopOutputCompletion, } from "./DesktopOutputTree.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const EXPORT = "export_build_environment"; const exportResultSchema = z.looseObject({ @@ -485,7 +485,7 @@ export const exportBuild = async ( ? cancelledBy(EXPORT, carriedReason(cause)) : adapterError( EXPORT, - redactSecrets(errorText(cause), capture.secrets), + redactSecrets(errorMessage(cause), capture.secrets), cause, ); if (published !== undefined) diff --git a/src/application/desktop/DesktopBuildSolves.ts b/src/application/desktop/DesktopBuildSolves.ts index c84db25336..affbc55ebe 100644 --- a/src/application/desktop/DesktopBuildSolves.ts +++ b/src/application/desktop/DesktopBuildSolves.ts @@ -56,7 +56,7 @@ import { silentProgressReporter, type ProgressReporter, } from "../../ports/ProgressReporter.js"; -import { errorText } from "./DesktopBuildCommands.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const MEASURE = "measure_build_task"; /** The file at the bundle's root that records each measured task. */ @@ -416,7 +416,7 @@ export const measureBuildTask = async ( : signal.aborted ? cancelledBy(MEASURE, signal) : new ProviderAdapterError(AGENTENV_PROVIDER, MEASURE, { - userMessage: `Measuring ${task} failed after ${String(solves.length)} solve(s): ${errorText(cause)}`, + userMessage: `Measuring ${task} failed after ${String(solves.length)} solve(s): ${errorMessage(cause)}`, remediationAction: "Check the bundle files and host I/O error, then retry or retain the completed solve results.", cause, diff --git a/src/application/desktop/DesktopBuildWitness.ts b/src/application/desktop/DesktopBuildWitness.ts index 0d181f6e44..2f1b4d199f 100644 --- a/src/application/desktop/DesktopBuildWitness.ts +++ b/src/application/desktop/DesktopBuildWitness.ts @@ -40,7 +40,6 @@ import { type ProgressReporter, } from "../../ports/ProgressReporter.js"; import type { ReadonlyActionLog } from "./DesktopBuildActionLog.js"; -import { errorText } from "./DesktopBuildCommands.js"; import { desktopOperationFailure } from "./DesktopCaptureRefusals.js"; import { settledAppData, type BuildSettle } from "./DesktopBuildSettle.js"; import { DesktopRemoteTaskReaders } from "./DesktopRemoteTaskReaders.js"; @@ -55,6 +54,7 @@ import { type EndedWitness, type WitnessRecord, } from "./DesktopBuildWitnessRecord.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const CHECK = "check_build_task"; const FRESH = @@ -313,7 +313,7 @@ export class DesktopBuildWitness { cause instanceof AnalysisError ? cause : new ProviderAdapterError(AGENTENV_PROVIDER, CHECK, { - userMessage: `Reading the app's state failed: ${errorText(cause)}`, + userMessage: `Reading the app's state failed: ${errorMessage(cause)}`, cause, }), ); @@ -586,7 +586,7 @@ export class DesktopBuildWitness { } catch (cause: unknown) { return err( new ProviderAdapterError(AGENTENV_PROVIDER, CHECK, { - userMessage: `The witness could not start its recording: ${errorText(cause)}`, + userMessage: `The witness could not start its recording: ${errorMessage(cause)}`, cause, }), ); diff --git a/src/application/desktop/DesktopBuildWitnessBundle.ts b/src/application/desktop/DesktopBuildWitnessBundle.ts index bb33607771..f91176db27 100644 --- a/src/application/desktop/DesktopBuildWitnessBundle.ts +++ b/src/application/desktop/DesktopBuildWitnessBundle.ts @@ -34,7 +34,7 @@ import { } from "../../desktop/AgentEnvComputer.js"; import { AGENTENV_PROVIDER } from "../../desktop/AgentEnvComputerHelper.js"; import { readHostFile } from "../../desktop/HostFileRead.js"; -import { errorText } from "./DesktopBuildCommands.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const CHECK = "check_build_task"; @@ -156,7 +156,7 @@ export const judgeScreenTask = async ( ? cause : cause.retainDiagnostics({ completed_judge_checks: results }) : new ProviderAdapterError(AGENTENV_PROVIDER, CHECK, { - userMessage: `The screen judge could not check the screen: ${errorText(cause)}`, + userMessage: `The screen judge could not check the screen: ${errorMessage(cause)}`, cause, ...(results.length === 0 ? {} diff --git a/src/application/desktop/DesktopBuildWitnessRecord.ts b/src/application/desktop/DesktopBuildWitnessRecord.ts index 35362cd0af..7d82483542 100644 --- a/src/application/desktop/DesktopBuildWitnessRecord.ts +++ b/src/application/desktop/DesktopBuildWitnessRecord.ts @@ -26,13 +26,13 @@ import { type BuildComputerAction, type ReadonlyActionLog, } from "./DesktopBuildActionLog.js"; -import { errorText } from "./DesktopBuildCommands.js"; import { DESKTOP_PROVIDER } from "./DesktopCaptureRefusals.js"; import { planOutputTree, writeOutputTree, desktopOutputFailure, } from "./DesktopOutputTree.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const CHECK = "check_build_task"; const RECORD = "witness.json"; @@ -114,7 +114,7 @@ const fetchRecording = async ( try { manifest ??= await computer.endRecording(recordingId, signal); } catch (cause: unknown) { - return { ok: false, error: errorText(cause) }; + return { ok: false, error: errorMessage(cause) }; } try { const segments = await computer.recordingSegments(manifest, signal); @@ -134,7 +134,7 @@ const fetchRecording = async ( }, }; } catch (cause: unknown) { - return { ok: false, error: errorText(cause), manifest }; + return { ok: false, error: errorMessage(cause), manifest }; } }; @@ -190,7 +190,7 @@ const writeRecordFolder = async ( cause instanceof AnalysisError ? cause : new ProviderAdapterError(AGENTENV_PROVIDER, CHECK, { - userMessage: `The witness record could not be written: ${errorText(cause)}`, + userMessage: `The witness record could not be written: ${errorMessage(cause)}`, cause, partialObservation: evidence, }), diff --git a/src/application/desktop/DesktopOutputTree.ts b/src/application/desktop/DesktopOutputTree.ts index 49e6b3765c..114dfd83f2 100644 --- a/src/application/desktop/DesktopOutputTree.ts +++ b/src/application/desktop/DesktopOutputTree.ts @@ -21,6 +21,7 @@ import { import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; import type { Evidence } from "../../domain/evidence.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** A published tree whose output handles could not be released. */ type FailedRelease = Extract< @@ -215,10 +216,7 @@ export const desktopOutputFailure = ( if (cancellation !== undefined && evidence !== undefined) cancellation.retainPartialObservation(evidence); if (release === undefined) return cancellation; - const reason = - release.cause instanceof Error - ? release.cause.message - : String(release.cause); + const reason = errorMessage(release.cause); const error = new ProviderAdapterError(context.provider, context.operation, { cause: release.cause, userMessage: `The ${context.what} was written to ${directory} and is complete, but its output handles could not be closed: ${reason}.`, diff --git a/src/application/desktop/DesktopRemoteTaskReaders.ts b/src/application/desktop/DesktopRemoteTaskReaders.ts index 15745adf81..bafb82efcf 100644 --- a/src/application/desktop/DesktopRemoteTaskReaders.ts +++ b/src/application/desktop/DesktopRemoteTaskReaders.ts @@ -27,6 +27,7 @@ import { AbortedWait, waitForAbortable, } from "../../process/AbortablePromise.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; type Exec = ( argv: readonly string[], @@ -151,7 +152,7 @@ export class DesktopRemoteTaskReaders { if (failure !== undefined) throw new ProviderAdapterError(AGENTENV_PROVIDER, "check_build_task", { cause: failure, - userMessage: `The task reader could not complete: ${failure instanceof Error ? failure.message : String(failure)}`, + userMessage: `The task reader could not complete: ${errorMessage(failure)}`, diagnostics: this.#facts(views, absent), }); } @@ -189,8 +190,7 @@ export class DesktopRemoteTaskReaders { } catch (cause: unknown) { for (const reference of this.#failures) reference.deref()?.retainDiagnostics({ - late_reader_failure: - cause instanceof Error ? cause.message : String(cause), + late_reader_failure: errorMessage(cause), }); } } else { @@ -238,7 +238,7 @@ export class DesktopRemoteTaskReaders { } this.#pending.delete(pending); } catch (cause: unknown) { - errors.push(cause instanceof Error ? cause.message : String(cause)); + errors.push(errorMessage(cause)); } } if (errors.length > 0) diff --git a/src/application/desktop/DesktopTaskReaderCleanup.ts b/src/application/desktop/DesktopTaskReaderCleanup.ts index 189a9a8d24..525977b485 100644 --- a/src/application/desktop/DesktopTaskReaderCleanup.ts +++ b/src/application/desktop/DesktopTaskReaderCleanup.ts @@ -11,6 +11,7 @@ import { type RetainedWorkerCleanup, } from "../../process/OwnedWorkerRuntime.js"; import { DESKTOP_PROVIDER } from "./DesktopCaptureRefusals.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "export_desktop_application"; @@ -26,7 +27,7 @@ const primaryFailure = (cause: unknown): AnalysisError | undefined => { ? cancelledBy(OPERATION, carriedReason(cause.cancellation?.reason)) : new ProviderAdapterError(DESKTOP_PROVIDER.id, OPERATION, { cause, - userMessage: `The task reader could not complete: ${cause instanceof Error ? cause.message : String(cause)}`, + userMessage: `The task reader could not complete: ${errorMessage(cause)}`, }); }; @@ -91,7 +92,7 @@ class ReaderCleanup implements RetainedWorkerCleanup { this.#released.confirm(); } catch (cause: unknown) { this.failure.retainDiagnostics({ - retry_failure: cause instanceof Error ? cause.message : String(cause), + retry_failure: errorMessage(cause), }); throw this.failure; } @@ -118,7 +119,7 @@ export const retainReaderCleanup = ( DESKTOP_PROVIDER.id, resources, { - reason: problem instanceof Error ? problem.message : String(problem), + reason: errorMessage(problem), ...readerDiagnostics(facts), }, { diff --git a/src/application/environment/environmentBundleWrite.ts b/src/application/environment/environmentBundleWrite.ts index 97c42ce661..cd7242c5fa 100644 --- a/src/application/environment/environmentBundleWrite.ts +++ b/src/application/environment/environmentBundleWrite.ts @@ -33,6 +33,7 @@ import type { EnvironmentExportInput, WrittenBundleFile, } from "./environmentExport.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** * A host failure on one file the bundle writer was reading or writing. @@ -344,11 +345,10 @@ export const writeEnvironmentBundle = async ( const primary = isHostSystemFailure(cause) ? new BundleFileHostFailure(plan.packageSource.path, "reading", cause) : cause; - throw new ArtifactReaderFailure( - "io", - primary instanceof Error ? primary.message : String(primary), - { cause: primary, partialObservation: publication }, - ); + throw new ArtifactReaderFailure("io", errorMessage(primary), { + cause: primary, + partialObservation: publication, + }); } } throw cause; diff --git a/src/application/il2cpp/Il2cppMetadataService.ts b/src/application/il2cpp/Il2cppMetadataService.ts index af086432bf..b8ba17e99e 100644 --- a/src/application/il2cpp/Il2cppMetadataService.ts +++ b/src/application/il2cpp/Il2cppMetadataService.ts @@ -28,6 +28,7 @@ import { type Il2cppMetadataProviderInput, } from "../../domain/il2cpp/il2cppMetadata.js"; import { err, ok, type Result } from "../../domain/result.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_il2cpp_metadata"; const NO_RETENTION: AnalysisViewRetention = { @@ -58,8 +59,7 @@ export class Il2cppMetadataService { this.provider.identity.id, [], { - reason: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { cause, operation: OPERATION }, ); diff --git a/src/application/javascript/ElectronActiveObservationService.ts b/src/application/javascript/ElectronActiveObservationService.ts index 3436bd6e06..d617c8630f 100644 --- a/src/application/javascript/ElectronActiveObservationService.ts +++ b/src/application/javascript/ElectronActiveObservationService.ts @@ -26,6 +26,7 @@ import { err, ok, type Result } from "../../domain/result.js"; import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js"; import { completeProviderEvidence } from "../ProviderOperationExecution.js"; import { jsonValueSchema } from "../../domain/jsonValue.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "capture_electron_scenario" as const; const PROVIDER_ID = "rea-playwright-electron-active"; @@ -91,7 +92,7 @@ const resolveInputPath = async ( issue: { path: [field], reason: "invalid_value", - message: `Cannot resolve ${field} ${selected}: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `Cannot resolve ${field} ${selected}: ${errorMessage(cause)}`, }, cause, }, @@ -136,7 +137,7 @@ const notExecutable = ( issue: { path: ["executable_path"], reason: "invalid_value", - message: `executable_path ${selected} is not an executable file: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `executable_path ${selected} is not an executable file: ${errorMessage(cause)}`, }, cause, }); diff --git a/src/application/javascript/ElectronBoundaryGraphContext.ts b/src/application/javascript/ElectronBoundaryGraphContext.ts index 75385ea46e..c21748f61e 100644 --- a/src/application/javascript/ElectronBoundaryGraphContext.ts +++ b/src/application/javascript/ElectronBoundaryGraphContext.ts @@ -1,5 +1,4 @@ import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js"; -import { sha256Text } from "../../domain/javascript/javascriptStaticAnalysisHelpers.js"; import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js"; import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js"; import { @@ -11,6 +10,7 @@ import { astObservationEvidence, staticInferenceEvidence, } from "./JavaScriptArtifactGraphEvidence.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Values for one Electron syntax relationship retained in the graph. */ export interface ElectronGraphEdgeInput { @@ -75,7 +75,7 @@ export const electronObservationIdentity = ( ) => ({ strategy: "observation-fingerprint" as const, stability: "observation-only" as const, - observation_sha256: sha256Text( + observation_sha256: sha256Hex( `${context.snapshot.manifest.root_sha256}\0${scope}\0${key}`, ), scope, diff --git a/src/application/releaseExposure/ReleaseExposureService.ts b/src/application/releaseExposure/ReleaseExposureService.ts index d21fd85b21..809c314b5b 100644 --- a/src/application/releaseExposure/ReleaseExposureService.ts +++ b/src/application/releaseExposure/ReleaseExposureService.ts @@ -53,6 +53,7 @@ import { err, ok, type Result } from "../../domain/result.js"; import { goBuildPaths } from "../../domain/releaseExposureGoPaths.js"; import { rustBinarySchema } from "../../domain/rust/rustBinary.js"; import type { ReleaseExposurePort } from "../../ports/releaseExposure/ReleaseExposurePort.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; export interface ReleaseExposureOwners { readonly reader: ReleaseExposurePort; @@ -321,7 +322,7 @@ export class ReleaseExposureService { return err(cause); return ok({ family: "unknown", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), archivePaths: [], }); } @@ -345,7 +346,7 @@ export class ReleaseExposureService { kind: "failed", role: candidate.role, path: candidate.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); } if (!result.ok) { @@ -429,12 +430,7 @@ export class ReleaseExposureService { } catch (cause) { if (cause instanceof AnalysisError && stopsAudit(cause)) return err(cause); - return ok( - failedMetadata( - cause instanceof Error ? cause.message : String(cause), - path, - ), - ); + return ok(failedMetadata(errorMessage(cause), path)); } } } @@ -580,7 +576,7 @@ const ownerCloseFailure = ( cause instanceof AnalysisError ? projectAnalysisError(cause) : { - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), }, })), }, diff --git a/src/application/reverse/ReverseEngineeringService.ts b/src/application/reverse/ReverseEngineeringService.ts index 84383484b0..8cbdc15e04 100644 --- a/src/application/reverse/ReverseEngineeringService.ts +++ b/src/application/reverse/ReverseEngineeringService.ts @@ -88,6 +88,7 @@ import { import { absoluteCallerPath } from "../../filesystem/callerPath.js"; import { parseAnalysisInput } from "../AnalysisInput.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; export type ReverseEngineeringOperation = | "inspect_with_objdump" @@ -296,7 +297,7 @@ export class ReverseEngineeringService { } catch (cause) { stopped = { status: "incomplete", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } if (stopped.status === "incomplete") { diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index 076bb1eb5c..a1637058da 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -67,6 +67,7 @@ import type { BundleResourceRoot, } from "../domain/apple/bundleResourceRoot.js"; import { BUNDLE_ARTIFACT_RESOURCE_OPERATIONS } from "../ports/BundleResourceOperations.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Read-only inventory and exclusively owned extraction provider. */ export class ArtifactProvider implements AnalysisProvider { @@ -127,9 +128,7 @@ const closeArtifactResources = ( ARTIFACT_GRAPH_PROVIDER.id, failure?.cleanup?.resources ?? [fallbackResource], { - reason: - failure?.cleanup?.reason ?? - (cause instanceof Error ? cause.message : String(cause)), + reason: failure?.cleanup?.reason ?? errorMessage(cause), }, { cause, operation: "close_binary" }, ); diff --git a/src/artifacts/DirectoryArtifactReader.ts b/src/artifacts/DirectoryArtifactReader.ts index 8c61f1538e..e492b2b62d 100644 --- a/src/artifacts/DirectoryArtifactReader.ts +++ b/src/artifacts/DirectoryArtifactReader.ts @@ -34,6 +34,7 @@ import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js"; import { decodeDirectoryEntryName } from "../filesystem/decodeDirectoryEntryName.js"; import { resolveArtifactSourcePath } from "./ArtifactSelectedSource.js"; import { invariantViolation } from "../domain/internalInvariant.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export type DirectoryArtifactEntry = ArtifactEntry & { readonly kind: "file" | "directory" | "symlink"; @@ -442,7 +443,7 @@ export class DirectoryArtifactReader implements ArtifactReader { if (outcome.kind !== "failed") throw validationCause; throw new ArtifactReaderFailure( "io", - `Directory inspection failed: ${failureMessage(outcome.cause)}; final source identity could not be validated: ${failureMessage(validationCause)}`, + `Directory inspection failed: ${errorMessage(outcome.cause)}; final source identity could not be validated: ${errorMessage(validationCause)}`, { cause: new AggregateError( [outcome.cause, validationCause], @@ -459,7 +460,7 @@ export class DirectoryArtifactReader implements ArtifactReader { ) throw new ArtifactReaderFailure( "integrity", - `Directory entry changed during inspection: ${entry.path}${outcome.kind === "failed" ? `; inspection failed: ${failureMessage(outcome.cause)}` : ""}`, + `Directory entry changed during inspection: ${entry.path}${outcome.kind === "failed" ? `; inspection failed: ${errorMessage(outcome.cause)}` : ""}`, { integrityCheck: "member-identity", ...(outcome.kind === "failed" ? { cause: outcome.cause } : {}), @@ -534,7 +535,7 @@ export class DirectoryArtifactReader implements ArtifactReader { } } if (failures.length > 0) { - const reason = failures.map(failureMessage).join("; "); + const reason = failures.map(errorMessage).join("; "); throw new ArtifactReaderFailure( "io", `Directory artifact cleanup failed: ${reason}`, @@ -633,7 +634,7 @@ const directoryIoFailure = ( if (cause instanceof ArtifactReaderFailure) return cause; const code = hostErrorCode(cause); const suffix = code === undefined ? "" : ` (${code})`; - const detail = failureMessage(cause); + const detail = errorMessage(cause); return new Failure( "io", `Could not ${operation} at ${path}${suffix}: ${detail}`, @@ -672,9 +673,6 @@ const entryOpenFailure = ( : failure; }; -const failureMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - type CapturedSourceIdentity = NonNullable; const mapStableFileRead = async function* ( diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts index 0b1f746627..767ad3b631 100644 --- a/src/artifacts/NativeDmgArtifactReader.ts +++ b/src/artifacts/NativeDmgArtifactReader.ts @@ -33,6 +33,7 @@ import { type NativeDmgInfo, } from "./NativeDmgOwnership.js"; import { invariantViolation } from "../domain/internalInvariant.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const HDIUTIL_COMMAND_TIMEOUT_MS = 120_000; /** Conditional recovery guidance; a path match never grants attachment ownership. */ const DMG_EXISTING_ATTACHMENT_RECOVERY = @@ -285,11 +286,11 @@ export class NativeDmgArtifactReader implements ArtifactReader { if (detachFailure !== undefined) throw new ArtifactReaderFailure( "unavailable", - `DMG detach or mount-root cleanup failed for ${JSON.stringify(this.path)}: ${failureMessage(detachFailure)}`, + `DMG detach or mount-root cleanup failed for ${JSON.stringify(this.path)}: ${errorMessage(detachFailure)}`, { cause: detachFailure, cleanup: { - reason: failureMessage(detachFailure), + reason: errorMessage(detachFailure), resources: [ ...this.#devices.map((device) => `DMG device ${device}`), ...(this.#attachMayHaveMounted @@ -361,7 +362,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { } catch (cause: unknown) { const mountRoot = this.#mountRoot ?? this.path; throw ArtifactReaderFailure.withCleanup(cause, { - reason: `DMG mounted directory remains owned: ${failureMessage(cause)}`, + reason: `DMG mounted directory remains owned: ${errorMessage(cause)}`, resources: [ `DMG mounted directory at ${mountRoot}`, `DMG mount root ${mountRoot}`, @@ -391,7 +392,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { await this.#resolveAttachOwnership(); return undefined; } catch (cause: unknown) { - this.#ownershipUncertainty = failureMessage(cause); + this.#ownershipUncertainty = errorMessage(cause); return cause; } } @@ -721,9 +722,6 @@ const existingImagePathListed = async ( return false; }; -const failureMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const processNotStarted = (cause: unknown): boolean => { if (!(cause instanceof Error)) return false; const syscall = Reflect.get(cause, "syscall"); diff --git a/src/artifacts/ReleaseExposureReader.ts b/src/artifacts/ReleaseExposureReader.ts index 5c3ca5a567..80f63e3688 100644 --- a/src/artifacts/ReleaseExposureReader.ts +++ b/src/artifacts/ReleaseExposureReader.ts @@ -121,6 +121,7 @@ import { htmlArtifactReferences } from "../domain/javascript/htmlArtifactReferen import { parseJavaScriptSource } from "../domain/javascript/javascriptSourceParser.js"; import { addSourceMapDirectives } from "../domain/javascript/javascriptStaticAnalysisCalls.js"; import { createJavaScriptAnalysisAccumulator } from "../domain/javascript/javascriptStaticAnalysisState.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "audit_release_exposure"; type PackageFormat = Extract< @@ -3722,7 +3723,7 @@ const releaseExposureFailurePrimary = ( cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index d6dc76753f..85e67d16e0 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -65,6 +65,7 @@ import { hasNibArchiveSignature, } from "../../domain/apple/appleArchiveFormat.js"; import { estimateBinaryPlistExpansion } from "../../domain/apple/propertyListDecodeBudget.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const MAX_BYTES = 64 * 1024 * 1024; /** Decoded representation budget, the same 8:1 ratio Interface Builder uses. */ @@ -490,7 +491,7 @@ const decodeSelectedArchive = ( isHostLimitFailure(cause) ? "limit" : "format", - `Cannot decode selected Foundation keyed archive: ${cause instanceof Error ? cause.message : String(cause)}`, + `Cannot decode selected Foundation keyed archive: ${errorMessage(cause)}`, { cause }, ); } diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index ef3c22a12f..3b3305a655 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -54,6 +54,7 @@ import { } from "./scanReader.js"; import type { ArtifactInventoryOptions } from "./types.js"; import type { ArtifactContainerIntegrityPair } from "../../domain/artifactIntegrity.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; export interface TransferredArtifactInventorySource { readonly owner: ArtifactResourceOwner; @@ -242,7 +243,7 @@ const scanCanonical = async ( cause.reason, rootFailure === undefined ? cause.message - : `${cause.message}; root observations could not be revalidated: ${rootFailure instanceof Error ? rootFailure.message : String(rootFailure)}`, + : `${cause.message}; root observations could not be revalidated: ${errorMessage(rootFailure)}`, { cause: rootFailure === undefined diff --git a/src/browser/CdpBrowserProvider.ts b/src/browser/CdpBrowserProvider.ts index d9014a599f..b16ece541c 100644 --- a/src/browser/CdpBrowserProvider.ts +++ b/src/browser/CdpBrowserProvider.ts @@ -98,6 +98,7 @@ import { CdpTargetSessionOwner, bindCdpTransportCleanup, } from "./CdpTargetSessionOwner.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const CLEANUP_DOMAINS = [ "Network", "Debugger", @@ -634,7 +635,7 @@ const withTargetSession = async < : new ProviderCleanupError( "rea-cdp-browser", [input.target_id], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation, cause }, ); } diff --git a/src/browser/CdpElectronProvider.ts b/src/browser/CdpElectronProvider.ts index 45cb888451..b2aff1ecfa 100644 --- a/src/browser/CdpElectronProvider.ts +++ b/src/browser/CdpElectronProvider.ts @@ -48,6 +48,7 @@ import { CdpTargetSessionOwner, bindCdpTransportCleanup, } from "./CdpTargetSessionOwner.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Passive Electron provider for local file pages exposed by loopback CDP. */ export class CdpElectronProvider implements ElectronObservationPort { readonly #owner = new CdpTargetSessionOwner(); @@ -324,8 +325,7 @@ export class CdpElectronProvider implements ElectronObservationPort { CDP_ELECTRON_PROVIDER_IDENTITY.id, [input.target_id], { - reason: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: "inspect_electron_page", cause }, ); diff --git a/src/browser/CdpTargetSessionOwner.ts b/src/browser/CdpTargetSessionOwner.ts index 87d6e3666e..2f6599b875 100644 --- a/src/browser/CdpTargetSessionOwner.ts +++ b/src/browser/CdpTargetSessionOwner.ts @@ -17,6 +17,7 @@ import { import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { CdpConnection } from "./CdpConnection.js"; import type { ExecutionOptions } from "../ports/AnalysisProvider.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Typed ownership facts shared by transport errors and their adapter projections. */ class CdpTransportCleanupFailure extends ProviderCleanupError { @@ -733,9 +734,7 @@ const cleanupError = ( reason: cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) - : cause instanceof Error - ? cause.message - : String(cause), + : errorMessage(cause), }, }); diff --git a/src/browser/PlaywrightBrowserScenarioProvider.ts b/src/browser/PlaywrightBrowserScenarioProvider.ts index 64fadcd160..75e525faa7 100644 --- a/src/browser/PlaywrightBrowserScenarioProvider.ts +++ b/src/browser/PlaywrightBrowserScenarioProvider.ts @@ -62,6 +62,7 @@ import { const OPERATION = "capture_browser_scenario" as const; import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number]; const SNAPSHOT_KINDS = [ @@ -540,9 +541,7 @@ export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapture PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id, (pending.cleanupResources ?? []).map(redactText), { - reason: redactText( - cause instanceof Error ? cause.message : String(cause), - ), + reason: redactText(errorMessage(cause)), }, { operation: OPERATION, cause }, ); diff --git a/src/browser/PlaywrightElectronActiveProvider.ts b/src/browser/PlaywrightElectronActiveProvider.ts index 4b13ab9d91..37e73dac00 100644 --- a/src/browser/PlaywrightElectronActiveProvider.ts +++ b/src/browser/PlaywrightElectronActiveProvider.ts @@ -64,6 +64,7 @@ const OPERATION = "capture_electron_scenario" as const; const STARTUP_TIMEOUT_MS = 60_000; import { PLAYWRIGHT_ELECTRON_ACTIVE_PROVIDER_IDENTITY } from "./providerIdentities.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const hookPath = fileURLToPath( new URL("../../scripts/electron-active-hook.cjs", import.meta.url), @@ -277,7 +278,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati actions, retained.state, ); - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); capture = { ...retainedCapture, limitations: [ @@ -322,9 +323,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati "Electron process and transport cleanup failed", ); const reason = failures - .map((failure) => - failure instanceof Error ? failure.message : String(failure), - ) + .map((failure) => errorMessage(failure)) .join("; "); const failure = new BrowserObservationError( OPERATION, @@ -585,7 +584,7 @@ const providerError = (cause: unknown): AnalysisError => { { cause, diagnostics: { - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), }, }, ); diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts index ec36401cef..abc8262f77 100644 --- a/src/browser/PlaywrightScenarioBrowser.ts +++ b/src/browser/PlaywrightScenarioBrowser.ts @@ -42,6 +42,7 @@ import { type PlaywrightCdpSession, } from "./PlaywrightCdpSession.js"; import { CdpMalformedReply } from "./protocol/CdpCommands.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "capture_browser_scenario" as const; @@ -142,7 +143,7 @@ export class PlaywrightScenarioBrowserCleanupOwner { const failure = new BrowserObservationError(OPERATION, "cleanup_failed", { cause, cleanup: { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: this.cleanupResources, }, }); @@ -702,7 +703,7 @@ export const failBrowserScenarioOperation = async ( const failure = new BrowserObservationError(OPERATION, "cleanup_failed", { cause, cleanup: { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: cleanup.cleanupResources ?? [], }, }); @@ -955,8 +956,7 @@ export const openPlaywrightScenarioBrowser = async ( remediationAction: chromiumLaunchRemediation(chromiumSandbox), diagnostics: { executable_path: executablePath, - startup_error: - cause instanceof Error ? cause.message : String(cause), + startup_error: errorMessage(cause), }, }, ) diff --git a/src/browser/PlaywrightScenarioRequest.ts b/src/browser/PlaywrightScenarioRequest.ts index 39809136a6..62752544f1 100644 --- a/src/browser/PlaywrightScenarioRequest.ts +++ b/src/browser/PlaywrightScenarioRequest.ts @@ -28,6 +28,7 @@ import { scenarioQueryLength, uriComponentLength, } from "./BrowserScenarioSerialization.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type RequestAction = Extract; @@ -482,7 +483,7 @@ export const performScenarioRequest = async (input: { if (primaryFailure !== undefined) throw new AggregateError( [primaryFailure.cause, cause], - `Scenario request failed: ${primaryFailure.cause instanceof Error ? primaryFailure.cause.message : String(primaryFailure.cause)}; route cleanup failed: ${cause instanceof Error ? cause.message : String(cause)}`, + `Scenario request failed: ${errorMessage(primaryFailure.cause)}; route cleanup failed: ${errorMessage(cause)}`, { cause: primaryFailure.cause }, ); throw cause; @@ -684,7 +685,7 @@ export const awaitSavedResponse = ( } catch (cause: unknown) { if (cause instanceof ScenarioRequestError) throw cause; throw new ScenarioRequestError( - `Step ${stepId}: no ${spec.method} ${spec.path} response could be read, so nothing was saved: ${cause instanceof Error ? cause.message : String(cause)}`, + `Step ${stepId}: no ${spec.method} ${spec.path} response could be read, so nothing was saved: ${errorMessage(cause)}`, { cause }, ); } @@ -830,9 +831,7 @@ const saveValues = ( try { secrets.save(`${stepId}.${name}`, name, value, secret); } catch (cause) { - throw new ScenarioRequestError( - `Step ${stepId}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + throw new ScenarioRequestError(`Step ${stepId}: ${errorMessage(cause)}`); } } }; diff --git a/src/browser/PlaywrightScenarioStorage.ts b/src/browser/PlaywrightScenarioStorage.ts index 601057d00d..fdd15cd92d 100644 --- a/src/browser/PlaywrightScenarioStorage.ts +++ b/src/browser/PlaywrightScenarioStorage.ts @@ -30,6 +30,7 @@ import { scenarioCommandTimeoutMs, withScenarioCommandDeadline, } from "./ScenarioCommandDeadline.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type StorageEventMethod = | "Runtime.executionContextCreated" @@ -745,7 +746,7 @@ export class PlaywrightScenarioStorage { { cause, cleanup: { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: ["browser_transport", "browser_storage_bootstrap"], }, }, diff --git a/src/browser/WebArtifactCleanup.ts b/src/browser/WebArtifactCleanup.ts index d995fec944..87d5eb74b8 100644 --- a/src/browser/WebArtifactCleanup.ts +++ b/src/browser/WebArtifactCleanup.ts @@ -9,6 +9,7 @@ import { LocalWebScriptArtifacts } from "./assets/LocalWebScriptArtifacts.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type WebArtifactOwner = | "web-source-location-artifacts" @@ -147,7 +148,7 @@ const webArtifactCleanupFailures = ( ? projection : { name: cause instanceof Error ? cause.name : "UnknownError", - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), resource: [...observation.resources], }, ), diff --git a/src/browser/WebBundleAnalysisWorkerServer.ts b/src/browser/WebBundleAnalysisWorkerServer.ts index 6b9e56d6e9..170f9afd93 100644 --- a/src/browser/WebBundleAnalysisWorkerServer.ts +++ b/src/browser/WebBundleAnalysisWorkerServer.ts @@ -34,6 +34,7 @@ import { } from "./WebBundleAnalysisWorkerProtocol.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface WebBundleScriptAnalyzer { ( @@ -135,7 +136,7 @@ const analyzeJob = async ( script = includedWebScriptSchema.parse(decoded); } catch (cause) { throw new WebBundleWorkerInputError( - `Web bundle worker source is not a valid included script: ${cause instanceof Error ? cause.message : String(cause)}`, + `Web bundle worker source is not a valid included script: ${errorMessage(cause)}`, ); } await send({ kind: "phase", id: request.id, phase: "analyze" }); @@ -153,7 +154,7 @@ const analyzeJob = async ( } catch (cause) { if (cause instanceof AnalysisResourceConstraintError) throw cause; throw new WebBundleWorkerOutputError( - `Web bundle analyzer returned an invalid result: ${cause instanceof Error ? cause.message : String(cause)}`, + `Web bundle analyzer returned an invalid result: ${errorMessage(cause)}`, ); } // A refused script crosses with its partial facts; the parent states the @@ -227,9 +228,7 @@ const analyzeJob = async ( cause.cleanupLeases !== undefined && cause.cleanupLeases.length > 0; // The parent owns resource-error formatting; send the canonical reason. - const rawMessage = - refusal?.reason ?? - (cause instanceof Error ? cause.message : String(cause)); + const rawMessage = refusal?.reason ?? errorMessage(cause); await send({ kind: "failure", id: request.id, diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index 3eb03e0822..60bb5e5826 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -62,6 +62,7 @@ import { sourceMapLimitRecovery, type SourceMapLimits, } from "../domain/sourceMapLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface WebSourceMapRequest { readonly scriptKey: string; @@ -375,11 +376,11 @@ class SourceMapResponseCleanup extends Error { : new ProviderAdapterError("rea-cdp-browser", "analyze_web_bundle", { cause, cleanup, - userMessage: cause instanceof Error ? cause.message : String(cause), + userMessage: errorMessage(cause), }); this.#released.bind(this.failure.bindCleanupResourceOwner(this)); const failed = (cause: unknown): void => { - reason = `Source-map response cancellation failed: ${cause instanceof Error ? cause.message : String(cause)}`; + reason = `Source-map response cancellation failed: ${errorMessage(cause)}`; this.failure.retainSecondaryFailure( new ProviderCleanupError( "rea-cdp-browser", diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index 822b987f73..2c727f88c8 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -31,6 +31,7 @@ import { malformedInput, ParseFailureError, } from "../../domain/parseFailure.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** The selected artifact and input field owning a reader failure. */ export interface WebArtifactReadContext { @@ -258,7 +259,7 @@ const webArtifactPrimaryError = ( diagnostics: { target_path: context.targetPath, field: context.field.join("."), - error_message: cause instanceof Error ? cause.message : String(cause), + error_message: errorMessage(cause), }, }); }; diff --git a/src/browser/execution/CdpRuntimeRequests.ts b/src/browser/execution/CdpRuntimeRequests.ts index c167526c95..0f7af4c247 100644 --- a/src/browser/execution/CdpRuntimeRequests.ts +++ b/src/browser/execution/CdpRuntimeRequests.ts @@ -11,6 +11,7 @@ import { assertRuntimeRetention, RuntimeRetention, } from "./CdpRuntimeRetention.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; type RuntimeRequestSources = Pick< CdpRuntimeSources, @@ -114,7 +115,7 @@ export class CdpRuntimeRequests { ? cause : new AnalysisOutputError( this.sources.session.operation, - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), ); } } diff --git a/src/browser/execution/CdpRuntimeSession.ts b/src/browser/execution/CdpRuntimeSession.ts index ef8809a494..5302453a51 100644 --- a/src/browser/execution/CdpRuntimeSession.ts +++ b/src/browser/execution/CdpRuntimeSession.ts @@ -42,6 +42,7 @@ import { type CdpTargetSession, } from "../CdpTargetSession.js"; import { CdpTargetDocument } from "../CdpTargetDocument.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** A domain this session can both enable and, on cleanup, disable. */ export type CdpRuntimeDomain = CdpDomainWith<"enable"> & @@ -299,7 +300,7 @@ export class CdpRuntimeSession { ); } catch (cause: unknown) { failures.push( - `${method}: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : cause instanceof Error ? cause.message : String(cause)}`, + `${method}: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : errorMessage(cause)}`, ); } }; @@ -320,7 +321,7 @@ export class CdpRuntimeSession { ); } catch (cause: unknown) { failures.push( - `Target.detachFromTarget: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : cause instanceof Error ? cause.message : String(cause)}`, + `Target.detachFromTarget: ${cause instanceof AnalysisError ? (cause.userMessage ?? cause.message) : errorMessage(cause)}`, ); } } @@ -337,8 +338,7 @@ export class CdpRuntimeSession { "rea-cdp-browser", [this.target.target_id], { - reason: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: this.operation, cause }, ); diff --git a/src/browser/execution/CdpRuntimeSources.ts b/src/browser/execution/CdpRuntimeSources.ts index 98db8f0e6c..277e6961bd 100644 --- a/src/browser/execution/CdpRuntimeSources.ts +++ b/src/browser/execution/CdpRuntimeSources.ts @@ -17,6 +17,7 @@ import { selectCdpScriptFrame, } from "../CdpScriptContextFacts.js"; import { RuntimeRetention } from "./CdpRuntimeRetention.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Source ownership is proven by execution context/frame metadata, independently of URL aliases. */ export class CdpRuntimeSources { @@ -85,7 +86,7 @@ export class CdpRuntimeSources { ? cause : new AnalysisOutputError( this.session.operation, - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), ); } } diff --git a/src/browser/history/CaptureFailures.ts b/src/browser/history/CaptureFailures.ts index 49ba2e5b74..027797f247 100644 --- a/src/browser/history/CaptureFailures.ts +++ b/src/browser/history/CaptureFailures.ts @@ -54,6 +54,7 @@ import { CAPTURE_LIMITS, type CaptureFormatError, } from "./CaptureFormatError.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_web_network_capture"; /** A refused protobuf body decode; a limit names the budget that owns it. */ @@ -316,7 +317,7 @@ export const historicalCaptureFailure = ( ...(descriptorRead ? { source_path: sourcePath, input_path: inputPath } : {}), - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), ...(origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure ? { failure_kind: cause.reason } diff --git a/src/browser/history/HistoricalCaptureDecoder.ts b/src/browser/history/HistoricalCaptureDecoder.ts index 181cc93da8..5ac2159bf3 100644 --- a/src/browser/history/HistoricalCaptureDecoder.ts +++ b/src/browser/history/HistoricalCaptureDecoder.ts @@ -74,6 +74,7 @@ import { redactExplicitFailure } from "../../domain/explicitSensitiveFailure.js" import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { readHistoricalCaptureReply } from "./HistoricalCaptureReply.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_web_network_capture"; @@ -521,10 +522,7 @@ export class HistoricalCaptureDecoder { [cleanupFailure.owner.resource], { capture_path: input.capture_path, - reason: - cleanupFailure.cause instanceof Error - ? cleanupFailure.cause.message - : String(cleanupFailure.cause), + reason: errorMessage(cleanupFailure.cause), }, { operation: OPERATION, diff --git a/src/browser/history/protobuf/ProtobufSchema.ts b/src/browser/history/protobuf/ProtobufSchema.ts index cd22847c97..3bbcf545b3 100644 --- a/src/browser/history/protobuf/ProtobufSchema.ts +++ b/src/browser/history/protobuf/ProtobufSchema.ts @@ -26,6 +26,7 @@ import { type ProtobufBudget, type WireSchema, } from "./ProtobufWire.js"; +import { errorMessage } from "../../../kernel/errorMessage.js"; export type ProtobufSchemaAdmissionFailure = | { @@ -266,7 +267,7 @@ export class ProtobufSchema implements WireSchema { return err({ kind: "malformed-descriptor", field: "descriptor_set_path", - message: `Malformed FileDescriptorSet: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `Malformed FileDescriptorSet: ${errorMessage(cause)}`, }); } const admitted = await admitRegistryDescriptor(descriptor, budget); @@ -280,7 +281,7 @@ export class ProtobufSchema implements WireSchema { return err({ kind: "malformed-descriptor", field: "descriptor_set_path", - message: `Invalid FileDescriptorSet declaration: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `Invalid FileDescriptorSet declaration: ${errorMessage(cause)}`, }); } if (message === undefined) diff --git a/src/browser/modules/NativeModuleResolver.ts b/src/browser/modules/NativeModuleResolver.ts index fcc7bb58b4..7c8fef8501 100644 --- a/src/browser/modules/NativeModuleResolver.ts +++ b/src/browser/modules/NativeModuleResolver.ts @@ -40,6 +40,7 @@ import type { import { webModuleResolutionSchema } from "../../domain/webModuleTrace.js"; import { ProviderStartupDeadline } from "../../process/ProviderDeadline.js"; import { importMapForTrustedResolver } from "./importMapForTrustedResolver.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "trace_web_module_imports"; const TIMEOUT_MS = 20000; @@ -89,7 +90,7 @@ const moduleResolverFailure = ( ...(remediationAction === undefined ? {} : { remediationAction }), diagnostics: { executable, - error_message: cause instanceof Error ? cause.message : String(cause), + error_message: errorMessage(cause), }, }); @@ -532,7 +533,7 @@ const cleanupFailure = ( "native-module-resolver", ["chromium-browser"], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { cause, diff --git a/src/captures/TsharkCaptureProvider.ts b/src/captures/TsharkCaptureProvider.ts index 72692555b3..9c1f3dad6d 100644 --- a/src/captures/TsharkCaptureProvider.ts +++ b/src/captures/TsharkCaptureProvider.ts @@ -95,6 +95,7 @@ import { selectWiresharkTool, } from "../pcap/PcapConfiguration.js"; import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_packet_capture"; @@ -567,7 +568,7 @@ export class TsharkCaptureProvider implements PacketCapturePort { ), observedOutput, unclassified: (cause) => { - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); if (phase === "workspace") return privateWorkspaceFailure( TSHARK_PROVIDER_IDENTITY.id, diff --git a/src/cli/desktopCaptureCommands.ts b/src/cli/desktopCaptureCommands.ts index 7a66a1f275..992d0f7f57 100644 --- a/src/cli/desktopCaptureCommands.ts +++ b/src/cli/desktopCaptureCommands.ts @@ -33,6 +33,7 @@ import { SessionRequestQueue } from "../desktop/DesktopSessionRequests.js"; import { withCommandCancellation } from "./commandCancellation.js"; import type { CliInstance } from "./types.js"; import { writeCliProgressLine } from "./cliProgress.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** One coherent view policy; invalid JSON and unknown controls fail at admission. */ const viewPolicyOption = z @@ -231,8 +232,7 @@ const withStateReaders = async ( ? ArtifactReaderFailure.cleanupObservation(cause, []) : { resources: [], - reason: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; const failure = new ProviderCleanupError( "rea-desktop", diff --git a/src/cli/reverseEngineeringCommands.ts b/src/cli/reverseEngineeringCommands.ts index 25565dfde6..ea8c72ecd4 100644 --- a/src/cli/reverseEngineeringCommands.ts +++ b/src/cli/reverseEngineeringCommands.ts @@ -47,6 +47,7 @@ import { } from "./analysisEvidenceDelivery.js"; import { finishAnalysisCommand } from "./finishAnalysisCommand.js"; import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const executeWithCleanup = async ( service: ReverseEngineeringService, @@ -119,13 +120,9 @@ const closeDebuggerCommandSession = async ( reason: cause instanceof AggregateError ? cause.errors - .map((error: unknown) => - error instanceof Error ? error.message : String(error), - ) + .map((error: unknown) => errorMessage(error)) .join("; ") - : cause instanceof Error - ? cause.message - : String(cause), + : errorMessage(cause), ...retainedDebuggerDiagnostics(cause), }, { diff --git a/src/composition/javascriptAnalysisWorkerProcess.ts b/src/composition/javascriptAnalysisWorkerProcess.ts index b1c399d0ed..40ed28ffb2 100644 --- a/src/composition/javascriptAnalysisWorkerProcess.ts +++ b/src/composition/javascriptAnalysisWorkerProcess.ts @@ -20,6 +20,7 @@ import { serveJavaScriptAnalysisWorker, type JavaScriptSourceWorkerAnalyzer, } from "../javascript/analysis/JavaScriptAnalysisWorkerServer.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const analyze: JavaScriptSourceWorkerAnalyzer = async ( file, @@ -132,8 +133,6 @@ const analyze: JavaScriptSourceWorkerAnalyzer = async ( try { await serveJavaScriptAnalysisWorker(analyze); } catch (cause: unknown) { - process.stderr.write( - `${cause instanceof Error ? cause.message : String(cause)}\n`, - ); + process.stderr.write(`${errorMessage(cause)}\n`); process.exitCode = 1; } diff --git a/src/composition/optionalObservationProviders.ts b/src/composition/optionalObservationProviders.ts index 599af1eb14..1be80ec929 100644 --- a/src/composition/optionalObservationProviders.ts +++ b/src/composition/optionalObservationProviders.ts @@ -16,6 +16,7 @@ import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../inspector/providerIdentity.js import type { V8InspectorAdmission } from "../inspector/V8InspectorProvider.js"; import type { WebBundleAnalysisAdmission } from "../browser/IsolatedWebBundleAnalyzer.js"; import { err, ok, type Result } from "../domain/result.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Precisely typed startup factories for the five existing observation ports. */ export type OptionalObservationFactories = { @@ -80,7 +81,7 @@ const loadPort = async ( } catch (cause: unknown) { return err({ providerId, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); } }; diff --git a/src/composition/webBundleAnalysisWorkerProcess.ts b/src/composition/webBundleAnalysisWorkerProcess.ts index ae0f9b6737..0fcce5af5e 100644 --- a/src/composition/webBundleAnalysisWorkerProcess.ts +++ b/src/composition/webBundleAnalysisWorkerProcess.ts @@ -1,11 +1,10 @@ import { analyzeCapturedWebScript } from "../domain/webBundleAnalyzer.js"; import { serveWebBundleAnalysisWorker } from "../browser/WebBundleAnalysisWorkerServer.js"; +import { errorMessage } from "../kernel/errorMessage.js"; try { await serveWebBundleAnalysisWorker(analyzeCapturedWebScript); } catch (cause: unknown) { - process.stderr.write( - `${cause instanceof Error ? cause.message : String(cause)}\n`, - ); + process.stderr.write(`${errorMessage(cause)}\n`); process.exitCode = 1; } diff --git a/src/contracts/catalog/catalogDiscovery.ts b/src/contracts/catalog/catalogDiscovery.ts index 91f89aa430..7742f82896 100644 --- a/src/contracts/catalog/catalogDiscovery.ts +++ b/src/contracts/catalog/catalogDiscovery.ts @@ -1,6 +1,6 @@ -import { createHash } from "node:crypto"; import { z } from "zod"; import type { createCatalogIdentity } from "./catalogIdentity.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; // Retained views are loaded like producers: their full cross-domain output // contract is unnecessary until a task actually queries retained analysis. @@ -88,8 +88,7 @@ export const DISCOVER_TOOLS = { } as const; export type CatalogIdentity = ReturnType; -const digest = (value: unknown): string => - createHash("sha256").update(JSON.stringify(value)).digest("hex"); +const digest = (value: unknown): string => sha256Hex(JSON.stringify(value)); /** Identity covers the discoverable inventory and policy, not mutable visibility. */ export const progressiveCatalogIdentity = ( diff --git a/src/contracts/catalog/catalogIdentity.ts b/src/contracts/catalog/catalogIdentity.ts index 898b762ebb..680fe9646c 100644 --- a/src/contracts/catalog/catalogIdentity.ts +++ b/src/contracts/catalog/catalogIdentity.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import canonicalize from "canonicalize"; import { contractsForToolFamilies } from "../toolFamilies.js"; @@ -30,6 +28,7 @@ import { type McpOutputSchemaProfile, COMPACT_INPUT_SCHEMA_PRESENTATION, } from "../mcpSchemaPresentation.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** * Digested per-tool projection. Every contract field that changes what a @@ -120,9 +119,6 @@ const canonicalJson = (value: unknown): string => { return encoded; }; -const sha256 = (encoded: string): string => - createHash("sha256").update(encoded).digest("hex"); - /** * Digests of an already presented tool and prompt catalog. Exported so tests * can compare the composed combined document with whole-document @@ -143,9 +139,9 @@ export const digestPresentedCatalogs = ( // prompt texts instead of canonicalizing the whole catalog a second time. const combined = `{"cli":${canonicalJson(CLI_COMMAND_NAMES)},"prompts":${promptCatalog},"tools":${tools}}`; return { - tools_sha256: sha256(tools), - prompts_sha256: sha256(promptCatalog), - combined_sha256: sha256(combined), + tools_sha256: sha256Hex(tools), + prompts_sha256: sha256Hex(promptCatalog), + combined_sha256: sha256Hex(combined), } as const; }; diff --git a/src/contracts/portablePattern.ts b/src/contracts/portablePattern.ts index 372c73173b..2ab43fc0df 100644 --- a/src/contracts/portablePattern.ts +++ b/src/contracts/portablePattern.ts @@ -4,6 +4,7 @@ import { INVALID_BASE64_PADDING_PATTERN, INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN, } from "../domain/stringPatterns.js"; +import { byteToHex } from "../kernel/byteToHex.js"; /** * An advertised `pattern` re-emitted into the portable regex grammar. @@ -44,7 +45,7 @@ const LITERAL_IN_CLASS = new Set("!#%&,:;<=>@`~'\" _.+*?$"); const ESCAPED_IN_CLASS = new Set("^$\\.*+?()[]{}|/-"); const MAX_REPEAT = 1000; -const hex = (code: number) => `\\x${code.toString(16).padStart(2, "0")}`; +const hex = (code: number) => `\\x${byteToHex(code)}`; const emitOutside = (code: number): string => { const character = String.fromCodePoint(code); diff --git a/src/cutter/CutterBridgeService.ts b/src/cutter/CutterBridgeService.ts index 7da70d06b5..30a0915790 100644 --- a/src/cutter/CutterBridgeService.ts +++ b/src/cutter/CutterBridgeService.ts @@ -20,6 +20,7 @@ import { type CutterDiscoveryOptions, } from "./CutterBridgeClient.js"; import { CUTTER_PROVIDER_IDENTITY } from "./CutterProviderIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface CutterBridgePort { listSessions( @@ -129,7 +130,7 @@ export class CutterBridgeService { "cutter", [], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { cause }, ); diff --git a/src/desktop/AgentEnvComputer.ts b/src/desktop/AgentEnvComputer.ts index d1c96ac99b..376a54568b 100644 --- a/src/desktop/AgentEnvComputer.ts +++ b/src/desktop/AgentEnvComputer.ts @@ -23,6 +23,7 @@ import { import { DRAWN_WAIT_MS, drawnScreenshot } from "./DrawnScreenshot.js"; import { awaitHttpReply, type HttpReply } from "./HttpReply.js"; import { redactExplicitText } from "../domain/explicitSensitiveValues.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const READY_TIMEOUT_MS = 180_000; const REQUEST_TIMEOUT_MS = 120_000; @@ -423,7 +424,7 @@ export class AgentEnvComputer { if (signal.aborted) throw signal.reason; if (cause instanceof ComputerStartFailure) throw cause; throw new ComputerStartFailure( - `The computer came up but REA could not use it: ${cause instanceof Error ? cause.message : String(cause)}`, + `The computer came up but REA could not use it: ${errorMessage(cause)}`, undefined, { cause, reason: stage === "readiness" ? "not_ready" : "unusable" }, ); diff --git a/src/desktop/AgentEnvComputerHelper.ts b/src/desktop/AgentEnvComputerHelper.ts index 6a96ea3661..f390e6b612 100644 --- a/src/desktop/AgentEnvComputerHelper.ts +++ b/src/desktop/AgentEnvComputerHelper.ts @@ -22,6 +22,7 @@ import { withArtifactFileHandle, type ArtifactResourceScope, } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const execFileAsync = promisify(execFile); @@ -178,7 +179,7 @@ export const removeSandbox = async ( await execFileAsync(docker, ["rm", "-f", ...containers], options); return undefined; } catch (cause: unknown) { - return `Removing sandbox ${sandbox}'s containers failed: ${cause instanceof Error ? cause.message : String(cause)}. ${manual}`; + return `Removing sandbox ${sandbox}'s containers failed: ${errorMessage(cause)}. ${manual}`; } }; diff --git a/src/desktop/AgentEnvSolveHelper.ts b/src/desktop/AgentEnvSolveHelper.ts index f885d533c0..ee1c104b19 100644 --- a/src/desktop/AgentEnvSolveHelper.ts +++ b/src/desktop/AgentEnvSolveHelper.ts @@ -19,6 +19,7 @@ import { agentEnvInterpreter, removeSandbox, } from "./AgentEnvComputerHelper.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const HELPER = fileURLToPath( new URL("../../bridge/agentenv/solve.py", import.meta.url), @@ -189,7 +190,7 @@ export const runSolveHelper = async (options: { [`sandbox root ${sandboxRoot.path}`], { reason: cleanup.reason, - spawn_error: cause instanceof Error ? cause.message : String(cause), + spawn_error: errorMessage(cause), }, options.operation, ); diff --git a/src/desktop/ApplicationStateDirectories.ts b/src/desktop/ApplicationStateDirectories.ts index 4b628fc054..12927bc735 100644 --- a/src/desktop/ApplicationStateDirectories.ts +++ b/src/desktop/ApplicationStateDirectories.ts @@ -3,6 +3,7 @@ import { basename, join } from "node:path"; import type { DesktopApplicationInventory } from "../domain/desktop/desktopCapture.js"; import { xdgBase } from "./XdgBase.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The environment whose XDG folders, and the home whose dot-folders, may hold the application's state. */ interface StateLocations { @@ -114,8 +115,7 @@ export const stateDirectories = async ( : { path, exists_at_start: null, - existence_error: - cause instanceof Error ? cause.message : String(cause), + existence_error: errorMessage(cause), }; } }), diff --git a/src/desktop/BuildComputerLongRuns.ts b/src/desktop/BuildComputerLongRuns.ts index 594701a943..f2082cb0af 100644 --- a/src/desktop/BuildComputerLongRuns.ts +++ b/src/desktop/BuildComputerLongRuns.ts @@ -18,6 +18,7 @@ import { type Answer, type ControlledComputer, } from "./BuildComputerController.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "export_build_environment"; const POLL_S = 30; @@ -170,8 +171,7 @@ export class BuildComputerLongRuns { : cause instanceof AnalysisError ? cause : new ProviderAdapterError(AGENTENV_PROVIDER, OPERATION, { - userMessage: - cause instanceof Error ? cause.message : String(cause), + userMessage: errorMessage(cause), cause, }); if (signal.aborted && cause instanceof AnalysisError && cause !== primary) @@ -280,7 +280,7 @@ export class BuildComputerLongRuns { } catch (cause: unknown) { return { verified: false, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } } diff --git a/src/desktop/DebianPackageFile.ts b/src/desktop/DebianPackageFile.ts index c7c6c5b7f7..e6fafe21f7 100644 --- a/src/desktop/DebianPackageFile.ts +++ b/src/desktop/DebianPackageFile.ts @@ -27,6 +27,7 @@ import { isRefusedRead, } from "./HostFileRead.js"; import type { QueryRunner } from "./HostQuery.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type PackageFileFacts = Pick< DesktopPackage, @@ -66,7 +67,7 @@ const hashPackageFile = async ( const read = stableFileHashCause(cause); if (!(cause instanceof StableFileHashFailure) || !isRefusedRead(read)) throw cause; - return `${path} could not be read: ${read instanceof Error ? read.message : String(read)}`; + return `${path} could not be read: ${errorMessage(read)}`; } }; diff --git a/src/desktop/DebianPackageInventory.ts b/src/desktop/DebianPackageInventory.ts index b54b988658..5dcea02bd1 100644 --- a/src/desktop/DebianPackageInventory.ts +++ b/src/desktop/DebianPackageInventory.ts @@ -37,6 +37,7 @@ import { installableLibraries, installablePackages, } from "./LibraryPackageInventory.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The host commands and apt folders Debian package identification reads. */ export type DebianPackageHost = AptRepositoryHost; @@ -73,9 +74,7 @@ const bothFailed = (first: unknown, second: unknown): unknown => { const causes = [first, second]; const both = new AggregateError( causes, - causes - .map((cause) => (cause instanceof Error ? cause.message : String(cause))) - .join("; "), + causes.map((cause) => errorMessage(cause)).join("; "), ); const cleanups = causes.flatMap((cause) => cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined diff --git a/src/desktop/DesktopBuildDoctorFacts.ts b/src/desktop/DesktopBuildDoctorFacts.ts index 637dba7db2..b01ba1a0c2 100644 --- a/src/desktop/DesktopBuildDoctorFacts.ts +++ b/src/desktop/DesktopBuildDoctorFacts.ts @@ -38,6 +38,7 @@ import { type BuildComputerSetting, } from "./BuildComputerEnvironment.js"; import { BUILD_COMPUTER_SETTINGS } from "../domain/desktop/buildComputerSettings.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const DEFAULT_DOCKER_ROOT = "/var/lib/docker"; const CONFIG_BYTES = 1024 * 1024; @@ -170,12 +171,7 @@ const attempt = async ( const stderr = failure?.stderr.trim() ?? ""; return { ok: false, - reason: - stderr === "" - ? cause instanceof Error - ? cause.message - : String(cause) - : stderr, + reason: stderr === "" ? errorMessage(cause) : stderr, }; } }; @@ -266,7 +262,7 @@ const freeSpace = async (path: string): Promise => { if (parent === candidate || !missingPath(cause)) return { path, - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), }; candidate = parent; } @@ -303,7 +299,7 @@ const archiveFact = async ( path, source, status: "unknown", - detail: `REA could not inspect ${path}: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `REA could not inspect ${path}: ${errorMessage(cause)}`, }; } if (source === "cache") return { path, source, status: "current" }; diff --git a/src/desktop/DesktopBuildOwnedCommand.ts b/src/desktop/DesktopBuildOwnedCommand.ts index 9117b6ec6e..afb4b75a28 100644 --- a/src/desktop/DesktopBuildOwnedCommand.ts +++ b/src/desktop/DesktopBuildOwnedCommand.ts @@ -22,6 +22,7 @@ import { cancelledBy, carriedReason, } from "../domain/analysisErrorCore.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Run a setup command with ownership of its entire process family and partial output. */ export const runDesktopBuildOwnedCommand = async (input: { @@ -212,6 +213,6 @@ export const desktopBuildOwnedCommandReason = (cause: unknown): string => { ? preparation.capturedOutput?.stderr.trim() : undefined) ?? ""; - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); return stderr === "" ? message : `${message}: ${stderr.slice(-2000)}`; }; diff --git a/src/desktop/DesktopBuildSetupHost.ts b/src/desktop/DesktopBuildSetupHost.ts index e702fb39e4..ba8187ee2a 100644 --- a/src/desktop/DesktopBuildSetupHost.ts +++ b/src/desktop/DesktopBuildSetupHost.ts @@ -34,6 +34,7 @@ import { desktopBuildOwnedCommandReason, runDesktopBuildOwnedCommand, } from "./DesktopBuildOwnedCommand.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const PACK_SCRIPT = fileURLToPath( new URL("../../scripts/pack-build-computer-runtime.mjs", import.meta.url), @@ -65,7 +66,7 @@ const exists = (path: string): Promise => const failureReason = (cause: unknown): string => { const stderr = execFileOutputFailure(cause)?.stderr.trim() ?? ""; - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); return stderr === "" ? message : `${message}: ${stderr.slice(-2000)}`; }; diff --git a/src/desktop/ScreenJudgeProcess.ts b/src/desktop/ScreenJudgeProcess.ts index 6f9f7c84ac..35f5370e68 100644 --- a/src/desktop/ScreenJudgeProcess.ts +++ b/src/desktop/ScreenJudgeProcess.ts @@ -20,6 +20,7 @@ import { agentEnvInterpreter, type ComputerRelease, } from "./AgentEnvComputerHelper.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const JUDGE_TIMEOUT_MS = 10 * 60 * 1000; const answerSchema = z.object({ @@ -176,7 +177,7 @@ export class ScreenJudgeProcess { AGENTENV_PROVIDER, [folder], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), ...(outcome === undefined ? {} : { completed_judge_result: outcome }), }, { @@ -212,7 +213,7 @@ export class ScreenJudgeProcess { : new ProviderAdapterError(AGENTENV_PROVIDER, "check_build_task", { cause, }); - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); const failure = new ProviderCleanupError( AGENTENV_PROVIDER, owner.cleanupResources, @@ -246,7 +247,7 @@ export class ScreenJudgeProcess { await item.lease.release(); this.#retained.delete(item); } catch (cause: unknown) { - failures.push(cause instanceof Error ? cause.message : String(cause)); + failures.push(errorMessage(cause)); resources.push(...(item.lease.cleanupResources ?? [])); } } diff --git a/src/desktop/SolveSandboxRoot.ts b/src/desktop/SolveSandboxRoot.ts index b15cf22c52..37c7bf798e 100644 --- a/src/desktop/SolveSandboxRoot.ts +++ b/src/desktop/SolveSandboxRoot.ts @@ -10,6 +10,7 @@ import { ProviderProcessSupervisor, spawnOwnedProviderProcess, } from "../process/ProviderProcess.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const CLEANUP = fileURLToPath( new URL("../../bridge/agentenv/solve_cleanup.py", import.meta.url), @@ -122,7 +123,7 @@ export class SolveSandboxRoot { } catch (error: unknown) { return { status: "incomplete", - reason: error instanceof Error ? error.message : String(error), + reason: errorMessage(error), }; } } diff --git a/src/domain/analysisSnapshot.ts b/src/domain/analysisSnapshot.ts index 8ebd284754..e0e005ab29 100644 --- a/src/domain/analysisSnapshot.ts +++ b/src/domain/analysisSnapshot.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import canonicalize from "canonicalize"; import { z } from "zod"; @@ -53,6 +51,7 @@ import { relationshipCoverageSchema, type RelationshipCoverage, } from "./relationshipCoverage.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const architectureSchema = z.enum(BINARY_ARCHITECTURES); const formatSchema = z.enum([ @@ -657,9 +656,7 @@ export const analysisQueryId = ( operation: string, parameters: Readonly>, ): string => - `query_${createHash("sha256") - .update(canonicalJson({ target, binding, operation, parameters })) - .digest("hex")}`; + `query_${sha256Hex(canonicalJson({ target, binding, operation, parameters }))}`; /** Create one serializable snapshot entry from a successful provider call. */ export const createAnalysisSnapshotEntry = (input: { diff --git a/src/domain/analysisView/webNetworkCaptureView.ts b/src/domain/analysisView/webNetworkCaptureView.ts index 0ef76625ef..89e653a271 100644 --- a/src/domain/analysisView/webNetworkCaptureView.ts +++ b/src/domain/analysisView/webNetworkCaptureView.ts @@ -3,7 +3,6 @@ import { protobufViewRequestSchema, } from "./protobufCaptureView.js"; import { analysisViewInputError } from "./analysisViewErrors.js"; -import { createHash } from "node:crypto"; import { z } from "zod"; import type { AnalysisError } from "../analysisErrorBase.js"; import { parseAnalysisViewResult } from "./analysisViewParent.js"; @@ -37,6 +36,7 @@ import { projectQlogCapturePage, } from "./qlogCaptureView.js"; import { evidenceFileTarget } from "../evidence.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Offsets page the parent's retained record order, preserving producer ordinals. */ export const captureViewRequestSchema = z.strictObject({ @@ -175,7 +175,7 @@ const describesText = (descriptor: BinaryField, text: string): boolean => { utf8.toString("utf8") === text && descriptor.bytes === utf8.length && descriptor.content_base64 === utf8.toString("base64") && - descriptor.sha256 === createHash("sha256").update(utf8).digest("hex") + descriptor.sha256 === sha256Hex(utf8) ); }; /** diff --git a/src/domain/android/androidJniBindings.ts b/src/domain/android/androidJniBindings.ts index 72dcd55082..f111430aeb 100644 --- a/src/domain/android/androidJniBindings.ts +++ b/src/domain/android/androidJniBindings.ts @@ -1,6 +1,5 @@ import { ARTIFACT_INTEGRITY_CHECKS } from "../artifactOperationError.js"; import { coverageStatusSchema } from "../coverage.js"; -import { createHash } from "node:crypto"; import { z } from "zod"; import { androidManifestSplitsSchema, @@ -16,6 +15,7 @@ import { jsonValueByteLength } from "../jsonValueByteLength.js"; import type { JsonValue } from "../jsonValue.js"; import { err, ok, type Result } from "../result.js"; import { dexDescriptorSchema } from "./dexTypes.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const count = z.int().nonnegative(); const digest = z.string().regex(/^[a-f0-9]{64}$/u); @@ -173,7 +173,7 @@ export const androidJniReportSchema = z.strictObject({ export type AndroidJniReport = z.infer; export const ANDROID_JNI_REPORT_BYTES = 16 * 1024 * 1024; const id = (kind: string, parts: readonly unknown[]): string => - `${kind}_${createHash("sha256").update(JSON.stringify(parts)).digest("hex")}`; + `${kind}_${sha256Hex(JSON.stringify(parts))}`; /** JNI escaping is over UTF-16 code units; it can fail for non-Java-source names. */ export const expectedJniNames = ( diff --git a/src/domain/android/androidJniLibrary.ts b/src/domain/android/androidJniLibrary.ts index 4474613a3e..619569c0e3 100644 --- a/src/domain/android/androidJniLibrary.ts +++ b/src/domain/android/androidJniLibrary.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { setImmediate as immediate } from "node:timers/promises"; import { err, ok, type Result } from "../result.js"; import { dexDescriptorSchema } from "./dexTypes.js"; @@ -23,6 +22,7 @@ import { ElfPointerRelocationFailure, type ElfPointerOverlay, } from "../native/elfPointerRelocations.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const MAXIMUM_STRING_BYTES = 65_535; const MAXIMUM_STRING_WORK = 64 * 1024 * 1024; @@ -128,7 +128,7 @@ export const inspectAndroidJniLibrary = async ( }; const exportSteps = parseNativeExportsSteps(bytes, { path: "[admitted immutable ELF bytes]", - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), bytes: bytes.length, }); let exportStep = exportSteps.next(); diff --git a/src/domain/apple/appleMachoFixups.ts b/src/domain/apple/appleMachoFixups.ts index 9592bf9397..a5ba75338e 100644 --- a/src/domain/apple/appleMachoFixups.ts +++ b/src/domain/apple/appleMachoFixups.ts @@ -9,6 +9,7 @@ import { readLeb128, type Leb128Read } from "../leb128.js"; import { issue } from "./appleDispatchDecodeFacts.js"; import type { DecodeIssue } from "./appleDispatchDecodeFacts.js"; import { decodeMachoName, type MachoName } from "./appleMachoNames.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Where a Mach-O stores pointer fixups, from its load commands. */ export interface FixupCommands { @@ -425,7 +426,7 @@ const readChainedPage = ( } catch (cause: unknown) { // A decode failure stays with this record; a host limit is not one. if (isHostLimitFailure(cause)) throw cause; - failure = cause instanceof Error ? cause.message : String(cause); + failure = errorMessage(cause); } return { locations, lastOffset, failure }; }; @@ -880,7 +881,7 @@ const chainedFixups = ( } catch (cause: unknown) { // A decode failure stays with this record; a host limit is not one. if (isHostLimitFailure(cause)) throw cause; - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); recordPointerFailure(reason, address, chainIndex); return { kind: "unsupported", reason }; } @@ -1168,9 +1169,7 @@ function* parseLegacyRebasesSteps( } catch (cause: unknown) { // A decode failure stays with this record; a host limit is not one. if (isHostLimitFailure(cause)) throw cause; - failures.push( - `rebase opcodes: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`rebase opcodes: ${errorMessage(cause)}`); unreadBytes += stream.size; } } @@ -1347,7 +1346,7 @@ function* readBindStreamSteps( if (isHostLimitFailure(cause)) throw cause; binding = { kind: "unsupported", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } const previous = binds.at(-1); @@ -1525,9 +1524,7 @@ function* parseLegacyBindsSteps( } catch (cause: unknown) { // A decode failure stays with this record; a host limit is not one. if (isHostLimitFailure(cause)) throw cause; - failures.push( - `${stream.stream} bind opcodes: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`${stream.stream} bind opcodes: ${errorMessage(cause)}`); } } const complete = failures.length === 0; diff --git a/src/domain/apple/machoSliceSelection.ts b/src/domain/apple/machoSliceSelection.ts index 193ef12a88..f79b07ce51 100644 --- a/src/domain/apple/machoSliceSelection.ts +++ b/src/domain/apple/machoSliceSelection.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { readUniversalMachoImage, readUniversalMachoSlice, @@ -18,6 +16,7 @@ import { import { AnalysisInputError } from "../analysisErrorCore.js"; import { err, ok, type Result } from "../result.js"; import { MACHO_ARCHITECTURE_POLICIES } from "./machoArchitectureSelection.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const cpuName = (cpuType: number, cpuSubtype: number): string => { const name = Object.entries(MACHO_CPU_TYPES).find( @@ -249,9 +248,7 @@ const selectedFatImage = ( byte_length: slice.size, cpu_type: slice.cpuType, cpu_subtype: slice.cpuSubtype, - container_table_sha256: createHash("sha256") - .update(bytes.subarray(0, fat.tableEnd)) - .digest("hex"), + container_table_sha256: sha256Hex(bytes.subarray(0, fat.tableEnd)), }, limitations, }); diff --git a/src/domain/browserNetworkEvidence.ts b/src/domain/browserNetworkEvidence.ts index 359847ea8b..9e330409c0 100644 --- a/src/domain/browserNetworkEvidence.ts +++ b/src/domain/browserNetworkEvidence.ts @@ -1,5 +1,5 @@ -import { createHash } from "node:crypto"; import { z } from "zod"; +import { sha256Hex } from "../kernel/sha256Hex.js"; export const PLAYWRIGHT_RESPONSE_BODY_PROVENANCE_LIMITATION = "Captured response-body bytes are the result of Playwright's Response.body() API. Playwright may satisfy that API with a credentialed follow-up load of the request URL when CDP has no body, so transaction and event links do not verify that retained bytes came from the original network transaction."; @@ -90,7 +90,7 @@ export const browserNetworkBodySchema = z.union([ path: ["bytes"], message: "Network body byte count disagrees with retained bytes", }); - if (createHash("sha256").update(bytes).digest("hex") !== artifact.sha256) + if (sha256Hex(bytes) !== artifact.sha256) context.addIssue({ code: "custom", path: ["sha256"], diff --git a/src/domain/browserObservationError.ts b/src/domain/browserObservationError.ts index 720a84a5b8..d83a411a85 100644 --- a/src/domain/browserObservationError.ts +++ b/src/domain/browserObservationError.ts @@ -8,6 +8,7 @@ import { type AnalysisErrorOptions, } from "./analysisErrorBase.js"; import { AnalysisCancelledError } from "./analysisErrorCore.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Describe browser cleanup failure without discarding its resource evidence. */ export const browserCleanupObservation = ( @@ -16,7 +17,7 @@ export const browserCleanupObservation = ( cause instanceof AnalysisError && cause.cleanup !== undefined ? cause.cleanup : { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: cause instanceof AnalysisError && cause.cleanupResources.length > 0 ? cause.cleanupResources diff --git a/src/domain/browserScenarioCaptureValues.ts b/src/domain/browserScenarioCaptureValues.ts index 89ce6c4bee..455171b361 100644 --- a/src/domain/browserScenarioCaptureValues.ts +++ b/src/domain/browserScenarioCaptureValues.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import { utcDateTimeSchema } from "./offsetDateTime.js"; @@ -11,6 +9,7 @@ import { import { sanitizedBrowserUrlSchema } from "./browserObservation.js"; import { webScreenshotArtifactSchema } from "./webScreenshot.js"; import { digestSchema } from "./../domain/digests.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const textArtifactSchema = z .strictObject({ @@ -20,7 +19,7 @@ const textArtifactSchema = z }) .superRefine((artifact, context) => { const bytes = Buffer.from(artifact.text); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); if (bytes.byteLength !== artifact.bytes || sha256 !== artifact.sha256) context.addIssue({ code: "custom", diff --git a/src/domain/bundleComparison.ts b/src/domain/bundleComparison.ts index aa38c2a50b..66963e1c1e 100644 --- a/src/domain/bundleComparison.ts +++ b/src/domain/bundleComparison.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import { @@ -13,6 +11,7 @@ import type { ResidualUnknown } from "./residualUnknown.js"; import { digestSchema, prefixedDigestSchema } from "./../domain/digests.js"; import { comparisonStatusSchema } from "./comparisonStatus.js"; import { localPathStringSchema } from "./localPath.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const evidenceIdSchema = prefixedDigestSchema("ev"); const classificationSchema = z.enum([ @@ -305,7 +304,7 @@ const historyEvidenceIds = (history: readonly ResidualUnknown[]): string[] => [...new Set(history.flatMap(referencedEvidenceIds))].sort(ascii); const bundleDigest = (bundle: EvidenceBundle): string => - createHash("sha256").update(serializeEvidenceBundle(bundle)).digest("hex"); + sha256Hex(serializeEvidenceBundle(bundle)); const same = (left: readonly string[], right: readonly string[]): boolean => left.length === right.length && diff --git a/src/domain/desktop/appBuild.ts b/src/domain/desktop/appBuild.ts index ff0d73951d..04839a142a 100644 --- a/src/domain/desktop/appBuild.ts +++ b/src/domain/desktop/appBuild.ts @@ -3,7 +3,6 @@ import { BUNDLE_SETTING_VARIABLE, } from "./buildComputerSettings.js"; import { buildSecretHandleSchema } from "./buildSecrets.js"; -import { createHash } from "node:crypto"; import { z } from "zod"; @@ -35,6 +34,7 @@ import { import { INSTALL_SCRIPT, type ExportPackageFile } from "./appExportInstall.js"; import { isArmoredKey } from "./aptRepositories.js"; import { DEBIAN_PACKAGE_NAME } from "./debianPackageFile.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** The Node.js release the build layer runs REA with: the one REA pins. */ export const BUILD_NODE_VERSION = "24.22.1"; @@ -272,7 +272,7 @@ const buildInstall = ( suite: install.suite, components: install.components, keyFile: `apt-keys/${name}.${isArmoredKey(aptKey) ? "asc" : "gpg"}`, - keySha256: createHash("sha256").update(aptKey).digest("hex"), + keySha256: sha256Hex(aptKey), }, } : undefined; diff --git a/src/domain/desktop/appSettle.ts b/src/domain/desktop/appSettle.ts index 2d5b0616f1..4acd70dcde 100644 --- a/src/domain/desktop/appSettle.ts +++ b/src/domain/desktop/appSettle.ts @@ -1,4 +1,4 @@ -import { createHash } from "node:crypto"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** How an app's data/get is read until its files settle; the exported verifier renders the same values. */ export interface SettleTiming { @@ -51,9 +51,7 @@ export const appFileDigests = (parts: readonly unknown[]): string => return [ [ textField(metadata?.[DATA_OBJECTS], "path") ?? `#${String(index)}`, - createHash("sha256") - .update(content ?? "") - .digest("hex"), + sha256Hex(content ?? ""), ], ]; }) diff --git a/src/domain/desktop/appWithheld.ts b/src/domain/desktop/appWithheld.ts index 751c823bf5..3b57abab3d 100644 --- a/src/domain/desktop/appWithheld.ts +++ b/src/domain/desktop/appWithheld.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { posix } from "node:path"; import { z } from "zod"; @@ -7,6 +6,7 @@ import { err, ok, type Result } from "../result.js"; import type { DesktopCheckpoint } from "./desktopCapture.js"; import { isWithinAny } from "./desktopStateDiff.js"; import { BUILD_COMPUTER_SETTINGS } from "./buildComputerSettings.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** The checkpoints a build marks around a sign-in or a licence's activation; what changes between them is withheld. */ export const SIGN_IN_START = "pre-sign-in"; @@ -206,11 +206,7 @@ export const withheldSettings = ( const taken = new Set(BUILD_COMPUTER_SETTINGS); const settings = new Set(); return files.map((file) => { - const hash = createHash("sha256") - .update(file) - .digest("hex") - .slice(0, 8) - .toUpperCase(); + const hash = sha256Hex(file).slice(0, 8).toUpperCase(); const plain = `${prefix}${upper(file) || "FILE"}`; const variable = plain.length <= MAX_VARIABLE && !taken.has(plain) diff --git a/src/domain/desktop/aptRepositories.ts b/src/domain/desktop/aptRepositories.ts index 3f9ec94acc..1a2315713c 100644 --- a/src/domain/desktop/aptRepositories.ts +++ b/src/domain/desktop/aptRepositories.ts @@ -1,4 +1,5 @@ import type { AptRepository } from "./desktopCapture.js"; +import { byteToHex } from "../../kernel/byteToHex.js"; /** * One `deb` line, or one deb822 stanza, of an apt sources file. A stanza's @@ -366,7 +367,7 @@ export const aptListFileName = (uri: string): string => { quoted += QUOTED.has(character) || code <= 0x20 || code >= 0x7f ? [...Buffer.from(character, "utf8")] - .map((byte) => `%${byte.toString(16).padStart(2, "0")}`) + .map((byte) => `%${byteToHex(byte)}`) .join("") : character; } diff --git a/src/domain/desktop/zipView.ts b/src/domain/desktop/zipView.ts index 5880896f01..dd2a827813 100644 --- a/src/domain/desktop/zipView.ts +++ b/src/domain/desktop/zipView.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import type { JsonValue } from "../jsonValue.js"; import { err, ok, type Result } from "../result.js"; import { @@ -15,6 +13,7 @@ import { type DesktopViewPolicy, } from "./desktopViewPolicy.js"; import { isRecord } from "../isRecord.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Why an archive has no view; the exported reader words it the same. */ export const UNREADABLE_ZIP = "not a readable zip archive"; @@ -95,7 +94,7 @@ export const zipEntry = ( return { name: header.name, size: header.size, - sha256: createHash("sha256").update(bytes).digest("hex"), + sha256: sha256Hex(bytes), format, view: read.ok ? read.value : null, view_error: read.ok ? null : read.error, diff --git a/src/domain/firmware/espImageFacts.ts b/src/domain/firmware/espImageFacts.ts index 96ee56e8a5..ca9d95eadf 100644 --- a/src/domain/firmware/espImageFacts.ts +++ b/src/domain/firmware/espImageFacts.ts @@ -26,6 +26,7 @@ import { u32, type EspSignedContentDigests, } from "./espImageStructures.js"; +import { byteToHex } from "../../kernel/byteToHex.js"; const SIGNATURE_SLOTS = 3; @@ -89,8 +90,7 @@ export interface EspImageObservations { type ByteRange = EspImageMetadata["undescribed_trailing"][number]; -const hexByte = (value: number): string => - `0x${value.toString(16).padStart(2, "0")}`; +const hexByte = (value: number): string => `0x${byteToHex(value)}`; /** * How each ESP image fact REA could not establish is reported. Decoding, diff --git a/src/domain/firmware/espImageStructures.ts b/src/domain/firmware/espImageStructures.ts index b04d79d7aa..a3915487bf 100644 --- a/src/domain/firmware/espImageStructures.ts +++ b/src/domain/firmware/espImageStructures.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { crc32 } from "node:zlib"; import type { @@ -6,6 +5,7 @@ import type { EspImageSignatureBlockMetadata, } from "../artifactFormatMetadata.js"; import { strictUtf8Decoder } from "../strictUtf8.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /* * Fixed-layout structures inside an ESP image, from ESP-IDF v6.1 @@ -234,9 +234,9 @@ export const decodeEspSignatureBlock = ( image_digest: imageDigest, image_digest_matches: expected === undefined ? null : expected === imageDigest, - public_key_sha256: createHash("sha256") - .update(block.subarray(layout.keyStart, layout.keyEnd)) - .digest("hex"), + public_key_sha256: sha256Hex( + block.subarray(layout.keyStart, layout.keyEnd), + ), signature_status: "unverified", }; }; diff --git a/src/domain/firmware/uf2.ts b/src/domain/firmware/uf2.ts index a40fccbe5d..ed4ef6e996 100644 --- a/src/domain/firmware/uf2.ts +++ b/src/domain/firmware/uf2.ts @@ -4,6 +4,7 @@ import { err, ok, type Result } from "../result.js"; import { mergeArenaRuns, type RunConflict } from "./addressRuns.js"; import type { RegionDecodeFailure, RegionDecoder } from "./regionDecoder.js"; import { UF2_FAMILY_REGISTRY, uf2FamilyName } from "./uf2Families.js"; +import { byteToHex } from "../../kernel/byteToHex.js"; /** Every UF2 block is 512 bytes: a 32-byte header, 476 data bytes, an end magic. */ export const UF2_BLOCK_BYTES = 512; @@ -476,5 +477,5 @@ const conflict = ({ incoming, }: RunConflict): RegionDecodeFailure => ({ kind: "format", - message: `${familyText(run.familyId)} address ${hex32(address)} is written with different values by ${blockSpan(writer)} (0x${existing.toString(16).padStart(2, "0")}) and ${blockSpan(run)} (0x${incoming.toString(16).padStart(2, "0")})`, + message: `${familyText(run.familyId)} address ${hex32(address)} is written with different values by ${blockSpan(writer)} (0x${byteToHex(existing)}) and ${blockSpan(run)} (0x${byteToHex(incoming)})`, }); diff --git a/src/domain/gpu/gpuCodeObjects.ts b/src/domain/gpu/gpuCodeObjects.ts index 0555e50365..42a1fc4026 100644 --- a/src/domain/gpu/gpuCodeObjects.ts +++ b/src/domain/gpu/gpuCodeObjects.ts @@ -1,11 +1,11 @@ import { z } from "zod"; -import { createHash } from "node:crypto"; import { digestSchema } from "../digests.js"; import { knownCoverageStatusSchema } from "../coverage.js"; import { absoluteLocalPathStringSchema, localPathStringSchema, } from "../localPath.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); /** * GPU inventories report known coverage: discovery, note and payload @@ -153,10 +153,7 @@ export const gpuPtxArtifactSchema = z path: ["byte_length"], message: "PTX text and its UTF-8 source extent disagree", }); - if ( - createHash("sha256").update(artifact.text, "utf8").digest("hex") !== - artifact.sha256 - ) + if (sha256Hex(artifact.text) !== artifact.sha256) context.addIssue({ code: "custom", path: ["sha256"], diff --git a/src/domain/javascript/javascriptAstFingerprint.ts b/src/domain/javascript/javascriptAstFingerprint.ts index b664fefd4b..96b2fd0739 100644 --- a/src/domain/javascript/javascriptAstFingerprint.ts +++ b/src/domain/javascript/javascriptAstFingerprint.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import * as t from "@babel/types"; import { semanticBindingAtRead } from "./javascriptSemanticMutationInitializers.js"; @@ -18,6 +16,7 @@ import { resolveSemanticBindingState, type JavaScriptBindingIndex, } from "./javascriptSemanticState.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Static CommonJS export names. */ export interface StaticExports { @@ -35,7 +34,7 @@ export const fingerprintJavaScriptAst = (node: t.Node): string => { return undefined; }, }); - return createHash("sha256").update(JSON.stringify(tokens)).digest("hex"); + return sha256Hex(JSON.stringify(tokens)); }; /** Collect statically declared CommonJS/bundler export names from one factory. */ diff --git a/src/domain/javascript/javascriptSemanticFingerprints.ts b/src/domain/javascript/javascriptSemanticFingerprints.ts index f836094e00..6fbcae0138 100644 --- a/src/domain/javascript/javascriptSemanticFingerprints.ts +++ b/src/domain/javascript/javascriptSemanticFingerprints.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import * as t from "@babel/types"; import { runtimeFunctionParameters } from "./javascriptAstValues.js"; @@ -19,6 +17,7 @@ import type { import { semanticCallableIdForNode } from "./javascriptSemanticProjection.js"; import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js"; import { traverseJavaScriptAstSteps } from "./javascriptSemanticTraversal.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; interface SemanticFingerprintCollectionInput { readonly state: JavaScriptSemanticAnalysisState; @@ -311,4 +310,4 @@ const isAsyncCallable = (node: t.Node): boolean => t.isFunction(node) && node.async; const digest = (value: readonly string[]): string => - createHash("sha256").update(JSON.stringify(value)).digest("hex"); + sha256Hex(JSON.stringify(value)); diff --git a/src/domain/javascript/javascriptStaticAnalysisBundler.ts b/src/domain/javascript/javascriptStaticAnalysisBundler.ts index 8c207d5e24..7785fbdc43 100644 --- a/src/domain/javascript/javascriptStaticAnalysisBundler.ts +++ b/src/domain/javascript/javascriptStaticAnalysisBundler.ts @@ -25,7 +25,6 @@ import { modulePropertyName, range, registrationKey, - sha256Text, sourceSlice, staticArrayValues, } from "./javascriptStaticAnalysisHelpers.js"; @@ -35,6 +34,7 @@ import type { JavaScriptBundlerRegistration, } from "./javascriptStaticAnalysisTypes.js"; import { JAVASCRIPT_AST_FINGERPRINT_ALGORITHM } from "./javascriptStaticAnalysisTypes.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Inspect a bundler registration call and recover its module table. */ export const inspectBundlerRegistration = ( @@ -295,7 +295,7 @@ const recoverBundlerModule = ( module: { module_key: key, factory_require_name: requireName, - source_sha256: sha256Text(sourceSlice(source, factory)), + source_sha256: sha256Hex(sourceSlice(source, factory)), structural_fingerprint_sha256: fingerprint, structural_fingerprint_algorithm: JAVASCRIPT_AST_FINGERPRINT_ALGORITHM, exports, diff --git a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts index 49bd4961f0..1682cac794 100644 --- a/src/domain/javascript/javascriptStaticAnalysisHelpers.ts +++ b/src/domain/javascript/javascriptStaticAnalysisHelpers.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { posix } from "node:path"; import { fileURLToPath } from "node:url"; @@ -846,10 +845,6 @@ export const registrationKey = ( ]), ]); -/** Hash exact UTF-8 source text. */ -export const sha256Text = (value: string): string => - createHash("sha256").update(value).digest("hex"); - /** Recognized route-construction call suffixes. */ export const STATIC_ROUTE_CALL_NAMES = [ "route", diff --git a/src/domain/managed/managedMemberInspectorCore.ts b/src/domain/managed/managedMemberInspectorCore.ts index 0a63cdbc2e..574e778999 100644 --- a/src/domain/managed/managedMemberInspectorCore.ts +++ b/src/domain/managed/managedMemberInspectorCore.ts @@ -33,7 +33,6 @@ import { type MetadataTokenFact, metadataToken, readMetadataString, - sha256Bytes, } from "./managedMetadataHeaps.js"; import { memberListTable } from "./managedMemberPointers.js"; import type { @@ -41,6 +40,7 @@ import type { TypeMemberListFacts, } from "./managedTypeMemberLists.js"; import type { TypeDefinitionRowFacts } from "./managedTypeDefinitionRows.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; export type ManagedType = ManagedMemberInspection["types"][number]; /** A renderable TypeDef projection paired with its original source row. */ @@ -862,7 +862,7 @@ export const readLocalSignatureFacts = ( if (cursor !== blob.length) malformedSignature("Trailing LocalVarSig data", cursor); return ok({ - raw_sha256: sha256Bytes(blob), + raw_sha256: sha256Hex(blob), has_context_dependent_types: contextDependent, }); } catch (cause: unknown) { @@ -1177,7 +1177,7 @@ const projectSignature = ( ): ManagedSignature => { return { raw_length: blob.length, - raw_sha256: rawSha256 ?? sha256Bytes(blob), + raw_sha256: rawSha256 ?? sha256Hex(blob), resolved_sha256: decoded.kind === "unknown" || decoded.parse_status === "malformed" ? null diff --git a/src/domain/managed/managedMetadataHeaps.ts b/src/domain/managed/managedMetadataHeaps.ts index 11aa6f1ca0..53f48017c1 100644 --- a/src/domain/managed/managedMetadataHeaps.ts +++ b/src/domain/managed/managedMetadataHeaps.ts @@ -1,6 +1,5 @@ import { decodeStrictUtf8 } from "../strictUtf8.js"; import type { ManagedParseIssue } from "./managedArtifact.js"; -import { createHash } from "node:crypto"; import { err, ok, type Result } from "../result.js"; import { managedDecodeBudget } from "./managedDecodeBudget.js"; @@ -390,10 +389,6 @@ export const metadataTokenFact = (raw: number): MetadataTokenFact => { return { raw, table, row, token: metadataToken(table, row) }; }; -/** Hash bytes without exposing their contents. */ -export const sha256Bytes = (bytes: Buffer): string => - createHash("sha256").update(bytes).digest("hex"); - /** Create a cursor bounded to one admitted metadata table row. */ export const metadataRowCursor = ( bytes: Buffer, diff --git a/src/domain/managed/managedReconstruction.ts b/src/domain/managed/managedReconstruction.ts index cb7cb2b951..efdce128ae 100644 --- a/src/domain/managed/managedReconstruction.ts +++ b/src/domain/managed/managedReconstruction.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import { evidenceSchema, type Evidence } from "../evidence.js"; @@ -19,6 +17,7 @@ import { AnalysisInputError } from "../analysisErrorCore.js"; import { EvidenceIntegrityError } from "../evidenceErrors.js"; import { err, ok, type Result } from "../result.js"; import { nonEmptyTextSchema } from "../textSchemas.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const evidenceIdSchema = prefixedDigestSchema("ev"); @@ -139,9 +138,6 @@ type ImportedMethod = ManagedReconstructionImportResult["methods"][number]; type StaticObservation = ManagedReconstructionImportResult["static_observation"]; -const sha256Text = (value: string): string => - createHash("sha256").update(value).digest("hex"); - const countLines = (text: string): number => text.length === 0 ? 0 : text.split(/\r\n|\r|\n/u).length; @@ -290,7 +286,7 @@ export const resolveManagedReconstructionImport = ( ]), ); } - const textSha256 = sha256Text(candidate.reconstruction.text); + const textSha256 = sha256Hex(candidate.reconstruction.text); if ( candidate.reconstruction.text_sha256 !== undefined && candidate.reconstruction.text_sha256 !== textSha256 diff --git a/src/domain/native/nativeAotPe.ts b/src/domain/native/nativeAotPe.ts index 27c3f2715a..94a51379bb 100644 --- a/src/domain/native/nativeAotPe.ts +++ b/src/domain/native/nativeAotPe.ts @@ -1,6 +1,5 @@ import { Budget } from "../budget.js"; import { observeMzWindowsHeader } from "../dosMz.js"; -import { createHash } from "node:crypto"; import { readPeOptionalHeaderFixedFields } from "../peOptionalHeader.js"; import { readPeCoffHeader } from "../peCoffHeader.js"; import { readPeSectionHeader } from "../peSectionHeader.js"; @@ -20,6 +19,7 @@ import { type NativeAotReason, type NativeAotTruncationReason, } from "./nativeAotReason.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const RTR_SIGNATURE = 0x00525452; const RTR_ROW_SIZE = 24; @@ -1290,7 +1290,7 @@ const hydrate = ( throw cause; } const hydrated = output.subarray(0, outputLength); - const sha256 = createHash("sha256").update(hydrated).digest("hex"); + const sha256 = sha256Hex(hydrated); image.addOverlay({ base, sizeBytes: outputLength, sha256, bytes: hydrated }); return { base, sizeBytes: outputLength, sha256 }; }; @@ -1484,7 +1484,7 @@ export const parseNativeAotPe = ( ), maximumSummaryBytes, ); - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); if (sha256 !== expectedSha256) throw new NativeAotSnapshotIdentityError(expectedSha256, sha256); let image: PeImage; @@ -2061,7 +2061,7 @@ export const parseNativeAotPe = ( if (raw !== null) { metadata.derived_memory = { ...descriptor, - sha256: createHash("sha256").update(raw).digest("hex"), + sha256: sha256Hex(raw), }; remaining -= descriptorBytes; } diff --git a/src/domain/native/nativeUiObservation.ts b/src/domain/native/nativeUiObservation.ts index 78c22e2522..5d3446ae4f 100644 --- a/src/domain/native/nativeUiObservation.ts +++ b/src/domain/native/nativeUiObservation.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import { @@ -9,6 +7,7 @@ import { import { decodeCanonicalBase64 } from "../webScreenshot.js"; import { readPngHeaderDimensions } from "../pngHeader.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const scope = { pid: z.int().positive(), @@ -103,7 +102,7 @@ const nativeUiScreenshotSchema = z }); return; } - if (createHash("sha256").update(bytes).digest("hex") !== screenshot.sha256) + if (sha256Hex(bytes) !== screenshot.sha256) context.addIssue({ code: "custom", message: "PNG screenshot digest mismatch", diff --git a/src/domain/process/processScenario.ts b/src/domain/process/processScenario.ts index f1ee910fcc..ec46993504 100644 --- a/src/domain/process/processScenario.ts +++ b/src/domain/process/processScenario.ts @@ -1,7 +1,7 @@ -import { createHash } from "node:crypto"; import canonicalize from "canonicalize"; import { z } from "zod"; import { jsonRecordSchema } from "../jsonRecord.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; const positiveBudget = z.int().safe().positive(); /** Read the explicitly committed output budget without applying scenario defaults. */ @@ -92,7 +92,7 @@ export const digestProcessCommitment = (value: unknown): string => { const serialized = canonicalize(value); if (serialized === undefined) throw new TypeError("Process capture commitment is not canonical JSON"); - return createHash("sha256").update(serialized).digest("hex"); + return sha256Hex(serialized); }; /** Explicit private-input facts contain no textual marker that can collide with a value. */ diff --git a/src/domain/safeJson.ts b/src/domain/safeJson.ts index 097150ed19..9f38b5c6ed 100644 --- a/src/domain/safeJson.ts +++ b/src/domain/safeJson.ts @@ -1,4 +1,5 @@ import { strictUtf8Decoder } from "./strictUtf8.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** JSON parsing without throws at an input boundary. */ export type SafeJsonParseResult = | { readonly ok: true; readonly value: unknown } @@ -12,7 +13,7 @@ export const safeParseUtf8Json = (bytes: Uint8Array): SafeJsonParseResult => { } catch (cause: unknown) { return { ok: false, - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), cause, }; } @@ -33,7 +34,7 @@ export const safeParseJson = ( } catch (cause: unknown) { return { ok: false, - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), cause, }; } diff --git a/src/domain/targetIdentity.ts b/src/domain/targetIdentity.ts index 8969a94146..ab8e0dc665 100644 --- a/src/domain/targetIdentity.ts +++ b/src/domain/targetIdentity.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import canonicalize from "canonicalize"; import { z } from "zod"; @@ -9,6 +7,7 @@ import type { } from "./binaryTargetTypes.js"; import { digestSchema } from "./digests.js"; import { rawBinaryEntryPointSchema } from "./rawBinary.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const flashOffsetSchema = z.number().int().min(0).max(0xffff_ffff).nullable(); const fatCpuSchema = z.number().int().min(0).max(0xffff_ffff).nullable(); @@ -205,7 +204,7 @@ export const targetIdentityKey = (identity: TargetIdentity): string => { const encoded = canonicalize(identity); if (encoded === undefined) throw new TypeError("RFC 8785 canonicalization rejected a target identity"); - return `target_${createHash("sha256").update(encoded).digest("hex")}`; + return `target_${sha256Hex(encoded)}`; }; /** Whether two identities name the same target. */ diff --git a/src/domain/validationFailure.ts b/src/domain/validationFailure.ts index 74eff909b5..bf1eb9ef8f 100644 --- a/src/domain/validationFailure.ts +++ b/src/domain/validationFailure.ts @@ -1,4 +1,5 @@ import { z } from "zod"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * What `describeValidationFailure` states in prose, as facts a caller can act @@ -33,8 +34,7 @@ export const firstValidationIssue = ( /** Locate the first schema issue, or keep a thrown constraint message. */ export const describeValidationFailure = (cause: unknown): string => { - if (!(cause instanceof z.ZodError)) - return cause instanceof Error ? cause.message : String(cause); + if (!(cause instanceof z.ZodError)) return errorMessage(cause); const [first, ...rest] = cause.issues; const location = first === undefined || first.path.length === 0 diff --git a/src/domain/wasm/wasmArtifact.ts b/src/domain/wasm/wasmArtifact.ts index 14269153f2..7a93001f5e 100644 --- a/src/domain/wasm/wasmArtifact.ts +++ b/src/domain/wasm/wasmArtifact.ts @@ -5,10 +5,10 @@ import { } from "./wasmInterface.js"; import { z } from "zod"; import { knownCoverageStatusSchema } from "../coverage.js"; -import { createHash } from "node:crypto"; import { constants as bufferConstants } from "node:buffer"; import { absoluteLocalPathStringSchema } from "../localPath.js"; +import { sha256Hex } from "../../kernel/sha256Hex.js"; /** Exact upstream release whose tool profile REA verified. */ export const WABT_VERSION = "1.0.42"; const WABT_MINIMUM_PATCH = Number(WABT_VERSION.split(".")[2]); @@ -199,10 +199,7 @@ export const wasmArtifactSchema = z limitations: z.array(z.string()), }) .superRefine((value, context) => { - if ( - createHash("sha256").update(value.wat.text, "utf8").digest("hex") !== - value.wat.sha256 - ) + if (sha256Hex(value.wat.text) !== value.wat.sha256) context.addIssue({ code: "custom", path: ["wat", "sha256"], diff --git a/src/domain/webContentArtifact.ts b/src/domain/webContentArtifact.ts index 5432f0e58d..b01281b0a7 100644 --- a/src/domain/webContentArtifact.ts +++ b/src/domain/webContentArtifact.ts @@ -1,10 +1,9 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Exact facts of the UTF-8 encoding and UTF-16 storage of retained text. */ export const webTextFacts = (text: string) => ({ - sha256: createHash("sha256").update(text).digest("hex"), + sha256: sha256Hex(text), utf8Bytes: Buffer.byteLength(text), utf16Units: text.length, }); diff --git a/src/domain/webScreenshot.ts b/src/domain/webScreenshot.ts index 8147cd2536..ffe470d925 100644 --- a/src/domain/webScreenshot.ts +++ b/src/domain/webScreenshot.ts @@ -1,5 +1,3 @@ -import { createHash } from "node:crypto"; - import { z } from "zod"; import { utcDateTimeSchema } from "./offsetDateTime.js"; @@ -13,6 +11,7 @@ import { browserObservationEndpointSchema, } from "./browserObservation.js"; import { browserVersionSchema } from "./browserObservationSchemas.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Self-verifying inline PNG artifact for CLI/MCP parity. */ export const webScreenshotArtifactSchema = z @@ -28,7 +27,7 @@ export const webScreenshotArtifactSchema = z context.addIssue({ code: "custom", message: "Invalid canonical base64" }); return; } - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); if (bytes.byteLength !== artifact.bytes || sha256 !== artifact.sha256) context.addIssue({ code: "custom", @@ -148,7 +147,7 @@ export type WebScreenshotDiff = z.infer; export const createWebScreenshotArtifact = ( bytes: Buffer, ): WebScreenshotArtifact => { - const sha256 = createHash("sha256").update(bytes).digest("hex"); + const sha256 = sha256Hex(bytes); return webScreenshotArtifactSchema.parse({ sha256, bytes: bytes.byteLength, diff --git a/src/domain/webScriptExportPlan.ts b/src/domain/webScriptExportPlan.ts index ba3645bab7..9b34ce3b20 100644 --- a/src/domain/webScriptExportPlan.ts +++ b/src/domain/webScriptExportPlan.ts @@ -1,13 +1,10 @@ -import { createHash } from "node:crypto"; - import type { CapturedWebScript, ExportedWebScript, } from "./webScriptExport.js"; import { urlDeclaresQueryOrFragment } from "./urlComponents.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; -const hash = (text: string): string => - createHash("sha256").update(text).digest("hex"); // Literal URL path characters that are also portable filename characters. // Percent escapes remain isolated: decoding them could change path identity. const PORTABLE_SEGMENT = /^[A-Za-z0-9_~.!$&'()+,;=@-]+$/u; @@ -23,7 +20,8 @@ export interface PlannedWebScript { export const isolatedWebScriptPath = ( source: CapturedWebScript["source"], index: number, -): string => `isolated/source-${index + 1}-${hash(JSON.stringify(source))}.js`; +): string => + `isolated/source-${index + 1}-${sha256Hex(JSON.stringify(source))}.js`; /** Preserve safe URL layouts only when every captured path is unambiguous. */ export const planWebScriptExport = ( @@ -99,7 +97,7 @@ const candidatePath = (script: CapturedWebScript): CandidatePath => { reason: "URL path is not an ordinary portable JavaScript module path.", }; return { - path: `origins/${hash(url.origin)}/${parts.join("/")}`, + path: `origins/${sha256Hex(url.origin)}/${parts.join("/")}`, reason: urlDeclaresQueryOrFragment(url) || url.username !== "" || diff --git a/src/domain/windowsNativeArtifact.ts b/src/domain/windowsNativeArtifact.ts index b1d301e8fe..199a99b893 100644 --- a/src/domain/windowsNativeArtifact.ts +++ b/src/domain/windowsNativeArtifact.ts @@ -1,8 +1,8 @@ import { observeMzWindowsHeader } from "./dosMz.js"; -import { createHash } from "node:crypto"; import { readPeCoffHeader } from "./peCoffHeader.js"; import { readPeOptionalHeaderIdentity } from "./peOptionalHeader.js"; import { err, ok, type Result } from "./result.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Fixed compatibility contract shared by the artifact producer and readers. */ export const WINDOWS_NATIVE_ARTIFACT = { @@ -128,9 +128,7 @@ export const validateWindowsNativeArtifact = ( manifest: WindowsNativeManifest, bytes: Buffer, ): Result => { - if ( - createHash("sha256").update(bytes).digest("hex") !== manifest.artifactSha256 - ) + if (sha256Hex(bytes) !== manifest.artifactSha256) return err( new WindowsNativeArtifactError( "Windows native artifact SHA-256 does not match package metadata", @@ -150,7 +148,7 @@ export const createWindowsNativeManifest = ( { ...WINDOWS_NATIVE_ARTIFACT, packageVersion, - artifactSha256: createHash("sha256").update(bytes).digest("hex"), + artifactSha256: sha256Hex(bytes), }, packageVersion, ); diff --git a/src/dotnet/ManagedMethodBodyReader.ts b/src/dotnet/ManagedMethodBodyReader.ts index 0bb72efbaa..f51972c49c 100644 --- a/src/dotnet/ManagedMethodBodyReader.ts +++ b/src/dotnet/ManagedMethodBodyReader.ts @@ -24,7 +24,6 @@ import { metadataTokenFact, type MetadataTokenFact, readMetadataBlob, - sha256Bytes, } from "../domain/managed/managedMetadataHeaps.js"; import { readLocalSignatureFacts, @@ -33,6 +32,7 @@ import { import { ManagedReaderFailure } from "../domain/managed/managedReaderFailure.js"; import type { ManagedMetadataLayout } from "../domain/managed/managedMetadataLayout.js"; import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; const EMPTY_CATCH_TOKENS: ReadonlyMap = new Map(); @@ -313,9 +313,8 @@ export const methodBody = ( local_var_sig_token: localSignature?.token ?? null, local_var_signature: localVarSignature, il_size: header.ilSize, - il_sha256: sha256Bytes(il), - normalized_il_sha256: - status === "present" ? sha256Bytes(normalized) : null, + il_sha256: sha256Hex(il), + normalized_il_sha256: status === "present" ? sha256Hex(normalized) : null, instruction_count: decoded.count, decoded_instruction_count: decoded.parsed.length, truncated_instructions: decoded.truncated, diff --git a/src/dotnet/ManagedStaticProvider.ts b/src/dotnet/ManagedStaticProvider.ts index 223119f5f7..606b1151e7 100644 --- a/src/dotnet/ManagedStaticProvider.ts +++ b/src/dotnet/ManagedStaticProvider.ts @@ -50,6 +50,7 @@ import { readManagedSnapshot, verifyManagedSourceIdentity, } from "./ManagedSnapshot.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Execution-free managed PE/CLI auxiliary provider. */ export class ManagedStaticProvider implements AnalysisProvider { @@ -199,9 +200,7 @@ class ManagedStaticClient implements AnalysisClient { MANAGED_STATIC_PROVIDER.id, cleanup?.resources ?? [this.target.path], { - reason: - cleanup?.reason ?? - (cause instanceof Error ? cause.message : String(cause)), + reason: cleanup?.reason ?? errorMessage(cause), }, { cause, operation }, ); diff --git a/src/electron/ElectronFuseFailures.ts b/src/electron/ElectronFuseFailures.ts index 4651476d0b..e630fea06b 100644 --- a/src/electron/ElectronFuseFailures.ts +++ b/src/electron/ElectronFuseFailures.ts @@ -29,6 +29,7 @@ import { } from "../filesystem/RegularFile.js"; import { ElectronFusePathFailure } from "./ElectronFusePath.js"; import { ElectronFuseResourceFailure } from "./ElectronFuseReader.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_electron_fuses"; @@ -140,7 +141,7 @@ export const electronFuseFailure = ( cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }, ); diff --git a/src/evm/EvmoleFailures.ts b/src/evm/EvmoleFailures.ts index bec0733371..94ca5059ff 100644 --- a/src/evm/EvmoleFailures.ts +++ b/src/evm/EvmoleFailures.ts @@ -25,6 +25,7 @@ import { EVM_WORKER_HEAP_MIB, } from "./EvmoleRelease.js"; import { EVMOLE_PROVIDER_IDENTITY } from "./EvmoleProviderIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_evm_interface"; @@ -153,10 +154,7 @@ export const evmFailureDialect = ( cause: unrecognised, diagnostics: { ...evmWorkerDiagnostics(context), - reason: - unrecognised instanceof Error - ? unrecognised.message - : String(unrecognised), + reason: errorMessage(unrecognised), }, }), }; diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index 0619150458..9bb417c002 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -89,6 +89,7 @@ import { selectEvmWorkerLimits, type EvmWorkerLimits, } from "./EvmWorkerLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_evm_interface"; @@ -199,7 +200,7 @@ const selectEvmLimiter = async ( : missing ? "Set REA_EVM_PRLIMIT_COMMAND to an existing absolute executable regular file for util-linux prlimit." : "Check the selected file and filesystem access, or set REA_EVM_PRLIMIT_COMMAND to an accessible absolute executable regular file for util-linux prlimit."; - const reason = `Offline EVM interface inspection requires caller-supplied util-linux prlimit: ${path}; ${cause instanceof Error ? cause.message : String(cause)}. ${recovery}`; + const reason = `Offline EVM interface inspection requires caller-supplied util-linux prlimit: ${path}; ${errorMessage(cause)}. ${recovery}`; return err({ path, code: missing ? "executable_missing" : "runtime_unavailable", @@ -319,7 +320,7 @@ const retainedCleanupFailure = (cause: unknown): ProviderCleanupError => { cause instanceof AnalysisError && cause.cleanupResources.length > 0 ? cause.cleanupResources : ["EVM provider cleanup"], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation: OPERATION, cause, @@ -583,7 +584,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { try { inheritedLimits = await readFile("/proc/self/limits", "utf8"); } catch (cause: unknown) { - const reason = `Could not read inherited Linux resource limits at /proc/self/limits: ${cause instanceof Error ? cause.message : String(cause)}`; + const reason = `Could not read inherited Linux resource limits at /proc/self/limits: ${errorMessage(cause)}`; throw new AnalysisCapabilityUnavailableError( EVMOLE_PROVIDER_IDENTITY.id, OPERATION, @@ -733,7 +734,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { ) : new AnalysisOutputError( OPERATION, - `Owned interface worker reply failed for ${input.path}: ${cause instanceof Error ? cause.message : String(cause)}`, + `Owned interface worker reply failed for ${input.path}: ${errorMessage(cause)}`, { cause, capturedOutput, @@ -887,10 +888,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { } catch (markerFailure: unknown) { fileFailure = { verified: false, - failure: - markerFailure instanceof Error - ? markerFailure.message - : String(markerFailure), + failure: errorMessage(markerFailure), }; } } @@ -1038,7 +1036,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { input, cleanupResult, [retainedRoot.path], - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), retainedOutput, cause, ); @@ -1087,9 +1085,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { EVMOLE_PROVIDER_IDENTITY.id, [...new Set(resources)], { - failures: failures.map((failure) => - failure instanceof Error ? failure.message : String(failure), - ), + failures: failures.map((failure) => errorMessage(failure)), }, { operation: OPERATION, cause: new AggregateError(failures) }, ); @@ -1128,7 +1124,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { ...(pending.process.cleanupResources ?? []), ]), ], - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), pending.output, cause, ); @@ -1154,7 +1150,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { pending.input, pending.result, lease.cleanupResources ?? [root.path], - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), pending.output, cause, ); diff --git a/src/evm/EvmoleInterfaceWorker.ts b/src/evm/EvmoleInterfaceWorker.ts index be5657b250..19f5cba0e6 100644 --- a/src/evm/EvmoleInterfaceWorker.ts +++ b/src/evm/EvmoleInterfaceWorker.ts @@ -14,6 +14,7 @@ import { selectedEvmProducerLimits, } from "../domain/evm/evmInterface.js"; import { readStableArtifact } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const requestSchema = z.strictObject({ snapshot_path: z.string(), @@ -84,7 +85,7 @@ const main = async (): Promise => { : cause instanceof UnsupportedContainer ? "unsupported" : "decoder", - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), }; } let encoded = JSON.stringify(reply); @@ -105,7 +106,7 @@ const main = async (): Promise => { }); } catch (markerFailure: unknown) { process.stderr.write( - `File-size failure marker unavailable: ${markerFailure instanceof Error ? markerFailure.message : String(markerFailure)}\n`, + `File-size failure marker unavailable: ${errorMessage(markerFailure)}\n`, ); } process.exitCode = EVM_FILE_SIZE_FAILURE_EXIT; diff --git a/src/evm/SolidityMetadata.ts b/src/evm/SolidityMetadata.ts index b21a7c5bf4..f7b9e1af7f 100644 --- a/src/evm/SolidityMetadata.ts +++ b/src/evm/SolidityMetadata.ts @@ -5,6 +5,7 @@ import type { SolidityMetadata, SolidityMetadataScalar, } from "../domain/evm/solidityMetadata.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const PROFILE = "terminal-cbor-scalars-v1"; const MAX_DEPTH = 64; @@ -160,10 +161,7 @@ const solidityFailure = ( }, }; return { - diagnostic: (cause instanceof Error ? cause.message : String(cause)).slice( - 0, - 512, - ), + diagnostic: errorMessage(cause).slice(0, 512), }; }; diff --git a/src/filesystem/StableFileHash.ts b/src/filesystem/StableFileHash.ts index 58f537d7b5..88ef1d86b8 100644 --- a/src/filesystem/StableFileHash.ts +++ b/src/filesystem/StableFileHash.ts @@ -15,6 +15,7 @@ import { type StableRegularFileDescriptor, } from "./RegularFile.js"; import type { OwnedFileHandle } from "./OwnedFileHandle.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface StableFileHashOptions { readonly signal?: AbortSignal; @@ -43,10 +44,7 @@ export class StableFileHashFailure extends Error { readonly path: string, override readonly cause: unknown, ) { - super( - `Could not hash ${path}: ${cause instanceof Error ? cause.message : String(cause)}`, - { cause }, - ); + super(`Could not hash ${path}: ${errorMessage(cause)}`, { cause }); this.name = this._tag; } } diff --git a/src/firmware/FirmwareCommand.ts b/src/firmware/FirmwareCommand.ts index bd4eee9f61..99fd86b519 100644 --- a/src/firmware/FirmwareCommand.ts +++ b/src/firmware/FirmwareCommand.ts @@ -54,6 +54,7 @@ import { FirmwareFileAccess, inventoryFirmwareOutput, } from "./FirmwareFiles.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Injectable owned launcher for production protocol and lifecycle tests. */ export type FirmwareLauncher = ( @@ -74,9 +75,6 @@ export const firmwareToolUnavailable = ( export const firmwareHostSupported = (platform: NodeJS.Platform): boolean => platform === "linux"; -const failureReason = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** * Why a configured tool path cannot run, or undefined when `accessPath` grants * `mode` and `statPath` is a regular file. @@ -92,7 +90,7 @@ const executableRegularFileRefusal = async ( ? undefined : "Configured path is not a regular file"; } catch (cause: unknown) { - return failureReason(cause); + return errorMessage(cause); } }; @@ -124,7 +122,7 @@ export const resolveFirmwareCommand = async ( throw firmwareToolUnavailable( engine, operation, - `${variable} is unavailable: ${failureReason(cause)}`, + `${variable} is unavailable: ${errorMessage(cause)}`, ); }, ); @@ -146,7 +144,7 @@ export const resolveFirmwareCommand = async ( sha256 = await files.hash(selection.resolvedPath, signal); } catch (cause: unknown) { if (cause instanceof ArtifactReaderFailure) throw cause; - throw engineUnavailable(failureReason(cause)); + throw engineUnavailable(errorMessage(cause)); } const limiter = environment.REA_FIRMWARE_PRLIMIT_COMMAND ?? "/usr/bin/prlimit"; @@ -167,7 +165,7 @@ export const resolveFirmwareCommand = async ( limiterSelection = await selectArtifactCommandPath(limiter, signal); } catch (cause: unknown) { if (cause instanceof ArtifactReaderFailure) throw cause; - throw limiterUnavailable(failureReason(cause)); + throw limiterUnavailable(errorMessage(cause)); } const limiterRefusal = await executableRegularFileRefusal( limiterSelection.resolvedPath, @@ -496,7 +494,7 @@ export const readFirmwareCommandReport = async (context: { const reportFailure = cause instanceof AnalysisOutputError ? cause.reason - : `Report could not be read: ${cause instanceof Error ? cause.message : String(cause)}`; + : `Report could not be read: ${errorMessage(cause)}`; const diagnostics = { ...(cause instanceof AnalysisOutputError ? cause.diagnostics : {}), report_path: context.path, diff --git a/src/firmware/FirmwareFailures.ts b/src/firmware/FirmwareFailures.ts index e844f70943..b8ba860de3 100644 --- a/src/firmware/FirmwareFailures.ts +++ b/src/firmware/FirmwareFailures.ts @@ -25,6 +25,7 @@ import type { FirmwareDeadline } from "./FirmwareDeadline.js"; import { firmwareDeadlineElapsed } from "./FirmwareDeadline.js"; import { z } from "zod"; import { FIRMWARE_LIMITS } from "./FirmwareRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Fixed firmware allowance. analysis_timeout_ms does not raise it. */ export const firmwareLimitRecovery = (allowance: string): string => @@ -229,7 +230,7 @@ export const firmwareFailureDialect = ( ...details, cause, diagnostics: { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }), }; diff --git a/src/firmware/FirmwareProvider.ts b/src/firmware/FirmwareProvider.ts index 90faf98c7a..88261d2fb9 100644 --- a/src/firmware/FirmwareProvider.ts +++ b/src/firmware/FirmwareProvider.ts @@ -69,6 +69,7 @@ import { firmwarePhaseInterruption, firmwareSignalInterruption, } from "./FirmwareFailures.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type Outcome = Awaited>; interface PendingFirmwareCleanup { @@ -293,7 +294,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort { pending.engine, [path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: pending.operation, cause }, ), @@ -314,7 +315,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort { pending.engine, [path, pending.tree?.tree.outputRoot ?? path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: pending.operation, cause }, ), @@ -335,7 +336,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort { pending.engine, [path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { operation: pending.operation, cause }, ), @@ -705,7 +706,7 @@ const finishFirmwareWorkspace = async ( ? [request.input.output_directory] : []), ], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { cause, operation: request.operation, diff --git a/src/firmware/FirmwarePublication.ts b/src/firmware/FirmwarePublication.ts index 2f7e780b50..a0ae7e8c18 100644 --- a/src/firmware/FirmwarePublication.ts +++ b/src/firmware/FirmwarePublication.ts @@ -49,6 +49,7 @@ const UNNAMED_DEPENDENCY_CONTINUATION = import { FIRMWARE_LIMITS } from "./FirmwareRelease.js"; import type { FirmwareDeadline } from "./FirmwareDeadline.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const depthContinuation = ( maxDepth: number, @@ -257,12 +258,8 @@ export const publishFirmwareExtraction = async (context: { "unblob", [context.outputDirectory, context.workspacePath], { - reason: - cleanupCause instanceof Error - ? cleanupCause.message - : String(cleanupCause), - previous_error: - cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cleanupCause), + previous_error: errorMessage(cause), }, { cause: cleanupCause, diff --git a/src/flutter/FlutterBuildProvider.ts b/src/flutter/FlutterBuildProvider.ts index bb5c9002a7..a581ff7fbb 100644 --- a/src/flutter/FlutterBuildProvider.ts +++ b/src/flutter/FlutterBuildProvider.ts @@ -71,6 +71,7 @@ import { } from "./DartElf.js"; import { readElfBuildIds } from "./ElfBuildId.js"; import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const APK_METADATA_READ_MAX_BYTES = 8 * 1024 * 1024; const LIBRARY_MAX_BYTES = 256 * 1024 * 1024; @@ -233,7 +234,7 @@ const inputFailureMessage = (path: string, cause: unknown): string => { return `Selected APK does not exist: ${path}`; if (cause instanceof NonRegularFileReadError) return `Selected APK is not a regular file: ${path}`; - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); return `The APK could not be read as a package: ${path}: ${message}`; }; @@ -592,17 +593,13 @@ export class FlutterBuildProvider { FLUTTER_PROVIDER_IDENTITY.id, [root], { - reason: causes - .map((cause) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + reason: causes.map((cause) => errorMessage(cause)).join("; "), retained_roots: [ { path: root, failures: causes.map((cause) => ({ name: cause instanceof Error ? cause.name : "UnknownError", - message: cause instanceof Error ? cause.message : String(cause), + message: errorMessage(cause), ...(cause instanceof Error && "code" in cause && typeof cause.code === "string" diff --git a/src/frida/FridaInstrumentationManager.ts b/src/frida/FridaInstrumentationManager.ts index e2f7cf1b69..cb0f2023cb 100644 --- a/src/frida/FridaInstrumentationManager.ts +++ b/src/frida/FridaInstrumentationManager.ts @@ -53,6 +53,7 @@ import { type FridaCapturePolicy, } from "../domain/fridaCapturePolicy.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const DEVICE_LOOKUP_TIMEOUT_MS = 1_000; @@ -1706,9 +1707,6 @@ const providerError = ( }); }; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const cancelledOperation = ( operation: string, signal: AbortSignal, diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index b3cfee220c..96d8c4bd8e 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -81,6 +81,7 @@ import { cancelledWithCallerReason, } from "../process/OwnedDebuggerSessionRegistry.js"; import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const STARTUP_TIMEOUT_MS = 10_000; @@ -300,10 +301,6 @@ class GdbProtocolFailureError extends Error { } } -/** Convert an unknown boundary failure without dropping non-Error values. */ -const gdbErrorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - interface GdbSession { readonly id: string; readonly miVersion: "mi3" | "mi2"; @@ -922,7 +919,7 @@ export class GdbSessionManager { ), ), ); - const startupFailureMessage = gdbErrorMessage(cause); + const startupFailureMessage = errorMessage(cause); return err( retainCleanup( new AnalysisCapabilityUnavailableError( @@ -984,7 +981,7 @@ export class GdbSessionManager { : new AnalysisCapabilityUnavailableError( "gdb", "start_gdb_session", - `GDB startup failed (${gdbErrorMessage(cause)}).`, + `GDB startup failed (${errorMessage(cause)}).`, errorDetails, ); return err(error); diff --git a/src/ghidra/GhidraCheckpoint.ts b/src/ghidra/GhidraCheckpoint.ts index ebf94c9e9c..501cb32ba7 100644 --- a/src/ghidra/GhidraCheckpoint.ts +++ b/src/ghidra/GhidraCheckpoint.ts @@ -34,6 +34,7 @@ import { ghidraFileFailure, readGhidraProfileArtifact, } from "./GhidraFileArtifacts.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const digest = z.string().regex(/^[a-f0-9]{64}$/); const sourceSchema = z @@ -403,7 +404,7 @@ export class GhidraCheckpoint { "ghidra", [...this.#pendingRemoval], { - reason: `Checkpoint file cleanup failed: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `Checkpoint file cleanup failed: ${errorMessage(cause)}`, checkpoint: this.observation, }, { cause }, diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 60371ef412..59c409004d 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -131,6 +131,7 @@ import { GhidraCheckpoint, type GhidraPackedProgram, } from "./GhidraCheckpoint.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const SHUTDOWN_TIMEOUT_MS = 10_000; /** @@ -348,7 +349,7 @@ export class GhidraClient { }, (cause: unknown) => { this.#logger.debug( - { error: cause instanceof Error ? cause.message : String(cause) }, + { error: errorMessage(cause) }, "Ghidra startup promise rejected during bookkeeping", ); if (this.#startupAttempt === attempt) this.#startupAttempt = undefined; @@ -843,7 +844,7 @@ export class GhidraClient { ), ], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), diagnostics: this.#diagnostics(), }, { cause }, @@ -901,7 +902,7 @@ export class GhidraClient { () => ok(null), (cause: unknown) => { this.#logger.error( - { error: cause instanceof Error ? cause.message : String(cause) }, + { error: errorMessage(cause) }, "Ghidra cleanup after active request cancellation failed", ); return err(this.#cleanupError(cause)); @@ -1515,7 +1516,7 @@ export class GhidraClient { firstCause ??= cause; leftovers.push({ path: root.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); } } diff --git a/src/ghidra/GhidraFileArtifacts.ts b/src/ghidra/GhidraFileArtifacts.ts index e74fa930b3..236f9c57e8 100644 --- a/src/ghidra/GhidraFileArtifacts.ts +++ b/src/ghidra/GhidraFileArtifacts.ts @@ -28,6 +28,7 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Bounded serial read; the caller owns admission and final descriptor cleanup. */ export const readGhidraProfileArtifact = ( @@ -104,9 +105,7 @@ export const ghidraFileFailure = ( const { cause: primary, origin } = artifactFilePrimaryFacts(cause); const admission = primary instanceof GhidraAdmissionError ? primary : undefined; - const reason = - admission?.code ?? - (primary instanceof Error ? primary.message : String(primary)); + const reason = admission?.code ?? errorMessage(primary); const systemCode = admission === undefined && primary instanceof Error && diff --git a/src/ghidra/GhidraJavaProbe.ts b/src/ghidra/GhidraJavaProbe.ts index 2c37fbc948..be2759cfc5 100644 --- a/src/ghidra/GhidraJavaProbe.ts +++ b/src/ghidra/GhidraJavaProbe.ts @@ -28,6 +28,7 @@ import { constants, accessSync, statSync } from "node:fs"; import { posix, win32 } from "node:path"; import { err, ok, type Result } from "../domain/result.js"; import type { AnalysisCapturedOutput } from "../domain/analysisErrorBase.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Bound the Java version probe so a chatty or hostile JVM cannot force an @@ -303,7 +304,7 @@ const observeGhidraJava = async ( classifyLaunchFailureCode(code)?.kind === "missing" ? "runtime_missing" : "runtime_unavailable", - detail: `${command}: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `${command}: ${errorMessage(cause)}`, ...(code === undefined ? {} : { processErrorCode: code }), ...(output === undefined ? {} : { output }), }; diff --git a/src/ghidra/GhidraLauncher.ts b/src/ghidra/GhidraLauncher.ts index a52c206a73..358982c782 100644 --- a/src/ghidra/GhidraLauncher.ts +++ b/src/ghidra/GhidraLauncher.ts @@ -74,6 +74,7 @@ import { inspectGhidraPspExtension, type GhidraPspExtension, } from "./GhidraPspExtension.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface GhidraLaunchSession { readonly runtimeRoot: string; @@ -650,7 +651,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher { const primaryMessage = cancellation !== undefined ? cancellation.message - : `Ghidra headless launch failed: ${cause instanceof Error ? cause.message : String(cause)}`; + : `Ghidra headless launch failed: ${errorMessage(cause)}`; return err( new GhidraLaunchError( `${primaryMessage}; process cleanup remains incomplete`, diff --git a/src/ghidra/GhidraProvider.ts b/src/ghidra/GhidraProvider.ts index 6bd7959cc1..12268eb136 100644 --- a/src/ghidra/GhidraProvider.ts +++ b/src/ghidra/GhidraProvider.ts @@ -97,6 +97,7 @@ import { admitGhidraInstallation, type GhidraAdmission, } from "./GhidraAdmission.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const SUPPORTED_ARCHITECTURES = new Set([ "x86", @@ -374,7 +375,7 @@ export class GhidraProvider implements AnalysisProviderCandidate { cause instanceof ArtifactReaderFailure ? (cause.cleanup?.resources ?? []) : [], - { reason: providerFailureText(cause) }, + { reason: errorMessage(cause) }, { cause }, ); bindArtifactFileCleanup(cause, error); @@ -754,9 +755,6 @@ const existingProjectUnsupported = (): ConfigurationError => { }); }; -const providerFailureText = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const inspectWindowsP0TargetSupport = ( target: BinaryTarget, diagnostics: Readonly>, diff --git a/src/ghidra/GhidraPspExtension.ts b/src/ghidra/GhidraPspExtension.ts index 640d4ed900..c80730c1cc 100644 --- a/src/ghidra/GhidraPspExtension.ts +++ b/src/ghidra/GhidraPspExtension.ts @@ -23,6 +23,7 @@ import { withArtifactRegularFile, } from "../resources/index.js"; import { OwnedDirectoryHandle } from "../filesystem/OwnedDirectoryHandle.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Installed processor code and data, distinct from REA's analysis-extension ABI. */ export const ghidraPspExtensionSchema = z.strictObject({ @@ -241,9 +242,7 @@ const GHIDRA_PSP_INSPECTION_DIALECT: ProviderFailureDialect = { const { cause: primary } = artifactFilePrimaryFacts(cause); const admission = primary instanceof GhidraAdmissionError ? primary : undefined; - const identity = - admission?.code ?? - (primary instanceof Error ? primary.message : String(primary)); + const identity = admission?.code ?? errorMessage(primary); const reason = `PSP_EXTENSION_UNAVAILABLE: ${identity} Use a compatible caller-installed ghidra-allegrex under GHIDRA_INSTALL_DIR/Ghidra/Extensions; REA does not install it.`; return new AnalysisCapabilityUnavailableError( "ghidra", diff --git a/src/ghidra/GhidraTemporaryDirectory.ts b/src/ghidra/GhidraTemporaryDirectory.ts index be94de2683..4e18d3ccc0 100644 --- a/src/ghidra/GhidraTemporaryDirectory.ts +++ b/src/ghidra/GhidraTemporaryDirectory.ts @@ -10,6 +10,7 @@ import { withArtifactFileHandle, } from "../resources/index.js"; import { ghidraSessionRoot } from "./GhidraSessionRoot.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Remediation for a host that denies writes under the session temporary root. @@ -61,9 +62,6 @@ const errorCode = (cause: unknown): string | undefined => ? cause.code : undefined; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** * Create and delete one file under the Ghidra session root from the REA * process. This proves only that REA itself can use the root; a host that diff --git a/src/go/GoBinaryProvider.ts b/src/go/GoBinaryProvider.ts index bc3f6da010..f6a7b3c37c 100644 --- a/src/go/GoBinaryProvider.ts +++ b/src/go/GoBinaryProvider.ts @@ -37,6 +37,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { readGoBinaryImage, type GoBinaryImage } from "./GoBinaryImage.js"; import { requireSelectedNativeImage } from "../domain/apple/machoSliceSelection.js"; import { BinaryResourceFailure } from "../domain/binaryContainer.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_go_binary"; @@ -128,7 +129,7 @@ const failureForPrimary = ( cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/gpu/GpuCodeObjectsProvider.ts b/src/gpu/GpuCodeObjectsProvider.ts index 2f7a89c480..d7ea05fee8 100644 --- a/src/gpu/GpuCodeObjectsProvider.ts +++ b/src/gpu/GpuCodeObjectsProvider.ts @@ -50,6 +50,7 @@ import { isSelectedRegularFileError, sameRegularFileState, } from "../filesystem/RegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_gpu_code_objects"; @@ -184,8 +185,7 @@ export class GpuCodeObjectsProvider implements GpuCodeObjectsPort { cause, diagnostics: { path: input.path, - reason: - primary instanceof Error ? primary.message : String(primary), + reason: errorMessage(primary), }, }); if ( diff --git a/src/hopper/BridgeLauncher.ts b/src/hopper/BridgeLauncher.ts index 1433170c44..90f3fa1d01 100644 --- a/src/hopper/BridgeLauncher.ts +++ b/src/hopper/BridgeLauncher.ts @@ -59,6 +59,7 @@ import type { BridgeMaxRequestBytes } from "../config/bridgeMaxRequestBytes.js"; import { HOPPER_SHUTDOWN_TIMEOUT_MS } from "./HopperSessionValues.js"; import { verifyMacHopperNativeHelper } from "./HopperMacPublisher.js"; import type { LinuxHopperLauncherVerification } from "../ports/LinuxHopperLauncherVerification.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const execFileAsync = promisify(execFile); const HOPPER_BACKGROUND_STARTUP_MS = 5_000; @@ -333,9 +334,9 @@ export class HopperApplicationLauncher implements BridgeLauncher { } catch (cause: unknown) { const failure = new HopperStartError({ cause, - userMessage: `Previous Hopper image cleanup remains incomplete: ${cause instanceof Error ? cause.message : String(cause)}`, + userMessage: `Previous Hopper image cleanup remains incomplete: ${errorMessage(cause)}`, cleanup: { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: this.#preparedImageResources.cleanupResources, }, }); diff --git a/src/hopper/HopperAnalysisProfile.ts b/src/hopper/HopperAnalysisProfile.ts index 065754ef3b..fa9f935881 100644 --- a/src/hopper/HopperAnalysisProfile.ts +++ b/src/hopper/HopperAnalysisProfile.ts @@ -55,6 +55,7 @@ import { type HopperMachOImage, } from "./HopperMachOImage.js"; import { hopperProducerIdentity } from "./HopperBridgeSources.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface HopperProfileOptions { readonly launcherPath: string; @@ -380,10 +381,7 @@ const readHopperProfileFile = async ( const cleanup = cause instanceof RegularFileCleanupFailure ? { - reason: - cause.cleanupCause instanceof Error - ? cause.cleanupCause.message - : String(cause.cleanupCause), + reason: errorMessage(cause.cleanupCause), resources: [path], } : undefined; @@ -406,13 +404,13 @@ const readHopperProfileFile = async ( : kind === "header" ? new BinaryTargetError( path, - `Cannot read the Mach-O container header: ${physical instanceof Error ? physical.message : String(physical)}`, + `Cannot read the Mach-O container header: ${errorMessage(physical)}`, { cause: physical, cleanup }, ) : new ProviderAdapterError("hopper", "resolve_analysis_profile", { cause: physical, cleanup, - userMessage: `Cannot fingerprint the selected Hopper launcher ${path}: ${physical instanceof Error ? physical.message : String(physical)}`, + userMessage: `Cannot fingerprint the selected Hopper launcher ${path}: ${errorMessage(physical)}`, remediationAction: "Select a readable regular Hopper launcher, then retry provider selection.", diagnostics: { diff --git a/src/hopper/HopperCleanup.ts b/src/hopper/HopperCleanup.ts index aaa1435989..b792f11dea 100644 --- a/src/hopper/HopperCleanup.ts +++ b/src/hopper/HopperCleanup.ts @@ -24,6 +24,7 @@ import { } from "./HopperDiagnostics.js"; import type { HopperRequestActivity } from "./HopperRequestQueue.js"; import { parseHopperShutdownReply } from "./HopperReplyContracts.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface CleanupIssue { readonly resource: string; @@ -141,7 +142,7 @@ export const cleanupHopperSession = async ( state.resources.add("hopper-lease"); state.issues.push({ resource: "hopper-lease", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); } } diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index 403d484b26..203bfbb8eb 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -114,6 +114,7 @@ import { hopperReplyEnvelope, responseResult, } from "./protocol.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Aggregate in-memory retention budget for this provider's launcher output. */ const HOPPER_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024; @@ -470,7 +471,7 @@ export class HopperClient< }, (cause: unknown) => { this.#logger.debug( - { error: cause instanceof Error ? cause.message : String(cause) }, + { error: errorMessage(cause) }, "Hopper startup promise rejected during bookkeeping", ); if (this.#startupAttempt === attempt) this.#startupAttempt = undefined; @@ -977,7 +978,7 @@ export class HopperClient< "hopper", ["hopper-launcher"], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, { cause }, ), diff --git a/src/hopper/HopperFileOffset.ts b/src/hopper/HopperFileOffset.ts index f7a4de82c3..98eca96cb6 100644 --- a/src/hopper/HopperFileOffset.ts +++ b/src/hopper/HopperFileOffset.ts @@ -41,6 +41,7 @@ import { type ProviderFailureDialect, } from "../providers/classifyProviderFailure.js"; import type { HopperReply } from "./HopperReplyContracts.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "address_to_file_offset"; const MAX_FAT_ARCHITECTURES = 128; @@ -200,7 +201,7 @@ const sourceAccessDialect = ( ? cancelled(partial, carriedReason(cause.reason)) : undefined, unclassified: (cause) => { - const reason = `Cannot verify original source bytes: ${cause instanceof Error ? cause.message : String(cause)}`; + const reason = `Cannot verify original source bytes: ${errorMessage(cause)}`; const code = typeof cause === "object" && cause !== null && "code" in cause ? cause.code @@ -220,10 +221,7 @@ const sourceAccessDialect = ( const descriptorCleanup = ( failure: RegularFileCleanupFailure, ): ProviderCleanupError => { - const reason = - failure.cleanupCause instanceof Error - ? failure.cleanupCause.message - : String(failure.cleanupCause); + const reason = errorMessage(failure.cleanupCause); return new ProviderCleanupError( "hopper", [failure.path], diff --git a/src/hopper/HopperImageCopy.ts b/src/hopper/HopperImageCopy.ts index 2022daca5d..62a5faa84d 100644 --- a/src/hopper/HopperImageCopy.ts +++ b/src/hopper/HopperImageCopy.ts @@ -9,6 +9,7 @@ import { import { err, ok, type Result } from "../domain/result.js"; import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface HopperImageCopyFileSystem { readonly open: typeof open; @@ -242,10 +243,7 @@ const hopperImageCopyFailure = (options: { "hopper", [attempt.owner.resource], { - reason: - attempt.cause instanceof Error - ? attempt.cause.message - : String(attempt.cause), + reason: errorMessage(attempt.cause), }, { cause: attempt.cause }, ); diff --git a/src/hopper/HopperMachOImage.ts b/src/hopper/HopperMachOImage.ts index d187ed9bbc..b2fbf29295 100644 --- a/src/hopper/HopperMachOImage.ts +++ b/src/hopper/HopperMachOImage.ts @@ -40,6 +40,7 @@ import { copyHopperSource, type HopperImageCopyOptions, } from "./HopperImageCopy.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const hopperFatMachOImageSchema = z.strictObject({ method: z.enum(["fat32_thin_slice", "fat64_thin_slice"]), @@ -110,7 +111,7 @@ export const resolveHopperMachOImage = async ( } catch (cause: unknown) { // Keep the OS error so a read-permission denial reports access_denied. return invalid( - `Cannot read Mach-O source for Hopper image preparation: ${cause instanceof Error ? cause.message : String(cause)}`, + `Cannot read Mach-O source for Hopper image preparation: ${errorMessage(cause)}`, cause, ); } @@ -141,7 +142,7 @@ const inspectAndFinalizeHopperMachOImage = async ( : err( new BinaryTargetError( target.path, - `Cannot validate Mach-O image: ${cause instanceof Error ? cause.message : String(cause)}`, + `Cannot validate Mach-O image: ${errorMessage(cause)}`, { cause }, ), ); @@ -193,10 +194,7 @@ const retainHopperPreflightCloseFailure = (options: { resource, ); const cleanup = { - reason: - options.closeFailure instanceof Error - ? options.closeFailure.message - : String(options.closeFailure), + reason: errorMessage(options.closeFailure), resources: [resource], }; const cancellationIsPrimary = diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index 3c39498362..efdfcc65cf 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -67,6 +67,7 @@ import { analysisClientFailureForOperation } from "../providers/AnalysisClientFa import { hopperCapabilities } from "./HopperProviderCapabilities.js"; import { HOPPER_PROVIDER_IDENTITY } from "./HopperProviderMetadata.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Concrete analysis provider backed by REA's private Hopper bridge. */ export class HopperProvider implements AnalysisProviderCandidate { @@ -255,7 +256,7 @@ export class HopperProvider implements AnalysisProviderCandidate { const failure = new ProviderCleanupError( HOPPER_PROVIDER_IDENTITY.id, this.#ownedResources.cleanupResources, - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { cause, operation: "close_owned_resources" }, ); bindArtifactFileCleanup(cause, failure); diff --git a/src/hopper/LinuxPrivateDisplayProbe.ts b/src/hopper/LinuxPrivateDisplayProbe.ts index c3ecbec45d..eb93dcda9c 100644 --- a/src/hopper/LinuxPrivateDisplayProbe.ts +++ b/src/hopper/LinuxPrivateDisplayProbe.ts @@ -16,6 +16,7 @@ import { type ProviderProcessLaunch, } from "../process/ProviderProcess.js"; import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const PYTHON_PATH = "/usr/bin/python3"; const UNSHARE_PATH = "/usr/bin/unshare"; @@ -168,7 +169,7 @@ export const runLinuxPrivateDisplayProbe: LinuxPrivateDisplayProbeRunner = cleanup = { status: "pending", lease, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } const snapshot = supervisor.snapshot(); diff --git a/src/ida/IdaAdmission.ts b/src/ida/IdaAdmission.ts index 2cc605593d..6f2805cc4a 100644 --- a/src/ida/IdaAdmission.ts +++ b/src/ida/IdaAdmission.ts @@ -8,6 +8,7 @@ import { } from "../process/PrivateRuntimeRoot.js"; import type { IdaConfiguration } from "./IdaConfiguration.js"; import { resolveIdaWorkspaceParent } from "./IdaWorkspace.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The repair for a workspaceRoot REA cannot create entries in. */ export const IDA_WORKSPACE_ROOT_REMEDIATION = @@ -79,6 +80,6 @@ const workspaceParentUnusable = async ( await access(parent, constants.W_OK | constants.X_OK); return undefined; } catch (cause: unknown) { - return `IDA workspaceRoot ${root ?? "the system temporary directory"} is not a usable directory: ${cause instanceof Error ? cause.message : String(cause)}`; + return `IDA workspaceRoot ${root ?? "the system temporary directory"} is not a usable directory: ${errorMessage(cause)}`; } }; diff --git a/src/ida/IdaConfiguration.ts b/src/ida/IdaConfiguration.ts index 021555a78d..743f24ec19 100644 --- a/src/ida/IdaConfiguration.ts +++ b/src/ida/IdaConfiguration.ts @@ -23,6 +23,7 @@ import { NonRegularFileReadError, } from "../filesystem/RegularFile.js"; import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Omitted registration `timeoutMs` for each upstream IDA MCP request. */ export const DEFAULT_IDA_REQUEST_TIMEOUT_MS = 300_000; @@ -248,10 +249,7 @@ export const readIdaConfiguration = ( carriedReason(cancellation.reason), { cleanup: { - reason: - cause.cleanupCause instanceof Error - ? cause.cleanupCause.message - : String(cause.cleanupCause), + reason: errorMessage(cause.cleanupCause), resources: [path], }, }, @@ -275,15 +273,12 @@ export const readIdaConfiguration = ( ? primary.message : primary instanceof NonRegularFileReadError ? `REA_IDA_MCP_CONFIG must select a regular JSON file: ${path}` - : `Cannot read IDA MCP registration ${path}: ${primary instanceof Error ? primary.message : String(primary)}` + : `Cannot read IDA MCP registration ${path}: ${errorMessage(primary)}` : `Cannot close IDA MCP registration ${path}; provide a readable JSON configuration.`; const error = new ConfigurationError(primaryMessage, { cause, cleanup: { - reason: - cause.cleanupCause instanceof Error - ? cause.cleanupCause.message - : String(cause.cleanupCause), + reason: errorMessage(cause.cleanupCause), resources: [path], }, settings: [ diff --git a/src/ida/IdaInput.ts b/src/ida/IdaInput.ts index 5c56eca32a..9f306e4074 100644 --- a/src/ida/IdaInput.ts +++ b/src/ida/IdaInput.ts @@ -5,6 +5,7 @@ import { err, ok } from "../domain/result.js"; import { invalidRegexPatternError } from "../process/RegexMatcher.js"; import { idaAddressSchema } from "./IdaProtocolValues.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Apply the named public contract and IDA's explicit-address boundary before startup. */ export const parseIdaInput = ( @@ -66,11 +67,7 @@ export const parseIdaInput = ( ); } catch (cause: unknown) { return err( - invalidRegexPatternError( - operation, - cause instanceof Error ? cause.message : String(cause), - { cause }, - ), + invalidRegexPatternError(operation, errorMessage(cause), { cause }), ); } } diff --git a/src/ida/IdaProvider.ts b/src/ida/IdaProvider.ts index 8ca9b10cc2..077b7d917a 100644 --- a/src/ida/IdaProvider.ts +++ b/src/ida/IdaProvider.ts @@ -57,6 +57,7 @@ import { } from "./IdaAdmission.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { ProviderInspectionScope } from "../ports/ProviderInspectionScope.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Families IDA admits today. Every other family is refused, including families @@ -183,7 +184,7 @@ export class IdaProvider implements AnalysisProviderCandidate { const failure = new ProviderCleanupError( IDA_PROVIDER_IDENTITY.id, this.#ownedResources.cleanupResources, - { cause: cause instanceof Error ? cause.message : String(cause) }, + { cause: errorMessage(cause) }, { cause, operation: "close_owned_resources" }, ); bindArtifactFileCleanup(cause, failure); diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index bbe85d5ad3..863068ae59 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -69,6 +69,7 @@ import { analysisClientFailureContext, analysisClientFailureForOperation, } from "../providers/AnalysisClientFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const legacyTools = [ "get_metadata", @@ -142,9 +143,7 @@ class IdaCleanupError extends ProviderAdapterError { failure_reason: cause instanceof AnalysisError ? (cause.diagnostics?.reason ?? cause.message) - : cause instanceof Error - ? cause.message - : String(cause), + : errorMessage(cause), workspace: path, ...(sessions === undefined ? {} diff --git a/src/ida/IdaWorkspace.ts b/src/ida/IdaWorkspace.ts index 7d8367fdb7..a4d6a5a080 100644 --- a/src/ida/IdaWorkspace.ts +++ b/src/ida/IdaWorkspace.ts @@ -16,6 +16,7 @@ import { assertArtifactReadActive, withArtifactFileHandle, } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Read a file digest with bounded memory rather than retaining binary bytes. */ export const idaFileDigest = async (path: string): Promise => { @@ -84,7 +85,7 @@ export class IdaWorkspace { settings: [ { setting: "workspaceRoot", - constraint: `Select an existing writable and searchable directory: ${cause instanceof Error ? cause.message : String(cause)}`, + constraint: `Select an existing writable and searchable directory: ${errorMessage(cause)}`, }, ], diagnostics: { workspace_root: root }, diff --git a/src/il2cpp/Il2cppMetadataProvider.ts b/src/il2cpp/Il2cppMetadataProvider.ts index eb32b256d1..a95186f28b 100644 --- a/src/il2cpp/Il2cppMetadataProvider.ts +++ b/src/il2cpp/Il2cppMetadataProvider.ts @@ -59,6 +59,7 @@ import { linkIl2cppBinarySteps, type Il2cppBinaryLink, } from "./Il2cppBinaryFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_il2cpp_metadata"; const INPUT_BYTES = 256 * 1024 * 1024; @@ -163,7 +164,7 @@ const failureForPrimary = ( cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }, ); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index 5bd0f58981..b70fbd9e64 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -99,6 +99,7 @@ import { javaScriptWorkerAdmissionSchema, type JavaScriptWorkerMessage, } from "./JavaScriptAnalysisWorkerProtocol.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "analyze_javascript_application"; const PROVIDER = "javascript-static-analysis"; @@ -199,7 +200,7 @@ export class JavaScriptAnalysisWorker { "JavaScript worker control frame is unterminated or oversized", ); } catch (cause: unknown) { - this.#latchOutputFailure(message(cause)); + this.#latchOutputFailure(errorMessage(cause)); } }; @@ -636,7 +637,7 @@ export class JavaScriptAnalysisWorker { }), ) : previous; - const error = this.#cleanupError(message(cause), primary); + const error = this.#cleanupError(errorMessage(cause), primary); this.#runtime.bindCleanupFailure(error); result = err({ javascript, @@ -1454,7 +1455,7 @@ export class JavaScriptAnalysisWorker { ) return new AnalysisOutputError( OPERATION, - `${path} during ${this.#phase}: ${message(cause)}`, + `${path} during ${this.#phase}: ${errorMessage(cause)}`, { cause, capturedOutput: this.#captured() }, ); return cause instanceof RuntimeControlUnavailableError @@ -1465,7 +1466,7 @@ export class JavaScriptAnalysisWorker { diagnostics: { source_path: path, phase: this.#phase, - message: message(cause), + message: errorMessage(cause), }, }); } @@ -1536,6 +1537,3 @@ export class JavaScriptAnalysisWorker { this.#terminalResponseId = undefined; } } - -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts index c904d3f6e2..44779c9633 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorkerServer.ts @@ -37,6 +37,7 @@ import { javaScriptWorkerMessageSchema, type JavaScriptWorkerMessage, } from "./JavaScriptAnalysisWorkerProtocol.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Trusted composition callback; this provider owns framing and temporary I/O. */ export interface JavaScriptSourceWorkerAnalyzer { @@ -239,9 +240,7 @@ const analyzeJob = async ( message: cause instanceof AnalysisResourceConstraintError ? cause.reason - : cause instanceof Error - ? cause.message - : String(cause), + : errorMessage(cause), }); } }; diff --git a/src/javascript/recovery/RecoveryFiles.ts b/src/javascript/recovery/RecoveryFiles.ts index e70f3d80e4..12f186d509 100644 --- a/src/javascript/recovery/RecoveryFiles.ts +++ b/src/javascript/recovery/RecoveryFiles.ts @@ -36,6 +36,7 @@ import { } from "../../filesystem/RegularFile.js"; import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js"; import { isStrictUtf8 } from "../../domain/strictUtf8.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "recover_javascript_sources"; @@ -218,7 +219,7 @@ const snapshotRecoveryInput = async ( ); throw recoveryInputFailure( "path", - `Cannot snapshot UTF-8 JavaScript input ${path}: ${recoveryFailureMessage(cause)}`, + `Cannot snapshot UTF-8 JavaScript input ${path}: ${errorMessage(cause)}`, cause, ); } @@ -286,7 +287,7 @@ const recoveryInputLayoutPath = async ( }); throw recoveryInputFailure( "path", - `Cannot resolve selected JavaScript input parent ${path}: ${recoveryFailureMessage(cause)}`, + `Cannot resolve selected JavaScript input parent ${path}: ${errorMessage(cause)}`, cause, ); } @@ -352,7 +353,7 @@ export const snapshotRecoveryInputs = async ( } catch (cause: unknown) { throw recoveryInputFailure( "path", - `Cannot preserve selected input path in published artifacts: ${path}: ${recoveryFailureMessage(cause)}`, + `Cannot preserve selected input path in published artifacts: ${path}: ${errorMessage(cause)}`, cause, ); } @@ -479,10 +480,6 @@ export const recoveryInputFailure = ( { path: [field], reason: "invalid_value", message }, ]); -/** Convert one caught boundary cause into diagnostic text without masking its type. */ -export const recoveryFailureMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Cancellation remains distinct from malformed source or provider output. */ export const checkRecoveryCancellation = (signal?: AbortSignal): void => { if (signal?.aborted === true) throw cancelledBy(OPERATION, signal); diff --git a/src/javascript/recovery/WakaruCommand.ts b/src/javascript/recovery/WakaruCommand.ts index 2c1ed2d95b..bdf969ad22 100644 --- a/src/javascript/recovery/WakaruCommand.ts +++ b/src/javascript/recovery/WakaruCommand.ts @@ -36,9 +36,9 @@ import { checkRecoveryDeadline, inventoryRecoveryFiles, fingerprintRecoveryFile, - recoveryFailureMessage, } from "./RecoveryFiles.js"; import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "recover_javascript_sources"; const WAKARU_REQUIREMENT = @@ -133,7 +133,7 @@ export const resolveWakaruCommand = async ( (cause.cleanup !== undefined || cause.reason === "cancelled")) ) throw cause; - const reason = `Configured Wakaru or util-linux prlimit is unavailable: ${recoveryFailureMessage(cause)}`; + const reason = `Configured Wakaru or util-linux prlimit is unavailable: ${errorMessage(cause)}`; throw new AnalysisCapabilityUnavailableError("wakaru", OPERATION, reason, { cause, userMessage: reason, @@ -189,7 +189,7 @@ export const runWakaruCommand = async (context: WakaruCommandContext) => { reason: "Failed to launch configured Wakaru through util-linux prlimit", command: context.command, - detail: recoveryFailureMessage(cause), + detail: errorMessage(cause), }, }); primary = diff --git a/src/javascript/recovery/WakaruProvider.ts b/src/javascript/recovery/WakaruProvider.ts index c22f513ef0..36095d69c8 100644 --- a/src/javascript/recovery/WakaruProvider.ts +++ b/src/javascript/recovery/WakaruProvider.ts @@ -37,7 +37,6 @@ import { err, ok, type Result } from "../../domain/result.js"; import { checkRecoveryCancellation, checkRecoveryDeadline, - recoveryFailureMessage, recoveryInputFailure, snapshotRecoveryInputs, } from "./RecoveryFiles.js"; @@ -50,6 +49,7 @@ import type { ProviderProcessSupervisor } from "../../process/ProviderProcess.js import { prepareWakaruExecution } from "./WakaruExecution.js"; import { RECOVERY_LIMITS } from "./WakaruRelease.js"; import { WakaruReportReadFailure } from "./WakaruReport.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "recover_javascript_sources"; @@ -146,7 +146,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree; throw recoveryInputFailure( "output_directory", - `Cannot create new recovery directory ${input.output_directory}: ${recoveryFailureMessage(cause)}`, + `Cannot create new recovery directory ${input.output_directory}: ${errorMessage(cause)}`, cause, ); } @@ -208,7 +208,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { residuals.push(tree.outputRoot); cleanupFailures.push({ resource: tree.outputRoot, - reason: recoveryFailureMessage(cause), + reason: errorMessage(cause), }); } } @@ -225,7 +225,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { residuals.push(failedRoot); cleanupFailures.push({ resource: failedRoot, - reason: recoveryFailureMessage(cause), + reason: errorMessage(cause), }); } } @@ -274,7 +274,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { ? failure : new ProviderAdapterError("wakaru", OPERATION, { cause: failure, - diagnostics: { reason: recoveryFailureMessage(failure) }, + diagnostics: { reason: errorMessage(failure) }, ...(failure instanceof ArtifactReaderFailure && failure.partialObservation !== undefined ? { partialObservation: failure.partialObservation } @@ -299,7 +299,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { previous_error: failure instanceof WakaruCleanupFailure ? (failure.diagnostics?.previous_error ?? null) - : recoveryFailureMessage(failure), + : errorMessage(failure), cleanup_failures: cleanupFailures, }, { @@ -346,7 +346,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { ? failure : new ProviderAdapterError("wakaru", OPERATION, { cause: failure, - diagnostics: { reason: recoveryFailureMessage(failure) }, + diagnostics: { reason: errorMessage(failure) }, ...(reportFailure === undefined ? {} : { capturedOutput: reportFailure.capturedOutput }), @@ -385,7 +385,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { const error = new ProviderCleanupError( "wakaru", pending.lease.cleanupResources ?? [], - { reason: recoveryFailureMessage(cause) }, + { reason: errorMessage(cause) }, { operation: OPERATION, cause }, ).bindCleanupResourceOwner(pending.lease); pending.lease.bindCleanupError(error); diff --git a/src/javascript/recovery/WakaruReport.ts b/src/javascript/recovery/WakaruReport.ts index 8908e6a4eb..b20e4cf281 100644 --- a/src/javascript/recovery/WakaruReport.ts +++ b/src/javascript/recovery/WakaruReport.ts @@ -15,13 +15,10 @@ import { } from "../../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import type { JavaScriptRecoveryResult } from "../../domain/javascript/javascriptRecovery.js"; -import { - isRecoveryFileSizeError, - readRecoveryFile, - recoveryFailureMessage, -} from "./RecoveryFiles.js"; +import { isRecoveryFileSizeError, readRecoveryFile } from "./RecoveryFiles.js"; import { RECOVERY_LIMITS, wakaruFixedLimitRecovery } from "./WakaruRelease.js"; import type { runWakaruCommand } from "./WakaruCommand.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const warningSchema = z.looseObject({ filename: z.string(), @@ -144,7 +141,7 @@ export const parseWakaruReports = async (context: ReportContext) => { cause, ...wakaruReportGuidance(cause), diagnostics: { - reason: `Unusable Wakaru recovery report: ${recoveryFailureMessage(cause)}`, + reason: `Unusable Wakaru recovery report: ${errorMessage(cause)}`, exit_code: execution.exit_code, signal: execution.signal, stdout: execution.stdout, @@ -283,7 +280,7 @@ export const validateRecoverySourceMap = ( } catch (cause: unknown) { throw new AnalysisOutputError( OPERATION, - `Invalid emitted source map for ${filename}: ${recoveryFailureMessage(cause)}`, + `Invalid emitted source map for ${filename}: ${errorMessage(cause)}`, { cause }, ); } diff --git a/src/javascript/sourceMaps/SourceMapCommand.ts b/src/javascript/sourceMaps/SourceMapCommand.ts index 5b9d0ade86..052d8fa7ed 100644 --- a/src/javascript/sourceMaps/SourceMapCommand.ts +++ b/src/javascript/sourceMaps/SourceMapCommand.ts @@ -49,6 +49,7 @@ import { type SpawnedOwnedProviderProcess, } from "../../process/ProviderProcess.js"; import { prepareProcessOwnershipInspection } from "../../process/ProcessOwnershipObservation.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "trace_web_source_location"; const PROVIDER = "source-map-decoder"; @@ -143,7 +144,7 @@ export const runSourceMapCommand = async ( : { capturedOutput: preparation.capturedOutput }), diagnostics: { map_path: path, - error_message: message(cause), + error_message: errorMessage(cause), phase: "process_ownership_preparation", }, }); @@ -236,7 +237,7 @@ class PreparationCleanup implements SourceMapCleanupOwner { } catch (cause: unknown) { return new SourceMapCleanupFailure(cleanup.cleanupResources, { map_path: this.path, - cleanup_failures: [message(cause)], + cleanup_failures: [errorMessage(cause)], }).bindCleanupDependencies([cleanup], this); } return cleanup.cleanupIncomplete @@ -423,7 +424,10 @@ class OwnedCodec implements SourceMapCleanupOwner { ? runtimeControlCapabilityError(PROVIDER, OPERATION, cause) : new ProviderAdapterError(PROVIDER, OPERATION, { cause, - diagnostics: { map_path: this.path, error_message: message(cause) }, + diagnostics: { + map_path: this.path, + error_message: errorMessage(cause), + }, }); } @@ -602,7 +606,7 @@ class OwnedCodec implements SourceMapCleanupOwner { await this.#runtime.close(); this.#runtime = undefined; } catch (cause: unknown) { - failures.push(message(cause)); + failures.push(errorMessage(cause)); } } if (failures.length === 0) { @@ -620,5 +624,3 @@ class OwnedCodec implements SourceMapCleanupOwner { ); } } -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/javascript/sourceMaps/SourceMapReply.ts b/src/javascript/sourceMaps/SourceMapReply.ts index 6910ced041..d3f613a3fa 100644 --- a/src/javascript/sourceMaps/SourceMapReply.ts +++ b/src/javascript/sourceMaps/SourceMapReply.ts @@ -10,6 +10,7 @@ import { err, ok, type Result } from "../../domain/result.js"; import { javaScriptRuntime } from "../../domain/runtimeVersion.js"; import type { WebSourceMapReport } from "../../domain/webSourceLocation.js"; import { sourceMapCodecReplySchema } from "./SourceMapCodecProtocol.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "trace_web_source_location"; @@ -27,7 +28,7 @@ export const parseSourceMapReply = ( return err( new AnalysisOutputError( OPERATION, - `Malformed codec JSON reply: ${cause instanceof Error ? cause.message : String(cause)}`, + `Malformed codec JSON reply: ${errorMessage(cause)}`, ), ); } diff --git a/src/jeb/JebMcpConnectionOwner.ts b/src/jeb/JebMcpConnectionOwner.ts index 18d939f7c5..56ee01c605 100644 --- a/src/jeb/JebMcpConnectionOwner.ts +++ b/src/jeb/JebMcpConnectionOwner.ts @@ -12,6 +12,7 @@ import { McpHttpUtf8Error, validateMcpHttpResponse, } from "../providers/Utf8McpResponse.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Physical SDK failure captured before any subsequent resource cleanup. */ export class JebMcpPhysicalFailure extends Error { @@ -156,11 +157,7 @@ export class JebMcpConnectionOwner { "jeb", this.cleanupResources, { - reason: failures - .map((cause) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + reason: failures.map((cause) => errorMessage(cause)).join("; "), }, { operation: "close_jeb_connection", diff --git a/src/jeb/JebProvider.ts b/src/jeb/JebProvider.ts index 83ac06489a..114c3e3011 100644 --- a/src/jeb/JebProvider.ts +++ b/src/jeb/JebProvider.ts @@ -50,6 +50,7 @@ import { type JebMcpConnection, type JebMcpConnectionFactory, } from "./JebMcpConnection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const JEB_CONNECTION_REMEDIATION = `Start a JEB client serving MCP (default ${DEFAULT_JEB_MCP_ENDPOINT}) or set REA_JEB_MCP_URL to the running endpoint.`; @@ -619,7 +620,7 @@ export class JebProvider implements JebAnalysisPort { return new AnalysisCapabilityUnavailableError( "jeb", operation, - physical instanceof Error ? physical.message : String(physical), + errorMessage(physical), { cause, diagnostics, userMessage: JEB_CONNECTION_REMEDIATION }, ); }, diff --git a/src/kernel/byteToHex.test.ts b/src/kernel/byteToHex.test.ts new file mode 100644 index 0000000000..9d5e632f70 --- /dev/null +++ b/src/kernel/byteToHex.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vitest"; + +import { byteToHex } from "./byteToHex.js"; + +it("pads one byte to two lowercase hexadecimal digits", () => { + expect(byteToHex(0)).toBe("00"); + expect(byteToHex(0x0a)).toBe("0a"); + expect(byteToHex(0xff)).toBe("ff"); +}); diff --git a/src/kernel/byteToHex.ts b/src/kernel/byteToHex.ts new file mode 100644 index 0000000000..924eb287d7 --- /dev/null +++ b/src/kernel/byteToHex.ts @@ -0,0 +1,6 @@ +/** + * Two lowercase hexadecimal digits for one byte value (0 to 255), with no + * prefix. Callers add their own notation, such as `0x`, `%` or `\x`. + */ +export const byteToHex = (byte: number): string => + byte.toString(16).padStart(2, "0"); diff --git a/src/kernel/errorMessage.test.ts b/src/kernel/errorMessage.test.ts new file mode 100644 index 0000000000..ebdcb8672a --- /dev/null +++ b/src/kernel/errorMessage.test.ts @@ -0,0 +1,10 @@ +import { expect, it } from "vitest"; + +import { errorMessage } from "./errorMessage.js"; + +it("uses an Error's message and stringifies any other caught value", () => { + expect(errorMessage(new TypeError("bad input"))).toBe("bad input"); + expect(errorMessage("plain text")).toBe("plain text"); + expect(errorMessage(42)).toBe("42"); + expect(errorMessage(undefined)).toBe("undefined"); +}); diff --git a/src/kernel/errorMessage.ts b/src/kernel/errorMessage.ts new file mode 100644 index 0000000000..bb969a9b2a --- /dev/null +++ b/src/kernel/errorMessage.ts @@ -0,0 +1,6 @@ +/** + * The message text of a caught value: an Error's message, or the value as a + * string. Use it wherever a diagnostic needs text from an unknown cause. + */ +export const errorMessage = (cause: unknown): string => + cause instanceof Error ? cause.message : String(cause); diff --git a/src/kernel/sha256Hex.test.ts b/src/kernel/sha256Hex.test.ts new file mode 100644 index 0000000000..11cbd24568 --- /dev/null +++ b/src/kernel/sha256Hex.test.ts @@ -0,0 +1,20 @@ +import { expect, it } from "vitest"; + +import { sha256Hex } from "./sha256Hex.js"; + +const EMPTY = + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + +it("digests empty input as the SHA-256 of no bytes", () => { + expect(sha256Hex("")).toBe(EMPTY); + expect(sha256Hex(Buffer.alloc(0))).toBe(EMPTY); + expect(sha256Hex(new Uint8Array(0))).toBe(EMPTY); +}); + +it("hashes strings as UTF-8 unless an encoding is named", () => { + expect(sha256Hex("é")).toBe(sha256Hex(Buffer.from("é", "utf8"))); + expect(sha256Hex("é", "latin1")).toBe(sha256Hex(Buffer.from([0xe9]))); + expect(sha256Hex("abc")).toBe( + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ); +}); diff --git a/src/kernel/sha256Hex.ts b/src/kernel/sha256Hex.ts new file mode 100644 index 0000000000..0fe24ae6c1 --- /dev/null +++ b/src/kernel/sha256Hex.ts @@ -0,0 +1,15 @@ +import { createHash } from "node:crypto"; + +/** + * The lowercase hexadecimal SHA-256 digest of one in-memory value. A string is + * hashed as UTF-8 unless `encoding` names another encoding. Incremental or + * streamed hashing keeps its own `Hash`. + */ +export const sha256Hex = ( + data: string | NodeJS.ArrayBufferView, + encoding?: BufferEncoding, +): string => + (typeof data === "string" && encoding !== undefined + ? createHash("sha256").update(data, encoding) + : createHash("sha256").update(data) + ).digest("hex"); diff --git a/src/kuna/KunaAdmission.ts b/src/kuna/KunaAdmission.ts index 8ac40db37f..6ec75e8074 100644 --- a/src/kuna/KunaAdmission.ts +++ b/src/kuna/KunaAdmission.ts @@ -8,6 +8,7 @@ import { type KunaConfigurationFailure, } from "./KunaConfiguration.js"; import { KUNA_COMMAND_REMEDIATION } from "./KunaRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Why Kuna is not admitted: its settings, or a command REA cannot run. */ export interface KunaAdmissionRefusal { @@ -58,7 +59,7 @@ export const admitKunaCommand = ( return refused(`REA_KUNA_COMMAND is not a regular file: ${command}.`); } catch (cause: unknown) { return refused( - `Cannot execute REA_KUNA_COMMAND ${command}: ${cause instanceof Error ? cause.message : String(cause)}.`, + `Cannot execute REA_KUNA_COMMAND ${command}: ${errorMessage(cause)}.`, ); } return ok(configuration.value); diff --git a/src/kuna/KunaCommand.ts b/src/kuna/KunaCommand.ts index 2245fe6367..76f4a7572f 100644 --- a/src/kuna/KunaCommand.ts +++ b/src/kuna/KunaCommand.ts @@ -50,6 +50,7 @@ import { } from "./KunaInstallation.js"; import type { KunaDeadline } from "./KunaConfiguration.js"; import { KUNA_PROVIDER_ID } from "./KunaRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * `kuna functions --json` costs ~210 bytes per function; this admits about @@ -106,9 +107,6 @@ type KunaCommandOutcome = readonly owner: ProviderProcessSupervisor | undefined; }; -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Preserve the operation's typed failure while attaching descriptor cleanup. */ export const kunaFileCleanupError = ( failure: RegularFileCleanupFailure, @@ -120,14 +118,14 @@ export const kunaFileCleanupError = ( return cancelledBy(operation, carriedReason(cancellation.reason), { diagnostics, cleanup: { - reason: message(failure.cleanupCause), + reason: errorMessage(failure.cleanupCause), resources: [failure.path], }, }); const cleanup = new ProviderCleanupError( KUNA_PROVIDER_ID, [failure.path], - { reason: message(failure.cleanupCause), ...diagnostics }, + { reason: errorMessage(failure.cleanupCause), ...diagnostics }, { cause: failure, operation }, ); if (failure.outcome.kind === "completed") return cleanup; @@ -138,7 +136,7 @@ export const kunaFileCleanupError = ( : new ProviderAdapterError(KUNA_PROVIDER_ID, operation, { cause: primaryCause, diagnostics, - userMessage: `Kuna ${operation} failed: ${message(primaryCause)}`, + userMessage: `Kuna ${operation} failed: ${errorMessage(primaryCause)}`, }); return analysisErrorWithCleanupFailure(primary, cleanup, operation); }; @@ -157,7 +155,7 @@ export const kunaRetainedResourceCleanupError = ( const cleanup = new ProviderCleanupError( KUNA_PROVIDER_ID, cause.cleanup?.resources ?? [], - { reason: message(cause) }, + { reason: errorMessage(cause) }, { cause, operation }, ); bindArtifactFileCleanup(cause, cleanup); @@ -249,7 +247,7 @@ export const runKunaCommand = async ( ? cancelledBy(request.operation, carriedReason(cancellation.reason)) : new ProviderAdapterError(KUNA_PROVIDER_ID, request.operation, { cause, - userMessage: `Cannot verify ${installation.executable}: ${message(cause)}`, + userMessage: `Cannot verify ${installation.executable}: ${errorMessage(cause)}`, }), }; } @@ -337,11 +335,7 @@ const copyIO = async ( try { return await operation(); } catch (cause: unknown) { - throw new ArtifactReaderFailure( - "io", - cause instanceof Error ? cause.message : String(cause), - { cause }, - ); + throw new ArtifactReaderFailure("io", errorMessage(cause), { cause }); } }; @@ -476,7 +470,7 @@ const commandFailure = ( kind: "failed", error: new ProviderAdapterError(KUNA_PROVIDER_ID, operation, { cause, - userMessage: `Cannot run ${request.installation.executable}: ${message(cause)}`, + userMessage: `Cannot run ${request.installation.executable}: ${errorMessage(cause)}`, }), }; const capturedOutput = capturedKunaOutput(cause.snapshot, cause.reason); diff --git a/src/kuna/KunaDoctor.ts b/src/kuna/KunaDoctor.ts index ee0f7be376..3244651e41 100644 --- a/src/kuna/KunaDoctor.ts +++ b/src/kuna/KunaDoctor.ts @@ -26,6 +26,7 @@ import { KUNA_VERIFIED_VERSION, KUNA_VERSION_PROBE_REMEDIATION, } from "./KunaRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Client settings consulted by this readiness probe. */ export const KUNA_DOCTOR_SETTINGS = [ @@ -230,7 +231,7 @@ const probeCleanupFailure = ( name: "version", ok: false, code: "cleanup_incomplete", - detail: `Kuna installation inspection could not confirm file cleanup: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `Kuna installation inspection could not confirm file cleanup: ${errorMessage(cause)}`, remediation: null, classification: "config_drift", details: { @@ -305,7 +306,7 @@ const cacheCheck = async ( name: "cache", ok: false, code: "open_options_invalid", - detail: `REA cannot write the Kuna cache root ${cacheRoot}: ${cause instanceof Error ? cause.message : String(cause)}`, + detail: `REA cannot write the Kuna cache root ${cacheRoot}: ${errorMessage(cause)}`, remediation: "Set REA_KUNA_CACHE_DIR to a directory the REA process user can write.", classification: "config_drift", @@ -350,7 +351,7 @@ const nearestDirectoryWritable = async ( reason: typeof absent === "string" ? absent - : `${candidate} is not writable: ${cause instanceof Error ? cause.message : String(cause)}`, + : `${candidate} is not writable: ${errorMessage(cause)}`, }; candidate = parent; } @@ -369,7 +370,7 @@ const entryAbsent = async (path: string): Promise => { } catch (cause: unknown) { return isMissing(cause) ? true - : `${path} cannot be inspected: ${cause instanceof Error ? cause.message : String(cause)}`; + : `${path} cannot be inspected: ${errorMessage(cause)}`; } }; diff --git a/src/kuna/KunaInstallation.ts b/src/kuna/KunaInstallation.ts index b03e560725..5dfb9194c2 100644 --- a/src/kuna/KunaInstallation.ts +++ b/src/kuna/KunaInstallation.ts @@ -53,6 +53,7 @@ import { KUNA_VERIFIED_VERSION, KUNA_VERSION_PROBE_REMEDIATION, } from "./KunaRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** `kuna --version` exits before loading specs or an input; it needs no budget beyond this. */ const VERSION_PROBE_TIMEOUT_MS = 10_000; @@ -281,9 +282,6 @@ const failure = ( diagnostics: Readonly>, ): Result => err({ code, reason, diagnostics }); -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - interface InstallationFileObservation { readonly phase: "fingerprint" | "identity"; readonly completedHash?: { readonly sha256: string; readonly bytes: number }; @@ -407,7 +405,7 @@ export const inspectKunaInstallation = async ( } catch (cause: unknown) { return failure( "executable_missing", - `Cannot execute REA_KUNA_COMMAND ${command}: ${message(cause)}. ${KUNA_COMMAND_REMEDIATION}`, + `Cannot execute REA_KUNA_COMMAND ${command}: ${errorMessage(cause)}. ${KUNA_COMMAND_REMEDIATION}`, { command }, ); } @@ -445,7 +443,7 @@ export const inspectKunaInstallation = async ( throw cause; return failure( "executable_missing", - `Cannot fingerprint ${executable}: ${message(stableFileHashCause(cause))}`, + `Cannot fingerprint ${executable}: ${errorMessage(stableFileHashCause(cause))}`, { command, executable }, ); } @@ -518,7 +516,7 @@ export const inspectKunaInstallation = async ( } return failure( "version_unresolved", - `${executable} --version failed: ${message(cause)}. ${KUNA_VERSION_PROBE_REMEDIATION}`, + `${executable} --version failed: ${errorMessage(cause)}. ${KUNA_VERSION_PROBE_REMEDIATION}`, { command, executable, @@ -607,14 +605,14 @@ export const inspectKunaInstallation = async ( } return failure( "executable_missing", - `Cannot observe ${executable} after its --version probe: ${message(stableFileHashCause(cause))}`, + `Cannot observe ${executable} after its --version probe: ${errorMessage(stableFileHashCause(cause))}`, { command, executable, version, verified: version === KUNA_VERIFIED_VERSION, identity_observation_phase: "post_probe", - identity_observation_failure: message(stableFileHashCause(cause)), + identity_observation_failure: errorMessage(stableFileHashCause(cause)), before_probe_sha256: beforeProbeFingerprint.sha256, before_probe_bytes: beforeProbeFingerprint.bytes, deadline_ms: deadline, diff --git a/src/kuna/KunaJsonStream.ts b/src/kuna/KunaJsonStream.ts index 28e01d740c..5bbedca065 100644 --- a/src/kuna/KunaJsonStream.ts +++ b/src/kuna/KunaJsonStream.ts @@ -17,6 +17,7 @@ import { err, ok, type Result } from "../domain/result.js"; import { KunaDocumentError } from "./KunaDocumentError.js"; import { kunaAddressFromJsonNumber } from "./KunaJson.js"; import { strictUtf8Decoder } from "../domain/strictUtf8.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * stream-json 3's synchronous tokenizer behind `parser`, which its @@ -86,9 +87,6 @@ const ADMISSION_INTERVAL_BYTES = 64 * 1024; /** Per-row reserve for the owner's arrays, sorting and projections. */ const ROW_REFERENCE_BYTES = 16; -const describe = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** * Longest key or kept number assembled. Kuna's field names and u64 decimals * are far shorter, so a longer key names no kept field and a longer kept @@ -259,7 +257,7 @@ export abstract class KunaJsonDocumentReader extends Writable { diagnostics: { code: cause.code, ...cause.facts }, userMessage: `${this.label} cannot be used`, }) - : this.unusable(describe(cause)); + : this.unusable(errorMessage(cause)); this.#text = ""; this.#inKey = false; this.#header = {}; diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index fccc6c2d0d..6661f3580b 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -73,6 +73,7 @@ import type { } from "./KunaProjectFiles.js"; import { KUNA_PROVIDER_ID } from "./KunaRelease.js"; import { releaseProducerIdentity } from "../filesystem/ProducerIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A manifest names five files and their digests; anything larger is not ours. */ const MANIFEST_MAX_BYTES = 64 * 1024; @@ -732,7 +733,7 @@ export class KunaProjectCache { const closeFailure = new ProviderCleanupError( KUNA_PROVIDER_ID, [retained.resource], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation: KUNA_EXPORT_OPERATION, cause: @@ -905,7 +906,7 @@ export class KunaProjectCache { const failure = new ProviderCleanupError( KUNA_PROVIDER_ID, copying.resources.cleanupResources, - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { cause, operation: KUNA_EXPORT_OPERATION }, ); bindArtifactFileCleanup(cause, failure); @@ -1384,7 +1385,7 @@ export class KunaProjectCache { const error = new ProviderCleanupError( KUNA_PROVIDER_ID, [path], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation: KUNA_EXPORT_OPERATION, cause }, ); const retained = { diff --git a/src/kuna/KunaProjectExport.ts b/src/kuna/KunaProjectExport.ts index 8c3e0a3566..ab19d48d85 100644 --- a/src/kuna/KunaProjectExport.ts +++ b/src/kuna/KunaProjectExport.ts @@ -59,6 +59,7 @@ import { RegularFileCleanupFailure, regularFileCancellation, } from "../filesystem/OwnedRegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Operation name every export and cache failure reports. */ export const KUNA_EXPORT_OPERATION = "kuna:decompile-project"; @@ -153,9 +154,6 @@ export interface KunaExportRequest { readonly deadline: KunaDeadline; } -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const isMissing = (cause: unknown): boolean => cause instanceof Error && "code" in cause && @@ -164,7 +162,7 @@ const isMissing = (cause: unknown): boolean => const projectCacheFailure = (cause: unknown) => new ProviderAdapterError(KUNA_PROVIDER_ID, KUNA_EXPORT_OPERATION, { cause, - userMessage: `Kuna project cache failed: ${message(cause)}`, + userMessage: `Kuna project cache failed: ${errorMessage(cause)}`, }); /** A project-cache read's own report, apart from its cleanup. */ diff --git a/src/kuna/KunaProjectReader.ts b/src/kuna/KunaProjectReader.ts index 7d75472feb..31e715e459 100644 --- a/src/kuna/KunaProjectReader.ts +++ b/src/kuna/KunaProjectReader.ts @@ -41,6 +41,7 @@ import { KUNA_PROVIDER_ID } from "./KunaRelease.js"; import type { PseudocodeAbsence } from "../domain/native/pseudocodeAbsence.js"; import { KUNA_FUNCTION_TEXT_BYTES } from "./KunaLimits.js"; import { kunaUnavailable } from "./KunaUnavailable.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The exact producing range for one facet, including a failed C block. */ export interface KunaProjectFileSpan { @@ -241,10 +242,7 @@ const spanCloseFailure = ( failure: RegularFileCleanupFailure, ownership: KunaSpanOwnership, ): AnalysisError => { - const reason = - failure.cleanupCause instanceof Error - ? failure.cleanupCause.message - : String(failure.cleanupCause); + const reason = errorMessage(failure.cleanupCause); const completed = failure.outcome.kind === "completed"; const marker = new ProviderCleanupError( KUNA_PROVIDER_ID, @@ -277,10 +275,7 @@ const spanCloseFailure = ( ? primaryCause : new ProviderAdapterError(KUNA_PROVIDER_ID, operation, { cause: primaryCause, - userMessage: - primaryCause instanceof Error - ? primaryCause.message - : String(primaryCause), + userMessage: errorMessage(primaryCause), }); return analysisErrorWithCleanupDependencies(primary, marker, operation); }; diff --git a/src/kuna/KunaReferenceFiles.ts b/src/kuna/KunaReferenceFiles.ts index 161d01ab6f..4464057071 100644 --- a/src/kuna/KunaReferenceFiles.ts +++ b/src/kuna/KunaReferenceFiles.ts @@ -8,6 +8,7 @@ import { compareKunaAddresses } from "./KunaAddress.js"; import { KunaDocumentError } from "./KunaDocumentError.js"; import { parseKunaJson } from "./KunaJson.js"; import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The raw xref budget also bounds its materialized rows. */ export const KUNA_XREF_OUTPUT_BYTES = 16 * 1024 * 1024; @@ -387,7 +388,7 @@ export const parseKunaIncomingReferences = ( ); } return err({ - code: cause instanceof Error ? cause.message : String(cause), + code: errorMessage(cause), }); } }; diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts index 34fe4f1857..9296bd7fe3 100644 --- a/src/kuna/KunaSessionClient.ts +++ b/src/kuna/KunaSessionClient.ts @@ -136,6 +136,7 @@ import { kunaUnavailable } from "./KunaUnavailable.js"; import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { kunaQueryFailureForCaller } from "./KunaQueryErrors.js"; import type { PseudocodeAbsence } from "../domain/native/pseudocodeAbsence.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** How often a request waiting on the project export reports that it still waits. */ const WAIT_PROGRESS_INTERVAL_MS = 10_000; @@ -238,10 +239,6 @@ const isUnavailableProject = (cause: unknown): boolean => cause.code === "ENOTDIR" || cause.code === "ESTALE"); -/** Read through a call so a check before an await does not narrow later ones. */ -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** How one Kuna session operation reports a failure nothing typed it as. */ const kunaSessionDialect = (operation: string): ProviderFailureDialect => ({ providerId: KUNA_PROVIDER_ID, @@ -249,7 +246,7 @@ const kunaSessionDialect = (operation: string): ProviderFailureDialect => ({ unclassified: (cause) => new ProviderAdapterError(KUNA_PROVIDER_ID, operation, { cause, - userMessage: `Kuna ${operation} failed: ${message(cause)}`, + userMessage: `Kuna ${operation} failed: ${errorMessage(cause)}`, }), }); @@ -2331,11 +2328,7 @@ export class KunaSessionClient implements AnalysisClient { KUNA_PROVIDER_ID, failures.map(({ path }) => path), { - reason: failures - .map(({ cause }) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + reason: failures.map(({ cause }) => errorMessage(cause)).join("; "), }, { operation, diff --git a/src/kuna/KunaTargetCommands.ts b/src/kuna/KunaTargetCommands.ts index fa4e3a830f..ab86849ef0 100644 --- a/src/kuna/KunaTargetCommands.ts +++ b/src/kuna/KunaTargetCommands.ts @@ -46,6 +46,7 @@ import { type ProviderFailureDialect, } from "../providers/classifyProviderFailure.js"; import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface WorkspaceRoot { readonly root: PrivateRuntimeRoot; @@ -317,7 +318,7 @@ export class KunaTargetCommands { const failure = new ProviderCleanupError( KUNA_PROVIDER_ID, [owned.root.path], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { cause }, ); owned.cleanup.bindCleanupError(failure); @@ -449,7 +450,7 @@ export class KunaTargetCommands { ? cause : new ProviderAdapterError(KUNA_PROVIDER_ID, "kuna:workspace", { cause, - userMessage: `Kuna workspace failed: ${cause instanceof Error ? cause.message : String(cause)}`, + userMessage: `Kuna workspace failed: ${errorMessage(cause)}`, }), owned, ); @@ -470,7 +471,7 @@ export class KunaTargetCommands { const cleanup = new ProviderCleanupError( KUNA_PROVIDER_ID, [owned.root.path], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { cause, operation: "kuna:workspace" }, ); owned.cleanup.bindCleanupError(cleanup); diff --git a/src/main/deferredRuntime.ts b/src/main/deferredRuntime.ts index b68df34218..f890010c95 100644 --- a/src/main/deferredRuntime.ts +++ b/src/main/deferredRuntime.ts @@ -19,6 +19,7 @@ import { SERVER_START_FAILED } from "./messages.js"; import { reportMcpTransportError } from "./reportMcpTransportError.js"; import { OwnedMcpServers } from "./OwnedMcpServers.js"; import { COMPACT_INPUT_SCHEMA_PRESENTATION } from "../contracts/mcpSchemaPresentation.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Verify the build-owned artifact before trusting its exact typed projection. */ const readCatalog = (): RecordedMcpCatalog => { @@ -245,10 +246,7 @@ export const runDeferred = async ( } } catch (cause) { finishServing(); - serverLogger.error( - { error: cause instanceof Error ? cause.message : String(cause) }, - SERVER_START_FAILED, - ); + serverLogger.error({ error: errorMessage(cause) }, SERVER_START_FAILED); try { await close(); } catch (cleanupCause) { diff --git a/src/main/transport.ts b/src/main/transport.ts index 7d6f2198bc..77ff995175 100644 --- a/src/main/transport.ts +++ b/src/main/transport.ts @@ -15,6 +15,7 @@ import { mcpHttpListenFailed, } from "./messages.js"; import { reportMcpTransportError } from "./reportMcpTransportError.js"; +import { errorMessage } from "../kernel/errorMessage.js"; interface ServerContext { readonly analysisSettings?: AnalysisSettings; @@ -57,7 +58,7 @@ export const startMcpTransport = async ( } catch (cause: unknown) { serverLogger.warn( { - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), }, "Optional MCP providers could not load; affected tools remain unavailable", ); @@ -185,7 +186,7 @@ export const startMcpTransport = async ( : MCP_CONNECTION_START_FAILED; serverLogger.error( { - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), }, startFailure, ); @@ -197,10 +198,7 @@ export const startMcpTransport = async ( optionalProviderCleanup, ]) { if (cleanup.status === "rejected") { - const reason = - cleanup.reason instanceof Error - ? cleanup.reason.message - : String(cleanup.reason); + const reason = errorMessage(cleanup.reason); serverLogger.error( { cleanup_error: reason }, "Provider cleanup rejected after MCP startup", diff --git a/src/mcpDoctor.ts b/src/mcpDoctor.ts index 8abf674e8c..c30a578831 100644 --- a/src/mcpDoctor.ts +++ b/src/mcpDoctor.ts @@ -39,6 +39,7 @@ import { MCP_DOCTOR_ALIAS, MCP_DOCTOR_OPTIONS } from "./mcpDoctorOptions.js"; import { OwnedMcpStdioTransport } from "./process/OwnedMcpStdioTransport.js"; import { isRecord } from "./domain/isRecord.js"; import { resolveMcpOutputSchemaProfile } from "./contracts/mcpSchemaPresentation.js"; +import { errorMessage } from "./kernel/errorMessage.js"; const OUTPUT_FORMATS = CLI_DOCUMENT_OUTPUT_FORMATS; type OutputFormat = (typeof OUTPUT_FORMATS)[number]; @@ -671,9 +672,6 @@ const captureStderr = () => { }; }; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Report the transport's typed cleanup reason and the resources it retains. */ const cleanupFailureDetail = (cause: unknown): string => { const detail = `MCP stdio cleanup failed: ${errorMessage(cause)}`; diff --git a/src/model/ModelArtifactProvider.ts b/src/model/ModelArtifactProvider.ts index 7b8de6b5ff..8ab8327f9d 100644 --- a/src/model/ModelArtifactProvider.ts +++ b/src/model/ModelArtifactProvider.ts @@ -54,6 +54,7 @@ import { isSelectedRegularFileError, sameRegularFileState, } from "../filesystem/RegularFile.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_model_artifact"; /** One admitted descriptor and bounded report at a time; retained cleanup blocks new work. */ @@ -182,8 +183,7 @@ export class ModelArtifactProvider implements ModelArtifactPort { cause, diagnostics: { path: input.path, - reason: - primary instanceof Error ? primary.message : String(primary), + reason: errorMessage(primary), }, }); if ( diff --git a/src/native/AppleDispatchMetadata.ts b/src/native/AppleDispatchMetadata.ts index ade5d8a4aa..a5fbe15d80 100644 --- a/src/native/AppleDispatchMetadata.ts +++ b/src/native/AppleDispatchMetadata.ts @@ -68,6 +68,7 @@ import { } from "./AppleSwiftNominalTypes.js"; import { inspectObjcClassImportBindings } from "./AppleObjcClassImportBindings.js"; import { invariantViolation } from "../domain/internalInvariant.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Decode validated little-endian 64-bit Apple Objective-C metadata without loading target code. */ export function* decodeAppleDispatchMetadataSteps( @@ -559,7 +560,7 @@ const appleDispatchMetadataPrimaryFailure = ( cause, diagnostics: { target_path: path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/AppleObjcCategories.ts b/src/native/AppleObjcCategories.ts index dbacab52e0..3715117f25 100644 --- a/src/native/AppleObjcCategories.ts +++ b/src/native/AppleObjcCategories.ts @@ -10,6 +10,7 @@ import { } from "../domain/apple/appleDispatchDecodeFacts.js"; import { BinaryFormatFailure } from "../domain/binaryContainer.js"; import type { ObjcProtocolListResult } from "./AppleObjcProtocols.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const CLASS_SYMBOL = /^_OBJC_(?:META)?CLASS_\$_(.+)$/u; @@ -100,7 +101,7 @@ export const decodeObjcCategories = (input: { issue( "objc_properties_categories", "category_class_unresolved", - `Category ${name} class reference 0x${local.toString(16)}: ${cause instanceof Error ? cause.message : String(cause)}`, + `Category ${name} class reference 0x${local.toString(16)}: ${errorMessage(cause)}`, `0x${(category + 8n).toString(16)}`, ), ); @@ -176,7 +177,7 @@ export const decodeObjcCategories = (input: { }); } catch (cause: unknown) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); input.issues.push( issue( "objc_properties_categories", diff --git a/src/native/AppleObjcClassImportBindings.ts b/src/native/AppleObjcClassImportBindings.ts index 13e1c68018..ad0a2bf779 100644 --- a/src/native/AppleObjcClassImportBindings.ts +++ b/src/native/AppleObjcClassImportBindings.ts @@ -1,6 +1,7 @@ import type { PointerFixups } from "../domain/apple/appleMachoFixups.js"; import type { MachoLayout } from "../domain/apple/appleMachoSelection.js"; import type { MachoImportBinding } from "../domain/native/objcSwiftMetadata.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface ObjcClassImportBindingScan { readonly bindings: readonly MachoImportBinding[]; @@ -107,9 +108,7 @@ export const inspectObjcClassImportBindings = (input: { addend: decoded.addend.toString(10), }); } catch (cause: unknown) { - reasons.add( - `${requestedAddress}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + reasons.add(`${requestedAddress}: ${errorMessage(cause)}`); } } diff --git a/src/native/AppleObjcDispatchFacets.ts b/src/native/AppleObjcDispatchFacets.ts index 0704ec0aa0..93d2b9aabb 100644 --- a/src/native/AppleObjcDispatchFacets.ts +++ b/src/native/AppleObjcDispatchFacets.ts @@ -16,6 +16,7 @@ import type { DispatchRecordBudget, ResolvedMetadataLocation, } from "./AppleSwiftDispatchFacets.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Byte readers shared by Objective-C class/method/ivar decode facets. */ export interface ObjcDispatchReaders { @@ -71,7 +72,7 @@ const resolveSuperclass = ( } catch (cause: unknown) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; failures.push( - `Superclass pointer ${hex(superclass)} of ${className} could not be decoded: ${cause instanceof Error ? cause.message : String(cause)}`, + `Superclass pointer ${hex(superclass)} of ${className} could not be decoded: ${errorMessage(cause)}`, ); return { name: null, address: hex(superclass) }; } @@ -252,9 +253,7 @@ export const decodeObjcDispatchFacets = (input: { } catch (cause: unknown) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; const admitted = budget.admit(); - failures.push( - `${hex(field)}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`${hex(field)}: ${errorMessage(cause)}`); return err(admitted ? "unmapped" : "exhausted"); } }; @@ -286,9 +285,7 @@ export const decodeObjcDispatchFacets = (input: { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; // record() admits the slot itself before decoding, so admitting // again here would count one protocol twice. - failures.push( - `${hex(field)}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`${hex(field)}: ${errorMessage(cause)}`); } } } @@ -427,9 +424,7 @@ export const decodeObjcDispatchFacets = (input: { readClass(read.pointer(address), true); } catch (cause) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; - failures.push( - `Metaclass of ${name}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`Metaclass of ${name}: ${errorMessage(cause)}`); } } }; @@ -464,9 +459,7 @@ export const decodeObjcDispatchFacets = (input: { // admitting again here would count one class twice: at the budget // boundary it would break before appending the failure reason, and // with larger limits malformed classes would starve valid ones. - failures.push( - `${hex(field)}: ${cause instanceof Error ? cause.message : String(cause)}`, - ); + failures.push(`${hex(field)}: ${errorMessage(cause)}`); } } } diff --git a/src/native/AppleObjcProperties.ts b/src/native/AppleObjcProperties.ts index 5c41d8c35d..1e7556e2e3 100644 --- a/src/native/AppleObjcProperties.ts +++ b/src/native/AppleObjcProperties.ts @@ -7,6 +7,7 @@ import { issue, type DecodeIssue, } from "../domain/apple/appleDispatchDecodeFacts.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type ObjcProperty = z.infer; @@ -154,7 +155,7 @@ export const readObjcPropertyList = ( if (expectedAppleMetadataReadFailure(cause) === null) throw cause; issues.push({ code: "property_decode_failed", - message: `property ${String(index)} could not be decoded: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `property ${String(index)} could not be decoded: ${errorMessage(cause)}`, location, }); } @@ -199,7 +200,7 @@ export const readObjcPropertiesOf = ( issue( "objc_properties_categories", "property_decode_failed", - `${context.owner}: ${cause instanceof Error ? cause.message : String(cause)}`, + `${context.owner}: ${errorMessage(cause)}`, location, ), ); diff --git a/src/native/AppleObjcProtocols.ts b/src/native/AppleObjcProtocols.ts index 2b7b0ac52c..016219168c 100644 --- a/src/native/AppleObjcProtocols.ts +++ b/src/native/AppleObjcProtocols.ts @@ -9,6 +9,7 @@ import { readObjcPropertyList } from "./AppleObjcProperties.js"; import type { ObjcSwiftMetadata } from "../domain/native/objcSwiftMetadata.js"; import type { SwiftNominalReaders } from "./AppleSwiftNominalTypes.js"; import { err, ok, type Result } from "../domain/result.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A failed list still owns the names read before its unreadable suffix. */ export type ObjcProtocolListResult = Result< @@ -68,7 +69,7 @@ export const createObjcProtocolReader = (input: { return err({ _tag: "ProtocolListUnreadable", names, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }); } }; @@ -201,9 +202,7 @@ export const createObjcProtocolReader = (input: { propertyReasons.push("protocol class properties are not decoded"); } catch (cause) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; - propertyReasons.push( - cause instanceof Error ? cause.message : String(cause), - ); + propertyReasons.push(errorMessage(cause)); } for (const message of propertyReasons) failures.push( @@ -239,7 +238,7 @@ export const createObjcProtocolReader = (input: { } catch (cause) { if (expectedAppleMetadataReadFailure(cause) === null) throw cause; failures.push( - `Protocol 0x${address.toString(16)}: ${cause instanceof Error ? cause.message : String(cause)}`, + `Protocol 0x${address.toString(16)}: ${errorMessage(cause)}`, ); } }; diff --git a/src/native/LldbCallTracer.ts b/src/native/LldbCallTracer.ts index 361cabba6d..2c48087f2d 100644 --- a/src/native/LldbCallTracer.ts +++ b/src/native/LldbCallTracer.ts @@ -78,6 +78,7 @@ import { readPartialCapture, projectLldbPartialObservation, } from "./LldbRetainedObservations.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "observe_native_calls"; const PROVIDER = "native-macos"; @@ -303,7 +304,7 @@ export class LldbCallTracer implements NativeCallTracer { this.#pendingCleanup = owner; const failure = new ProviderAdapterError(PROVIDER, OPERATION, { cause, - diagnostics: { reason: errorReason(cause) }, + diagnostics: { reason: errorMessage(cause) }, partialObservation: partial.observation, ...(this.#pendingCleanup === owner ? { @@ -356,7 +357,7 @@ export class LldbCallTracer implements NativeCallTracer { this.#pendingCleanup = owner; if (primaryFailure?.cleanupIncomplete === true) bindLldbCleanup(primaryFailure, owner); - throw lldbCleanupFailure(owner, errorReason(cause), cause); + throw lldbCleanupFailure(owner, errorMessage(cause), cause); } }, // A cancellation keeps the trace as cancelled; a retained cleanup @@ -476,7 +477,7 @@ export class LldbCallTracer implements NativeCallTracer { } return lldbCleanupFailure( owner, - failures.map(errorReason).join("; "), + failures.map(errorMessage).join("; "), new AggregateError(failures, "LLDB cleanup remains incomplete"), ); } @@ -891,9 +892,7 @@ export class LldbCallTracer implements NativeCallTracer { result_failure: readback.error instanceof z.ZodError ? `Tracer result failed schema validation (${readback.error.issues.length} issues)` - : readback.error instanceof Error - ? readback.error.message - : String(readback.error), + : errorMessage(readback.error), } : {}), exit_code: exited.exitCode, @@ -939,10 +938,10 @@ export class LldbCallTracer implements NativeCallTracer { reason: "LLDB target output capture could not be read", ...(stdout.ok ? {} - : { stdout_capture_error: errorReason(stdout.error) }), + : { stdout_capture_error: errorMessage(stdout.error) }), ...(stderr.ok ? {} - : { stderr_capture_error: errorReason(stderr.error) }), + : { stderr_capture_error: errorMessage(stderr.error) }), ...(lifecycleCleanup === undefined ? {} : { target_cleanup: lifecycleCleanup }), @@ -1064,7 +1063,7 @@ const retainPartialReadFailures = ( : new AggregateError(readFailures, "LLDB partial readback failed"), diagnostics: { reason: "LLDB could not read all available partial observation data", - read_failures: readFailures.map(errorReason), + read_failures: readFailures.map(errorMessage), }, }); return failure.retainSecondaryFailure(readbackFailure, { @@ -1123,18 +1122,18 @@ const partialNativeObservation = async (options: { journalLimitations: journal.ok ? journal.value.limitations : [ - `The observation journal could not be read: ${errorReason(journal.error)}`, + `The observation journal could not be read: ${errorMessage(journal.error)}`, ], limitations: [ ...(stdout.ok ? stdout.value.limitations : [ - `The target stdout capture could not be read: ${errorReason(stdout.error)}`, + `The target stdout capture could not be read: ${errorMessage(stdout.error)}`, ]), ...(stderr.ok ? stderr.value.limitations : [ - `The target stderr capture could not be read: ${errorReason(stderr.error)}`, + `The target stderr capture could not be read: ${errorMessage(stderr.error)}`, ]), ], reason: options.reason, @@ -1292,9 +1291,6 @@ interface RetainedLldbResources { targetStopped: boolean; } -const errorReason = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Preserve compiler facts and a foreign helper marker without inventing an LLDB exit. */ const lldbPreparationFailure = ( cause: DarwinProcessOwnershipInspectionError, @@ -1538,8 +1534,7 @@ const runLldb = async ( targetIdentityFailure = observation.reason; } catch (cause: unknown) { observation = undefined; - targetIdentityFailure = - cause instanceof Error ? cause.message : String(cause); + targetIdentityFailure = errorMessage(cause); } if (observation?.state === "readable") targetIdentity = observation.identity; @@ -1594,7 +1589,7 @@ const runLldb = async ( ? { kind: "exited", exitCode: null, - output: cause instanceof Error ? cause.message : String(cause), + output: errorMessage(cause), } : { kind: interruption }, ); diff --git a/src/native/LldbRetainedObservations.ts b/src/native/LldbRetainedObservations.ts index 489ef6b594..ba734c21b6 100644 --- a/src/native/LldbRetainedObservations.ts +++ b/src/native/LldbRetainedObservations.ts @@ -10,6 +10,7 @@ import type { Result } from "../domain/result.js"; import { nativeCallEventSchema } from "../domain/native/nativeCallObservation.js"; import type { NativeCallPartialObservation } from "../domain/native/nativeCallPartialObservation.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface ParsedLldbJournal { readonly events: ReturnType[]; @@ -238,7 +239,7 @@ export const readLldbObservationJournal = ( : []), ...(read.status === "read-failure" ? [ - `The observation journal read failed after ${String(bytesRead)} bytes: ${errorReason(read.cause)}`, + `The observation journal read failed after ${String(bytesRead)} bytes: ${errorMessage(read.cause)}`, ] : []), ], @@ -275,7 +276,7 @@ export const readPartialCapture = ( : []), ...(read.status === "read-failure" ? [ - `A target output capture read failed after ${String(bytesRead)} bytes: ${errorReason(read.cause)}`, + `A target output capture read failed after ${String(bytesRead)} bytes: ${errorMessage(read.cause)}`, ] : []), ], @@ -284,6 +285,3 @@ export const readPartialCapture = ( ? { ...value, status: read.status, readFailure: read.cause } : { ...value, status: read.status }; }); - -const errorReason = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/native/NativeCallTarget.ts b/src/native/NativeCallTarget.ts index b6dc6b3523..c39620709b 100644 --- a/src/native/NativeCallTarget.ts +++ b/src/native/NativeCallTarget.ts @@ -27,6 +27,7 @@ import { ArtifactFileCleanupFailure, bindArtifactFileCleanup, } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "observe_native_calls"; @@ -75,7 +76,7 @@ export const nativeCallTargetFailure = ( path, phase: "target-digest", reason: "Unable to verify the selected target digest", - detail: physical instanceof Error ? physical.message : String(physical), + detail: errorMessage(physical), }, }); }; @@ -133,10 +134,7 @@ export const verifyNativeCallTarget = async ( [target.path], { phase: "target-digest-close", - reason: - cause.cleanupCause instanceof Error - ? cause.cleanupCause.message - : String(cause.cleanupCause), + reason: errorMessage(cause.cleanupCause), ...completed, }, { operation: OPERATION, cause: framed, cleanupPrimary: primary }, diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index ceb1cc67a6..2c78b6bb79 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -176,6 +176,7 @@ import { NativeUiInterruptionControl } from "./NativeUiInterruptionControl.js"; import type { ResolvedAppBundleResourceRoot } from "../domain/apple/bundleResourceRoot.js"; import { UnsupportedBinaryPlistUidError } from "../domain/apple/plistScalars.js"; import { NATIVE_COMMAND_OUTPUT_BUDGET_BYTES } from "../domain/native/nativeCommandOutput.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type SignatureRuntimeRootFactory = () => Promise< Pick @@ -1055,7 +1056,7 @@ class NativeMacOSClient implements AnalysisClient { diagnostics: { phase: "codesign-capture", path: this.target.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }), ); diff --git a/src/native/NativeMachoSource.ts b/src/native/NativeMachoSource.ts index 90c3ba6144..28ccb51922 100644 --- a/src/native/NativeMachoSource.ts +++ b/src/native/NativeMachoSource.ts @@ -9,6 +9,7 @@ import { hashStableRootArtifactHandle, targetDigestChangedFailure, } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A positional reader for one slice of the descriptor bound to the target. */ export interface NativeMachoSource { @@ -33,9 +34,7 @@ export class NativeMachoSourceVerificationFailure extends ArtifactReaderFailure verificationCause instanceof ArtifactReaderFailure ? verificationCause.reason : "io", - verificationCause instanceof Error - ? verificationCause.message - : String(verificationCause), + errorMessage(verificationCause), { cause: verificationCause, ...(verificationCause instanceof ArtifactReaderFailure diff --git a/src/native/NativePlistSource.ts b/src/native/NativePlistSource.ts index 586fbaf058..272691ed27 100644 --- a/src/native/NativePlistSource.ts +++ b/src/native/NativePlistSource.ts @@ -42,6 +42,7 @@ import { MAX_NATIVE_PLIST_BYTES, NATIVE_PLIST_INPUT_ALLOWANCE, } from "./parsers/plist.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Resolved lookup identity and selection intent, independent of file readiness. @@ -250,7 +251,7 @@ const nativePlistPrimaryFailure = ( cause, diagnostics: { phase: "plist-scope", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); const { path } = selection; @@ -283,7 +284,7 @@ const nativePlistPrimaryFailure = ( diagnostics: { path, phase: "plist-file", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/NativeUiCleanupError.ts b/src/native/NativeUiCleanupError.ts index c5db91803a..6a936c2311 100644 --- a/src/native/NativeUiCleanupError.ts +++ b/src/native/NativeUiCleanupError.ts @@ -2,6 +2,7 @@ import { AnalysisCleanupLeaseGroup } from "../resources/index.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { NativeUiObservationResult } from "../domain/native/nativeUiObservation.js"; import type { NativeUiHelperRuntime } from "./NativeUiHelperRuntime.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Exact runtime owners remain reachable for standalone callers' cleanup retry. */ export class NativeUiCleanupError extends ProviderCleanupError { @@ -27,7 +28,7 @@ export class NativeUiCleanupError extends ProviderCleanupError { reason: "Native UI runtime cleanup remains incomplete", failures: failures.map(({ runtime, cause }) => ({ resources: [...runtime.resources()], - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), })), }, { diff --git a/src/native/NativeUiObservation.ts b/src/native/NativeUiObservation.ts index 7ed923052c..80de344f83 100644 --- a/src/native/NativeUiObservation.ts +++ b/src/native/NativeUiObservation.ts @@ -36,6 +36,7 @@ import { NATIVE_UI_OUTPUT_WEIGHT, } from "./NativeUiOutputBudget.js"; import { NativeUiInterruptionControl } from "./NativeUiInterruptionControl.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const helper = fileURLToPath( new URL("../../bridge/native/ReaNativeUI.swift", import.meta.url), @@ -284,7 +285,7 @@ const observeWithHelper = async ( cause, diagnostics: { helper_path: helper, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), remediation: "Native helper failed, timed out, or returned malformed capture data; install compatible Xcode command-line tools and inspect local OS permissions", }, diff --git a/src/native/SignatureTargetBinding.ts b/src/native/SignatureTargetBinding.ts index ce23efe1ef..f264c7e3e2 100644 --- a/src/native/SignatureTargetBinding.ts +++ b/src/native/SignatureTargetBinding.ts @@ -38,6 +38,7 @@ import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { finalizedResult, runOwned } from "../providers/runOwned.js"; import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacosProviderIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type SignatureOwner = Extract< ArtifactResourceOwner, @@ -93,7 +94,7 @@ const signatureReadFailure = ( path: target.path, phase: "target-version-binding", system_code: typeof code === "string" ? code : null, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }, ); @@ -244,7 +245,7 @@ const signatureCleanupFailure = ( NATIVE_MACOS_PROVIDER_IDENTITY.id, resources, { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), phase: `signature-snapshot-${phase}`, path: target.path, }, @@ -270,7 +271,7 @@ const snapshotFailure = ( diagnostics: { path: target.path, phase: `signature-snapshot-${phase}`, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }, ); diff --git a/src/native/apple/AppleIpsProvider.ts b/src/native/apple/AppleIpsProvider.ts index 9e8b577b2e..b47878765e 100644 --- a/src/native/apple/AppleIpsProvider.ts +++ b/src/native/apple/AppleIpsProvider.ts @@ -41,6 +41,7 @@ import { } from "./AppleIps.errors.js"; import { parseAppleIps } from "./AppleIpsParser.js"; import { resolveAppleIpsJoin } from "./AppleIpsMachOJoin.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_apple_ips"; @@ -310,7 +311,7 @@ const appleIpsFailurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/exports/NativeExportsProvider.ts b/src/native/exports/NativeExportsProvider.ts index 2cbad9552c..bf6731a3fa 100644 --- a/src/native/exports/NativeExportsProvider.ts +++ b/src/native/exports/NativeExportsProvider.ts @@ -36,6 +36,7 @@ import { type NativeExportLimit, parseNativeExports, } from "../../domain/native/nativeExportParser.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_native_exports"; @@ -168,7 +169,7 @@ const nativeExportsFailurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/hardening/BinaryHardeningProvider.ts b/src/native/hardening/BinaryHardeningProvider.ts index 1ca022ed52..33769c8d4f 100644 --- a/src/native/hardening/BinaryHardeningProvider.ts +++ b/src/native/hardening/BinaryHardeningProvider.ts @@ -32,6 +32,7 @@ import { BinaryResourceFailure } from "../../domain/binaryContainer.js"; import { readElfHardening } from "./ElfHardening.js"; import { readMachoHardening } from "./MachoHardening.js"; import { readPeHardening } from "./PeHardening.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_binary_hardening"; @@ -182,7 +183,7 @@ const binaryHardeningFailurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/initializers/NativeInitializersProvider.ts b/src/native/initializers/NativeInitializersProvider.ts index d322dca971..d958d5860b 100644 --- a/src/native/initializers/NativeInitializersProvider.ts +++ b/src/native/initializers/NativeInitializersProvider.ts @@ -36,6 +36,7 @@ import { ElfPointerRelocationFailure } from "../../domain/native/elfPointerReloc import { requireSelectedNativeImage } from "../../domain/apple/machoSliceSelection.js"; import { readElfInitializers } from "./ElfInitializers.js"; import { readMachoInitializers } from "./MachoInitializers.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_native_initializers"; @@ -261,7 +262,7 @@ const failurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/parsers/plist.ts b/src/native/parsers/plist.ts index abf25c1ba0..188b2f647a 100644 --- a/src/native/parsers/plist.ts +++ b/src/native/parsers/plist.ts @@ -45,6 +45,7 @@ import { XmlPlistTextDecodeError, } from "../../domain/propertyListXmlText.js"; import { decodeStrictUtf8 } from "../../domain/strictUtf8.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** * Input ceiling matches native command output; projection is bounded separately. @@ -102,7 +103,7 @@ const plistNestingError = (cause: unknown): AnalysisResourceConstraintError => new AnalysisResourceConstraintError( "inspect_plist", "memory", - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), { maximum_nesting_depth: MAX_NATIVE_PLIST_NESTING_DEPTH }, { cause, @@ -139,11 +140,9 @@ const plistOutputError = (cause: unknown, reason?: string): PlistParseError => { if (cause instanceof InternalInvariantError) throw cause; return cause instanceof PlistNestingLimitError ? plistNestingError(cause) - : new AnalysisOutputError( - "inspect_plist", - reason ?? (cause instanceof Error ? cause.message : String(cause)), - { cause }, - ); + : new AnalysisOutputError("inspect_plist", reason ?? errorMessage(cause), { + cause, + }); }; /** diff --git a/src/native/pe/PeBinaryFailure.ts b/src/native/pe/PeBinaryFailure.ts index 25cd5981ce..edf929bdac 100644 --- a/src/native/pe/PeBinaryFailure.ts +++ b/src/native/pe/PeBinaryFailure.ts @@ -22,6 +22,7 @@ import { BinaryResourceFailure, binaryResourceAllowance, } from "../../domain/binaryContainer.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; interface PeBinaryInput { readonly path: string; @@ -102,7 +103,7 @@ const peBinaryFailurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/native/pe/PeCertificateAsn1.ts b/src/native/pe/PeCertificateAsn1.ts index 63cc20259a..046a05789f 100644 --- a/src/native/pe/PeCertificateAsn1.ts +++ b/src/native/pe/PeCertificateAsn1.ts @@ -4,6 +4,7 @@ import { Asn1BerReader, type Asn1BerNode, } from "../../domain/asn1Ber.js"; +import { byteToHex } from "../../kernel/byteToHex.js"; const OID_NAMES: Readonly> = { "1.2.840.113549.1.7.1": "data", @@ -219,7 +220,7 @@ const decodeDirectoryString = ( return node.content.toString("latin1"); default: return fail( - `Unsupported certificate name encoding (DER tag 0x${node.tag.toString(16).padStart(2, "0")}).`, + `Unsupported certificate name encoding (DER tag 0x${byteToHex(node.tag)}).`, ); } }; diff --git a/src/native/pwndbg/PwndbgCoreContext.ts b/src/native/pwndbg/PwndbgCoreContext.ts index 7fe9744b02..c7c94fbccc 100644 --- a/src/native/pwndbg/PwndbgCoreContext.ts +++ b/src/native/pwndbg/PwndbgCoreContext.ts @@ -45,6 +45,7 @@ import { } from "../../domain/native/pwntoolsResourceLimits.js"; import { readPwntoolsFailureEvidence } from "../pwntools/PwntoolsResourceLimits.js"; import type { PwntoolsCommand } from "../pwntools/PwntoolsDecoder.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_recorded_crash"; const replySchema = z.discriminatedUnion("ok", [ @@ -75,7 +76,7 @@ interface ConfiguredPathRefusal { } const hostPathRefusal = (cause: unknown): ConfiguredPathRefusal => ({ - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), cause, }); @@ -284,7 +285,7 @@ export const inspectPwndbgCore = async ({ } const error = new AnalysisOutputError( OPERATION, - `Core-only debugger reply failed: ${cause instanceof Error ? cause.message : String(cause)}`, + `Core-only debugger reply failed: ${errorMessage(cause)}`, { cause, ...(cause instanceof ArtifactReaderFailure && cause.reason === "limit" diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index ff3a4b675d..668a7cb443 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -82,6 +82,7 @@ import { import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsProviderIdentity.js"; import { pwntoolsInputBytes } from "../../config/pwntoolsInputLimit.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Names the detected host so a host refusal is not read as a target refusal. */ const pwntoolsHostRequirement = ( @@ -543,7 +544,7 @@ export class PwntoolsDecoder< } const error = new AnalysisOutputError( OPERATION, - `Owned pwntools decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : cause instanceof Error ? cause.message : String(cause)}`, + `Owned pwntools decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : errorMessage(cause)}`, { cause, capturedOutput, @@ -808,7 +809,7 @@ export class PwntoolsDecoder< failure = new ProviderCleanupError( this.identity.id, [this.#pendingCleanup?.root?.path ?? "pwntools decoder"], - { reason: cause instanceof Error ? cause.message : String(cause) }, + { reason: errorMessage(cause) }, { operation: this.profile.operation, cause }, ); } @@ -876,7 +877,7 @@ export class PwntoolsDecoder< ] : ownedCommandResources(ownership, pending.root?.path), { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), captured_output: { ...(pending.diagnostics ?? capturedProviderOutput(process.supervisor.snapshot())), @@ -950,7 +951,7 @@ export class PwntoolsDecoder< this.identity.id, [root.path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), ...(pending.diagnostics === undefined ? {} : { captured_output: { ...pending.diagnostics } }), diff --git a/src/native/pwntools/PwntoolsFailures.ts b/src/native/pwntools/PwntoolsFailures.ts index 09fc17d10c..b4b8b524e8 100644 --- a/src/native/pwntools/PwntoolsFailures.ts +++ b/src/native/pwntools/PwntoolsFailures.ts @@ -24,6 +24,7 @@ import { PWNTOOLS_FILE_SIZE_FAILURE_EXIT, } from "./PwntoolsRelease.js"; import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsProviderIdentity.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Operation identity supplied by each adapter sharing the pwntools boundary. */ export interface PwntoolsFailureContext { @@ -199,7 +200,7 @@ export const pwntoolsFailureDialect = ( cause, diagnostics: { ...pwntoolsPhaseDiagnostics(state), - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }), }; diff --git a/src/native/pwntools/PwntoolsResourceLimits.ts b/src/native/pwntools/PwntoolsResourceLimits.ts index 86399c5e77..79c8435eab 100644 --- a/src/native/pwntools/PwntoolsResourceLimits.ts +++ b/src/native/pwntools/PwntoolsResourceLimits.ts @@ -15,6 +15,7 @@ import { PWNTOOLS_FILE_SIZE_FAILURE_EXIT, } from "./PwntoolsRelease.js"; import { z } from "zod"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Actual limits reported by the owned bridge after lowering inherited soft limits. */ export const pwntoolsResourceLimitsSchema = z.strictObject({ @@ -76,8 +77,7 @@ export const readPwntoolsFailureEvidence = async ( ).catch((cause: unknown) => { const completed = completedStableArtifact(cause); if (completed === undefined) throw cause; - finalizationFailures["resource.failure"] = - cause instanceof Error ? cause.message : String(cause); + finalizationFailures["resource.failure"] = errorMessage(cause); return completed; }); const expected = @@ -92,10 +92,7 @@ export const readPwntoolsFailureEvidence = async ( } catch (markerFailure: unknown) { marker = { resource: null, - failure: - markerFailure instanceof Error - ? markerFailure.message - : String(markerFailure), + failure: errorMessage(markerFailure), }; } } @@ -118,8 +115,7 @@ export const readPwntoolsFailureEvidence = async ( ).catch((cause: unknown) => { const completed = completedStableArtifact(cause); if (completed === undefined) throw cause; - finalizationFailures["limits.json"] = - cause instanceof Error ? cause.message : String(cause); + finalizationFailures["limits.json"] = errorMessage(cause); return completed; }); const decoded = safeParseUtf8Json(reported.bytes); @@ -133,10 +129,7 @@ export const readPwntoolsFailureEvidence = async ( } catch (reportFailure: unknown) { limitReport = { limits: null, - failure: - reportFailure instanceof Error - ? reportFailure.message - : String(reportFailure), + failure: errorMessage(reportFailure), }; } } diff --git a/src/native/windows/WindowsShortcutParser.ts b/src/native/windows/WindowsShortcutParser.ts index 48021bb240..d3b3b82307 100644 --- a/src/native/windows/WindowsShortcutParser.ts +++ b/src/native/windows/WindowsShortcutParser.ts @@ -13,6 +13,7 @@ import type { } from "../../domain/native/windowsShortcut.js"; import { WindowsShortcutResourceFailure } from "./WindowsShortcut.errors.js"; import { malformedInput } from "../../domain/parseFailure.js"; +import { byteToHex } from "../../kernel/byteToHex.js"; type Artifact = WindowsShortcut["artifact"]; @@ -230,7 +231,7 @@ const uuidV1 = ( evidence_kind: "derived", version: 1, mac: [...bytes.subarray(offset + 10, offset + 16)] - .map((byte) => byte.toString(16).padStart(2, "0")) + .map((byte) => byteToHex(byte)) .join(":"), timestamp_iso8601: isoFromUnsigned100ns(timestamp, UUID_UNIX_EPOCH), timestamp_100ns: timestamp.toString(10), diff --git a/src/native/windows/WindowsShortcutProvider.ts b/src/native/windows/WindowsShortcutProvider.ts index 2e8b41459f..51af3c2c67 100644 --- a/src/native/windows/WindowsShortcutProvider.ts +++ b/src/native/windows/WindowsShortcutProvider.ts @@ -38,6 +38,7 @@ import { type WindowsShortcutSelectedBoundary, } from "./WindowsShortcut.errors.js"; import { parseWindowsShortcut } from "./WindowsShortcutParser.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; const OPERATION = "inspect_windows_shortcut"; @@ -329,7 +330,7 @@ const windowsShortcutFailurePrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/pcap/PcapCommand.ts b/src/pcap/PcapCommand.ts index f857b4bb4d..f1198eb734 100644 --- a/src/pcap/PcapCommand.ts +++ b/src/pcap/PcapCommand.ts @@ -46,6 +46,7 @@ import { attributePcapLimitedExit, PCAP_LIMITER_REMEDIATION, } from "./PcapNativeBound.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export type PcapCommandLauncher = NonNullable< Parameters[2] @@ -281,7 +282,7 @@ export const runPcapCommand = async (options: { ); const outcome = providerOutcomeOf(cause); if (outcome === undefined) { - const diagnostic = cause instanceof Error ? cause.message : String(cause); + const diagnostic = errorMessage(cause); const details = { cause, ...cleanupDetails }; if (!commandAttempted) throw preparationFailure(diagnostic, details); // An errno the launcher raised without a spawn identity names no stage. diff --git a/src/pcap/PcapDnsWire.ts b/src/pcap/PcapDnsWire.ts index 3761a848f0..7028f82500 100644 --- a/src/pcap/PcapDnsWire.ts +++ b/src/pcap/PcapDnsWire.ts @@ -1,5 +1,6 @@ import { isIPv4, isIPv6 } from "node:net"; import { err, ok, type Result } from "../domain/result.js"; +import { byteToHex } from "../kernel/byteToHex.js"; interface DnsWireFailure { readonly kind: "invalid_dns_wire"; @@ -125,11 +126,7 @@ const decodeName = ( labels.push(label.toString("hex")); folded.push( [...label] - .map((byte) => - (byte >= 65 && byte <= 90 ? byte + 32 : byte) - .toString(16) - .padStart(2, "0"), - ) + .map((byte) => byteToHex(byte >= 65 && byte <= 90 ? byte + 32 : byte)) .join(""), ); at += length; diff --git a/src/pcap/PcapNativeBound.ts b/src/pcap/PcapNativeBound.ts index 04e8f77054..1c56d69486 100644 --- a/src/pcap/PcapNativeBound.ts +++ b/src/pcap/PcapNativeBound.ts @@ -20,6 +20,7 @@ import type { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResou import { prlimitCeilingArguments } from "../process/LinuxResourceLimits.js"; import type { runPcapCommand } from "./PcapCommand.js"; import type { ArtifactCommandPath } from "../process/ArtifactCommandPath.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const PRLIMIT_COMMAND_ENV = "REA_TSHARK_PRLIMIT_COMMAND"; /** Repair for an unusable selected capture limiter; readiness and admission share it. */ @@ -179,7 +180,7 @@ export const preparePcapNativeBound = async ( configuration_key: PRLIMIT_COMMAND_ENV, configured, }, - userMessage: `${reason} (${cause instanceof Error ? cause.message : String(cause)}) ${PCAP_LIMITER_REMEDIATION}`, + userMessage: `${reason} (${errorMessage(cause)}) ${PCAP_LIMITER_REMEDIATION}`, remediationAction: PCAP_LIMITER_REMEDIATION, }); } diff --git a/src/pcap/PcapProvider.ts b/src/pcap/PcapProvider.ts index 00c9e78956..c3e0f4cfbd 100644 --- a/src/pcap/PcapProvider.ts +++ b/src/pcap/PcapProvider.ts @@ -78,6 +78,7 @@ import { selectArtifactCommandPath, type ArtifactCommandPath, } from "../process/ArtifactCommandPath.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const FIELDS = [ "frame.number", @@ -324,7 +325,7 @@ export class PcapProvider { unclassified: (failure) => pcapToolUnavailable( operation, - `Cannot read selected Wireshark tool ${path}: ${failure instanceof Error ? failure.message : String(failure)}`, + `Cannot read selected Wireshark tool ${path}: ${errorMessage(failure)}`, { cause: failure }, ), }); @@ -638,7 +639,7 @@ export class PcapProvider { cause instanceof AnalysisCapabilityUnavailableError ? "executable_missing" : "version_unresolved", - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), // Keep the failing owner's repair, such as the limiter's; only an // unattributed tool failure falls back to the Wireshark guidance. remediation: @@ -825,7 +826,7 @@ export class PcapProvider { this.#resources.readCleanupFailure(read, primary, undefined, operation), unclassified: (cause) => new AnalysisProtocolError( - `Packet-capture analysis failed: ${cause instanceof Error ? cause.message : String(cause)}`, + `Packet-capture analysis failed: ${errorMessage(cause)}`, { cause }, ), }; diff --git a/src/pcap/PcapSnapshot.ts b/src/pcap/PcapSnapshot.ts index 594aa6338d..67cee7148d 100644 --- a/src/pcap/PcapSnapshot.ts +++ b/src/pcap/PcapSnapshot.ts @@ -27,6 +27,7 @@ import { runtimeControlCapabilityError, } from "../domain/runtimeControlUnavailableError.js"; import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_pcap_capture"; const MAX_CAPTURE_BYTES = 2 * 1024 ** 3; @@ -129,7 +130,7 @@ export class PcapSnapshot { { path: ["path"], reason: "invalid_value", - message: `Cannot read selected capture ${path}: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `Cannot read selected capture ${path}: ${errorMessage(cause)}`, }, ]); } diff --git a/src/process/ArtifactCommandPath.ts b/src/process/ArtifactCommandPath.ts index 7ea3f4084d..984d40563a 100644 --- a/src/process/ArtifactCommandPath.ts +++ b/src/process/ArtifactCommandPath.ts @@ -10,6 +10,7 @@ import { AnalysisAccessDeniedError, AnalysisArtifactChangedError, } from "../domain/analysisErrorCore.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** The selected launch spelling and the physical file whose bytes are fingerprinted. */ export interface ArtifactCommandPath { @@ -71,7 +72,7 @@ export const assertArtifactCommandPath = async ( ...failureOptions, diagnostics: { path: selected.invocationPath, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), system_code: systemCode ?? null, }, }); diff --git a/src/process/DarwinHelperCache.ts b/src/process/DarwinHelperCache.ts index f4db8b39aa..7fa6f93419 100644 --- a/src/process/DarwinHelperCache.ts +++ b/src/process/DarwinHelperCache.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { constants, type Stats } from "node:fs"; import { @@ -26,6 +25,7 @@ import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { withOwnedRegularFile } from "../filesystem/OwnedRegularFile.js"; import { readStableFileBytes } from "../filesystem/readStableFileBytes.js"; import { execFileOutput } from "./ExecFileOutput.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** Bumped when the entry layout or the key material changes meaning. */ const CACHE_FORMAT = 2; @@ -47,9 +47,6 @@ const manifestSchema = z.strictObject({ // Sticky directories let only an entry's owner rename or remove it. const STICKY = 0o1000; -const sha256 = (value: string | Uint8Array): string => - createHash("sha256").update(value).digest("hex"); - /** Per-user namespace REA owns for the compiled Darwin ownership helper. */ export const defaultDarwinHelperCacheDirectory = (home: string): string => appendCallerPath(home, "Library/Caches/rea/process-helper", "darwin"); @@ -206,7 +203,9 @@ export const createDarwinHelperCache = (options: { [string[], string, string] >([ Promise.all( - options.sources.map(async (source) => sha256(await readFile(source))), + options.sources.map(async (source) => + sha256Hex(await readFile(source)), + ), ), xcrun(["--find", "swiftc"], signal), xcrun(["--show-sdk-path"], signal), @@ -220,7 +219,7 @@ export const createDarwinHelperCache = (options: { fileIdentity(compilerPath), fileIdentity(join(sdkPath, "SDKSettings.json")), ]); - return sha256( + return sha256Hex( JSON.stringify({ format: CACHE_FORMAT, sources, @@ -327,7 +326,7 @@ export const createDarwinHelperCache = (options: { ); return helper !== undefined && helper.byteLength === manifest.data.size && - sha256(helper) === manifest.data.sha256 + sha256Hex(helper) === manifest.data.sha256 ? executable : undefined; }; @@ -407,7 +406,7 @@ export const createDarwinHelperCache = (options: { JSON.stringify({ format: CACHE_FORMAT, key: entryKey, - sha256: sha256(helper), + sha256: sha256Hex(helper), size: helper.byteLength, }), { mode: 0o600, flag: "wx" }, diff --git a/src/process/DarwinProcessRunTokenReader.ts b/src/process/DarwinProcessRunTokenReader.ts index 08c0b2d0d0..0e7f717084 100644 --- a/src/process/DarwinProcessRunTokenReader.ts +++ b/src/process/DarwinProcessRunTokenReader.ts @@ -42,6 +42,7 @@ import type { ProcessRunTokenObservation, ProcessTableEntry, } from "./ProcessOwnership.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const responseSchema = z.strictObject({ results: z.array( @@ -362,7 +363,7 @@ const compilerInspectionError = ( const suffix = diagnostics ? `: ${diagnostics}${truncationNote}` : outcome === undefined - ? `: ${cause instanceof Error ? cause.message : String(cause)}` + ? `: ${errorMessage(cause)}` : ": no compiler diagnostics were captured"; return new DarwinProcessOwnershipInspectionError( `${prefix} (${description})${suffix}`, diff --git a/src/process/OwnedCommand.ts b/src/process/OwnedCommand.ts index 86c696a32a..636c4cbb57 100644 --- a/src/process/OwnedCommand.ts +++ b/src/process/OwnedCommand.ts @@ -38,6 +38,7 @@ import { ProviderStartupDeadline, waitForAbortableDelay, } from "./ProviderDeadline.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A short-lived command failed its lifecycle or complete-output contract. */ export class OwnedCommandFailure extends Error { @@ -357,7 +358,7 @@ const collectOwnedCommand = async ( ? finishCommandInput(launched.process.stdin, (cause) => { inputFailure ??= { cause, - message: `stdin stream failed: ${cause instanceof Error ? cause.message : String(cause)}`, + message: `stdin stream failed: ${errorMessage(cause)}`, processError: cause instanceof Error ? cause : undefined, }; if (processFailure === undefined) { @@ -610,7 +611,6 @@ const consumeStdout = ( } return pipeline(stdout, sink, { signal }).then( () => undefined, - (cause: unknown) => - `stdout stream failed: ${cause instanceof Error ? cause.message : String(cause)}`, + (cause: unknown) => `stdout stream failed: ${errorMessage(cause)}`, ); }; diff --git a/src/process/OwnedDebuggerSessionRegistry.ts b/src/process/OwnedDebuggerSessionRegistry.ts index 60e8aee102..622ae390ec 100644 --- a/src/process/OwnedDebuggerSessionRegistry.ts +++ b/src/process/OwnedDebuggerSessionRegistry.ts @@ -14,6 +14,7 @@ import { retainedDebuggerCleanupFailure, type OwnedDebuggerStopResult, } from "./ownedDebuggerSession.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** What the registry needs from a persistent debugger session it owns. */ export interface RegisteredDebuggerSession { @@ -187,7 +188,7 @@ export class OwnedDebuggerSessionRegistry< .then(() => this.#options.stopProcess(session)) .catch((cause: unknown): OwnedDebuggerStopResult => ({ status: "incomplete", - reason: `${this.#options.stopFailurePrefix}: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `${this.#options.stopFailurePrefix}: ${errorMessage(cause)}`, })) .then((stopped) => { if (stopped.status !== "incomplete") { diff --git a/src/process/OwnedLease.ts b/src/process/OwnedLease.ts index 3bda3e1535..7ea91431dc 100644 --- a/src/process/OwnedLease.ts +++ b/src/process/OwnedLease.ts @@ -1,4 +1,3 @@ -import { createHash } from "node:crypto"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { chmod, mkdir, open, rm, rmdir } from "node:fs/promises"; import { constants as fsConstants } from "node:fs"; @@ -18,6 +17,7 @@ import { } from "../resources/index.js"; import { safeParseJson } from "../domain/safeJson.js"; +import { sha256Hex } from "../kernel/sha256Hex.js"; /** The process that holds a lease, as that process reports itself. */ export interface LeaseOwner { @@ -94,10 +94,7 @@ export const acquireOwnedLease = async (input: { if (cause instanceof ArtifactReaderFailure) cleanupCauses.set(error, cause); return error; }; - const key = createHash("sha256") - .update(JSON.stringify(input.identity)) - .digest("hex") - .slice(0, 32); + const key = sha256Hex(JSON.stringify(input.identity)).slice(0, 32); const resources = input.resources ?? new ArtifactResourceScope(); const owner = { runId: input.runId, processId: process.pid }; if (HOST_PLATFORM.platform === "win32") { diff --git a/src/process/OwnedMcpStdioTransport.ts b/src/process/OwnedMcpStdioTransport.ts index b437828f54..38afaea007 100644 --- a/src/process/OwnedMcpStdioTransport.ts +++ b/src/process/OwnedMcpStdioTransport.ts @@ -31,6 +31,7 @@ import { AnalysisCleanupLease, AnalysisCleanupLeaseGroup, } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Injectable acquisition seam; production owns a POSIX group or Windows job. */ export type OwnedMcpLauncher = ( @@ -318,7 +319,7 @@ export class OwnedMcpStdioTransport implements Transport { this.#releasedPreparations.add(owner); return; } catch (cause: unknown) { - reason = cause instanceof Error ? cause.message : String(cause); + reason = errorMessage(cause); } const failure = new ProviderCleanupError( this.settings.provider, diff --git a/src/process/OwnedWorkerRuntime.ts b/src/process/OwnedWorkerRuntime.ts index c2689fae0b..9cee691ad8 100644 --- a/src/process/OwnedWorkerRuntime.ts +++ b/src/process/OwnedWorkerRuntime.ts @@ -14,6 +14,7 @@ import type { AnalysisCleanupResourceOwner, AnalysisError, } from "../domain/analysisErrorBase.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface OwnedWorkerRuntimeOptions { readonly rootPrefix: string; @@ -431,7 +432,7 @@ export class OwnedWorkerRuntime { this.#cleanupEpoch = undefined; } catch (cause: unknown) { this.#registry.add(this); - throw this.#cleanupError(message(cause), cause); + throw this.#cleanupError(errorMessage(cause), cause); } } this.#closed = true; @@ -483,6 +484,3 @@ export class OwnedWorkerRuntime { ); } } - -const message = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/process/ProcessOwnership.ts b/src/process/ProcessOwnership.ts index 547fce0ecd..fc9fd3ce7d 100644 --- a/src/process/ProcessOwnership.ts +++ b/src/process/ProcessOwnership.ts @@ -6,7 +6,6 @@ import { promisify } from "node:util"; import { setTimeout as delay } from "node:timers/promises"; import { - errorMessage, readNativeProcessIdentityMap, readProcessOwnershipFacts, reobserveUnavailableTokenFacts, @@ -34,6 +33,7 @@ import { type ProcessLifecycleObservation, type ProcessExitSettlementBudget, } from "./ProcessLifecycle.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const execFileAsync = promisify(execFile); diff --git a/src/process/ProcessOwnershipObservation.ts b/src/process/ProcessOwnershipObservation.ts index 056bde8aee..43c9dd4449 100644 --- a/src/process/ProcessOwnershipObservation.ts +++ b/src/process/ProcessOwnershipObservation.ts @@ -64,6 +64,7 @@ import type { ProcessTableEntry, } from "./ProcessOwnership.js"; import type { ProcessOwnershipEvidenceOwner } from "./ProcessOwnershipEvidence.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Native preparation transfers its typed helper owner instead of an unavailable row. */ const rethrowInspectionFailure = (cause: unknown): void => { @@ -1986,6 +1987,3 @@ const processIsGone = async ( return false; } }; - -export const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/process/ProcessRunTokenObservations.ts b/src/process/ProcessRunTokenObservations.ts index 4272067eb6..838a908df1 100644 --- a/src/process/ProcessRunTokenObservations.ts +++ b/src/process/ProcessRunTokenObservations.ts @@ -9,6 +9,7 @@ import type { ProcessTableEntry, } from "./ProcessOwnership.js"; import { liveProcesses } from "./ProcessOwnershipProcessTree.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Structured native token availability, distinct from failed reads and caller cancellation. */ export class ProcessRunTokenReadError extends Error { @@ -23,9 +24,6 @@ export class ProcessRunTokenReadError extends Error { } } -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Only a variable observed on this process supplies its run token. */ export const processRunIdFromEnvironment = ( environment: Readonly>, diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.ts index 6f4094f12e..8930563254 100644 --- a/src/process/ProviderProcess.ts +++ b/src/process/ProviderProcess.ts @@ -40,6 +40,7 @@ import { type RuntimeExhaustion, } from "./RuntimeExhaustion.js"; import { isStrictUtf8 } from "../domain/strictUtf8.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const DEFAULT_TERMINATION_GRACE_MS = 250; const DEFAULT_KILL_GRACE_MS = 1_000; @@ -889,9 +890,7 @@ export class ProviderProcessSupervisor { if (this.#inspectionCleanup.size > 0) return this.#inspectionStopFailure( [...this.#inspectionCleanup.values()] - .map(({ cause }) => - cause instanceof Error ? cause.message : String(cause), - ) + .map(({ cause }) => errorMessage(cause)) .join("; "), ); if (this.launch.cleanup !== undefined) { diff --git a/src/process/RegularFileRead.ts b/src/process/RegularFileRead.ts index da253495d0..d5955ab339 100644 --- a/src/process/RegularFileRead.ts +++ b/src/process/RegularFileRead.ts @@ -28,6 +28,7 @@ import type { AnalysisCleanupObservation, AnalysisError, } from "../domain/analysisErrorBase.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A scope handoff preserves the same descriptor outcome and exact retry capability. */ export class RetainedRegularFileCleanupFailure< @@ -130,7 +131,7 @@ export const retryRegularFileCleanup = async ( cleanupLease: released.lease, failure: retained, cleanup: { - reason: `${failureMessage(failure.cleanupCause)}; retry: ${failureMessage(released.cause)}`, + reason: `${errorMessage(failure.cleanupCause)}; retry: ${errorMessage(released.cause)}`, resources: [failure.path], }, }; @@ -184,9 +185,6 @@ export const retryRegularFileCleanupFailures = async ( }; }; -const failureMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Completed stable read facts survive cancellation during descriptor finalization. */ export interface RegularFileCompletion { readonly value: Value; diff --git a/src/process/capture/ProcessCaptureLifecycle.ts b/src/process/capture/ProcessCaptureLifecycle.ts index 9b74f179d9..ff659dc32b 100644 --- a/src/process/capture/ProcessCaptureLifecycle.ts +++ b/src/process/capture/ProcessCaptureLifecycle.ts @@ -92,6 +92,7 @@ import type { TerminalFrame, } from "../../domain/process/processCapture.js"; import { partialProcessCaptureObservationSchema } from "../../domain/process/processCapture.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; interface TerminalExitOptions { readonly terminal: Pick; readonly scenario: ProcessScenario; @@ -822,7 +823,7 @@ export const describeUnverifiedCause = ( cause: unknown, fallback: string, ): string => { - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); return message.trim() === "" ? fallback : message; }; diff --git a/src/process/capture/ProcessTerminalObservation.ts b/src/process/capture/ProcessTerminalObservation.ts index a52958194a..1ca6af200e 100644 --- a/src/process/capture/ProcessTerminalObservation.ts +++ b/src/process/capture/ProcessTerminalObservation.ts @@ -8,6 +8,7 @@ import type { TerminalCaptureRetention, } from "./ProcessCaptureLifecycle.js"; import type { RenderedTerminalFrame } from "../../domain/process/processCapture.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; interface ProcessTerminalObservation { readonly retention: TerminalCaptureRetention; @@ -18,7 +19,7 @@ const terminalFailure = (cause: unknown): AnalysisError => cause instanceof AnalysisError ? cause : new ProcessCaptureError( - `Terminal observation failed: ${cause instanceof Error ? cause.message : String(cause)}`, + `Terminal observation failed: ${errorMessage(cause)}`, { cause }, ); diff --git a/src/process/ownedDebuggerSession.ts b/src/process/ownedDebuggerSession.ts index 3636d13523..ebf5a5b301 100644 --- a/src/process/ownedDebuggerSession.ts +++ b/src/process/ownedDebuggerSession.ts @@ -21,6 +21,7 @@ import type { import type { JsonValue } from "../domain/jsonValue.js"; import { parseLinuxProcessStat } from "./LinuxProcessStat.js"; import { OwnedDebuggerCleanupError } from "./ownedDebuggerCleanupError.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Result of terminating one debugger process owned by this application. */ export type OwnedDebuggerStopResult = @@ -325,8 +326,8 @@ const finishExitedDebuggerSession = async ( status: "incomplete", reason: platform === "win32" - ? `Owned ${debuggerName} Windows Job Object settlement could not be verified: ${cause instanceof Error ? cause.message : String(cause)}` - : `Owned ${debuggerName} inherited output stream settlement could not be verified: ${cause instanceof Error ? cause.message : String(cause)}`, + ? `Owned ${debuggerName} Windows Job Object settlement could not be verified: ${errorMessage(cause)}` + : `Owned ${debuggerName} inherited output stream settlement could not be verified: ${errorMessage(cause)}`, }; } if (platform !== "win32") session.supervisor.unrefOutputStreams(); @@ -366,7 +367,7 @@ export const stopOwnedDebuggerProcess = async ( } catch (cause: unknown) { return { status: "incomplete", - reason: `Owned ${debuggerName} inferior process identity could not be verified after debugger exit: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `Owned ${debuggerName} inferior process identity could not be verified after debugger exit: ${errorMessage(cause)}`, }; } } @@ -415,7 +416,7 @@ export const stopOwnedDebuggerProcess = async ( } catch (cause: unknown) { return { status: "incomplete", - reason: `Owned ${debuggerName} inferior detach could not be verified: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `Owned ${debuggerName} inferior detach could not be verified: ${errorMessage(cause)}`, }; } } diff --git a/src/process/privateWorkspaceFailure.ts b/src/process/privateWorkspaceFailure.ts index 6d74c303a2..89cf3374ad 100644 --- a/src/process/privateWorkspaceFailure.ts +++ b/src/process/privateWorkspaceFailure.ts @@ -1,6 +1,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Host storage exhaustion; only these errors establish a storage constraint. */ const STORAGE_EXHAUSTION_CODES: ReadonlySet = new Set([ @@ -41,7 +42,7 @@ export const privateWorkspaceFailure = ( ): AnalysisError => { const code = systemCode(cause); const path = systemPath(cause) ?? workspacePath; - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); if (code !== null && (STORAGE_EXHAUSTION_CODES.has(code) || code === "EFBIG")) return new AnalysisResourceConstraintError( operation, diff --git a/src/providers/OwnedCommandCleanup.ts b/src/providers/OwnedCommandCleanup.ts index 6a13ea06c8..685ee39851 100644 --- a/src/providers/OwnedCommandCleanup.ts +++ b/src/providers/OwnedCommandCleanup.ts @@ -21,6 +21,7 @@ import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js"; import { OwnedCommandFailure } from "../process/OwnedCommand.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Transfer exact helper and command cleanup capabilities to the caller's scope. */ export const retainOwnedCommandCleanup = ( @@ -49,10 +50,7 @@ export const retainOwnedCommandCleanup = ( providerId, [preparation.path], { - reason: - preparation.cleanupCause instanceof Error - ? preparation.cleanupCause.message - : String(preparation.cleanupCause), + reason: errorMessage(preparation.cleanupCause), }, { cause: preparation, operation }, ); diff --git a/src/providers/artifactResourceFailure.ts b/src/providers/artifactResourceFailure.ts index b80c313201..00bda8c4b3 100644 --- a/src/providers/artifactResourceFailure.ts +++ b/src/providers/artifactResourceFailure.ts @@ -15,6 +15,7 @@ import { classifyProviderFailure, type ProviderFailureDialect, } from "./classifyProviderFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * The dialect for a failure the artifact resources observed: a selected input @@ -35,8 +36,6 @@ export const artifactResourceDialect = ( : undefined; const captured = observedOutput === undefined ? {} : { capturedOutput: observedOutput }; - const reasonOf = (cause: unknown) => - cause instanceof Error ? cause.message : String(cause); const shared = { providerId, operation, @@ -71,7 +70,7 @@ export const artifactResourceDialect = ( { path: ["path"], reason: "invalid_value", - message: reasonOf(cause), + message: errorMessage(cause), }, ], ), @@ -97,7 +96,7 @@ export const artifactResourceDialect = ( diagnostics: { stage: "integrity", resource_path: context.path, - reason: reasonOf(cause), + reason: errorMessage(cause), }, }), }; diff --git a/src/providers/runOwned.ts b/src/providers/runOwned.ts index 0ea57b09a6..6c00a2c632 100644 --- a/src/providers/runOwned.ts +++ b/src/providers/runOwned.ts @@ -23,6 +23,7 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Result } from "../domain/result.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** What closing the work's owner established. */ export type CleanupOutcome = @@ -186,7 +187,7 @@ const closeFailure = ( options.fallbackResource ?? `${options.operation} resources`, ) : { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), resources: [], }; return new ProviderCleanupError( diff --git a/src/python/PythonPycProvider.ts b/src/python/PythonPycProvider.ts index e789424285..cc56c571b4 100644 --- a/src/python/PythonPycProvider.ts +++ b/src/python/PythonPycProvider.ts @@ -25,6 +25,7 @@ import { err, ok } from "../domain/result.js"; import { PythonPycResourceFailure } from "./PythonPyc.errors.js"; import { parseFailureAnalysisError } from "../domain/parseFailureAnalysisError.js"; import { parsePythonPyc } from "./PythonPycParser.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_python_pyc"; @@ -104,7 +105,7 @@ const failureForPrimary = ( cause, diagnostics: { path: input.path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/resources/ArtifactFileOperation.ts b/src/resources/ArtifactFileOperation.ts index 0ff4e99650..3371590a0e 100644 --- a/src/resources/ArtifactFileOperation.ts +++ b/src/resources/ArtifactFileOperation.ts @@ -25,6 +25,7 @@ import { import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { ArtifactLimitBoundary } from "../domain/artifactOperationError.js"; import { ParseFailureError, type LimitRef } from "../domain/parseFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Artifact projection plus the exact descriptor owner and physical operation outcome. */ export class ArtifactFileCleanupFailure< @@ -66,11 +67,9 @@ export class ArtifactFileCleanupFailure< fileCleanupFailure.operationFailure !== undefined && fileCleanupFailure.outcome.kind === "failed" && Object.is(primary, fileCleanupFailure.operationFailure.operationCause) - ? new ArtifactReaderFailure( - "io", - primary instanceof Error ? primary.message : String(primary), - { cause: primary }, - ) + ? new ArtifactReaderFailure("io", errorMessage(primary), { + cause: primary, + }) : primary, ArtifactReaderFailure.cleanupObservation( fileCleanupFailure.cleanupCause, diff --git a/src/resources/ArtifactReader.ts b/src/resources/ArtifactReader.ts index 4f630d17c5..bbe58ecc3b 100644 --- a/src/resources/ArtifactReader.ts +++ b/src/resources/ArtifactReader.ts @@ -24,6 +24,7 @@ import type { AnalysisCleanupObservation, AnalysisPartialObservation, } from "../domain/analysisErrorBase.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface ArtifactReaderFailureOptions extends ErrorOptions { /** Recovery guidance established by the producing adapter, separate from diagnostics. */ @@ -440,9 +441,6 @@ const combineCleanup = ( resources: [...new Set([...primary.resources, ...cleanup.resources])], }; -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - /** Read explicit source authority; unrelated domain cleanup remains unresolved. */ export const artifactPrimaryCleanupLeases = ( cause: unknown, diff --git a/src/resources/ArtifactResourceScope.ts b/src/resources/ArtifactResourceScope.ts index 23c1889b54..5ca7bf70ea 100644 --- a/src/resources/ArtifactResourceScope.ts +++ b/src/resources/ArtifactResourceScope.ts @@ -11,6 +11,7 @@ import { artifactPrimaryCleanupLeases, } from "./ArtifactReader.js"; import { AnalysisCleanupLease } from "./AnalysisCleanupLease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** * Capabilities the scope needs from an output tree and a private runtime @@ -275,11 +276,7 @@ export class ArtifactResourceScope { return err( new AggregateError( failures, - failures - .map((cause) => - cause instanceof Error ? cause.message : String(cause), - ) - .join("; "), + failures.map((cause) => errorMessage(cause)).join("; "), ), ); } diff --git a/src/resources/SafeOutputTree.ts b/src/resources/SafeOutputTree.ts index fb86ad89e3..3dd93a796a 100644 --- a/src/resources/SafeOutputTree.ts +++ b/src/resources/SafeOutputTree.ts @@ -41,6 +41,7 @@ import { type DirectoryIdentity, type FileIdentity, } from "./SafeOutputTreeIdentity.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** One file durably written to an operation-owned output tree. */ export interface SafeOutputFile { @@ -519,7 +520,7 @@ export class SafeOutputTree { if (!complete) throw new ArtifactReaderFailure( "integrity", - `Output cleanup could not be verified${removalFailure === undefined ? "" : `: ${removalFailure instanceof Error ? removalFailure.message : String(removalFailure)}`}`, + `Output cleanup could not be verified${removalFailure === undefined ? "" : `: ${errorMessage(removalFailure)}`}`, { integrityCheck: "output-lifecycle", cause: removalFailure, diff --git a/src/resources/SafeOutputTreeCreationFailure.ts b/src/resources/SafeOutputTreeCreationFailure.ts index b29f7618eb..c9bdd8332d 100644 --- a/src/resources/SafeOutputTreeCreationFailure.ts +++ b/src/resources/SafeOutputTreeCreationFailure.ts @@ -1,5 +1,6 @@ import { ArtifactReaderFailure } from "./ArtifactReader.js"; import type { SafeOutputTree } from "./SafeOutputTree.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Setup failed after this tree was acquired; callers still own this exact tree. */ export class SafeOutputTreeCreationFailure extends ArtifactReaderFailure { @@ -28,6 +29,3 @@ export class SafeOutputTreeCreationFailure extends ArtifactReaderFailure { this.tree = tree; } } - -const errorMessage = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index 72c88f6706..c8973c16e4 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -77,6 +77,7 @@ import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const CLEANUP_COMMAND_TIMEOUT_MS = 1_000; const STARTUP_TIMEOUT_MS = 30_000; @@ -521,7 +522,7 @@ export class RizinDebugSessionManager { { path: ["inferior_tty"], reason: "invalid_value", - message: `Cannot use selected terminal ${input.inferior_tty}: ${primaryCause instanceof Error ? primaryCause.message : String(primaryCause)}`, + message: `Cannot use selected terminal ${input.inferior_tty}: ${errorMessage(primaryCause)}`, }, ], ) diff --git a/src/rust/RustBinaryProvider.ts b/src/rust/RustBinaryProvider.ts index 8356fc3624..bdeb6c1c1f 100644 --- a/src/rust/RustBinaryProvider.ts +++ b/src/rust/RustBinaryProvider.ts @@ -46,6 +46,7 @@ import { type RustProducerLimits, } from "../domain/rust/rustResourceLimits.js"; import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "inspect_rust_binary"; @@ -389,7 +390,7 @@ const artifactFailure = ( cause, diagnostics: { path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }, }); }; diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 106bf23b0e..c6b85a0036 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -65,6 +65,7 @@ import { type McpOutputSchemaProfile, COMPACT_INPUT_SCHEMA_PRESENTATION, } from "../contracts/mcpSchemaPresentation.js"; +import { errorMessage } from "../kernel/errorMessage.js"; export interface CreateServerOptions extends CapabilityServiceOptions { readonly analysisSettings?: AnalysisSettings; @@ -318,7 +319,7 @@ export const createServer = ( void closeProviders().catch((cause: unknown) => { logger.error( { - error: cause instanceof Error ? cause.message : String(cause), + error: errorMessage(cause), ...retainedDebuggerDiagnostics(cause), }, "Provider cleanup failed during server shutdown", diff --git a/src/server/http/serveStreamableHttp.ts b/src/server/http/serveStreamableHttp.ts index 80bdff3622..edb74797e6 100644 --- a/src/server/http/serveStreamableHttp.ts +++ b/src/server/http/serveStreamableHttp.ts @@ -44,6 +44,7 @@ import { AnalysisResourceConstraintError, OwnerCancellation, } from "../../domain/analysisErrorCore.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** MCP endpoint path shared by `rea mcp --http` and agent environment servers. */ export const MCP_HTTP_PATH = "/mcp"; @@ -127,9 +128,6 @@ const jsonError = jsonRpcErrorResponse; const protocolOf = (instance: McpServer | Server): Server => "server" in instance ? instance.server : instance; -const describe = (cause: unknown): string => - cause instanceof Error ? cause.message : String(cause); - const NO_SHUTDOWN_HOOK = (): void => undefined; const SHUTTING_DOWN = (): Response => jsonError(503, -32000, "Server shutting down"); @@ -592,7 +590,7 @@ export const serveStreamableHttp = async ( httpServer.on("request", (request, response) => { void requests.handle(request, response).catch((cause: unknown) => { logger?.warn( - { error: describe(cause) }, + { error: errorMessage(cause) }, "MCP HTTP request did not complete", ); response.destroy(); @@ -713,7 +711,7 @@ const serveNodeRequest = async ( } catch (cause: unknown) { // A client that left mid-stream is routine; a failure before headers is not. logger?.[response.headersSent ? "debug" : "warn"]( - { error: describe(cause) }, + { error: errorMessage(cause) }, "MCP HTTP request did not complete", ); if (response.headersSent) response.destroy(); diff --git a/src/server/http/streamableHttpListenError.ts b/src/server/http/streamableHttpListenError.ts index aebe1298ba..cd9bed4811 100644 --- a/src/server/http/streamableHttpListenError.ts +++ b/src/server/http/streamableHttpListenError.ts @@ -1,4 +1,5 @@ import { err, ok, type Result } from "../../domain/result.js"; +import { errorMessage } from "../../kernel/errorMessage.js"; /** Parsed listener failure facts for recovery guidance. */ export type StreamableHttpListenFailure = @@ -115,8 +116,8 @@ export class StreamableHttpListenError extends Error { constructor(cause: unknown, phase: StreamableHttpListenPhase = "startup") { super( phase === "startup" - ? `MCP HTTP listener startup failed: ${cause instanceof Error ? cause.message : String(cause)}` - : `MCP HTTP listener failed after binding: ${cause instanceof Error ? cause.message : String(cause)}`, + ? `MCP HTTP listener startup failed: ${errorMessage(cause)}` + : `MCP HTTP listener failed after binding: ${errorMessage(cause)}`, { cause }, ); this.phase = phase; diff --git a/src/server/registerCloseLifecycleTool.ts b/src/server/registerCloseLifecycleTool.ts index c766b7537b..df039706bf 100644 --- a/src/server/registerCloseLifecycleTool.ts +++ b/src/server/registerCloseLifecycleTool.ts @@ -15,6 +15,7 @@ import { mcpProgressReporter } from "./mcpProgress.js"; import type { LifecycleToolRegistration } from "./registerSessionTools.js"; import { logToolExecution } from "./toolLogging.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Expected lifecycle failures keep the same typed result when a child rejects. */ const closeResult = async ( @@ -55,10 +56,7 @@ export const registerCloseLifecycleTool = ({ if (resourceClose.status === "rejected") logger.warn( { - error: - resourceClose.reason instanceof Error - ? resourceClose.reason.message - : String(resourceClose.reason), + error: errorMessage(resourceClose.reason), }, "Process capture cleanup threw while closing the session", ); diff --git a/src/server/registerSessionTools.ts b/src/server/registerSessionTools.ts index 267274d6ba..6a1cb0813a 100644 --- a/src/server/registerSessionTools.ts +++ b/src/server/registerSessionTools.ts @@ -42,6 +42,7 @@ import { logToolExecution } from "./toolLogging.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; import { withAdmittedAnalysis } from "./analysisAdmission.js"; import { runAdmittedToolOperation } from "./admittedToolOperation.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const recordProcessResidualUnknowns = ( session: BinarySessionPort, @@ -454,7 +455,7 @@ export const registerSessionTools = ( } finally { void processResources.close().catch((cause: unknown) => { logger.error( - { error: cause instanceof Error ? cause.message : String(cause) }, + { error: errorMessage(cause) }, "Process capture cleanup failed during server shutdown", ); }); diff --git a/src/signals/SigrokRecordingProvider.ts b/src/signals/SigrokRecordingProvider.ts index 468efe7da7..0d5d946da2 100644 --- a/src/signals/SigrokRecordingProvider.ts +++ b/src/signals/SigrokRecordingProvider.ts @@ -86,6 +86,7 @@ import { } from "../process/OwnedCommand.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { privateWorkspaceFailure } from "../process/privateWorkspaceFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OPERATION = "decode_signal_recording"; @@ -540,7 +541,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort { ), observedOutput, unclassified: (cause) => { - const reason = cause instanceof Error ? cause.message : String(cause); + const reason = errorMessage(cause); if (phase === "workspace") return privateWorkspaceFailure( SIGROK_PROVIDER_IDENTITY.id, diff --git a/src/sqlite/SqliteDatabaseFailures.ts b/src/sqlite/SqliteDatabaseFailures.ts index 07e8c94495..28ef9cb491 100644 --- a/src/sqlite/SqliteDatabaseFailures.ts +++ b/src/sqlite/SqliteDatabaseFailures.ts @@ -39,6 +39,7 @@ import { classifyProviderFailure, type ProviderFailureDialect, } from "../providers/classifyProviderFailure.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** Keep typed cleanup history and one canonical output owner, including after resolution. */ export const createSqliteCleanupError = ( @@ -177,7 +178,7 @@ export const sqliteDatabaseDialect = ( diagnostics: { phase, path, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), ...(cause instanceof OwnedCommandFailure && cause.snapshot !== null ? { failure_kind: cause.reason, diff --git a/src/sqlite/SqliteDatabaseInspection.ts b/src/sqlite/SqliteDatabaseInspection.ts index 93bb8bd63d..95352f61af 100644 --- a/src/sqlite/SqliteDatabaseInspection.ts +++ b/src/sqlite/SqliteDatabaseInspection.ts @@ -17,6 +17,7 @@ import { SqliteInspectionFailure, sqlitePrimaryResultCode, } from "./SqliteDatabaseLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** SQLite's generic SQL error, raised while compiling or evaluating an expression. */ const SQLITE_ERROR = 1; @@ -192,7 +193,7 @@ const decodeSchemaText = ( } catch (cause: unknown) { throw new SqliteInspectionFailure( "format", - `SQLite schema ${label} contains malformed ${encoding} text: ${cause instanceof Error ? cause.message : String(cause)}`, + `SQLite schema ${label} contains malformed ${encoding} text: ${errorMessage(cause)}`, ); } }; @@ -749,9 +750,9 @@ const resultColumnLimitFailure = ( ) return undefined; return new SqliteColumnLimitFailure( - `SQLite cannot return ${String(selectedColumns)} selected result columns; this connection permits at most ${String(engineColumnLimit)}: ${ - cause instanceof Error ? cause.message : String(cause) - }`, + `SQLite cannot return ${String(selectedColumns)} selected result columns; this connection permits at most ${String(engineColumnLimit)}: ${errorMessage( + cause, + )}`, selectedColumns, engineColumnLimit, ); @@ -784,7 +785,7 @@ const rowEvaluationFailure = ( if (sqlitePrimaryResultCode(cause) !== SQLITE_ERROR) return cause; const unavailable = new SqliteInspectionFailure( "row-evaluation", - `SQLite cannot prepare or evaluate rows of table ${JSON.stringify(table.name)} on REA's read-only connection: ${cause instanceof Error ? cause.message : String(cause)}`, + `SQLite cannot prepare or evaluate rows of table ${JSON.stringify(table.name)} on REA's read-only connection: ${errorMessage(cause)}`, ); const generated = new Set( table.columns @@ -845,7 +846,7 @@ const rowEvaluationFailure = ( ] .map( ([name, failure]) => - `${JSON.stringify(name)}: ${failure instanceof Error ? failure.message : String(failure)}`, + `${JSON.stringify(name)}: ${errorMessage(failure)}`, ) .join("; ")}`, remaining.length > 0 ? remaining : readableStoredColumns(), diff --git a/src/sqlite/SqliteDatabaseProvider.ts b/src/sqlite/SqliteDatabaseProvider.ts index c049216ff4..053c90c629 100644 --- a/src/sqlite/SqliteDatabaseProvider.ts +++ b/src/sqlite/SqliteDatabaseProvider.ts @@ -56,6 +56,7 @@ import { sqliteReplyFinalizationFailure, type SqliteWorkerLauncher, } from "./SqliteDatabaseWorkerExecution.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const operation = "inspect_sqlite_database"; type SqliteOutcome = Result; @@ -505,7 +506,7 @@ const cleanupSqliteRoot = async ( return err( sqliteCleanupFailure( [root.path], - cause instanceof Error ? cause.message : String(cause), + errorMessage(cause), result, input, output, diff --git a/src/sqlite/SqliteDatabaseWorker.ts b/src/sqlite/SqliteDatabaseWorker.ts index 5464f189e6..2c60128ebc 100644 --- a/src/sqlite/SqliteDatabaseWorker.ts +++ b/src/sqlite/SqliteDatabaseWorker.ts @@ -9,6 +9,7 @@ import { SqliteInspectionFailure, sqlitePrimaryResultCode, } from "./SqliteDatabaseLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const requestSchema = z.strictObject({ snapshot_path: z.string(), @@ -33,7 +34,7 @@ const main = async (): Promise => { }; } catch (cause: unknown) { const code = sqlitePrimaryResultCode(cause); - const message = cause instanceof Error ? cause.message : String(cause); + const message = errorMessage(cause); reply = cause instanceof SqliteColumnEvaluationFailure ? { diff --git a/src/sqlite/SqliteDatabaseWorkerExecution.ts b/src/sqlite/SqliteDatabaseWorkerExecution.ts index abecc67db8..3ccf5982d9 100644 --- a/src/sqlite/SqliteDatabaseWorkerExecution.ts +++ b/src/sqlite/SqliteDatabaseWorkerExecution.ts @@ -45,6 +45,7 @@ import { SQLITE_INSPECTION_REASONS, SQLITE_STRUCTURED_INSPECTION_REASONS, } from "./SqliteDatabaseLimits.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const operation = "inspect_sqlite_database"; const { @@ -304,7 +305,7 @@ const sqliteReplyReadDialect = ( unclassified: (cause, details) => new AnalysisOutputError( operation, - `Owned SQLite worker reply is missing or malformed: ${cause instanceof Error ? cause.message : String(cause)}`, + `Owned SQLite worker reply is missing or malformed: ${errorMessage(cause)}`, { ...details, cause, capturedOutput }, ), }); diff --git a/src/wasm/WabtArtifactProvider.ts b/src/wasm/WabtArtifactProvider.ts index 574afb2dfd..3ba42125a0 100644 --- a/src/wasm/WabtArtifactProvider.ts +++ b/src/wasm/WabtArtifactProvider.ts @@ -75,6 +75,7 @@ import { import { parseWabtOutput } from "./WabtOutput.js"; import { parseWabtWat } from "./WabtWat.js"; import { associateWasmGlue } from "./WasmGlueAdapter.js"; +import { errorMessage } from "../kernel/errorMessage.js"; type Launcher = NonNullable[2]>["launcher"]; type AcquiredGlue = @@ -780,7 +781,7 @@ export class WabtArtifactProvider implements WasmArtifactPort { WABT_PROVIDER_IDENTITY.id, [runtime.path], { - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), previous_error: result.ok ? null : projectAnalysisError(result.error), @@ -817,9 +818,7 @@ const resourceCleanupFailure = (cause: unknown): ProviderCleanupError => { WABT_PROVIDER_IDENTITY.id, cleanup?.resources ?? ["artifact-resources"], { - reason: - cleanup?.reason ?? - (cause instanceof Error ? cause.message : String(cause)), + reason: cleanup?.reason ?? errorMessage(cause), }, { operation: OPERATION, cause }, ); diff --git a/src/wasm/WabtFailures.ts b/src/wasm/WabtFailures.ts index 393f71b0e5..27f28debd3 100644 --- a/src/wasm/WabtFailures.ts +++ b/src/wasm/WabtFailures.ts @@ -32,6 +32,7 @@ import { type WasmResourceLimits, } from "../domain/wasm/wasmArtifact.js"; import { WABT_ACCEPTED_RANGE, WABT_PROVIDER_IDENTITY } from "./WabtRelease.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const OUTPUT_LIMIT_EXCERPT_BYTES = 4096; const OPERATION = "inspect_wasm_artifact"; @@ -148,8 +149,6 @@ export const wabtFailureDialect = ( execution?.observedOutput === undefined ? {} : { capturedOutput: execution.observedOutput }; - const reasonOf = (cause: unknown) => - cause instanceof Error ? cause.message : String(cause); const capturedOutput = (kind: ProviderOutcome["kind"]) => (snapshot: ProviderProcessSnapshot) => kind === "output-limit" @@ -300,7 +299,7 @@ export const wabtFailureDialect = ( } : {}), unclassified: (unrecognised, details) => { - const reason = reasonOf(unrecognised); + const reason = errorMessage(unrecognised); if (phase === "configuration") { const admission = unrecognised instanceof WabtAdmissionError ? unrecognised : undefined; diff --git a/src/windows/WindowsNativeLoader.ts b/src/windows/WindowsNativeLoader.ts index dd47c4d113..fae44c1b29 100644 --- a/src/windows/WindowsNativeLoader.ts +++ b/src/windows/WindowsNativeLoader.ts @@ -12,6 +12,7 @@ import { validateWindowsNativeArtifact, } from "../domain/windowsNativeArtifact.js"; import { RuntimeControlUnavailableError } from "../domain/runtimeControlUnavailableError.js"; +import { errorMessage } from "../kernel/errorMessage.js"; /** A native resource remains opaque until the addon validates its object tag. */ export const windowsHandleSchema = z.custom( @@ -182,7 +183,7 @@ export const loadWindowsNativeAuthority = ( return { available: false, failureStage: "load", - reason: `REA Windows native controls are unavailable: Windows refused to load the verified native/windows/build/rea-windows-x64.node: ${cause instanceof Error ? cause.message : String(cause)} ${WINDOWS_NATIVE_LOAD_REFUSED_REMEDIATION}`, + reason: `REA Windows native controls are unavailable: Windows refused to load the verified native/windows/build/rea-windows-x64.node: ${errorMessage(cause)} ${WINDOWS_NATIVE_LOAD_REFUSED_REMEDIATION}`, }; } const binding = bindingSchema.parse(loadedModule); @@ -194,7 +195,7 @@ export const loadWindowsNativeAuthority = ( available: false, failureStage: "self-test", retryable: true, - reason: `REA Windows native self-test failed: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `REA Windows native self-test failed: ${errorMessage(cause)}`, }; } const parsed = inspectionSchema.safeParse(observed); @@ -210,7 +211,7 @@ export const loadWindowsNativeAuthority = ( return { available: false, failureStage: "artifact", - reason: `REA Windows native controls are unavailable: ${cause instanceof Error ? cause.message : String(cause)}`, + reason: `REA Windows native controls are unavailable: ${errorMessage(cause)}`, }; } }; diff --git a/src/windows/WindowsOwnedProcess.ts b/src/windows/WindowsOwnedProcess.ts index 8316a0d53d..c228da2ca5 100644 --- a/src/windows/WindowsOwnedProcess.ts +++ b/src/windows/WindowsOwnedProcess.ts @@ -9,6 +9,7 @@ import { windowsHandleSchema, type WindowsNativeAuthority, } from "./WindowsNativeLoader.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const launchSchema = z.strictObject({ pid: z.int().positive().max(0xffff_ffff), @@ -130,7 +131,7 @@ export class WindowsNativeSpawnControlError extends RuntimeControlUnavailableErr typeof Reflect.get(cause, "win32Code") === "number" ? Reflect.get(cause, "win32Code") : undefined; - super(message ?? (cause instanceof Error ? cause.message : String(cause)), { + super(message ?? errorMessage(cause), { cause, retryable: true, remediationAction: WINDOWS_SPAWN_CONTROL_REMEDIATION, @@ -434,7 +435,7 @@ export class WindowsOwnedProcess extends EventEmitter { } catch (cause: unknown) { return { cleaned: false, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } } @@ -460,7 +461,7 @@ export class WindowsOwnedProcess extends EventEmitter { } catch (cause: unknown) { return { cleaned: false, - reason: cause instanceof Error ? cause.message : String(cause), + reason: errorMessage(cause), }; } finally { if (timer !== undefined) clearTimeout(timer); diff --git a/src/windows/WindowsPrivateRuntime.ts b/src/windows/WindowsPrivateRuntime.ts index 33a0e44891..b6262050e3 100644 --- a/src/windows/WindowsPrivateRuntime.ts +++ b/src/windows/WindowsPrivateRuntime.ts @@ -14,6 +14,7 @@ import { windowsHandleSchema, type WindowsNativeAuthority, } from "./WindowsNativeLoader.js"; +import { errorMessage } from "../kernel/errorMessage.js"; const runtimeSchema = windowsFileIdentitySchema.extend({ path: z.string(), @@ -225,10 +226,7 @@ export class WindowsPrivateRuntime { throw ArtifactReaderFailure.withCleanup( primary === undefined ? closeFailure.cause : primary.cause, { - reason: - closeFailure.cause instanceof Error - ? closeFailure.cause.message - : String(closeFailure.cause), + reason: errorMessage(closeFailure.cause), resources: [file.requestedPath], }, undefined,