refactor(kernel): give error-message, byte-hex and SHA-256 hex helpers one owner in a new src/kernel layer (#11542)

* refactor(kernel): give error-to-message text one owner in a new src/kernel layer

* fix(kernel): keep the regex worker's own error text inside its isolated source

* refactor(kernel): exclude copies that run in another realm from the error-message guard by name

The regex worker's source string and the page.evaluate fetch in PlaywrightScenarioRequest cannot import errorMessage. The guard now names them, so the counted baseline does not invite a later slice to rewrite them.

* refactor(kernel): migrate the long tail of inline error-message copies to errorMessage (#11552)

Every provider and adapter folder with six or fewer copies now calls errorMessage from src/kernel. Local helpers whose whole body was the copy (failureMessage, gdbErrorMessage, message, describe, reasonOf, recoveryFailureMessage and four local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): give byte-to-hex formatting one owner in src/kernel (#11560)

byteToHex returns the two lowercase hexadecimal digits of one byte. All eight inline copies (native, contracts, domain firmware and desktop, pcap) call it, keeping their own 0x, % or \x notation, and a counted guard with an empty baseline keeps new copies out.

Refs #11548

* refactor(kernel): give one-shot SHA-256 hex digests one owner in src/kernel (#11562)

sha256Hex digests one in-memory value. A counted guard records the one-shot createHash("sha256").update(x).digest("hex") chains (115 in 101 files) and the first slice migrates domain, contracts and process (35 copies), removing local wrappers (sha256, sha256Text, hash) and the exported sha256Text. Incremental and streamed hashing is not counted.

Refs #11548

* refactor(kernel): migrate the application layer's inline error-message copies to errorMessage (#11563)

All 69 copies in src/application call errorMessage from src/kernel. Local helpers whose whole body was the copy (errorDetail, causeReason and five local errorMessage definitions) are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the native provider's inline error-message copies to errorMessage (#11567)

All 49 copies in src/native call errorMessage from src/kernel. The local errorReason helpers in LldbCallTracer and LldbRetainedObservations, whose whole body was the copy, are removed and their call sites call the owner.

Refs #11548

* refactor(kernel): migrate the remaining inline error-message copies to errorMessage (#11569)
This commit is contained in:
morluto authored and GitHub committed 2026-11-16 07:05:30 +08:00
1 parent ff0176256a
commit 5f718ce30e
291 files changed
+976 -978

No files matched your search

+2 -1
View File
@@ -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
+1 -1
View File
@@ -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",
+4 -1
View File
@@ -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", [
+1 -1
View File
@@ -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",
+46 -1
View File
@@ -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 =
/(?<![\w$.])([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s+instanceof\s+Error\s*\?\s*\1\.message\s*:\s*String\(\s*\1\s*\)/gu;
checkCounted(
"inline error-to-message conversion (use errorMessage from src/kernel/errorMessage)",
"inline-error-message",
files,
(content, path) =>
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
@@ -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
}
+15 -34
View File
@@ -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 },
),
),
+3 -6
View File
@@ -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 },
);
+2 -1
View File
@@ -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),
},
});
};
+5 -7
View File
@@ -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);
+5 -13
View File
@@ -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),
},
});
};
+4 -7
View File
@@ -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<ReturnType<AndroidAnalysisPort["execute"]>>;
@@ -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 },
);
+2 -1
View File
@@ -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),
},
});
+2 -4
View File
@@ -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(
@@ -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);
+3 -2
View File
@@ -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)}`,
});
}
};
@@ -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;
+3 -5
View File
@@ -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);
+2 -1
View File
@@ -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.`,
};
}
}
+2 -1
View File
@@ -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)}`;
}
};
+3 -2
View File
@@ -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;
+2 -4
View File
@@ -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 = <Value>(
cause: failure,
path,
cleanup: {
reason:
failure.cleanupCause instanceof Error
? failure.cleanupCause.message
: String(failure.cleanupCause),
reason: errorMessage(failure.cleanupCause),
resources: [failure.path],
},
});
+2 -1
View File
@@ -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);
+4 -3
View File
@@ -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),
},
};
}
+2 -1
View File
@@ -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}`,
{
+3 -2
View File
@@ -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,
});
}
@@ -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);
+1 -3
View File
@@ -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);
+5 -7
View File
@@ -84,6 +84,7 @@ import {
registrationWriteBlocker,
type SetupClient,
} from "./SupportedClients.js";
import { errorMessage } from "../kernel/errorMessage.js";
export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure<string> {
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,
+1 -3
View File
@@ -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,
+4 -6
View File
@@ -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)}`,
});
}
}
+7 -9
View File
@@ -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,
+2 -1
View File
@@ -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]),
},
+7 -6
View File
@@ -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<boolean, ClientPathFailure> => {
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.`,
};
}
});
+2 -1
View File
@@ -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)
+4 -10
View File
@@ -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<void> {
@@ -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", () => {
+2 -4
View File
@@ -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);
}
};
+2 -7
View File
@@ -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
+2 -4
View File
@@ -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 },
+3 -2
View File
@@ -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),
},
),
},
@@ -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 [];
};
+7 -12
View File
@@ -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(
@@ -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,
@@ -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],
};
}
@@ -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)
@@ -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,
@@ -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,
}),
);
@@ -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
? {}
@@ -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,
}),
+2 -4
View File
@@ -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}.`,
@@ -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)
@@ -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),
},
{
@@ -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;
@@ -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 },
);
@@ -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,
});
@@ -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,
@@ -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),
},
})),
},
@@ -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") {
+2 -3
View File
@@ -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" },
);
+5 -7
View File
@@ -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<ArtifactEntry["sourceIdentity"]>;
const mapStableFileRead = async function* (
+5 -7
View File
@@ -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");
+2 -1
View File
@@ -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),
},
});
};
+2 -1
View File
@@ -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 },
);
}
+2 -1
View File
@@ -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
+2 -1
View File
@@ -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 },
);
}
+2 -2
View File
@@ -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 },
);
+2 -3
View File
@@ -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),
},
});
@@ -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 },
);
@@ -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),
},
},
);
+4 -4
View File
@@ -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),
},
},
)
+4 -5
View File
@@ -28,6 +28,7 @@ import {
scenarioQueryLength,
uriComponentLength,
} from "./BrowserScenarioSerialization.js";
import { errorMessage } from "../kernel/errorMessage.js";
type RequestAction = Extract<BrowserScenarioAction, { action: "request" }>;
@@ -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)}`);
}
}
};
+2 -1
View File
@@ -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"],
},
},
+2 -1
View File
@@ -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],
},
),
+4 -5
View File
@@ -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,
+3 -2
View File
@@ -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",
+2 -1
View File
@@ -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),
},
});
};
+2 -1
View File
@@ -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),
);
}
}
+4 -4
View File
@@ -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 },
);
+2 -1
View File
@@ -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),
);
}
}
+2 -1
View File
@@ -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 }
@@ -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,
@@ -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)
+3 -2
View File
@@ -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,
+2 -1
View File
@@ -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,
+2 -2
View File
@@ -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",
+3 -6
View File
@@ -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),
},
{
@@ -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;
}
@@ -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 <Port>(
} catch (cause: unknown) {
return err({
providerId,
reason: cause instanceof Error ? cause.message : String(cause),
reason: errorMessage(cause),
});
}
};
@@ -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;
}
+2 -3
View File
@@ -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<typeof createCatalogIdentity>;
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 = (
+4 -8
View File
@@ -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;
};
+2 -1
View File
@@ -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);
+2 -1
View File
@@ -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 },
);
+2 -1
View File
@@ -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" },
);
+2 -1
View File
@@ -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}`;
}
};
+2 -1
View File
@@ -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,
);
+2 -2
View File
@@ -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),
};
}
}),
+3 -3
View File
@@ -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),
};
}
}
+2 -1
View File
@@ -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)}`;
}
};
+2 -3
View File
@@ -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
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff. Show more