chore: reconcile iNES inventory with current main

This commit is contained in:
64579525
2026-10-13 09:36:35 +08:00
646 changed files with 49020 additions and 6280 deletions
+5 -5
View File
@@ -12,6 +12,7 @@ import {
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
import { err, ok, type Result } from "../domain/result.js";
/** Decoded representation bound for one binary Info.plist. */
@@ -195,11 +196,10 @@ const resolveLayoutExecutable = async (
let name: string;
try {
name =
plist.subarray(0, 6).toString("ascii") === "bplist"
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
parseBinaryPlistExecutable(plist))
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
name = hasBinaryPlistSignature(plist)
? await (fileSystem.decodeBinaryPlist?.(plistPath) ??
parseBinaryPlistExecutable(plist))
: parseXmlPlistExecutable(decodeXmlPlistText(plist));
} catch (cause: unknown) {
return err(
new BinaryTargetError(
+44 -11
View File
@@ -30,7 +30,8 @@ import {
rawBinarySelectionError,
} from "../domain/rawBinary.js";
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
import { observeMzWindowsHeader } from "../domain/dosMz.js";
import { hasBinaryPlistSignature } from "../domain/apple/appleArchiveFormat.js";
import {
hasZipSignature,
isZipPackageFormat,
@@ -330,8 +331,7 @@ const detectArtifactFormat = async (
return zipPackageFormatForPath(lower) ?? "zip";
}
// Binary plists, including keyed archives, often use other extensions.
if (magic.length >= 8 && magic.subarray(0, 8).equals(Buffer.from("bplist00")))
return "plist";
if (hasBinaryPlistSignature(magic)) return "plist";
const named = namedArtifactFormat(lower);
if (named !== undefined) return named;
if (
@@ -443,11 +443,31 @@ const readExecutableMetadata = async (
const fileSize = (await handle.stat()).size;
throwIfTargetResolutionCancelled(signal);
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
const offset = mzWindowsHeaderOffset(bytes);
if (offset !== null) {
if (offset < 64)
let windowsHeader = observeMzWindowsHeader(bytes, fileSize);
let signatureBytes: Buffer | undefined;
if (windowsHeader.state === "signature-needed") {
const { offset } = windowsHeader;
const signature = Buffer.alloc(Math.min(4, fileSize - offset));
const observedSignature = await handle.read(
signature,
0,
signature.length,
offset,
);
throwIfTargetResolutionCancelled(signal);
signatureBytes = signature.subarray(0, observedSignature.bytesRead);
windowsHeader = observeMzWindowsHeader(bytes, fileSize, signatureBytes);
}
if (windowsHeader.state === "declared") {
if (windowsHeader.offset < 64)
return err("invalid Windows new-header offset in MZ image");
return readPeMetadata(handle, offset, signal);
return readPeMetadata(
handle,
windowsHeader.offset,
bytes,
fileSize,
signal,
);
}
// MZ relocation records may extend past the initial probe; their format
// bounds are at most 65535 records inside a 65535-paragraph header.
@@ -470,7 +490,12 @@ const readExecutableMetadata = async (
fileSize,
);
}
return parseExecutableHeader(bytes, hostArchitecture, fileSize);
return parseExecutableHeader(
bytes,
hostArchitecture,
fileSize,
signatureBytes,
);
}
if (bytes.length >= 8) {
const magic = bytes.readUInt32BE(0);
@@ -521,6 +546,8 @@ const readExecutableMetadata = async (
const readPeMetadata = async (
handle: FileHandle,
offset: number,
mzPrefix: Buffer,
fileSize: number,
signal?: AbortSignal,
): Promise<Result<ExecutableMetadata, string>> => {
throwIfTargetResolutionCancelled(signal);
@@ -534,9 +561,15 @@ const readPeMetadata = async (
throwIfTargetResolutionCancelled(signal);
if (fileHeaderRead.bytesRead !== fileHeader.length)
return err("invalid or truncated PE header");
const signature = fileHeader.toString("ascii", 0, 2);
if (["NE", "LE", "LX"].includes(signature))
return err(`unsupported ${signature} executable in MZ image`);
const windowsHeader = observeMzWindowsHeader(
mzPrefix,
fileSize,
fileHeader.subarray(0, 4),
);
if (windowsHeader.state !== "declared")
return err("invalid Windows new-header signature in MZ image");
if (["NE", "LE", "LX"].includes(windowsHeader.signature))
return err(`unsupported ${windowsHeader.signature} executable in MZ image`);
const optionalHeaderSize = fileHeader.readUInt16LE(20);
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
const record = Buffer.alloc(24 + optionalHeaderSize);
+30
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
import type {
OptionalProviderLoadFailures,
OptionalProviderLoadFailure,
@@ -42,6 +43,8 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly packetCaptureEnabled?: boolean;
readonly signalRecordingEnabled?: boolean;
readonly wasmArtifactEnabled?: boolean;
readonly evmInterfaceEnabled?: boolean;
readonly processCaptureEnabled: boolean;
@@ -341,6 +344,15 @@ const workflowAvailabilityFor = ({
}: AvailabilityContext): Availability | null => {
if (name === "inspect_go_binary")
return { reason: "available", remediation: null };
if (name === "inspect_sqlite_database") {
const capability = sqliteDatabaseCapability(process.versions.node);
return capability.available
? { reason: "available", remediation: null }
: {
reason: "provider_unavailable",
remediation: capability.reason,
};
}
if (name === "trace_web_module_imports")
return {
reason: "available",
@@ -385,6 +397,22 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (name === "inspect_packet_capture")
return policy.packetCaptureEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
};
if (name === "decode_signal_recording")
return policy.signalRecordingEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux, supply sigrok-cli 0.7.2 via absolute REA_SIGROK_COMMAND and util-linux prlimit (REA_SIGROK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
};
if (name === "inspect_wasm_artifact")
return policy.wasmArtifactEnabled === true
? { reason: "available", remediation: null }
@@ -453,6 +481,8 @@ const workflowAvailabilityFor = ({
remediation: "Run process capture on a supported Linux or macOS host.",
};
if (kind === "application") return { reason: "available", remediation: null };
if (kind === "flutter-provider")
return { reason: "available", remediation: null };
const electron = electronProviderAvailability(name, kind, policy);
if (electron !== null) return electron;
if (kind === "runtime-provider")
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { parseClientConfiguration } from "./ClientConfigurationDocument.js";
describe("parseClientConfiguration shape diagnostics", () => {
it.each([
["null", "null"],
["array", "[]"],
["string", '"x"'],
] as const)("names a non-object JSON root (%s)", (_label, text) => {
expect(() => parseClientConfiguration(text, "json")).toThrow(
new TypeError("The configuration root must be an object"),
);
});
it.each([
["null", "null"],
["array", "[]"],
["string", '"x"'],
] as const)(
'names a non-object "mcpServers" value (%s)',
(_label, servers) => {
expect(() =>
parseClientConfiguration(`{"mcpServers":${servers},"keep":1}`, "json"),
).toThrow(new TypeError('"mcpServers" must be an object'));
},
);
it("still rejects unparsable JSON with SyntaxError", () => {
expect(() => parseClientConfiguration("not-json", "json")).toThrow(
SyntaxError,
);
});
});
+54 -17
View File
@@ -86,6 +86,7 @@ export const clientConfigurationServersKey = (
case "hermes":
return "mcp_servers";
case "opencode":
case "zcode":
return "mcp";
case "vscode":
return "servers";
@@ -106,16 +107,21 @@ const parseDocument = (
format: ClientConfigurationFormat,
): Record<string, unknown> => {
if (format === "toml" || format === "grok")
return objectSchema.parse(parseToml(text));
return requireObject(parseToml(text), "The configuration root");
// Pi loads `mcp.json` with a strict `JSON.parse` and no BOM tolerance, so
// comments, trailing commas, a BOM, or an empty existing file must be
// rejected instead of registering into a document Pi cannot load.
if (format === "pi") return objectSchema.parse(JSON.parse(text));
if (format === "pi")
return requireObject(JSON.parse(text), "The configuration root");
// An empty file, which some clients create before any server is added,
// holds no settings to preserve.
if (isEmptyClientConfigurationText(text)) return {};
// Hermes stores MCP servers in `mcp_servers` inside a YAML document.
if (format === "hermes") return objectSchema.parse(parseYaml(text));
if (format === "hermes")
return requireObject(parseYaml(text), "The configuration root");
// ZCode loads nonempty native files with strict JSON.parse.
if (format === "zcode")
return requireObject(JSON.parse(text), "The configuration root");
const errors: ParseError[] = [];
// Accept a UTF-8 BOM without shifting diagnostics or editing the original text.
const jsonText = text.startsWith("\uFEFF") ? ` ${text.slice(1)}` : text;
@@ -125,12 +131,13 @@ const parseDocument = (
throw new SyntaxError(
`Invalid JSON/JSONC at offset ${firstError.offset}: ${printParseErrorCode(firstError.error)}`,
);
return objectSchema.parse(document);
return requireObject(document, "The configuration root");
};
/** A parsed configuration whose structure, not its syntax, cannot hold MCP servers. */
export class ClientConfigurationShapeError extends TypeError {}
/** Validate and copy own properties, excluding non-record YAML values and parser-injected prototypes. */
const requireObject = (
value: unknown,
description: string,
@@ -142,6 +149,23 @@ const requireObject = (
});
};
/** ZCode reads the same-scope fallback as strict JSON with a mcpServers table. */
export const parseZcodeFallbackConfiguration = (
text: string,
): ClientConfigurationDocument => {
const document = requireObject(JSON.parse(text), "ZCode fallback root");
return {
document,
servers:
document.mcpServers === undefined
? {}
: requireObject(document.mcpServers, "ZCode fallback mcpServers"),
serversPath: ["mcpServers"],
dialect: "json",
legacyServers: {},
};
};
/** Members of OpenCode V2's `mcp` object that are not server names. */
const OPENCODE_V2_MCP_SETTINGS = new Set(["servers", "timeout"]);
@@ -154,21 +178,26 @@ export const parseClientConfiguration = (
throw new TypeError("client does not have a supported MCP config format");
// DeepSeek Harness stores a Cordis patch list, not a server table.
if (format === "dsh") return parseDshCordisDocument(text);
let document: Record<string, unknown>;
try {
document = parseDocument(text, format);
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
throw new ClientConfigurationShapeError(
"The configuration root must be an object",
{ cause },
);
throw cause;
}
const document = parseDocument(text, format);
const serversKey = clientConfigurationServersKey(format);
const value = document[serversKey];
const servers =
value === undefined ? {} : requireObject(value, `"${serversKey}"`);
// ZCode reads stdio servers from the nested `mcp.servers` table of
// `~/.zcode/cli/config.json`; entries carry `command`, `args`, and `env`.
if (format === "zcode") {
const nested = servers.servers;
return {
document,
servers:
nested === undefined
? {}
: requireObject(nested, `"${serversKey}.servers"`),
serversPath: [serversKey, "servers"],
dialect: format,
legacyServers: {},
};
}
const native = servers.servers;
// A V1 server named `servers` has a string `type` discriminator; the V2
// table may instead hold a server object named `type`.
@@ -228,8 +257,16 @@ export const withClientServers = (
: editDshDocument(parsed);
const [key = "", nested] = parsed.serversPath;
if (nested === undefined) return { ...parsed.document, [key]: servers };
const outer = { ...objectSchema.parse(parsed.document[key]) };
if (removeLegacy !== undefined && !OPENCODE_V2_MCP_SETTINGS.has(removeLegacy))
// A fresh document may not hold the outer table yet (for example a new
// ZCode `config.json` without an `mcp` object), so treat absence as empty.
const outerValue = parsed.document[key];
const outer =
outerValue === undefined ? {} : { ...objectSchema.parse(outerValue) };
if (
parsed.dialect === "opencode_v2" &&
removeLegacy !== undefined &&
!OPENCODE_V2_MCP_SETTINGS.has(removeLegacy)
)
delete outer[removeLegacy];
return { ...parsed.document, [key]: { ...outer, [nested]: servers } };
};
+3 -1
View File
@@ -226,7 +226,9 @@ const registrationAligned = (
const command = [registration.command, ...registration.args];
if (
(client.format !== "grok" && registration.disabled === true) ||
(registration.enabled === false && !forcedEnabled)
(registration.enabled === false && !forcedEnabled) ||
// ZCode's native flag is `enable`; other dialects leave that field opaque.
(client.format === "zcode" && registration.enable === false)
)
return false;
if (!isOwnedClientRegistrationCommand(command, currentCommandPath))
+11 -1
View File
@@ -4,6 +4,9 @@ import { createServerIdentity } from "../serverIdentity.js";
import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
import { providerCapabilitySet } from "../contracts/toolOutputSchemaPrimitives.js";
import { providerCapabilitySets } from "./binary/BinarySessionStatus.js";
import { sqliteDatabaseCapability } from "./sqlite/SqliteDatabaseCapability.js";
/** Read target-free provider status and operation availability. */
export const runSessionStatus = async (
@@ -17,8 +20,15 @@ export const runSessionStatus = async (
if (!config.ok) return { error: projectAnalysisError(config.error) };
const session = await dependencies.createBinarySession(config.value, logger);
try {
const status = jsonObjectSchema.parse(session.status());
return {
...jsonObjectSchema.parse(session.status()),
...status,
capabilities: [
...providerCapabilitySet.array().parse(status.capabilities),
...providerCapabilitySets([
sqliteDatabaseCapability(process.versions.node),
]),
],
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
}),
+3
View File
@@ -21,6 +21,7 @@ import {
parseFunctionDossier,
parseListCount,
parseRelatedAddresses,
parseSegmentImageBase,
parseSegments,
} from "../domain/hopperValues.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -527,6 +528,7 @@ export class EnhancedTools {
const segments = parseSegments(segmentsResult.value);
if (!segments.ok) return segments;
const imageBase = parseSegmentImageBase(segmentsResult.value);
const procedureCount = parseListCount(proceduresResult.value, "procedures");
if (!procedureCount.ok) return procedureCount;
const stringCount = parseListCount(stringsResult.value, "strings");
@@ -543,6 +545,7 @@ export class EnhancedTools {
segment_count: segments.value.length,
procedure_count: procedureCount.value,
string_count: stringCount.value,
...(imageBase === undefined ? {} : { image_base: imageBase }),
});
}
+2 -10
View File
@@ -1,9 +1,9 @@
import { resolve } from "node:path";
import {
createImmutableEvidenceBundle,
describeEvidenceBundleFailure,
describeValidationFailure,
parseImmutableEvidenceBundle,
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
@@ -49,15 +49,7 @@ export const readImmutableEvidenceBundle = (
signal?: AbortSignal,
resources?: ArtifactResourceScope,
): Promise<Result<EvidenceBundle, EvidenceReadFailure>> =>
readBundle(
path,
(input) => {
const bundle = parseEvidenceBundle(input);
return createImmutableEvidenceBundle(bundle.records, bundle.unknowns);
},
signal,
resources,
);
readBundle(path, parseImmutableEvidenceBundle, signal, resources);
const readBundle = async (
path: string,
+6 -4
View File
@@ -3,6 +3,7 @@ import type {
MipsAbiFlags,
MipsElfMetadata,
} from "../domain/binaryTargetTypes.js";
import { readElfFixedHeader } from "../domain/elfFixedHeader.js";
import { err, ok, type Result } from "../domain/result.js";
import {
readMipsElfSharedLoad,
@@ -64,21 +65,22 @@ export const readMipsElfMetadata = async (
const header = await read(0, 52, "ELF32 header");
if (!header.ok) return header;
const bytes = header.value;
const fixedHeader = readElfFixedHeader(bytes, fileSize);
if (!fixedHeader.ok) return fixedHeader;
const little = metadata.byteOrder === "little";
const u16 = (data: Buffer, offset: number): number =>
little ? data.readUInt16LE(offset) : data.readUInt16BE(offset);
const u32 = (data: Buffer, offset: number): number =>
little ? data.readUInt32LE(offset) : data.readUInt32BE(offset);
if (
bytes.toString("hex", 0, 4) !== "7f454c46" ||
bytes[4] !== 1 ||
bytes[5] !== (little ? 1 : 2) ||
fixedHeader.value.elfClass !== 32 ||
fixedHeader.value.byteOrder !== metadata.byteOrder ||
u16(bytes, 18) !== 8 ||
u16(bytes, 16) !== metadata.type ||
u32(bytes, 36) !== metadata.flags
)
return err("MIPS ELF header no longer matches the resolved identity");
if (bytes[6] !== 1 || u32(bytes, 20) !== 1 || u16(bytes, 40) !== 52)
if (fixedHeader.value.headerSize !== 52)
return err("invalid MIPS ELF32 version or header size");
const tables = [
@@ -109,12 +109,18 @@ const resolveInternalSpecifier = (
: { to: match, resolution: "internal" };
};
type ReadFile = Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>;
const appendFile = (
entry: Extract<ReferenceSourceEntry, { status: "read"; kind: "file" }>,
entry: ReadFile,
lookupPath: ReferenceSourcePathLookup,
output: ParsedReferenceSourceEntries,
): void => {
const language = detectReferenceSourceLanguage(entry.path);
const parsed =
language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language)
? undefined
: parseReferenceSourceImports(entry.path, entry.bytes, language);
output.entries.push({
path: entry.path,
kind: "file",
@@ -123,11 +129,9 @@ const appendFile = (
language,
classifications: classifyReferenceSourcePath(entry.path),
content_state: "hashed",
limitations: [],
limitations: [...(parsed?.limitations ?? [])],
});
if (language === null || !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
return;
const parsed = parseReferenceSourceImports(entry.path, entry.bytes, language);
if (parsed === undefined) return;
for (const relationship of parsed.relationships) {
if (relationship.resolution !== "internal") {
output.relationships.push(relationship);
+17 -11
View File
@@ -1,6 +1,6 @@
import fs from "node:fs";
import { lstat } from "node:fs/promises";
import { join, resolve } from "node:path";
import { dirname, join, resolve } from "node:path";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
@@ -32,18 +32,24 @@ export const readReferenceSourceVcs = async (
): Promise<Result<ReferenceSourceVcsInfo, ReferenceSourceReaderError>> => {
try {
return await resources.run(async () => {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(root, ".git"));
} catch (cause: unknown) {
return ok(
errorCode(cause) === "ENOENT"
? { kind: "none", head: null, dirty: null }
: unknownVcs(),
);
// Like Git, a subdirectory belongs to its nearest enclosing repository;
// only a missing `.git` at every ancestor means no version control.
let repository = resolve(root);
for (;;) {
if (isAborted(signal)) return ok(unknownVcs());
try {
await lstat(join(repository, ".git"));
break;
} catch (cause: unknown) {
if (errorCode(cause) !== "ENOENT") return ok(unknownVcs());
}
const parent = dirname(repository);
if (parent === repository)
return ok({ kind: "none", head: null, dirty: null });
repository = parent;
}
try {
const head = await resolveSourceHead(root, resources, signal);
const head = await resolveSourceHead(repository, resources, signal);
if (isAborted(signal)) return ok(unknownVcs());
return ok({ kind: "git", head, dirty: null });
} catch (cause: unknown) {
+89 -10
View File
@@ -1,5 +1,9 @@
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
import { readClientConfigurationFiles } from "./ClientConfigurationFiles.js";
import {
readClientConfigurationFiles,
readConfigurationText,
} from "./ClientConfigurationFiles.js";
import { err, ok, type Result } from "../domain/result.js";
import {
clientRegistrationEntry,
clientConfigurationValuesEqual,
@@ -8,6 +12,7 @@ import {
legacyClientServerPath,
OMP_DISABLED_SERVERS_KEY,
parseClientConfiguration,
parseZcodeFallbackConfiguration,
serializeClientConfiguration,
withClientServers,
type ClientConfigurationDocument,
@@ -120,12 +125,15 @@ const configureClientDocument = async (
void cause;
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
client,
environment,
command,
parsed,
);
const fallback = await readZcodeFallbackServers(client, parsed);
if (!fallback.ok) {
throwCleanupFailure(fallback.error);
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(client, environment, command, {
...parsed,
servers: { ...fallback.value, ...parsed.servers },
});
if (registrationCurrent(parsed, desired)) return { status: "unchanged" };
return persistClientConfiguration({
client,
@@ -134,6 +142,7 @@ const configureClientDocument = async (
original,
parsed,
desired,
fallbackServers: fallback.value,
});
};
@@ -144,6 +153,7 @@ interface ClientConfigurationUpdate {
readonly original: string | undefined;
readonly parsed: ClientConfigurationDocument;
readonly desired: unknown;
readonly fallbackServers: Readonly<Record<string, unknown>>;
}
const persistClientConfiguration = async ({
@@ -153,6 +163,7 @@ const persistClientConfiguration = async ({
original,
parsed,
desired,
fallbackServers,
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
const backupPath =
original === undefined ? undefined : `${client.configPath}.rea.backup`;
@@ -169,7 +180,11 @@ const persistClientConfiguration = async ({
);
const registered = withClientServers(
parsed,
{ ...parsed.servers, [PRODUCT_IDENTITY.mcpServerKey]: desired },
{
...fallbackServers,
...parsed.servers,
[PRODUCT_IDENTITY.mcpServerKey]: desired,
},
PRODUCT_IDENTITY.mcpServerKey,
);
// OMP's denylist would hide the registration; keep every other listed name.
@@ -194,6 +209,9 @@ const persistClientConfiguration = async ({
await writeFileAtomic(
transactionPath,
serializeClientConfiguration(document, format, original, [
...Object.keys(fallbackServers)
.filter((name) => name !== PRODUCT_IDENTITY.mcpServerKey)
.map((name) => clientServerPath(parsed, name)),
clientServerPath(parsed, PRODUCT_IDENTITY.mcpServerKey),
...(legacyPath === undefined ? [] : [legacyPath]),
...(enableOmp ? [[OMP_DISABLED_SERVERS_KEY]] : []),
@@ -213,7 +231,14 @@ const persistClientConfiguration = async ({
await readRegularFileText(transactionPath),
format,
);
if (!registrationCurrent(readback, desired)) {
if (
!registrationCurrent(readback, desired) ||
Object.entries(fallbackServers).some(
([name, entry]) =>
name !== PRODUCT_IDENTITY.mcpServerKey &&
!clientConfigurationValuesEqual(readback.servers[name], entry),
)
) {
await restoreConfig(transactionPath, original);
return { status: "failed", reason: "readback" };
}
@@ -329,7 +354,14 @@ export const inspectClientConfiguration = async (
original = await readRegularFileText(transactionPath);
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
if (isMissing(cause)) return { status: "create" };
if (isMissing(cause)) {
const fallback = await readZcodeFallbackServers(client);
if (!fallback.ok) {
throwCleanupFailure(fallback.error);
return { status: "invalid", remediation: fallback.error.detail };
}
return { status: "create" };
}
return {
status: "invalid",
remediation: `The configuration file could not be read. Check its permissions before rerunning setup. ${cause instanceof Error ? cause.message : String(cause)}`,
@@ -359,6 +391,11 @@ export const inspectClientConfiguration = async (
);
if (registrationCurrent(parsed, desired))
return { status: "already_current" };
const fallback = await readZcodeFallbackServers(client, parsed);
if (!fallback.ok) {
throwCleanupFailure(fallback.error);
return { status: "invalid", remediation: fallback.error.detail };
}
} catch (cause: unknown) {
if (cause instanceof RegularFileCleanupFailure) throw cause;
// Malformed configuration is reported with the invalid remediation.
@@ -382,6 +419,48 @@ const throwCleanupFailure = (error: ClientConfigurationFileError): void => {
if (error.cleanupFailure !== undefined) throw error.cleanupFailure;
};
/** Admit the fallback only when the first native ZCode server would suppress it. */
const readZcodeFallbackServers = async (
client: SetupClient,
parsed?: ClientConfigurationDocument,
): Promise<
Result<Readonly<Record<string, unknown>>, ClientConfigurationFileError>
> => {
if (
client.format !== "zcode" ||
(parsed !== undefined && Object.keys(parsed.servers).length > 0)
)
return ok({});
const path = client.zcodeFallbackPath;
const detail = `The ZCode fallback configuration ${path ?? "path"} is unresolved, malformed or unreadable. Repair it before rerunning setup: the first native server would suppress that fallback.`;
if (path === undefined)
return err({ kind: "unreadable", path: client.configPath, detail });
const transactionPath = await resolveClientConfigTransactionPath(path);
if (transactionPath === undefined)
return err({ kind: "unreadable", path, detail });
const source = await readConfigurationText(transactionPath);
if (!source.ok)
return err({ ...source.error, detail: `${detail} ${source.error.detail}` });
if (source.value === undefined) return ok({});
try {
const parsed = parseZcodeFallbackConfiguration(source.value);
const environment = clientRegistrationEnvironment(parsed);
if (!environment.ok)
return err({
kind: "malformed",
path,
detail: `${detail} ${environment.error.settings.map(({ setting, constraint }) => `${setting}: ${constraint}`).join("; ")}`,
});
return ok(parsed.servers);
} catch (cause: unknown) {
return err({
kind: "malformed",
path,
detail: `${detail} ${cause instanceof Error ? cause.message : String(cause)}`,
});
}
};
const preserveConfigBackup = async (
source: string,
destination: string,
+63 -10
View File
@@ -26,6 +26,8 @@ export interface SetupClient {
};
/** Unresolved path evidence only; consumers must not perform I/O on it. */
readonly configPathError?: string;
/** Same-scope fallback ZCode stops loading after its first native server. */
readonly zcodeFallbackPath?: string;
readonly markerPath?: string;
readonly format?:
| "json"
@@ -38,6 +40,7 @@ export interface SetupClient {
| "omp"
| "pi"
| "hermes"
| "zcode"
| "dsh"
| "unsupported";
}
@@ -64,6 +67,7 @@ interface ClientDefinition {
readonly configPath: ClientPath;
readonly markerPath: ClientPath;
readonly format: NonNullable<SetupClient["format"]>;
readonly zcodeFallbackPath?: (context: ClientPathContext) => string;
readonly skillPath?: ClientPath;
readonly configPaths?: (context: ClientPathContext) => readonly string[];
readonly geminiSettings?: (
@@ -71,6 +75,10 @@ interface ClientDefinition {
) => NonNullable<SetupClient["geminiSettings"]>;
}
/** XDG treats an empty config-home value as unset. */
const xdgConfigHome = ({ home, env }: ClientPathContext): string =>
env.XDG_CONFIG_HOME || join(home, ".config");
const vscodeUserDirectory = ({
home,
platform,
@@ -84,7 +92,23 @@ const vscodeUserDirectory = ({
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Code", "User");
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Code", "User");
return join(xdgConfigHome({ home, platform, env }), "Code", "User");
};
const traeUserDirectory = ({
home,
platform,
env,
}: ClientPathContext): string => {
if (platform === "win32")
return join(
env.APPDATA ?? join(home, "AppData", "Roaming"),
"Trae",
"User",
);
if (platform === "darwin")
return join(home, "Library", "Application Support", "Trae", "User");
return join(xdgConfigHome({ home, platform, env }), "Trae", "User");
};
const claudeDesktopDirectory = ({
@@ -95,7 +119,7 @@ const claudeDesktopDirectory = ({
if (platform === "win32")
return join(env.APPDATA ?? join(home, "AppData", "Roaming"), "Claude");
if (platform === "linux")
return join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "Claude");
return join(xdgConfigHome({ home, platform, env }), "Claude");
return join(home, "Library", "Application Support", "Claude");
};
@@ -108,6 +132,9 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
const codexDirectory = ({ home, env }: ClientPathContext): string =>
env.CODEX_HOME || join(home, ".codex");
const qoderDirectory = ({ home, env }: ClientPathContext): string =>
env.QODER_CONFIG_DIR || join(home, ".qoder");
/** Match Qwen Code's home override, including tilde and cwd-relative paths. */
const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const override = env.QWEN_HOME;
@@ -245,19 +272,13 @@ const openCodeOverrideDirectory = (
const opencodeDirectory = (context: ClientPathContext): string =>
openCodeOverrideDirectory(context.env) ??
join(
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
"opencode",
);
join(xdgConfigHome(context), "opencode");
/** OpenCode loads global JSON before JSONC, then explicit file and directory overrides. */
const openCodeConfigurationPaths = (
context: ClientPathContext,
): readonly string[] => {
const directory = join(
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
"opencode",
);
const directory = join(xdgConfigHome(context), "opencode");
const overrideDirectory = openCodeOverrideDirectory(context.env);
const paths = [
join(directory, "config.json"),
@@ -460,6 +481,15 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: vscodeUserDirectory,
format: "vscode",
},
{
name: "trae",
displayName: "Trae",
skillPath: [".trae", "skills"],
configPath: (context: ClientPathContext) =>
join(traeUserDirectory(context), "mcp.json"),
markerPath: traeUserDirectory,
format: "json",
},
{
name: "grok_build",
displayName: "Grok Build",
@@ -499,6 +529,26 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: hermesDirectory,
format: "hermes",
},
{
name: "qoder",
displayName: "Qoder",
skillPath: (context: ClientPathContext) =>
join(qoderDirectory(context), "skills"),
configPath: (context: ClientPathContext) =>
join(qoderDirectory(context), "settings.json"),
markerPath: qoderDirectory,
format: "json",
},
{
name: "zcode",
zcodeFallbackPath: ({ home }: ClientPathContext) =>
join(home, ".agents", "mcp.json"),
displayName: "ZCode",
configPath: [".zcode", "cli", "config.json"],
markerPath: [".zcode", "cli"],
skillPath: [".zcode", "skills"],
format: "zcode",
},
{
name: "dsh",
displayName: "DeepSeek Harness",
@@ -590,6 +640,9 @@ export const supportedClients = (
...new Set([...definition.configPaths(context), configPath]),
],
}),
...(definition.zcodeFallbackPath === undefined
? {}
: { zcodeFallbackPath: definition.zcodeFallbackPath(context) }),
markerPath: marker.value,
format: definition.format,
};
+1 -1
View File
@@ -289,7 +289,7 @@ const readClientConfiguration = async (
"failed",
cause instanceof ClientConfigurationShapeError
? `Configuration was not changed: ${cause.message}. Repair it, then rerun uninstall.`
: `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
: `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : client.format === "hermes" || client.format === "dsh" ? "YAML" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
),
);
}
@@ -102,6 +102,38 @@ export interface AnalysisViewRetention {
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
}
/** Fail before analysis when selected delivery cannot keep its complete source. */
export const requireAnalysisViewRetention = (
operation: string,
retention: AnalysisViewRetention,
): Result<
{
readonly evidenceById: EvidenceLookup;
readonly recordEvidence: EvidenceWriter["recordEvidence"];
},
AnalysisError
> => {
if (
retention.recordEvidence === undefined ||
retention.evidenceById === undefined
)
return err(
new AnalysisCapabilityUnavailableError(
ANALYSIS_VIEW_PROVIDER.id,
operation,
"summary detail requires a server session that retains Evidence for later views",
{
userMessage:
"This server does not retain Evidence. Select detail complete to receive the complete analysis inline.",
},
),
);
return ok({
evidenceById: retention.evidenceById,
recordEvidence: retention.recordEvidence,
});
};
/**
* Retain complete analysis Evidence in the session, then project its summary
* view from the retained record. Callers page or select the rest through
@@ -111,29 +143,16 @@ export const summarizeRetainedAnalysis = (
evidence: Evidence,
retention: AnalysisViewRetention,
): Result<Evidence, AnalysisError> => {
if (
retention.recordEvidence === undefined ||
retention.evidenceById === undefined
)
return err(
new AnalysisCapabilityUnavailableError(
ANALYSIS_VIEW_PROVIDER.id,
evidence.operation,
"summary detail requires a server session that retains Evidence for later views",
{
userMessage:
"This server does not retain Evidence. Select detail complete to receive the complete analysis inline.",
},
),
);
const recorded = retention.recordEvidence(evidence);
const ready = requireAnalysisViewRetention(evidence.operation, retention);
if (!ready.ok) return ready;
const recorded = ready.value.recordEvidence(evidence);
if (!recorded.ok) return recorded;
return inspectAnalysisViewValidated(
{
source: { kind: "retained-evidence", evidence_id: evidence.evidence_id },
view: { kind: "summary" },
},
retention.evidenceById,
ready.value.evidenceById,
);
};
@@ -19,6 +19,10 @@ import type {
UnknownStatus,
UpdateUnknownInput,
} from "../../domain/residualUnknown.js";
import type {
UnknownPage,
UnknownQuery,
} from "../investigation/InvestigationRecordPort.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisExecution,
@@ -350,6 +354,10 @@ export abstract class BinarySessionRecords {
return this.#records.listUnknowns(filters);
}
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
return this.#records.listUnknownsPage(query);
}
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
@@ -198,15 +198,19 @@ type CapabilityAvailabilityCode = Exclude<
CapabilityDescriptor["availabilityCode"],
undefined
>;
type CapabilityProjection = Omit<CapabilityDescriptor, "available" | "reason"> &
(
// Wire capability projection also covers target-free operations outside binary routing.
type CapabilityProjection = Omit<
CapabilityDescriptor,
"operation" | "available" | "reason"
> & { readonly operation: string } & (
| { readonly available: true; readonly reason: null }
| { readonly available: false; readonly reason: string }
);
type ProviderCapabilityGroup = ProviderCapabilitySet["groups"][number];
/** Group inline capability facts without merging distinct providers or states. */
const providerCapabilitySets = (
/** Project provider descriptors once for binary and target-free status consumers. */
export const providerCapabilitySets = (
descriptors: readonly CapabilityProjection[],
): ProviderCapabilitySet[] => {
const providers = new Map<
@@ -10,6 +10,11 @@ import type { ProviderIdentity } from "../AnalysisProvider.js";
/** Replaceable offline binary-layout provider; owns its parser and process protocol. */
export interface BinaryLayoutPort {
readonly identity: ProviderIdentity;
inspectAndClose(
input: InspectBinaryLayoutInput,
options?: ExecutionOptions,
): Promise<Result<BinaryLayout, AnalysisError>>;
close?(): Promise<void>;
inspect(
input: InspectBinaryLayoutInput,
options?: ExecutionOptions,
@@ -17,6 +17,9 @@ it.each([
"rejects malformed selection before starting the provider: %j",
async (input) => {
const service = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
@@ -32,6 +35,9 @@ it.each([
it("records the decoded layout once in its Evidence", async () => {
const layout = binaryLayoutFixture();
const service = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(layout)),
});
@@ -49,6 +55,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
"ELF core belongs to recorded-crash analysis.",
);
const service = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(err(failure)),
});
@@ -58,6 +67,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
it("cancels before invocation and after an acquired observation", async () => {
const controller = new AbortController();
const service = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
controller.abort();
@@ -77,6 +89,9 @@ it("cancels before invocation and after an acquired observation", async () => {
},
});
const untouched = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
@@ -112,6 +127,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
permissions: { read: true, write: false, execute: true },
});
const service = new BinaryLayoutService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
@@ -21,10 +21,36 @@ const OPERATION = "inspect_binary_layout";
export class BinaryLayoutService {
constructor(readonly provider: BinaryLayoutPort) {}
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
return this.#inspect(rawInput, options, (input) =>
this.provider.inspect(input, options),
);
}
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
inspectAndClose(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
return this.#inspect(rawInput, options, (input) =>
this.provider.inspectAndClose(input, options),
);
}
async #inspect(
rawInput: unknown,
options: ExecutionOptions | undefined,
inspect: (
input: Parameters<BinaryLayoutPort["inspect"]>[0],
) => ReturnType<BinaryLayoutPort["inspect"]>,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
@@ -45,7 +71,7 @@ export class BinaryLayoutService {
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
const inspected = await inspect(input.data);
if (!inspected.ok) return inspected;
const diagnostics = binaryLayoutSchema.shape.diagnostics.safeParse(
inspected.value.diagnostics,
@@ -12,6 +12,11 @@ import type { Result } from "../../domain/result.js";
/** Replaceable decoder of supplied recordings; historical PID is never live authority. */
export interface RecordedCrashPort {
readonly identity: ProviderIdentity;
inspectAndClose(
input: InspectRecordedCrashInput,
options?: ExecutionOptions,
): Promise<Result<RecordedCrash, AnalysisError>>;
close?(): Promise<void>;
inspect(
input: InspectRecordedCrashInput,
options?: ExecutionOptions,
@@ -13,6 +13,9 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
const fixture = recordedCrashFixture();
fixture.debugger = recordedCrashDebuggerFixture();
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
@@ -36,6 +39,9 @@ it.each([
"rejects malformed selection before starting the provider: %j",
async (input) => {
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
@@ -55,6 +61,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
"ELF core belongs to recorded-crash analysis.",
);
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(err(failure)),
});
@@ -64,6 +73,9 @@ it("preserves a provider's actionable unsupported reason", async () => {
it("cancels before invocation and after an acquired observation", async () => {
const controller = new AbortController();
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
controller.abort();
@@ -83,6 +95,9 @@ it("cancels before invocation and after an acquired observation", async () => {
},
});
const untouched = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
@@ -117,6 +132,9 @@ it.each(["different-path", "invalid-digest", "outside-range"])(
flags: "0x5",
});
const service = new RecordedCrashService({
inspectAndClose(input, options) {
return this.inspect(input, options);
},
identity: RECORDED_CRASH_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
@@ -21,10 +21,36 @@ const OPERATION = "inspect_recorded_crash";
export class RecordedCrashService {
constructor(readonly provider: RecordedCrashPort) {}
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
return this.#inspect(rawInput, options, (input) =>
this.provider.inspect(input, options),
);
}
/** Complete the owned one-shot lifecycle before validating and publishing Evidence. */
inspectAndClose(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
return this.#inspect(rawInput, options, (input) =>
this.provider.inspectAndClose(input, options),
);
}
async #inspect(
rawInput: unknown,
options: ExecutionOptions | undefined,
inspect: (
input: Parameters<RecordedCrashPort["inspect"]>[0],
) => ReturnType<RecordedCrashPort["inspect"]>,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
@@ -45,7 +71,7 @@ export class RecordedCrashService {
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
const inspected = await inspect(input.data);
if (!inspected.ok) return inspected;
const diagnostics = recordedCrashSchema.shape.diagnostics.safeParse(
inspected.value.diagnostics,
@@ -0,0 +1,93 @@
import { isAbsolute } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
inspectPacketCaptureInputSchema,
packetCaptureSchema,
type InspectPacketCaptureInput,
} from "../../domain/captures/packetCapture.js";
import { err, ok, type Result } from "../../domain/result.js";
export interface PacketCapturePort {
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
close(): Promise<void>;
}
/** One shared validation and Evidence owner for CLI and MCP. */
export class PacketCaptureService {
constructor(readonly provider: PacketCapturePort) {}
close(): Promise<void> {
return this.provider.close();
}
async inspect(
raw: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "inspect_packet_capture";
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const input = inspectPacketCaptureInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute local path.",
},
]),
);
const decoded = await this.provider.inspect(input.data, options);
if (!decoded.ok) return decoded;
const execution = decoded.value;
const report = packetCaptureSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
)
return err(
new AnalysisOutputError(
operation,
"Capture analyzer returned malformed data or changed the selected artifact identity/options.",
),
);
const evidence = createEvidence(execution.subject, execution.provider, {
operation,
parameters: input.data,
result: report.data,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
});
return options?.signal?.aborted
? err(
new AnalysisCancelledError(operation, {
partialObservation: evidence,
}),
)
: ok(evidence);
}
}
@@ -0,0 +1,23 @@
import type {
AnalysisExecution,
ExecutionOptions,
ProviderAvailability,
} from "../AnalysisProvider.js";
import type { FlutterRequest } from "../../domain/flutter/flutterBuildAnalysis.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Result } from "../../domain/result.js";
/**
* Flutter build-identification boundary by pure APK parsing.
* Implementation details belong to the provider adapter.
*/
export interface FlutterBuildAnalysisPort {
/** Pure parsing; always available. */
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
/** The provider holds no long-lived resources; safe to call always. */
close(): Promise<void>;
execute(
request: FlutterRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,93 @@
import { expect, it } from "vitest";
import { FlutterBuildAnalysisService } from "./FlutterBuildAnalysisService.js";
import type { FlutterBuildAnalysisPort } from "./FlutterBuildAnalysisPort.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { parseEvidence } from "../../domain/evidence.js";
import { ok } from "../../domain/result.js";
const identity = {
id: "flutter",
name: "Flutter build identification",
version: null,
};
const execution = createAnalysisExecution(
{
target: { path: "/targets/app.apk", bytes: 10, sha256: "a".repeat(64) },
flutter_detected: true,
abis: [],
coverage: "complete",
},
identity,
);
const refusing: FlutterBuildAnalysisPort = {
async inspectAvailability() {
throw new Error("must not probe");
},
async close() {},
async execute() {
throw new Error("must not execute");
},
};
const malformedSelections: readonly unknown[] = [
{ path: "/targets/app.apk", extra: true },
{ path: 7 },
{},
{ path: "/targets/app.apk", abi: "not a locale" },
];
it.each(malformedSelections)("refuses %j at admission", async (input) => {
const settled = await new FlutterBuildAnalysisService(refusing).execute(
"identify_flutter_build",
input,
);
expect(settled.ok).toBe(false);
if (settled.ok) return;
expect(settled.error._tag).toBe("AnalysisInputError");
});
it("passes the validated request to the provider and seals Evidence", async () => {
const seen: unknown[] = [];
const recording: FlutterBuildAnalysisPort = {
async inspectAvailability() {
return { status: "available", code: null, reason: null, diagnostics: {} };
},
async close() {},
async execute(request) {
seen.push(request);
return ok(execution);
},
};
const result = await new FlutterBuildAnalysisService(recording).execute(
"identify_flutter_build",
{ path: "/targets/app.apk" },
);
expect(seen).toEqual([
{
operation: "identify_flutter_build",
input: { path: "/targets/app.apk" },
},
]);
if (!result.ok) throw new Error(result.error.message);
const evidence = parseEvidence(result.value);
expect(evidence.provider).toEqual(identity);
expect(evidence.confidence).toBe("observed");
});
it("settles an already-aborted call as cancellation before execution", async () => {
const controller = new AbortController();
controller.abort();
const settled = await new FlutterBuildAnalysisService(refusing).execute(
"identify_flutter_build",
{ path: "/targets/app.apk" },
{
signal: controller.signal,
},
);
expect(settled.ok).toBe(false);
if (settled.ok) return;
expect(settled.error).toBeInstanceOf(AnalysisCancelledError);
});
@@ -0,0 +1,31 @@
import type { FlutterBuildAnalysisPort } from "./FlutterBuildAnalysisPort.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
flutterRequestSchema,
type FlutterOperation,
} from "../../domain/flutter/flutterBuildAnalysis.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { executeProviderOperation } from "../ProviderOperationExecution.js";
import type { Result } from "../../domain/result.js";
/** Shared CLI/MCP admission, execution, and Evidence composition for Flutter. */
export class FlutterBuildAnalysisService {
constructor(readonly provider: FlutterBuildAnalysisPort) {}
/** Run one caller-selected Flutter request and retain target identity inline. */
execute(
operation: FlutterOperation,
input: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
return executeProviderOperation(
operation,
input,
options,
flutterRequestSchema,
this.provider,
"observed",
);
}
}
@@ -986,3 +986,39 @@ it("serializes script loading against concurrent close and unloads the loaded sc
expect(bindings.device.session.scripts[0]?.isDestroyed).toBe(true);
expect(bindings.device.session.isDetached()).toBe(true);
});
it("names the unknown session or script ID it rejects", async () => {
const { manager, started } = await startLocalAttachedSession();
if (!started.ok) throw started.error;
const missing = "00000000-0000-4000-8000-000000000009";
const sessionIssue = {
path: ["session_id"],
reason: "invalid_value",
message: `No open Frida session ${missing}; start one with start_frida_session.`,
};
for (const result of [
await manager.closeSession(missing),
await manager.resumeSession(missing),
await manager.loadScript(missing, { sourceKind: "inline", source: "" }),
await manager.unloadScript(missing, missing),
])
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", issues: [sessionIssue] },
});
expect(
await manager.unloadScript(started.value.sessionId, missing),
).toMatchObject({
ok: false,
error: {
issues: [
{
path: ["script_id"],
reason: "invalid_value",
message: `No loaded Frida script ${missing} in this session.`,
},
],
},
});
await manager.closeAll();
});
@@ -1,3 +1,6 @@
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, it } from "vitest";
import type { FridaInstrumentationPort } from "./FridaInstrumentationPort.js";
@@ -102,6 +105,66 @@ it.each(["startSession", "instrument"] as const)(
},
);
it.each([
[join(tmpdir(), "rea-missing-frida-script.js"), "no file exists there"],
[tmpdir(), "it is not a regular file"],
])(
"rejects the unreadable script file %s before starting Frida",
async (path, reason) => {
let starts = 0;
const provider = createProvider({
async startSession() {
starts += 1;
return { ok: true, value: createSession() };
},
});
const service = new FridaInstrumentationService(provider);
const result = await service.instrument({
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: { sourceKind: "file", path },
durationMs: 1,
});
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(AnalysisInputError);
expect((result.error as AnalysisInputError).issues).toEqual([
{
path: ["path"],
reason: "invalid_value",
message: `Cannot read Frida script file ${path}: ${reason}.`,
},
]);
expect(starts).toBe(0);
},
);
it("reports cancellation before checking a file script source", async () => {
const service = new FridaInstrumentationService(createProvider());
const controller = new AbortController();
controller.abort(new Error("cancelled before call"));
const result = await service.instrument(
{
mode: "spawn",
deviceId: "local",
program: "/tmp/fixture",
source: {
sourceKind: "file",
path: join(tmpdir(), "rea-missing-frida-script.js"),
},
durationMs: 1,
},
controller.signal,
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
});
it("does not resume a spawned target when cancellation arrives during script loading", async () => {
const controller = new AbortController();
let resumes = 0;
@@ -1,11 +1,15 @@
import { constants } from "node:fs";
import { access, stat } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
@@ -19,6 +23,64 @@ import type {
StartFridaSessionInput,
} from "./FridaInstrumentationPort.js";
const unreadableScriptFile = async (
source: FridaScriptSource,
): Promise<AnalysisError | undefined> => {
if (source.sourceKind !== "file") return undefined;
let reason: string;
let cause: unknown;
try {
if (!(await stat(source.path)).isFile())
reason = "it is not a regular file";
else {
await access(source.path, constants.R_OK);
return undefined;
}
} catch (failure: unknown) {
cause = failure;
const code =
failure instanceof Error && "code" in failure ? failure.code : undefined;
if (code === "EACCES" || code === "EPERM")
return new AnalysisAccessDeniedError(
"instrument_with_frida",
source.path,
code,
{ cause },
);
reason =
code === "ENOENT" ? "no file exists there" : String(code ?? failure);
}
return new AnalysisInputError(
"instrument_with_frida",
cause === undefined ? undefined : { cause },
[
{
path: ["path"],
reason: "invalid_value",
message: `Cannot read Frida script file ${source.path}: ${reason}.`,
},
],
);
};
/**
* Reject an unreadable script file before any attach or spawn effect;
* cancellation before or during the check still wins.
*/
const rejectBeforeStart = async (
source: FridaScriptSource,
signal: AbortSignal | undefined,
): Promise<AnalysisError | undefined> => {
const cancelled = () =>
new AnalysisCancelledError(
"instrument_with_frida",
signal?.reason === undefined ? {} : { cause: signal.reason },
);
if (signal?.aborted) return cancelled();
const unreadable = await unreadableScriptFile(source);
return signal?.aborted ? cancelled() : unreadable;
};
/** Shared CLI/MCP workflows for Frida's device and instrumentation operations. */
export class FridaInstrumentationService {
readonly #provider: FridaInstrumentationPort;
@@ -163,6 +225,8 @@ export class FridaInstrumentationService {
AnalysisError
>
> {
const rejected = await rejectBeforeStart(input.source, signal);
if (rejected !== undefined) return err(rejected);
const started = await this.#startSession(
input,
signal,
+27
View File
@@ -0,0 +1,27 @@
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
/** A session ID that names no open Frida session owned by this process. */
export const unknownFridaSession = (
operation: string,
sessionId: string,
): AnalysisInputError =>
new AnalysisInputError(operation, undefined, [
{
path: ["session_id"],
reason: "invalid_value",
message: `No open Frida session ${sessionId}; start one with start_frida_session.`,
},
]);
/** A script ID that names no loaded script in the selected session. */
export const unknownFridaScript = (
operation: string,
scriptId: string,
): AnalysisInputError =>
new AnalysisInputError(operation, undefined, [
{
path: ["script_id"],
reason: "invalid_value",
message: `No loaded Frida script ${scriptId} in this session.`,
},
]);
@@ -26,6 +26,7 @@ import {
} from "../../domain/residualUnknown.js";
import { err, ok, type Result } from "../../domain/result.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import type { UnknownPage, UnknownQuery } from "./InvestigationRecordPort.js";
type EvidenceLedgerFailure = EvidenceIntegrityError;
type RecordResult = Result<"added" | "duplicate", EvidenceLedgerFailure>;
@@ -326,18 +327,39 @@ export class EvidenceLedger {
readonly domain?: string;
} = {},
): ResidualUnknown[] {
return [...this.#unknownHeads.values()]
return this.listUnknownsPage(filters).items;
}
/** Select a stable page of current heads before detaching record payloads. */
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
const offset = query.offset ?? 0;
const matching = [...this.#unknownHeads.values()]
.filter(
(unknown) =>
(filters.status === undefined || unknown.status === filters.status) &&
(filters.severity === undefined ||
unknown.severity === filters.severity) &&
(filters.domain === undefined || unknown.domain === filters.domain),
(query.status === undefined || unknown.status === query.status) &&
(query.severity === undefined ||
unknown.severity === query.severity) &&
(query.domain === undefined || unknown.domain === query.domain),
)
.sort((left, right) =>
compareUnicodeCodePoints(left.unknown_id, right.unknown_id),
)
.map((unknown) => structuredClone(unknown));
);
const start = Math.min(offset, matching.length);
const end =
query.limit === undefined
? undefined
: start + Math.min(query.limit, matching.length - start);
const page = matching.slice(start, end);
const nextOffset =
offset <= matching.length && start + page.length < matching.length
? start + page.length
: null;
return {
items: page.map((unknown) => structuredClone(unknown)),
total: matching.length,
offset,
next_offset: nextOffset,
};
}
/** Return current resolution validity; imported invalid states are rejected. */
@@ -38,6 +38,21 @@ export interface EvidenceUnknownWriter {
): Result<ResidualUnknown | null, AnalysisError>;
}
export type UnknownPage = {
readonly items: ResidualUnknown[];
readonly total: number;
readonly offset: number;
readonly next_offset: number | null;
};
export interface UnknownQuery {
readonly status?: UnknownStatus;
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
readonly offset?: number;
readonly limit?: number;
}
/** Optimistic Unknown revisions and consistency verification. */
export interface UnknownRegistryPort {
recordUnknown(
@@ -51,6 +66,7 @@ export interface UnknownRegistryPort {
readonly severity?: ResidualUnknown["severity"];
readonly domain?: string;
}): ResidualUnknown[];
listUnknownsPage(query?: UnknownQuery): UnknownPage;
verifyUnknownResolution(unknownId: string): Result<
{
readonly valid: boolean;
@@ -19,6 +19,8 @@ import type {
EvidenceWriter,
EvidenceUnknownWriter,
UnknownRegistryPort,
UnknownPage,
UnknownQuery,
} from "./InvestigationRecordPort.js";
/** One investigation's validated record owner, independent of binary execution. */
@@ -124,6 +126,10 @@ export class InvestigationRecords
return this.#evidence.listUnknowns(filters);
}
listUnknownsPage(query: UnknownQuery = {}): UnknownPage {
return this.#evidence.listUnknownsPage(query);
}
/** Verify registry consistency without asserting the answer is true. */
verifyUnknownResolution(unknownId: string): Result<
{
@@ -1,18 +1,11 @@
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import type { ProviderIdentity } from "../AnalysisProvider.js";
import type { CanonicalElectronActiveObservationInput } from "./ElectronActiveObservationPort.js";
import type { Evidence, EvidenceObservation } from "../../domain/evidence.js";
import { createEvidence } from "../../domain/evidence.js";
import type {
ElectronActiveObservationInput,
ElectronActiveObservationResult,
} from "../../domain/javascript/electronActiveObservation.js";
import type { ElectronActiveObservationResult } from "../../domain/javascript/electronActiveObservation.js";
import { jsonObjectSchema, jsonValueSchema } from "../../domain/jsonValue.js";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
readonly application_root: string;
};
/** Commit the selected Electron experiment and its observed result. */
export const createElectronActiveEvidence = (
input: CanonicalElectronActiveObservationInput,
@@ -9,11 +9,15 @@ import type {
} from "../../domain/javascript/electronActiveObservation.js";
import type { Result } from "../../domain/result.js";
/** Caller selections resolved once before entering the runtime adapter. */
export type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & { readonly application_root: string };
/** Provider-neutral boundary for owned Electron runtime experiments. */
export interface ElectronActiveObservationPort {
identity(): ProviderIdentity;
capture(
input: ElectronActiveObservationInput,
input: CanonicalElectronActiveObservationInput,
options?: ExecutionOptions,
): Promise<Result<ElectronActiveObservationResult, AnalysisError>>;
}
@@ -2,57 +2,80 @@ import { dirname } from "node:path";
import { realpath } from "node:fs/promises";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { ElectronActiveObservationPort } from "./ElectronActiveObservationPort.js";
import type {
CanonicalElectronActiveObservationInput,
ElectronActiveObservationPort,
} from "./ElectronActiveObservationPort.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
type AnalysisInputIssue,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import type { ElectronActiveObservationInput } from "../../domain/javascript/electronActiveObservation.js";
import { err, type Result } from "../../domain/result.js";
import { err, ok, type Result } from "../../domain/result.js";
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
const OPERATION = "capture_electron_scenario" as const;
const PROVIDER_ID = "rea-playwright-electron-active";
type CanonicalElectronActiveObservationInput =
ElectronActiveObservationInput & {
readonly application_root: string;
};
const resolveInputPath = async (
field: "executable_path" | "application_path" | "application_root",
selected: string,
): Promise<
Result<
string,
{ readonly issue: AnalysisInputIssue; readonly cause: unknown }
>
> => {
try {
return ok(await realpath(selected));
} catch (cause: unknown) {
return err({
issue: {
path: [field],
reason: "invalid_value",
message: `Cannot resolve ${field} ${selected}: ${cause instanceof Error ? cause.message : String(cause)}`,
},
cause,
});
}
};
const canonicalizeInput = async (
input: ElectronActiveObservationInput,
): Promise<Result<CanonicalElectronActiveObservationInput, AnalysisError>> => {
try {
const [executablePath, applicationPath] = await Promise.all([
realpath(input.executable_path),
realpath(input.application_path),
]);
const applicationRoot =
input.application_root === undefined
? dirname(applicationPath)
: await realpath(input.application_root);
return {
ok: true,
value: {
...input,
executable_path: executablePath,
application_path: applicationPath,
application_root: applicationRoot,
},
};
} catch (cause: unknown) {
const [executable, application, root] = await Promise.all([
resolveInputPath("executable_path", input.executable_path),
resolveInputPath("application_path", input.application_path),
input.application_root === undefined
? Promise.resolve(ok(undefined))
: resolveInputPath("application_root", input.application_root),
]);
if (!executable.ok || !application.ok || !root.ok) {
const failures = [executable, application, root].flatMap((result) =>
result.ok ? [] : [result.error],
);
return err(
new AnalysisInputError(OPERATION, { cause }, [
new AnalysisInputError(
OPERATION,
{
path: ["application_path"],
reason: "invalid_format",
message:
"Electron executable, application, and root must resolve to existing paths",
cause: new AggregateError(
failures.map(({ cause }) => cause),
"Electron paths could not be resolved",
),
},
]),
failures.map(({ issue }) => issue),
),
);
}
return ok({
...input,
executable_path: executable.value,
application_path: application.value,
application_root: root.value ?? dirname(application.value),
});
};
/** Canonicalize request paths and execute one provider-owned Electron run. */
@@ -1,4 +1,6 @@
import { createHash } from "node:crypto";
import { moduleKindForJavaScriptReference } from "./JavaScriptArtifactPathResolution.js";
import { setImmediate } from "node:timers/promises";
import { resolveJavaScriptSourceMapReference } from "../../domain/javascript/javascriptSourceMapPaths.js";
@@ -380,7 +382,10 @@ function* analyzeArtifactFileSteps<
yield;
const semantics =
analysis.parse_status === "complete" || analysis.parse_status === "partial"
? yield* analyzeParsedJavaScriptSemanticsSteps(parsed)
? yield* analyzeParsedJavaScriptSemanticsSteps(
parsed,
moduleKindForJavaScriptReference(file.path, "static-import"),
)
: null;
const projected =
semantics === null
@@ -376,10 +376,14 @@ const resolveReference = (
): ResolvedReference | null => {
const specifier = reference.specifier;
if (specifier === null) return null;
const chunk = resolveBundlerChunkReference(context, sourcePath, reference);
const isWorker =
reference.kind === "worker" || reference.kind === "service-worker";
const chunk = isWorker
? null
: resolveBundlerChunkReference(context, sourcePath, reference);
if (chunk !== null) return chunk;
const module =
reference.module_runtime === undefined
isWorker || reference.module_runtime === undefined
? undefined
: context.moduleNodes.get(
moduleLookupKey(sourcePath, reference.module_runtime, specifier),
@@ -391,24 +395,23 @@ const resolveReference = (
: { path: `${sourcePath}#module:${specifier}`, file, node: module };
}
// Worker scripts are URLs relative to the script, not module specifiers.
const path =
reference.kind === "worker" || reference.kind === "service-worker"
? resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "url-reference",
files: context.filesByPath,
}).resolved_path
: resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require" ||
reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
: undefined,
);
const path = isWorker
? resolveArtifactPathByContext({
declaredPath: specifier,
sourcePath,
context: "url-reference",
files: context.filesByPath,
}).resolved_path
: resolveArtifactPath(
specifier,
sourcePath,
context.filesByPath,
reference.kind === "require" ||
reference.kind === "static-import" ||
reference.kind === "dynamic-import"
? moduleKindForJavaScriptReference(sourcePath, reference.kind)
: undefined,
);
if (path === null) return null;
const file = context.filesByPath.get(path);
const node = context.fileNodes.get(path);
@@ -509,17 +509,6 @@ describe("contextual JavaScript artifact path resolution", () => {
resolution_status: "resolved",
resolved_path: "renderer/local.js",
});
expect(
resolve({
declaredPath: "file:///assets/app.js#entry",
sourcePath: "main.js",
context: "module-specifier",
files,
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
});
it.each(["node:fs", "electron", "../../escape.js", "%2e%2e/escape.js"])(
@@ -576,24 +565,52 @@ describe("contextual JavaScript artifact path resolution", () => {
});
});
describe("CommonJS file URL resolution", () => {
it("keeps file URL resolution specific to the import loader", () => {
const files = fileMap([file("entry.cjs", "root"), file("dep.cjs", "root")]);
const input = {
declaredPath: "file:///dep.cjs",
sourcePath: "entry.cjs",
context: "module-specifier" as const,
files,
};
describe("JavaScript file URL resolution", () => {
it("resolves file URL paths without interpreting query bytes as path syntax", () => {
const files = fileMap([file("assets/app.js", "root")]);
for (const declaredPath of [
"file:///assets/app.js#entry",
"FILE:///assets/app.js?token=%2F#entry",
]) {
expect(
resolve({
declaredPath,
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: "assets/app.js",
});
}
expect(resolve({ ...input, moduleKind: "require" })).toMatchObject({
resolution_status: "external",
resolved_path: null,
});
expect(resolve({ ...input, moduleKind: "import" })).toMatchObject({
resolution_status: "resolved",
resolved_path: "dep.cjs",
});
for (const declaredPath of [
"file:///assets%2Fapp.js",
"file:///assets%2\nFapp.js",
]) {
expect(
resolve({
declaredPath,
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "rejected", resolved_path: null });
}
expect(
resolve({
declaredPath: "file:/assets/app.js",
sourcePath: "main.js",
context: "module-specifier",
moduleKind: "import",
files,
}),
).toMatchObject({ resolution_status: "external", resolved_path: null });
});
});
@@ -2000,15 +2017,143 @@ describe("TypeScript NodeNext emitted-extension resolution", () => {
});
});
describe("url-reference directory and empty-segment semantics", () => {
it.each([
"./worker.js/.",
"./worker.js/child/..",
"./worker.js/",
"/dist/worker.js/.",
"./worker.js/.?cache=1#entry",
])("keeps directory-form URLs distinct from files: %s", (declaredPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file("dist/worker.js", "root")]),
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "not-found",
resolved_path: null,
});
});
it.each(["./nested//worker.js", "./nested//../worker.js"])(
"does not collapse empty URL path segments: %s",
(declaredPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([
file("dist/worker.js", "root"),
file("dist/nested/worker.js", "root"),
]),
}),
).toMatchObject({ resolved_path: null });
},
);
it.each([
["./nested/.././worker.js?cache=1#entry", "dist/worker.js"],
["./.worker.js", "dist/.worker.js"],
])("resolves exact file URLs with dots: %s", (declaredPath, resolvedPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(resolvedPath, "root")]),
}),
).toMatchObject({
resolution_status: "resolved",
resolved_path: resolvedPath,
});
});
});
describe("url-reference JavaScript artifact path resolution", () => {
it.each([
["C|?cache=1#entry", "dist/C|"],
["/c:/worker.js", "c:/worker.js"],
["/./c|/worker.js", "c|/worker.js"],
["../c|/worker.js", "c|/worker.js"],
["/nested/../c|/worker.js", "c|/worker.js"],
["c|/../worker.js", "dist/worker.js"],
])("leaves drive-letter URL paths unresolved: %s", (declaredPath, decoy) => {
const resolution = resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(decoy, "root")]),
});
expect(resolution).toMatchObject({
declared_path: declaredPath,
resolution_status: "unavailable",
resolved_path: null,
});
expect(resolution.limitations.length).toBeGreaterThan(0);
});
it.each([
["./c|/worker.js", "dist/c|/worker.js"],
["c|name/worker.js", "dist/c|name/worker.js"],
["/%63|/worker.js", "c|/worker.js"],
["/c%3A/worker.js", "c:/worker.js"],
])(
"retains non-drive URL path identities: %s",
(declaredPath, resolvedPath) => {
expect(
resolve({
declaredPath,
sourcePath: "dist/app.mjs",
context: "url-reference",
files: fileMap([file(resolvedPath, "root")]),
}),
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: resolvedPath,
});
},
);
it.each(["?value=", "#value="])(
"admits the pathname independently of its %s suffix",
(suffix) => {
for (const value of ["%2F", "%2E", "%5C", "%00", "%FF", "\\", "\0"]) {
const declaredPath = `./worker.js${suffix}${value}`;
expect(
resolve({
declaredPath,
sourcePath: "dist/app.js",
context: "url-reference",
files: fileMap([file("dist/worker.js", "root")]),
}),
declaredPath,
).toMatchObject({
declared_path: declaredPath,
resolution_status: "resolved",
resolved_path: "dist/worker.js",
});
}
},
);
it.each([
"app\0.js.map?valid=1",
"nested\\worker.js#valid",
"app%00.js.map",
"app%FF.js.map",
"app%C0%AF.js.map",
"app%2ejs.map",
"nested%2fworker.js",
"nested%5cworker.js",
"h\nttp://[",
"../../outside.js.map",
"../../outside/.",
])("rejects an inadmissible URL path: %s", (declaredPath) => {
const resolution = resolve({
declaredPath,
@@ -68,12 +68,20 @@ export interface ResolveArtifactPathInput {
export const moduleKindForJavaScriptReference = (
sourcePath: string,
referenceKind: "static-import" | "dynamic-import" | "require",
resolutionMode?: "import" | "require",
): "import" | "require" =>
referenceKind === "require" ||
resolutionMode ??
(referenceKind === "require" ||
(referenceKind === "static-import" &&
posix.extname(sourcePath).toLowerCase() === ".cts")
? "require"
: "import";
: "import");
/** Preserve an explicitly retained loader mode on graph relationships. */
export const moduleResolutionModeProperties = (
mode: "import" | "require" | undefined,
): Readonly<Record<string, "import" | "require">> =>
mode === undefined ? {} : { resolution_mode: mode };
const EXTENSIONS = [
".js",
@@ -145,17 +153,15 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
input.declaredPath.startsWith("#")
)
return resolvePackageImportAlias(input, input.declaredPath);
const rejected = rejectDeclaration(input.declaredPath);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(input);
if (typeof candidate !== "string") return candidate;
const confined = confineCandidate(candidate);
if (typeof confined !== "string") return confined;
if (input.context === "html-reference")
if (input.context === "html-reference" || input.context === "url-reference")
return (
resolveFileCandidates(input, [confined]) ??
unresolvedCandidate("not-found", [
`The exact HTML resource ${confined} was not found among the selected application files.`,
`The exact ${input.context === "html-reference" ? "HTML" : "URL"} resource ${confined} was not found among the selected application files.`,
])
);
const isModuleUrlPath =
@@ -193,19 +199,32 @@ const contextualCandidate = (
input: ResolveArtifactPathInput,
): string | CandidateResolution => {
const { context } = input;
// URL suffixes are evidence, not pathname bytes. Admit only the path while
// retaining the complete declaration on the resolution result.
let declared =
context === "html-reference" || context === "url-reference"
context === "url-reference"
? stripQueryAndFragment(input.declaredPath)
: input.declaredPath;
if (context === "html-reference") return htmlCandidate(input);
if (context === "module-specifier") {
if (context === "module-specifier" && /^file:/iu.test(declared)) {
const fileUrl = fileUrlPath(declared);
if (fileUrl === null)
return unresolvedCandidate("rejected", [
"The file URL path contains syntax that cannot identify a canonical artifact path.",
]);
if (fileUrl !== undefined)
return input.moduleKind === "require"
? unresolvedCandidate("external", [
"Node CommonJS require specifiers do not resolve file URLs as local artifacts.",
])
: fileUrl;
return unresolvedCandidate("external", [
"File URL authorities or invalid file URL forms cannot be mapped to artifact-local paths.",
]);
}
const rejected = rejectDeclaration(declared);
if (rejected !== null) return rejected;
if (context === "html-reference") return htmlCandidate(input);
if (context === "module-specifier") {
if (hasScheme(declared))
return unresolvedCandidate("external", [
"URL and Node builtin schemes are outside static artifact module resolution.",
@@ -222,12 +241,39 @@ const contextualCandidate = (
"URL schemes and protocol-relative URLs are outside this local artifact path context.",
]);
if (context === "url-reference") {
// A file base gives raw drive-letter segments special meaning, including
// after dot segments reach the root. Parse before percent decoding so an
// encoded drive-like filename stays literal. The synthetic base establishes
// only this ambiguity; it does not establish the source's runtime scheme.
const sourceUrlPath = input.sourcePath
.split("/")
.map(encodeURIComponent)
.join("/");
const fileReference = URL.parse(declared, `file:///${sourceUrlPath}`);
if (fileReference === null)
return unresolvedCandidate("rejected", [
"The URL reference cannot be parsed as a URL.",
]);
if (/^\/[A-Za-z]:(?:\/|$)/u.test(fileReference.pathname))
return unresolvedCandidate("unavailable", [
"Drive-letter URL paths cannot be mapped without the source URL scheme and filesystem root.",
]);
const decoded = percentDecodeUrlPath(declared);
if (decoded === null)
return unresolvedCandidate("rejected", [
"The URL reference path percent-decodes to NUL or to bytes that are not UTF-8.",
]);
declared = decoded;
// Empty URL segments are significant; canonical filesystem paths cannot
// preserve them, including their interaction with following dot segments.
if (decoded.includes("//"))
return unresolvedCandidate("unavailable", [
"Repeated URL path separators cannot be mapped to an exact canonical artifact file.",
]);
return exactUrlPathCandidate(
decoded,
relativeCandidate(input.sourcePath, decoded),
"URL",
);
}
return relativeCandidate(input.sourcePath, declared);
};
@@ -681,37 +727,34 @@ const htmlCandidate = (
const basePath = decodedBase.startsWith("/")
? decodedBase.slice(1)
: posix.join(posix.dirname(input.sourcePath), decodedBase);
if (declaredPath === "") return emptyHtmlReference(decodedBase, basePath);
if (declaredPath === "")
return exactUrlPathCandidate(decodedBase, basePath, "HTML");
return posix.join(htmlBaseDirectory(decodedBase, basePath), declaredPath);
};
const emptyHtmlReference = (
base: string,
basePath: string,
const exactUrlPathCandidate = (
declared: string,
candidate: string,
kind: "HTML" | "URL",
): string | CandidateResolution => {
if (!htmlBaseIsDirectory(base)) return basePath;
const confined = confineCandidate(basePath);
if (!urlPathIsDirectory(declared)) return candidate;
const confined = confineCandidate(candidate);
if (typeof confined !== "string") return confined;
return unresolvedCandidate("not-found", [
`The HTML reference resolves to directory ${confined || "."}, not an exact selected application file.`,
`The ${kind} reference resolves to directory ${confined || "."}, not an exact selected application file.`,
]);
};
/**
* The directory a relative HTML reference resolves against. A base path
* ending in "/" or in a "." or ".." segment is already a directory, because a
* relative reference resolves against the base URL's directory and those
* segments are dropped rather than stepped through.
*/
const htmlBaseIsDirectory = (base: string): boolean =>
base.endsWith("/") ||
base.endsWith("/.") ||
base.endsWith("/..") ||
base === "." ||
base === "..";
/** Whether a URL path retains directory form after dot-segment normalization. */
const urlPathIsDirectory = (path: string): boolean =>
path.endsWith("/") ||
path.endsWith("/.") ||
path.endsWith("/..") ||
path === "." ||
path === "..";
const htmlBaseDirectory = (base: string, basePath: string): string =>
htmlBaseIsDirectory(base) ? basePath : posix.dirname(basePath);
urlPathIsDirectory(base) ? basePath : posix.dirname(basePath);
const confineCandidate = (candidate: string): string | CandidateResolution => {
const normalized = normalizeJoinedLogicalPath(candidate);
@@ -854,8 +897,6 @@ const resolveDirectory = (
files: input.files,
...(input.moduleKind === undefined ? {} : { moduleKind: input.moduleKind }),
};
const rejected = rejectDeclaration(entryInput.declaredPath);
if (rejected !== null) return rejected;
const candidate = contextualCandidate(entryInput);
if (typeof candidate !== "string") return candidate;
const confined = confineCandidate(candidate);
@@ -1162,12 +1203,26 @@ const exactPackageTargetNotFound = (
],
});
const fileUrlPath = (value: string): string | undefined => {
if (!value.startsWith("file://")) return undefined;
const fileUrlPath = (value: string): string | null | undefined => {
if (!/^file:\/\//iu.test(value)) return undefined;
// URL parsing removes tabs and newlines and normalizes encoded dot segments.
// Check the raw path first, excluding URL identity suffixes, then check the
// parsed pathname so parser normalization cannot introduce a separator.
const rawPath = stripQueryAndFragment(value);
if (
value.includes("\0") ||
value.includes("\\") ||
/[\t\n\r]/u.test(rawPath) ||
!admitsCanonicalPathSyntax(rawPath)
)
return null;
try {
const url = new URL(value);
if (url.protocol !== "file:" || url.hostname !== "") return undefined;
return decodeURIComponent(url.pathname).replace(/^\/+/, "");
if (!admitsCanonicalPathSyntax(url.pathname)) return null;
const decoded = decodeURIComponent(url.pathname);
if (decoded.includes("\0")) return null;
return decoded.replace(/^\/+/, "");
} catch (cause: unknown) {
// Unparseable file URLs have no path to resolve.
void cause;
@@ -31,6 +31,7 @@ import {
} from "./JavaScriptArtifactGraphEvidence.js";
import {
moduleKindForJavaScriptReference,
moduleResolutionModeProperties,
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "./JavaScriptArtifactPathResolution.js";
@@ -281,6 +282,7 @@ const resolveModuleTarget = (
input.link.kind === "require" || input.link.kind === "commonjs-export"
? "require"
: "static-import",
input.link.resolutionMode,
),
});
if (resolution.resolution_status !== "resolved")
@@ -373,6 +375,7 @@ const relationshipProperties = (
origin?: JavaScriptModuleOrigin,
) => ({
module_link_kind: link.kind,
...moduleResolutionModeProperties(link.resolutionMode),
specifier: origin?.specifier ?? link.specifier,
imported_name: origin?.importedPath.at(-1) ?? link.importedName,
imported_path: origin?.importedPath ?? [],
@@ -0,0 +1,93 @@
import { isAbsolute } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
decodeSignalRecordingInputSchema,
signalRecordingSchema,
type DecodeSignalRecordingInput,
} from "../../domain/signals/signalRecording.js";
import { err, ok, type Result } from "../../domain/result.js";
export interface SignalRecordingPort {
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
decode(
input: DecodeSignalRecordingInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
close(): Promise<void>;
}
/** One shared validation and Evidence owner for CLI and MCP. */
export class SignalRecordingService {
constructor(readonly provider: SignalRecordingPort) {}
close(): Promise<void> {
return this.provider.close();
}
async decode(
raw: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "decode_signal_recording";
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const input = decodeSignalRecordingInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute local path.",
},
]),
);
const decoded = await this.provider.decode(input.data, options);
if (!decoded.ok) return decoded;
const execution = decoded.value;
const report = signalRecordingSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
)
return err(
new AnalysisOutputError(
operation,
"Decoder returned malformed data or changed the selected recording identity/options.",
),
);
const evidence = createEvidence(execution.subject, execution.provider, {
operation,
parameters: input.data,
result: report.data,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
});
return options?.signal?.aborted
? err(
new AnalysisCancelledError(operation, {
partialObservation: evidence,
}),
)
: ok(evidence);
}
}
@@ -0,0 +1,31 @@
import { expect, it } from "vitest";
import { expandProviderCapabilities } from "../../contracts/toolOutputSchemaPrimitives.js";
import { providerCapabilitySets } from "../binary/BinarySessionStatus.js";
import { sqliteDatabaseCapability } from "./SqliteDatabaseCapability.js";
it.each([
["22.23.1", false],
["24.11.0", false],
["24.14.9", false],
["24.15.0", true],
["25.1.0", false],
["26.0.0", true],
["24.15.0-rc.1", false],
["invalid", false],
])(
"reports SQLite inspection availability on Node %s as %s",
(version, available) => {
const [capability] = expandProviderCapabilities(
providerCapabilitySets([sqliteDatabaseCapability(version)]),
);
expect(capability).toMatchObject({
operation: "inspect_sqlite_database",
available,
reason: available
? null
: expect.stringContaining("Node.js 24.x >=24.15 or 26+"),
availability_code: available ? null : "unsupported_version",
limitations: [expect.stringContaining("DatabaseSync.limits")],
});
},
);
@@ -0,0 +1,33 @@
import { satisfies } from "semver";
import { toolContract } from "../../contracts/toolContracts.js";
import { SQLITE_PROVIDER_IDENTITY } from "../../domain/sqlite/sqliteDatabase.js";
const SQLITE_RUNTIME_REQUIREMENT =
"SQLite inspection requires Node.js 24.x >=24.15 or 26+ with the native DatabaseSync.limits API. Other REA features retain their published runtime requirements. The inspection worker verifies the API before querying the snapshot.";
/** Discover inspection readiness without opening a database or starting a worker. */
export const sqliteDatabaseCapability = (nodeVersion: string) => {
const contract = toolContract("inspect_sqlite_database");
const facts = {
operation: contract.name,
provider: SQLITE_PROVIDER_IDENTITY,
effects: {
mutatesArtifact: contract.effects.mutatesTarget,
launchesProcess: contract.effects.launchesProcess,
mayShowUi: contract.effects.changesUiState,
mayAccessNetwork: contract.effects.accessesNetwork,
mayWriteFilesystem: contract.effects.writesFilesystem,
changesPermissions: false,
requiresRoot: false,
},
limitations: [SQLITE_RUNTIME_REQUIREMENT],
};
return satisfies(nodeVersion, "^24.15.0 || >=26.0.0")
? { ...facts, available: true as const, reason: null }
: {
...facts,
available: false as const,
reason: SQLITE_RUNTIME_REQUIREMENT,
availabilityCode: "unsupported_version" as const,
};
};
@@ -0,0 +1,17 @@
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { InspectSqliteDatabaseInput } from "../../domain/sqlite/sqliteDatabase.js";
import type { Result } from "../../domain/result.js";
/** Offline database inspection boundary shared by CLI and MCP. */
export interface SqliteDatabasePort {
/** Await and retry provider-owned snapshot cleanup. */
close?(): Promise<void>;
inspect(
input: InspectSqliteDatabaseInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,147 @@
import { expect, it } from "vitest";
import { SqliteDatabaseService } from "./SqliteDatabaseService.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err } from "../../domain/result.js";
import { ok } from "../../domain/result.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
const fixture = () => ({
artifact: { path: "/selected.db", sha256: "a".repeat(64), bytes: 4096 },
wal: null,
engine: { name: "SQLite", version: "3.50.2" },
database_encoding: "UTF-8",
schema: {
scope: "inventory",
completeness: "complete",
tables: [],
indexes: [],
views: [],
triggers: [],
},
rows: null,
limitations: [],
});
const execution = (value: unknown) =>
createAnalysisExecution(
value,
{ id: "sqlite", name: "SQLite", version: "3.50.2" },
{
subject: { path: "/selected.db", sha256: "a".repeat(64), format: "file" },
locations: [{ kind: "artifact-path", path: "/selected.db" }],
},
);
it.each([
{ path: "relative.db" },
{ path: "/selected.db", approval: true },
{ path: "/selected.db", row_limit: 1 },
{ path: "/selected.db", table: 1 },
{ path: "/selected.db", table: "data", row_limit: 0 },
{
path: "/selected.db",
table: "data",
row_limit: Number.MAX_SAFE_INTEGER + 1,
},
])(
"rejects invalid SQLite selection before provider effects: %j",
async (input) => {
const service = new SqliteDatabaseService({
inspect: () => {
throw new Error("Invalid selection must not read a database");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
},
);
it("preserves producer failures and rejects pre-cancelled requests before effects", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"rea-sqlite",
"inspect_sqlite_database",
"Selected worker could not start",
);
const service = new SqliteDatabaseService({
inspect: () => Promise.resolve(err(failure)),
});
expect(await service.inspect({ path: "/selected.db" })).toEqual(err(failure));
const signal = AbortSignal.abort();
const untouched = new SqliteDatabaseService({
inspect: () => {
throw new Error("Cancelled selection must not read a database");
},
});
expect(
await untouched.inspect({ path: "/selected.db" }, { signal }),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
});
it.each(["path", "digest", "subject", "wal", "table"])(
"rejects producer results with changed caller binding: %s",
async (problem) => {
const value = fixture();
if (problem === "path") value.artifact.path = "/other.db";
if (problem === "digest") value.artifact.sha256 = "b".repeat(64);
const observed = execution({
...value,
...(problem === "wal"
? { wal: { path: "/other.db-wal", sha256: "b".repeat(64), bytes: 32 } }
: {}),
});
const service = new SqliteDatabaseService({
inspect: () =>
Promise.resolve(
ok({
...observed,
...(problem === "subject" ? { subject: null } : {}),
}),
),
});
expect(
await service.inspect({
path: "/selected.db",
...(problem === "table" ? { table: "selected" } : {}),
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } });
},
);
it("preserves completed observed evidence when cancellation arrives after provider completion", async () => {
const value = fixture();
const service = new SqliteDatabaseService({
inspect: () => Promise.resolve(ok(execution(value))),
});
expect(await service.inspect({ path: "/selected.db" })).toMatchObject({
ok: true,
value: {
confidence: "observed",
subject: {
local_path: "/selected.db",
digest: { sha256: "a".repeat(64) },
},
normalized_result: value,
},
});
const controller = new AbortController();
const cancelled = new SqliteDatabaseService({
inspect: () => {
controller.abort();
return Promise.resolve(ok(execution(value)));
},
});
expect(
await cancelled.inspect(
{ path: "/selected.db" },
{ signal: controller.signal },
),
).toMatchObject({
ok: true,
value: { normalized_result: value },
});
});
@@ -0,0 +1,121 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { SqliteDatabasePort } from "./SqliteDatabasePort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import {
createEvidence,
type Evidence,
type EvidenceSubjectTarget,
} from "../../domain/evidence.js";
import {
inspectSqliteDatabaseInputSchema,
sqliteDatabaseSchema,
type InspectSqliteDatabaseInput,
type SqliteDatabase,
SQLITE_ROW_LIMIT_DEFAULT,
sqliteSchemaScope,
sqliteInspectionParameters,
} from "../../domain/sqlite/sqliteDatabase.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
const OPERATION = "inspect_sqlite_database";
const matchesSelectedDatabase = (
report: SqliteDatabase,
input: InspectSqliteDatabaseInput,
subject: EvidenceSubjectTarget,
): boolean =>
report.artifact.path === input.path &&
subject.path === input.path &&
subject.sha256 === report.artifact.sha256 &&
subject.format === "file" &&
(report.wal === null || report.wal.path === `${input.path}-wal`) &&
report.schema.scope === sqliteSchemaScope(input) &&
(report.schema.scope !== "selected_table" ||
(report.schema.tables.length === 1 &&
report.schema.tables[0]?.name === input.table &&
report.schema.indexes.every((index) => index.table === input.table) &&
report.schema.triggers.every(
(trigger) => trigger.table === input.table,
) &&
report.schema.views.length === 0)) &&
(input.table === undefined
? report.rows === null
: report.rows?.table === input.table &&
report.rows.row_limit === (input.row_limit ?? SQLITE_ROW_LIMIT_DEFAULT) &&
(input.columns === undefined ||
(report.rows.columns.length === input.columns.length &&
report.rows.columns.every(
(name, index) => name === input.columns?.[index],
))));
/** Shared snapshot inspection and caller-selection validation for CLI and MCP. */
export class SqliteDatabaseService {
constructor(readonly provider: SqliteDatabasePort) {}
/** Await provider shutdown, retaining failed cleanup owners for retry. */
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
/** Inspect an explicit database snapshot and preserve its original database/WAL identity. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectSqliteDatabaseInputSchema.safeParse(rawInput);
if (!input.success)
return err(
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
const execution = inspected.value;
const report = sqliteDatabaseSchema.safeParse(execution.result);
if (
!report.success ||
execution.subject === null ||
!matchesSelectedDatabase(report.data, input.data, execution.subject)
)
return err(
new AnalysisOutputError(
OPERATION,
"SQLite adapter returned malformed data or changed the selected database identity/table/row limit.",
),
);
return ok(
createEvidence(execution.subject, execution.provider, {
operation: OPERATION,
parameters: sqliteInspectionParameters(input.data),
result: jsonValueSchema.parse(report.data),
...(execution.rawResult === null
? {}
: { rawResult: execution.rawResult }),
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
}),
);
}
}