chore: integrate main for process progress verification

This commit is contained in:
N0zoM1z0
2026-10-10 17:33:17 +08:00
252 changed files with 13258 additions and 1040 deletions
@@ -1,4 +1,9 @@
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
import {
parse as parseYaml,
parseDocument as parseYamlDocument,
stringify as stringifyYaml,
} from "yaml";
import { isDeepStrictEqual } from "node:util";
import {
applyEdits,
@@ -70,6 +75,7 @@ export const clientConfigurationServersKey = (
switch (format) {
case "toml":
case "grok":
case "hermes":
return "mcp_servers";
case "opencode":
return "mcp";
@@ -93,6 +99,12 @@ const parseDocument = (
): Record<string, unknown> => {
if (format === "toml" || format === "grok")
return objectSchema.parse(parseToml(text));
// 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));
// Hermes stores MCP servers in `mcp_servers` inside a YAML document.
if (format === "hermes") return objectSchema.parse(parseYaml(text));
// An empty file, which some clients create before any server is added,
// holds no settings to preserve.
if (isEmptyClientConfigurationText(text)) return {};
@@ -1265,6 +1277,8 @@ export const serializeClientConfiguration = (
return serializeCodexConfiguration(document, originalText);
if (format === "grok")
return serializeGrokConfiguration(document, originalText);
if (format === "hermes")
return serializeHermesConfiguration(document, originalText);
// An empty original holds no comments or settings to preserve. Writing a
// fresh document also keeps a lone BOM from shifting past the closing brace.
if (
@@ -1303,6 +1317,34 @@ export const legacyClientServerPath = (
? [parsed.serversPath[0] ?? "mcp", name]
: undefined;
/**
* Keep an existing Hermes `config.yaml` intact aside from the REA server entry.
* Hermes config files carry user comments and unrelated settings, so the rea
* entry is upserted into the parsed YAML document (which retains formatting and
* comments) rather than re-serializing the whole object.
*/
const serializeHermesConfiguration = (
document: Record<string, unknown>,
originalText: string | undefined,
): string => {
if (
originalText === undefined ||
isEmptyClientConfigurationText(originalText)
)
return stringifyYaml(document);
const serversKey = clientConfigurationServersKey("hermes");
const servers = document[serversKey];
const entry =
typeof servers === "object" && servers !== null
? (servers as Record<string, unknown>)[PRODUCT_IDENTITY.mcpServerKey]
: undefined;
const yamlDocument = parseYamlDocument(originalText);
if (entry === undefined)
yamlDocument.deleteIn([serversKey, PRODUCT_IDENTITY.mcpServerKey]);
else yamlDocument.setIn([serversKey, PRODUCT_IDENTITY.mcpServerKey], entry);
return yamlDocument.toString();
};
/** Build the stdio entry shape expected by one client's configuration dialect. */
export const clientRegistrationEntry = (
format: ClientRegistrationDialect,
@@ -1331,6 +1373,7 @@ export const clientRegistrationEntry = (
};
case "vscode":
case "omp":
case "pi":
return {
type: "stdio",
command: executable,
@@ -1353,6 +1396,15 @@ export const clientRegistrationEntry = (
args,
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
};
case "hermes":
// Hermes reads stdio servers from `mcp_servers.<name>` and connects them
// unless `enabled` is false, so the entry states it explicitly.
return {
command: executable,
args,
...(Object.keys(environment).length === 0 ? {} : { env: environment }),
enabled: true,
};
default:
return {
command: executable,
@@ -1361,3 +1413,45 @@ export const clientRegistrationEntry = (
};
}
};
/** Parse one Gemini policy at its source boundary before consolidating scopes. */
export const parseGeminiMcpPolicy = (parsed: ClientConfigurationDocument) =>
z
.object({
allowed: z.array(z.string()).optional(),
excluded: z.array(z.string()).optional(),
})
.passthrough()
.parse(parsed.document.mcp ?? {});
/** Gemini consolidates excludes by union and allowlists by normalized intersection. */
export const geminiServerPolicyBlock = (
policies: readonly ReturnType<typeof parseGeminiMcpPolicy>[],
serverKey: string,
): string | undefined => {
if (policies.some(({ excluded }) => excluded?.includes(serverKey)))
return `Gemini mcp.excluded blocks ${serverKey}. Review the selected settings policies before rerunning setup.`;
const allowlists = policies.flatMap(({ allowed }) =>
allowed === undefined ? [] : [allowed],
);
const allowed = allowlists.reduce<string[] | undefined>(
(previous, current) => {
if (previous === undefined) return current;
const normalized = new Set(
current.map((name) => name.toLowerCase().trim()),
);
return previous.filter((name) =>
normalized.has(name.toLowerCase().trim()),
);
},
undefined,
);
// Gemini's manager applies the consolidated allowlist only when nonempty.
if (
allowed !== undefined &&
allowed.length > 0 &&
!allowed.includes(serverKey)
)
return `Gemini mcp.allowed does not include ${serverKey}. Review the selected settings policies before rerunning setup.`;
return undefined;
};
+108
View File
@@ -0,0 +1,108 @@
import { err, ok, type Result } from "../domain/result.js";
import { readFile } from "node:fs/promises";
import {
effectiveClientServer,
parseClientConfiguration,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import type { SetupClient } from "./SupportedClients.js";
/** A named source failure that setup can explain without losing the bad path. */
export interface ClientConfigurationFileError {
readonly kind: "unreadable" | "malformed";
readonly path: string;
readonly detail: string;
}
/** Preserve named read failures and distinguish a missing source from an empty file. */
export const readConfigurationText = async (
path: string,
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
try {
return ok(await readFile(path, "utf8"));
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
return ok(undefined);
return err({
kind: "unreadable",
path,
detail: `Configuration ${path} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`,
});
}
};
/** Read and parse one configuration at its source boundary. */
export const readConfigurationFile = async (
path: string,
format: SetupClient["format"],
): Promise<
Result<ClientConfigurationDocument | undefined, ClientConfigurationFileError>
> => {
const source = await readConfigurationText(path);
if (!source.ok) return source;
const content = source.value;
if (content === undefined) return ok(undefined);
try {
return ok(parseClientConfiguration(content, format));
} catch (cause: unknown) {
return err({
kind: "malformed",
path,
detail: `Configuration ${path} is malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
});
}
};
/** Read every applicable user file; malformed lower-priority files also stop setup. */
export const readClientConfigurationFiles = async (
client: SetupClient,
): Promise<
Result<readonly ClientConfigurationDocument[], ClientConfigurationFileError>
> => {
const documents: ClientConfigurationDocument[] = [];
for (const path of client.configPaths ?? [client.configPath]) {
const document = await readConfigurationFile(path, client.format);
if (!document.ok) return document;
if (document.value !== undefined) documents.push(document.value);
}
return ok(documents);
};
/** OpenCode merges server objects in file order, replacing arrays and scalar values. */
const mergeConfigurationValue = (previous: unknown, next: unknown): unknown => {
if (!isObject(previous) || !isObject(next)) return next;
return Object.fromEntries(
[...new Set([...Object.keys(previous), ...Object.keys(next)])].map(
(key) => [
key,
Object.hasOwn(next, key)
? mergeConfigurationValue(previous[key], next[key])
: previous[key],
],
),
);
};
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Project a client's effective user registration without modifying its source files. */
export const effectiveClientConfiguration = (
documents: readonly ClientConfigurationDocument[],
): ClientConfigurationDocument | undefined => {
const last = documents.at(-1);
if (last === undefined) return undefined;
if (documents.length === 1) return last;
const servers: Record<string, unknown> = {};
for (const document of documents) {
const names = new Set([
...Object.keys(document.legacyServers),
...Object.keys(document.servers),
]);
for (const name of names)
servers[name] = mergeConfigurationValue(
servers[name],
effectiveClientServer(document, name),
);
}
return { ...last, servers, legacyServers: {} };
};
+72 -30
View File
@@ -1,10 +1,14 @@
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
import {
effectiveClientConfiguration,
readClientConfigurationFiles,
} from "./ClientConfigurationFiles.js";
import {
clientServerForcedEnabled,
clientServerListedDisabled,
effectiveClientServer,
parseClientConfiguration,
} from "./ClientConfigurationDocument.js";
import { access, readFile } from "node:fs/promises";
import { access } from "node:fs/promises";
import { resolve } from "node:path";
import { z } from "zod";
@@ -16,6 +20,7 @@ import {
npxRegistrationCommand,
} from "./ClientRegistrationIdentity.js";
import {
clientEvidencePaths,
manualRegistrationRemediation,
supportedClients,
} from "./SupportedClients.js";
@@ -78,28 +83,19 @@ export const readClientRegistrationStatuses = async (
for (const client of supportedClients(
home,
options.platform,
options.environment === undefined
? undefined
: {
APPDATA: options.environment.APPDATA,
CLAUDE_CONFIG_DIR: options.environment.CLAUDE_CONFIG_DIR,
CODEX_HOME: options.environment.CODEX_HOME,
COPILOT_HOME: options.environment.COPILOT_HOME,
GROK_HOME: options.environment.GROK_HOME,
OMP_PROFILE: options.environment.OMP_PROFILE,
OPENCODE_CONFIG: options.environment.OPENCODE_CONFIG,
PI_CODING_AGENT_DIR: options.environment.PI_CODING_AGENT_DIR,
PI_CONFIG_DIR: options.environment.PI_CONFIG_DIR,
PI_PROFILE: options.environment.PI_PROFILE,
SAND_DATA_ROOT: options.environment.SAND_DATA_ROOT,
XDG_CONFIG_HOME: options.environment.XDG_CONFIG_HOME,
},
options.environment,
)) {
if (
!(await exists(client.markerPath)) &&
!(await exists(client.configPath))
)
if (client.configPathError !== undefined) {
statuses.push({
client: client.name,
config_path: client.configPath,
command: [],
state: "invalid",
remediation: client.configPathError,
});
continue;
}
if (!(await clientEvidencePresent(client))) continue;
const manualRemediation = manualRegistrationRemediation(client.name);
if (client.format === "unsupported") {
if (manualRemediation !== undefined)
@@ -113,8 +109,36 @@ export const readClientRegistrationStatuses = async (
continue;
}
try {
const content = await readFile(client.configPath, "utf8");
const parsed = parseClientConfiguration(content, client.format);
const files = await readClientConfigurationFiles(client);
if (!files.ok) {
statuses.push({
client: client.name,
config_path: client.configPath,
command: [],
state: "invalid",
remediation: files.error.detail,
});
continue;
}
const parsed = effectiveClientConfiguration(files.value);
if (parsed === undefined) {
statuses.push(
unavailableStatus(client.name, client.configPath, "missing"),
);
continue;
}
const policy = await readClientPolicyBlock(client, parsed);
if (!policy.ok) {
statuses.push({
client: client.name,
config_path: client.configPath,
command: [],
state: "invalid",
remediation: policy.error.detail,
});
continue;
}
const policyBlock = policy.value;
const raw = effectiveClientServer(parsed, PRODUCT_IDENTITY.mcpServerKey);
if (raw === undefined) {
statuses.push(
@@ -139,9 +163,14 @@ export const readClientRegistrationStatuses = async (
options.platform ?? process.platform,
clientServerForcedEnabled(parsed, PRODUCT_IDENTITY.mcpServerKey),
) &&
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey)
!clientServerListedDisabled(
parsed,
PRODUCT_IDENTITY.mcpServerKey,
) &&
policyBlock === undefined
? "aligned"
: "stale",
policyBlock,
),
);
} catch (cause: unknown) {
@@ -168,7 +197,7 @@ const registrationAligned = (
): boolean => {
const command = [registration.command, ...registration.args];
if (
registration.disabled === true ||
(client.format !== "grok" && registration.disabled === true) ||
(registration.enabled === false && !forcedEnabled)
)
return false;
@@ -181,9 +210,9 @@ const registrationAligned = (
)
return false;
if (client.format === "vscode" && registration.type !== "stdio") return false;
// OMP infers stdio for a command entry without an explicit type.
// OMP and Pi infer stdio for a command entry without an explicit type.
if (
client.format === "omp" &&
(client.format === "omp" || client.format === "pi") &&
registration.type !== undefined &&
registration.type !== "stdio"
)
@@ -245,7 +274,7 @@ const parseRegistration = (
if (client.format === "commandcode" && registration.transport !== "stdio")
throw new TypeError("Expected an stdio registration");
if (
client.format === "omp" &&
(client.format === "omp" || client.format === "pi") &&
registration.type !== undefined &&
registration.type !== "stdio"
)
@@ -261,10 +290,17 @@ const configuredStatus = (
configPath: string,
command: RegistrationCommand,
state: "aligned" | "stale",
policyRemediation?: string,
): ClientRegistrationStatus =>
state === "aligned"
? { client, config_path: configPath, command, state, remediation: null }
: { client, config_path: configPath, command, state, remediation };
: {
client,
config_path: configPath,
command,
state,
remediation: policyRemediation ?? remediation,
};
const unavailableStatus = (
client: string,
@@ -278,6 +314,12 @@ const unavailableStatus = (
remediation,
});
const clientEvidencePresent = async (client: SetupClient): Promise<boolean> => {
for (const path of clientEvidencePaths(client))
if (await exists(path)) return true;
return false;
};
const exists = async (path: string | undefined): Promise<boolean> => {
if (path === undefined) return false;
try {
+2 -2
View File
@@ -16,7 +16,6 @@ import {
type LinuxDistribution,
} from "./LinuxHopper.js";
import {
claudeCodeSkillsDirectory,
readInstalledSkillIdentity,
type InstalledSkillIdentity,
} from "./SetupSkill.js";
@@ -441,7 +440,8 @@ export const systemDoctorHost = (
readInstalledSkillIdentity(
homeDirectory,
clientIds,
claudeCodeSkillsDirectory(homeDirectory, environment),
environment,
platform,
),
clientRegistrations: () =>
readClientRegistrationStatuses(homeDirectory, undefined, {
+202
View File
@@ -0,0 +1,202 @@
import { realpath } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { stripComments } from "jsonc-parser";
import { z } from "zod";
import { err, ok, type Result } from "../domain/result.js";
import { PRODUCT_IDENTITY } from "../identity.js";
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
import {
clientConfigurationValuesEqual,
clientRegistrationEntry,
geminiServerPolicyBlock,
parseGeminiMcpPolicy,
type ClientConfigurationDocument,
} from "./ClientConfigurationDocument.js";
import {
readConfigurationFile,
readConfigurationText,
type ClientConfigurationFileError,
} from "./ClientConfigurationFiles.js";
import type { SetupClient } from "./SupportedClients.js";
type SettingsSource = { path: string; document: ClientConfigurationDocument };
const folderTrustSchema = z
.object({
security: z
.object({
folderTrust: z
.object({ enabled: z.boolean().optional() })
.passthrough()
.optional(),
})
.passthrough()
.optional(),
})
.passthrough();
const trustRulesSchema = z.record(
z.string(),
z.enum(["TRUST_FOLDER", "TRUST_PARENT", "DO_NOT_TRUST"]),
);
const sourceFailure = (
path: string,
cause: unknown,
): ClientConfigurationFileError => ({
kind: "malformed",
path,
detail: `Gemini settings in ${path} are malformed: ${cause instanceof Error ? cause.message : String(cause)}`,
});
// Gemini resolves symlinks when possible and compares macOS/Windows paths without case.
const normalizedPath = async (
path: string,
platform: NodeJS.Platform,
): Promise<string> => {
const physical = await realpath(path).catch(() => path);
const absolute = resolve(physical).replaceAll("\\", "/");
return platform === "win32" || platform === "darwin"
? absolute.toLowerCase()
: absolute;
};
const workspaceTrusted = async (
settings: NonNullable<SetupClient["geminiSettings"]>,
sources: readonly SettingsSource[],
): Promise<Result<boolean, ClientConfigurationFileError>> => {
let enabled = true;
for (const { path, document } of sources) {
const parsed = folderTrustSchema.safeParse(document.document);
if (!parsed.success) return err(sourceFailure(path, parsed.error));
enabled = parsed.data.security?.folderTrust?.enabled ?? enabled;
}
if (settings.trustOverride !== undefined) return ok(settings.trustOverride);
if (!enabled) return ok(true);
const text = await readConfigurationText(settings.trustedFoldersPath);
if (!text.ok) return text;
if (text.value === undefined) return ok(false);
let rules: z.output<typeof trustRulesSchema>;
try {
// Gemini strips comments, but rejects trailing commas, BOMs and invalid trust levels.
rules = trustRulesSchema.parse(JSON.parse(stripComments(text.value)));
} catch (cause: unknown) {
return err(sourceFailure(settings.trustedFoldersPath, cause));
}
const workspace = await normalizedPath(
settings.workspaceDirectory,
settings.platform,
);
let longest = -1;
let trusted = false;
for (const [path, level] of Object.entries(rules)) {
const effective = await normalizedPath(
level === "TRUST_PARENT" ? dirname(path) : path,
settings.platform,
);
if (
(workspace === effective ||
workspace.startsWith(
effective.endsWith("/") ? effective : `${effective}/`,
)) &&
path.length > longest
) {
longest = path.length;
trusted = level !== "DO_NOT_TRUST";
}
}
return ok(trusted);
};
/** Check effective Gemini scopes while preserving their authority and source identity. */
export const readClientPolicyBlock = async (
client: SetupClient,
userDocument?: ClientConfigurationDocument,
desiredRegistration?: unknown,
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
if (client.name !== "gemini_cli" || client.geminiSettings === undefined)
return ok(undefined);
const settings = client.geminiSettings;
const sources: SettingsSource[] = [];
const higher: SettingsSource[] = [];
for (const path of [
settings.defaultsPath,
client.configPath,
settings.systemPath,
]) {
const parsed =
path === client.configPath && userDocument !== undefined
? ok(userDocument)
: await readConfigurationFile(path, "json");
if (!parsed.ok) return parsed;
if (parsed.value !== undefined)
sources.push({ path, document: parsed.value });
}
const workspace = await normalizedPath(
settings.workspaceDirectory,
settings.platform,
);
const home = await normalizedPath(
dirname(dirname(client.configPath)),
settings.platform,
);
if (workspace !== home) {
const path = resolve(
settings.workspaceDirectory,
".gemini",
"settings.json",
);
const document = await readConfigurationFile(path, "json");
if (!document.ok) return document;
if (document.value !== undefined) {
const trusted = await workspaceTrusted(settings, sources);
if (!trusted.ok) return trusted;
if (trusted.value) {
const source = { path, document: document.value };
const systemIndex = sources.findIndex(
(item) => item.path === settings.systemPath,
);
sources.splice(
systemIndex < 0 ? sources.length : systemIndex,
0,
source,
);
higher.push(source);
}
}
}
const system = sources.find(({ path }) => path === settings.systemPath);
if (system !== undefined) higher.push(system);
const policies: ReturnType<typeof parseGeminiMcpPolicy>[] = [];
for (const { path, document } of sources) {
try {
policies.push(parseGeminiMcpPolicy(document));
} catch (cause: unknown) {
return err(sourceFailure(path, cause));
}
}
const policy = geminiServerPolicyBlock(
policies,
PRODUCT_IDENTITY.mcpServerKey,
);
if (policy !== undefined)
return ok(
`${policy} Settings sources: ${sources.map(({ path }) => path).join(", ")}.`,
);
// mcpServers uses shallow merge: the entire same-name definition is replaced.
const override = higher.findLast(({ document }) =>
Object.hasOwn(document.servers, PRODUCT_IDENTITY.mcpServerKey),
);
const desired =
desiredRegistration ??
userDocument?.servers[PRODUCT_IDENTITY.mcpServerKey] ??
clientRegistrationEntry("json", npxRegistrationCommand(), {});
if (
override !== undefined &&
!clientConfigurationValuesEqual(
override.document.servers[PRODUCT_IDENTITY.mcpServerKey],
desired,
)
)
return ok(
`Gemini mcpServers.${PRODUCT_IDENTITY.mcpServerKey} in ${override.path} overrides the user registration. Review that settings file before rerunning setup; REA does not modify system or workspace settings.`,
);
return ok(undefined);
};
+2 -2
View File
@@ -2,8 +2,6 @@ import fs from "node:fs";
import { lstat, readFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { resolveRef } from "isomorphic-git";
export type ReferenceSourceVcsInfo =
| {
readonly kind: "git";
@@ -42,6 +40,8 @@ export const readReferenceSourceVcs = async (
};
const resolveSourceHead = async (root: string): Promise<string> => {
// isomorphic-git is loaded on first use so CLI and MCP startup skip it.
const { resolveRef } = await import("isomorphic-git");
const dotgit = join(root, ".git");
if (!(await lstat(dotgit)).isFile())
return resolveRef({ fs, dir: root, ref: "HEAD" });
+4 -1
View File
@@ -1,3 +1,4 @@
import { skillDestinations } from "./SetupSkill.js";
import {
type ClientConfigurationInspection,
type ClientConfigurationResult,
@@ -18,7 +19,9 @@ import { setupRegistrationCommand } from "./SetupHost.js";
export class FakeSetupHost implements SetupHost {
readonly platform: NodeJS.Platform;
readonly homeDirectory = "/fixture/home";
readonly claudeCodeSkillsDirectory = "/fixture/home/.claude/skills";
skillDestinations(clientIds: readonly string[]) {
return skillDestinations(this.homeDirectory, clientIds);
}
readonly registrationCommand: readonly string[];
nodeVersion = "24.18.0";
version: string | undefined = "14.5";
+70 -1
View File
@@ -1,3 +1,5 @@
import { readClientPolicyBlock } from "./GeminiClientSettings.js";
import { readClientConfigurationFiles } from "./ClientConfigurationFiles.js";
import {
clientRegistrationEntry,
clientConfigurationValuesEqual,
@@ -33,6 +35,8 @@ export const configureClientConfiguration = (
environment: SetupProviderEnvironment = {},
command: readonly string[] = npxRegistrationCommand(),
): Promise<ClientConfigurationResult> => {
if (client.configPathError !== undefined)
return Promise.resolve({ status: "failed", reason: "path" });
if (client.format === undefined || client.format === "unsupported")
return Promise.resolve({ status: "failed", reason: "readback" });
return configureClientDocument(client, environment, command, client.format);
@@ -44,6 +48,15 @@ const configureClientDocument = async (
command: readonly string[],
format: NonNullable<SetupClient["format"]>,
): Promise<ClientConfigurationResult> => {
const files = await readClientConfigurationFiles(client);
if (!files.ok) return { status: "failed", reason: "readback" };
const policy = await readClientPolicyBlock(
client,
undefined,
clientConfigurationDesired(client, environment, command, client.format),
);
if (!policy.ok || policy.value !== undefined)
return { status: "failed", reason: "readback" };
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
@@ -61,6 +74,13 @@ const configureClientDocument = async (
original ?? (format === "toml" || format === "grok" ? "" : "{}"),
format,
);
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(client, environment, command, parsed.dialect),
);
if (!policy.ok || policy.value !== undefined)
return { status: "failed", reason: "readback" };
} catch (cause: unknown) {
// Malformed existing configuration fails the readback gate.
void cause;
@@ -154,10 +174,14 @@ export const clientConfigurationAligned = async (
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<boolean> => {
if (client.configPathError !== undefined) return false;
try {
const files = await readClientConfigurationFiles(client);
if (!files.ok) return false;
const original = await readFile(client.configPath, "utf8");
const parsed = parseClientConfiguration(original, client.format);
return registrationCurrent(
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(
client,
@@ -166,6 +190,19 @@ export const clientConfigurationAligned = async (
parsed.dialect,
),
);
return (
policy.ok &&
policy.value === undefined &&
registrationCurrent(
parsed,
clientConfigurationDesired(
client,
providerEnvironment,
command,
parsed.dialect,
),
)
);
} catch (cause: unknown) {
// Unreadable configuration is treated as not aligned so setup repairs it.
void cause;
@@ -179,7 +216,25 @@ export const inspectClientConfiguration = async (
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
): Promise<ClientConfigurationInspection> => {
if (client.configPathError !== undefined)
return { status: "invalid", remediation: client.configPathError };
if (client.format === "unsupported") return { status: "already_current" };
const files = await readClientConfigurationFiles(client);
if (!files.ok) return { status: "invalid", remediation: files.error.detail };
const policy = await readClientPolicyBlock(
client,
undefined,
clientConfigurationDesired(
client,
providerEnvironment,
command,
client.format,
),
);
if (!policy.ok)
return { status: "invalid", remediation: policy.error.detail };
if (policy.value !== undefined)
return { status: "invalid", remediation: policy.value };
const transactionPath = await resolveClientConfigTransactionPath(
client.configPath,
);
@@ -202,6 +257,20 @@ export const inspectClientConfiguration = async (
}
try {
const parsed = parseClientConfiguration(original, client.format);
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(
client,
providerEnvironment,
command,
parsed.dialect,
),
);
if (!policy.ok)
return { status: "invalid", remediation: policy.error.detail };
if (policy.value !== undefined)
return { status: "invalid", remediation: policy.value };
const desired = clientConfigurationDesired(
client,
providerEnvironment,
+19 -14
View File
@@ -14,9 +14,13 @@ import {
systemLinuxHopperInstallHost,
} from "./LinuxHopper.js";
import { installMacHopper, systemMacHopperInstallHost } from "./MacHopper.js";
import { supportedClients, type SetupClient } from "./SupportedClients.js";
import {
claudeCodeSkillsDirectory as resolveClaudeCodeSkillsDirectory,
clientEvidencePaths,
supportedClients,
type SetupClient,
} from "./SupportedClients.js";
import {
skillDestinations,
canonicalSkillNeedsInstall,
installCanonicalSkill,
} from "./SetupSkill.js";
@@ -90,14 +94,11 @@ export const systemSetupHost = (
const doctorHost = selectedDoctorHost ?? systemDoctorHost({ environment });
const platform = doctorHost.platform;
const { homeDirectory } = doctorHost;
const claudeSkillsDirectory = resolveClaudeCodeSkillsDirectory(
homeDirectory,
environment,
);
return {
platform,
homeDirectory,
claudeCodeSkillsDirectory: claudeSkillsDirectory,
skillDestinations: (clientIds) =>
skillDestinations(homeDirectory, clientIds, environment, platform),
registrationCommand: setupRegistrationCommand(
platform,
environment.npm_command === "exec",
@@ -153,10 +154,11 @@ export const systemSetupHost = (
canonicalSkillNeedsInstall(
homeDirectory,
clientIds,
claudeSkillsDirectory,
environment,
platform,
),
installSkill: (clientIds) =>
installCanonicalSkill(homeDirectory, clientIds, claudeSkillsDirectory),
installCanonicalSkill(homeDirectory, clientIds, environment, platform),
doctor: (scope) => runDoctor(undefined, doctorHost, scope),
};
};
@@ -169,17 +171,20 @@ export const detectClients = async (
): Promise<readonly SetupClient[]> => {
const detected: SetupClient[] = [];
for (const candidate of supportedClients(home, platform, environment)) {
const [hasConfig, hasMarker] = await Promise.all([
exists(candidate.configPath),
candidate.markerPath === undefined ? false : exists(candidate.markerPath),
]);
if (hasConfig || hasMarker) detected.push(candidate);
if (candidate.configPathError !== undefined) continue;
if (await clientEvidencePresent(candidate)) detected.push(candidate);
}
return detected;
};
const major = (version: string): number =>
Number.parseInt(version.split(".")[0] ?? "0", 10);
const clientEvidencePresent = async (client: SetupClient): Promise<boolean> => {
for (const path of clientEvidencePaths(client))
if (await exists(path)) return true;
return false;
};
const exists = async (path: string): Promise<boolean> => {
try {
await access(path);
+5 -12
View File
@@ -5,7 +5,7 @@ import {
linuxHopperInstallDisclosure,
type LinuxPackageFamily,
} from "./LinuxHopper.js";
import { skillDestinations } from "./SetupSkill.js";
import type { SkillDestination } from "./SetupSkill.js";
import { macHopperInstallDisclosure } from "./MacHopper.js";
import type {
SetupAction,
@@ -188,7 +188,7 @@ export const planSetupActions = async (input: {
installHopper: input.discovery.installHopper,
installSkill: input.installSkill,
skillClientIds: input.skillClientIds,
claudeCodeSkillsDirectory: input.host.claudeCodeSkillsDirectory,
skillDestinations: input.host.skillDestinations(input.skillClientIds),
clients: clientPlans,
providerEnvironment: input.providerEnvironment,
...(input.discovery.linuxPackageFamily === undefined
@@ -210,7 +210,7 @@ const setupPlan = (input: {
readonly installHopper: boolean;
readonly installSkill: boolean;
readonly skillClientIds: readonly string[];
readonly claudeCodeSkillsDirectory: string;
readonly skillDestinations: readonly SkillDestination[];
readonly clients: readonly {
readonly client: SetupClient;
readonly operation: "create" | "update";
@@ -268,15 +268,8 @@ const setupPlan = (input: {
...(backupPath === undefined ? {} : { backupPath }),
})),
...(input.installSkill
? skillDestinations(
input.homeDirectory,
input.skillClientIds,
input.claudeCodeSkillsDirectory,
).map(({ client, path }): SetupAction => ({
id:
client === "claude_code"
? "install_skill:claude_code"
: "install_skill",
? input.skillDestinations.map(({ client, path }): SetupAction => ({
id: client === "shared" ? "install_skill" : `install_skill:${client}`,
kind: "install_skill",
label:
client === "claude_code"
+27 -44
View File
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { PRODUCT_IDENTITY } from "../identity.js";
import { clientSkillDirectories } from "./SupportedClients.js";
const SKILL_FILES = [
"SKILL.md",
@@ -21,7 +22,7 @@ interface CanonicalSkillFile {
/** Managed skill location selected for a client family. */
export interface SkillDestination {
readonly client: "shared" | "claude_code";
readonly client: string;
readonly path: string;
}
@@ -32,44 +33,19 @@ export interface InstalledSkillIdentity {
readonly canonical: boolean;
}
/** Resolve Claude Code personal skills from the selected environment. */
export const claudeCodeSkillsDirectory = (
home: string,
environment: { readonly CLAUDE_CONFIG_DIR?: string } = {},
): string =>
join(environment.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "skills");
/** Resolve the skill roots required by a client selection, or all owned roots. */
export const skillDestinations = (
home: string,
clientIds: readonly string[] | undefined,
claudeSkillsDirectory = claudeCodeSkillsDirectory(home),
): readonly SkillDestination[] => {
const includeClaude =
clientIds === undefined || clientIds.includes("claude_code");
const includeShared =
clientIds === undefined ||
clientIds.length === 0 ||
clientIds.some((clientId) => clientId !== "claude_code");
return [
...(includeShared
? [
{
client: "shared" as const,
path: join(home, ".agents/skills", PRODUCT_IDENTITY.skillName),
},
]
: []),
...(includeClaude
? [
{
client: "claude_code" as const,
path: join(claudeSkillsDirectory, PRODUCT_IDENTITY.skillName),
},
]
: []),
];
};
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): readonly SkillDestination[] =>
clientSkillDirectories(home, clientIds, environment, platform).map(
({ client, directory }) => ({
client,
path: join(directory, PRODUCT_IDENTITY.skillName),
}),
);
const readOptionalText = async (path: string): Promise<string | undefined> => {
try {
@@ -84,10 +60,11 @@ const readOptionalText = async (path: string): Promise<string | undefined> => {
const canonicalSkillFiles = async (
home: string,
clientIds: readonly string[],
claudeSkillsDirectory?: string,
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): Promise<readonly CanonicalSkillFile[]> =>
Promise.all(
skillDestinations(home, clientIds, claudeSkillsDirectory).flatMap(
skillDestinations(home, clientIds, environment, platform).flatMap(
({ path: root }) =>
SKILL_FILES.map(async (relativePath) => {
const destination = join(root, relativePath);
@@ -110,11 +87,12 @@ const canonicalSkillFiles = async (
export const canonicalSkillNeedsInstall = async (
home: string,
clientIds: readonly string[] = [],
claudeSkillsDirectory?: string,
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): Promise<boolean> => {
try {
return (
await canonicalSkillFiles(home, clientIds, claudeSkillsDirectory)
await canonicalSkillFiles(home, clientIds, environment, platform)
).some(({ content, original }) => original !== content);
} catch (cause: unknown) {
// Unreadable skill state fails open to install so setup can repair it.
@@ -139,14 +117,16 @@ const restoreSkillFiles = async (
export const installCanonicalSkill = async (
home: string,
clientIds: readonly string[] = [],
claudeSkillsDirectory?: string,
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): Promise<"installed" | "unchanged" | "failed"> => {
let changed: readonly CanonicalSkillFile[] = [];
try {
const canonical = await canonicalSkillFiles(
home,
clientIds,
claudeSkillsDirectory,
environment,
platform,
);
changed = canonical.filter(({ content, original }) => original !== content);
if (changed.length === 0) return "unchanged";
@@ -179,12 +159,14 @@ export const installCanonicalSkill = async (
export const readInstalledSkillIdentity = async (
home: string,
clientIds: readonly string[],
claudeSkillsDirectory?: string,
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): Promise<InstalledSkillIdentity | undefined> => {
const destinations = skillDestinations(
home,
clientIds,
claudeSkillsDirectory,
environment,
platform,
);
let content: string | undefined;
for (const destination of destinations) {
@@ -202,7 +184,8 @@ export const readInstalledSkillIdentity = async (
canonical: !(await canonicalSkillNeedsInstall(
home,
clientIds,
claudeSkillsDirectory,
environment,
platform,
)),
version: /^\s{2}version:\s*"([^"]+)"\s*$/mu.exec(content)?.[1] ?? null,
toolCount: toolCount === undefined ? null : Number.parseInt(toolCount, 10),
+2 -1
View File
@@ -1,5 +1,6 @@
import type { DoctorReport, DoctorScope, runDoctor } from "./Doctor.js";
import type { LinuxDistribution } from "./LinuxHopper.js";
import type { SkillDestination } from "./SetupSkill.js";
import type { SetupClient } from "./SupportedClients.js";
import type {
SetupFailureCode,
@@ -42,7 +43,7 @@ export type ClientConfigurationInspection =
export interface SetupHost {
readonly platform: NodeJS.Platform;
readonly homeDirectory: string;
readonly claudeCodeSkillsDirectory: string;
skillDestinations(clientIds: readonly string[]): readonly SkillDestination[];
readonly registrationCommand: readonly string[];
readonly nodeVersion: string;
macosVersion(): Promise<string | undefined>;
+354 -60
View File
@@ -1,4 +1,5 @@
import { isAbsolute, join } from "node:path";
import { dirname, isAbsolute, join, resolve, win32 } from "node:path";
import { fileURLToPath } from "node:url";
import { lstatSync } from "node:fs";
/** One supported client configuration location. */
@@ -6,6 +7,19 @@ export interface SetupClient {
readonly name: string;
readonly displayName?: string;
readonly configPath: string;
/** User configuration files in increasing precedence, including the write target. */
readonly configPaths?: readonly string[];
/** Read-only Gemini scopes and trust inputs; never setup write targets. */
readonly geminiSettings?: {
readonly systemPath: string;
readonly defaultsPath: string;
readonly workspaceDirectory: string;
readonly trustedFoldersPath: string;
readonly trustOverride?: boolean;
readonly platform: NodeJS.Platform;
};
/** Unresolved path evidence only; consumers must not perform I/O on it. */
readonly configPathError?: string;
readonly markerPath?: string;
readonly format?:
| "json"
@@ -16,6 +30,8 @@ export interface SetupClient {
| "commandcode"
| "grok"
| "omp"
| "pi"
| "hermes"
| "unsupported";
}
@@ -24,20 +40,7 @@ type ClientPath = readonly string[] | ((paths: ClientPathContext) => string);
interface ClientPathContext {
readonly home: string;
readonly platform: NodeJS.Platform;
readonly env: {
readonly APPDATA?: string | undefined;
readonly CLAUDE_CONFIG_DIR?: string | undefined;
readonly CODEX_HOME?: string | undefined;
readonly COPILOT_HOME?: string | undefined;
readonly GROK_HOME?: string | undefined;
readonly OMP_PROFILE?: string | undefined;
readonly OPENCODE_CONFIG?: string | undefined;
readonly PI_CODING_AGENT_DIR?: string | undefined;
readonly PI_CONFIG_DIR?: string | undefined;
readonly PI_PROFILE?: string | undefined;
readonly SAND_DATA_ROOT?: string | undefined;
readonly XDG_CONFIG_HOME?: string | undefined;
};
readonly env: Readonly<NodeJS.ProcessEnv>;
}
interface ClientDefinition {
@@ -46,6 +49,11 @@ interface ClientDefinition {
readonly configPath: ClientPath;
readonly markerPath: ClientPath;
readonly format: NonNullable<SetupClient["format"]>;
readonly skillPath?: ClientPath;
readonly configPaths?: (context: ClientPathContext) => readonly string[];
readonly geminiSettings?: (
context: ClientPathContext,
) => NonNullable<SetupClient["geminiSettings"]>;
}
const vscodeUserDirectory = ({
@@ -83,10 +91,73 @@ const claudeCodeMarkerDirectory = ({ home, env }: ClientPathContext): string =>
env.CLAUDE_CONFIG_DIR ?? join(home, ".claude");
const codexDirectory = ({ home, env }: ClientPathContext): string =>
env.CODEX_HOME ?? join(home, ".codex");
env.CODEX_HOME || join(home, ".codex");
/** Match Qwen Code's home override, including tilde and cwd-relative paths. */
const qwenCodeDirectory = ({ home, env }: ClientPathContext): string => {
const override = env.QWEN_HOME;
if (!override) return join(home, ".qwen");
const expanded =
override === "~"
? home
: override.startsWith("~/") || override.startsWith("~\\")
? join(
home,
...override
.slice(2)
.split(/[/\\]+/)
.filter(Boolean),
)
: override;
return isAbsolute(expanded) ? expanded : resolve(expanded);
};
const grokDirectory = ({ home, env }: ClientPathContext): string =>
env.GROK_HOME ?? join(home, ".grok");
env.GROK_HOME || join(home, ".grok");
/**
* Hermes Agent home. `HERMES_HOME` wins; otherwise the platform default mirrors
* Hermes's own resolver (`%LOCALAPPDATA%\\hermes` on Windows, `~/.hermes`
* elsewhere), including the optional `HERMES_DATA_DIR_SUFFIX` that is appended
* to the literal `hermes`/`.hermes` directory name.
*/
const hermesDirectory = ({
home,
platform,
env,
}: ClientPathContext): string => {
const override = env.HERMES_HOME?.trim();
if (override) {
const expandedVariables = override.replace(
/\$(\w+|\{[^}]*\})/gu,
(match, variable: string) => {
const key = variable.startsWith("{") ? variable.slice(1, -1) : variable;
return env[key] ?? match;
},
);
const expanded =
platform === "win32"
? expandedVariables.replace(
/%([^%]+)%/gu,
(match, variable: string) => env[variable] ?? match,
)
: expandedVariables;
if (expanded === "~") return home;
if (
expanded.startsWith("~/") ||
(platform === "win32" && expanded.startsWith("~\\"))
)
return join(home, expanded.slice(2));
return resolve(expanded);
}
const suffix = env.HERMES_DATA_DIR_SUFFIX ?? "";
return platform === "win32"
? join(
env.LOCALAPPDATA?.trim() || join(home, "AppData", "Local"),
`hermes${suffix}`,
)
: join(home, `.hermes${suffix}`);
};
/** Grok Bot uses an absolute SAND_DATA_ROOT; anything else stays ~/.grokbot. */
const grokBotDirectory = ({ home, env }: ClientPathContext): string => {
@@ -132,17 +203,49 @@ const ompProfile = ({ env }: ClientPathContext): string | undefined => {
/**
* The OMP agent directory whose `mcp.json` holds user-scope MCP servers. OMP
* joins PI_CONFIG_DIR to the home directory, and a named profile ignores
* PI_CODING_AGENT_DIR. OMP resolves a relative agent directory against each
* process's working directory, so only an absolute override names one file.
* PI_CODING_AGENT_DIR. Relative overrides use the setup process working directory.
*/
const ompAgentDirectory = (context: ClientPathContext): string => {
const root = join(context.home, context.env.PI_CONFIG_DIR || ".omp");
const profile = ompProfile(context);
if (profile !== undefined) return join(root, "profiles", profile, "agent");
const override = context.env.PI_CODING_AGENT_DIR;
return override !== undefined && override !== "" && isAbsolute(override)
? override
: join(root, "agent");
return override ? resolve(override) : join(root, "agent");
};
/**
* Pi's public getAgentDir()/normalizePath semantics, not OMP's profiles.
* Keep relative overrides relative: filesystem consumers resolve them in cwd.
*/
const piAgentDirectory = ({
home,
platform,
env,
}: ClientPathContext): string => {
const paths = platform === "win32" ? win32 : { join };
let directory = env.PI_CODING_AGENT_DIR;
if (!directory) return paths.join(home, ".pi", "agent");
if (
platform === "win32" &&
directory.startsWith("/") &&
!directory.startsWith("//") &&
!directory.includes("\\")
) {
const drive = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(
directory,
);
if (drive !== null)
directory = `${drive[1]?.toUpperCase()}:\\${drive[2]?.replaceAll("/", "\\") ?? ""}`;
}
if (directory === "~") return home;
if (
directory.startsWith("~/") ||
(platform === "win32" && directory.startsWith("~\\"))
)
return paths.join(home, directory.slice(2));
if (directory.startsWith("file://"))
return fileURLToPath(directory, { windows: platform === "win32" });
return directory;
};
const copilotDirectory = ({ home, env }: ClientPathContext): string =>
@@ -151,21 +254,66 @@ const copilotDirectory = ({ home, env }: ClientPathContext): string =>
const commandCodeDirectory = ({ home }: ClientPathContext): string =>
join(home, ".commandcode");
const opencodeDirectory = ({ home, env }: ClientPathContext): string =>
join(env.XDG_CONFIG_HOME ?? join(home, ".config"), "opencode");
/**
* OpenCode appends `OPENCODE_CONFIG_DIR` only when the value is non-empty.
* An empty variable is the same as unset and leaves the XDG directory in place.
*/
const openCodeOverrideDirectory = (
env: ClientPathContext["env"],
): string | undefined => {
const directory = env.OPENCODE_CONFIG_DIR;
return directory === undefined || directory === "" ? undefined : directory;
};
const opencodeDirectory = (context: ClientPathContext): string =>
openCodeOverrideDirectory(context.env) ??
join(
context.env.XDG_CONFIG_HOME ?? join(context.home, ".config"),
"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 overrideDirectory = openCodeOverrideDirectory(context.env);
const paths = [
join(directory, "config.json"),
join(directory, "opencode.json"),
join(directory, "opencode.jsonc"),
...(context.env.OPENCODE_CONFIG ? [context.env.OPENCODE_CONFIG] : []),
...(overrideDirectory !== undefined
? [
join(overrideDirectory, "opencode.json"),
join(overrideDirectory, "opencode.jsonc"),
]
: []),
];
const resolved = paths.map((path) => resolve(path));
return resolved.filter((path, index) => resolved.lastIndexOf(path) === index);
};
const existingOpenCodeConfigPath = (context: ClientPathContext): string => {
if (context.env.OPENCODE_CONFIG !== undefined)
return context.env.OPENCODE_CONFIG;
const directory = opencodeDirectory(context);
const candidates = [
"opencode.json",
"opencode.jsonc",
".opencode.json",
".opencode.jsonc",
].map((filename) => join(directory, filename));
// The selected directory is loaded after an explicit file by OpenCode V1.
const overrideDirectory = openCodeOverrideDirectory(context.env);
const candidates =
overrideDirectory !== undefined
? [
join(overrideDirectory, "opencode.json"),
join(overrideDirectory, "opencode.jsonc"),
].map((path) => resolve(path))
: context.env.OPENCODE_CONFIG
? [resolve(context.env.OPENCODE_CONFIG)]
: [
join(opencodeDirectory(context), "opencode.json"),
join(opencodeDirectory(context), "opencode.jsonc"),
].map((path) => resolve(path));
return (
candidates.find((path) => {
[...candidates].reverse().find((path) => {
try {
lstatSync(path);
return true;
@@ -177,21 +325,60 @@ const existingOpenCodeConfigPath = (context: ClientPathContext): string => {
);
}
}) ??
candidates[0] ??
join(directory, "opencode.json")
resolve(
overrideDirectory !== undefined
? join(overrideDirectory, "opencode.json")
: context.env.OPENCODE_CONFIG ||
join(opencodeDirectory(context), "opencode.json"),
)
);
};
const geminiSettings = ({
home,
platform,
env,
}: ClientPathContext): NonNullable<SetupClient["geminiSettings"]> => {
const system =
env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ||
(platform === "darwin"
? "/Library/Application Support/GeminiCli/settings.json"
: platform === "win32"
? "C:\\ProgramData\\gemini-cli\\settings.json"
: "/etc/gemini-cli/settings.json");
const trustOverride =
env.GEMINI_RESTRICTED_MODE === "true" ||
env.GEMINI_CLI_TRUST_WORKSPACE === "false"
? false
: env.GEMINI_CLI_TRUST_WORKSPACE === "true"
? true
: undefined;
return {
systemPath: system,
defaultsPath:
env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ||
join(dirname(system), "system-defaults.json"),
workspaceDirectory: process.cwd(),
trustedFoldersPath:
env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ||
join(env.GEMINI_CLI_HOME || home, ".gemini", "trustedFolders.json"),
...(trustOverride === undefined ? {} : { trustOverride }),
platform,
};
};
const devinDirectory = ({ home, platform, env }: ClientPathContext): string =>
platform === "win32"
? join(env.APPDATA ?? join(home, "AppData", "Roaming"), "devin")
: join(home, ".config", "devin");
: join(env.XDG_CONFIG_HOME || join(home, ".config"), "devin");
/** Stable product metadata used to derive setup discovery and documentation. */
export const SUPPORTED_CLIENT_DEFINITIONS = [
{
name: "claude_code",
displayName: "Claude Code",
skillPath: ({ home, env }: ClientPathContext) =>
join(env.CLAUDE_CONFIG_DIR ?? join(home, ".claude"), "skills"),
configPath: (context: ClientPathContext) =>
join(claudeCodeConfigDirectory(context), ".claude.json"),
markerPath: claudeCodeMarkerDirectory,
@@ -223,8 +410,13 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
{
name: "gemini_cli",
displayName: "Gemini CLI",
configPath: [".gemini", "settings.json"],
markerPath: [".gemini"],
geminiSettings,
configPath: ({ home, env }: ClientPathContext) =>
join(env.GEMINI_CLI_HOME || home, ".gemini", "settings.json"),
markerPath: ({ home, env }: ClientPathContext) =>
join(env.GEMINI_CLI_HOME || home, ".gemini"),
skillPath: ({ home, env }: ClientPathContext) =>
join(env.GEMINI_CLI_HOME || home, ".agents", "skills"),
format: "json",
},
{
@@ -246,12 +438,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
name: "opencode",
displayName: "OpenCode",
configPath: existingOpenCodeConfigPath,
configPaths: openCodeConfigurationPaths,
markerPath: opencodeDirectory,
format: "opencode",
},
{
name: "antigravity",
displayName: "Antigravity",
skillPath: [".gemini", "config", "skills"],
configPath: [".gemini", "config", "mcp_config.json"],
markerPath: [".gemini", "config"],
format: "json",
@@ -272,6 +466,14 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: commandCodeDirectory,
format: "commandcode",
},
{
name: "qwen_code",
displayName: "Qwen Code",
configPath: (context: ClientPathContext) =>
join(qwenCodeDirectory(context), "settings.json"),
markerPath: qwenCodeDirectory,
format: "json",
},
{
name: "vscode",
displayName: "VS Code",
@@ -296,6 +498,27 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
markerPath: ompAgentDirectory,
format: "omp",
},
{
name: "pi",
displayName: "Pi",
configPath: (context: ClientPathContext) =>
(context.platform === "win32" ? win32 : { join }).join(
piAgentDirectory(context),
"mcp.json",
),
markerPath: piAgentDirectory,
format: "pi",
},
{
name: "hermes",
displayName: "Hermes",
skillPath: (context: ClientPathContext) =>
join(hermesDirectory(context), "skills"),
configPath: (context: ClientPathContext) =>
join(hermesDirectory(context), "config.yaml"),
markerPath: hermesDirectory,
format: "hermes",
},
{
name: "grok_bot",
displayName: "Grok Bot",
@@ -305,6 +528,23 @@ export const SUPPORTED_CLIENT_DEFINITIONS = [
},
] as const satisfies readonly ClientDefinition[];
/**
* Paths whose presence means doctor and setup should inspect the client.
* Layered sources count: OpenCode still loads its XDG files when a custom
* directory override does not exist.
*/
export const clientEvidencePaths = (
client: Pick<SetupClient, "configPath" | "configPaths" | "markerPath">,
): readonly string[] => [
...new Set(
[
client.configPath,
...(client.configPaths ?? []),
client.markerPath,
].filter((path): path is string => path !== undefined && path.length > 0),
),
];
const resolvePath = (path: ClientPath, context: ClientPathContext): string =>
typeof path === "function" ? path(context) : join(context.home, ...path);
@@ -312,27 +552,81 @@ const resolvePath = (path: ClientPath, context: ClientPathContext): string =>
export const supportedClients = (
home: string,
platform: NodeJS.Platform = process.platform,
env: ClientPathContext["env"] = {
APPDATA: process.env.APPDATA,
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
CODEX_HOME: process.env.CODEX_HOME,
COPILOT_HOME: process.env.COPILOT_HOME,
GROK_HOME: process.env.GROK_HOME,
OMP_PROFILE: process.env.OMP_PROFILE,
OPENCODE_CONFIG: process.env.OPENCODE_CONFIG,
PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR,
PI_CONFIG_DIR: process.env.PI_CONFIG_DIR,
PI_PROFILE: process.env.PI_PROFILE,
SAND_DATA_ROOT: process.env.SAND_DATA_ROOT,
XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
},
env: ClientPathContext["env"] = process.env,
): readonly SetupClient[] => {
const context = { home, platform, env };
return SUPPORTED_CLIENT_DEFINITIONS.map((definition) => ({
name: definition.name,
displayName: definition.displayName,
configPath: resolvePath(definition.configPath, context),
markerPath: resolvePath(definition.markerPath, context),
format: definition.format,
}));
const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS;
return definitions.map((definition) => {
try {
const configPath = resolvePath(definition.configPath, context);
return {
name: definition.name,
displayName: definition.displayName,
configPath,
...(definition.geminiSettings === undefined
? {}
: { geminiSettings: definition.geminiSettings(context) }),
...(definition.configPaths === undefined
? {}
: {
configPaths: [
...new Set([...definition.configPaths(context), configPath]),
],
}),
markerPath: resolvePath(definition.markerPath, context),
format: definition.format,
};
} catch (cause: unknown) {
if (definition.name !== "pi") throw cause;
return {
name: definition.name,
displayName: definition.displayName,
format: definition.format,
configPath: env.PI_CODING_AGENT_DIR ?? "",
configPathError: `Invalid PI_CODING_AGENT_DIR: ${cause instanceof Error ? cause.message : String(cause)}. Repair the override before configuring Pi.`,
};
}
});
};
/** Resolve personal skill roots using the same client environment as setup. */
export const clientSkillDirectories = (
home: string,
clientIds: readonly string[] | undefined,
environment: Readonly<NodeJS.ProcessEnv> = {},
platform: NodeJS.Platform = process.platform,
): readonly { readonly client: string; readonly directory: string }[] => {
const definitions: readonly ClientDefinition[] = SUPPORTED_CLIENT_DEFINITIONS;
const selected =
clientIds === undefined
? [
"shared",
...definitions
.filter(({ skillPath }) => skillPath !== undefined)
.map(({ name }) => name),
]
: clientIds.length === 0
? ["shared"]
: clientIds;
const destinations = new Map<string, { client: string; directory: string }>();
for (const client of selected) {
const definition = definitions.find(({ name }) => name === client);
const directory =
definition?.skillPath === undefined
? join(home, ".agents", "skills")
: resolvePath(definition.skillPath, {
home,
platform,
env: environment,
});
if (!destinations.has(directory))
destinations.set(directory, {
client:
directory === join(home, ".agents", "skills") ? "shared" : client,
directory,
});
}
return [...destinations.values()].sort((left, right) =>
left.directory.localeCompare(right.directory),
);
};
+88 -15
View File
@@ -15,7 +15,7 @@ import writeFileAtomic from "write-file-atomic";
import { z } from "zod";
import { PRODUCT_IDENTITY } from "../identity.js";
import { claudeCodeSkillsDirectory, skillDestinations } from "./SetupSkill.js";
import { skillDestinations } from "./SetupSkill.js";
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
import {
@@ -124,11 +124,12 @@ export const runUninstall = async (
status: "retained",
detail: "Hopper is not owned by REA uninstall.",
});
const reported = collapseUninstallItems(items);
return {
status: items.some(({ status }) => status === "failed")
status: reported.some(({ status }) => status === "failed")
? "failed"
: "complete",
items,
items: reported,
};
};
@@ -171,7 +172,16 @@ export const systemUninstallHost = (
selectedHome ?? homeDirectoryFromEnvironment(environment, platform);
return {
clients: () =>
Promise.resolve(supportedClients(home, platform, environment)),
Promise.resolve(
supportedClients(home, platform, environment).flatMap((client) =>
client.configPaths === undefined
? [client]
: client.configPaths.map((configPath) => ({
...client,
configPath,
})),
),
),
inspectClient: async (client) => {
const read = await readClientConfiguration(client, fileSystem);
return read.kind === "item" && read.item.status === "failed"
@@ -179,7 +189,8 @@ export const systemUninstallHost = (
: undefined;
},
removeClient: (client) => removeClient(client, fileSystem),
removeSkill: () => removeManagedSkills(home, fileSystem, environment),
removeSkill: () =>
removeManagedSkills(home, fileSystem, environment, platform),
purgeData: async () => [
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
@@ -200,6 +211,8 @@ const readClientConfiguration = async (
client: SetupClient,
fileSystem: UninstallFileSystem,
): Promise<ClientConfigurationRead> => {
if (client.configPathError !== undefined)
return itemRead(item(client.name, "failed", client.configPathError));
if (client.format === "unsupported")
return itemRead(
item(
@@ -404,18 +417,16 @@ const removeManagedSkills = async (
home: string,
fileSystem: UninstallFileSystem,
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform,
): Promise<UninstallItem> => {
const results = await Promise.all(
skillDestinations(
home,
undefined,
claudeCodeSkillsDirectory(home, environment),
).map(({ client, path }) =>
removeManagedPath(
path,
client === "claude_code" ? "Claude Code skill" : "skill",
fileSystem,
),
skillDestinations(home, undefined, environment, platform).map(
({ client, path }) =>
removeManagedPath(
path,
client === "claude_code" ? "Claude Code skill" : "skill",
fileSystem,
),
),
);
const failed = results.find(({ status }) => status === "failed");
@@ -451,6 +462,68 @@ const item = (
status: UninstallItem["status"],
detail: string,
): UninstallItem => ({ name, status, detail });
/**
* Layered clients are removed file by file, but callers look up one status by
* client name. A missing earlier file must not hide a later removal.
*/
const collapseUninstallItems = (
items: readonly UninstallItem[],
): UninstallItem[] => {
const collapsed: UninstallItem[] = [];
for (const next of items) {
const index = collapsed.findIndex(({ name }) => name === next.name);
const current = collapsed[index];
if (current === undefined) {
collapsed.push(next);
continue;
}
collapsed[index] = mergeUninstallItems(current, next);
}
return collapsed;
};
const mergeUninstallItems = (
current: UninstallItem,
next: UninstallItem,
): UninstallItem => {
const status = preferredUninstallStatus(current.status, next.status);
const details = [current, next]
.filter(
(entry) =>
entry.status === status ||
(status === "removed" && entry.status === "retained"),
)
.map(({ detail }) => detail);
return item(current.name, status, [...new Set(details)].join(" "));
};
const preferredUninstallStatus = (
current: UninstallItem["status"],
next: UninstallItem["status"],
): UninstallItem["status"] =>
uninstallStatusPriority(next) > uninstallStatusPriority(current)
? next
: current;
const uninstallStatusPriority = (status: UninstallItem["status"]): number => {
switch (status) {
case "failed":
return 3;
case "removed":
return 2;
case "retained":
return 1;
case "skipped":
return 0;
default: {
const exhaustive: never = status;
throw new TypeError(
`Unhandled uninstall item status: ${String(exhaustive)}`,
);
}
}
};
const registrationSchema = z
.object({ command: z.string(), args: z.array(z.string()) })
.passthrough();
+9
View File
@@ -7,6 +7,13 @@ import { safeParseJson, type SafeJsonParseResult } from "../domain/safeJson.js";
export const JSON_INPUT_RESOURCE_REMEDIATION =
"Provide a smaller valid JSON value. For Evidence workflows, re-analyze a smaller selection of the original target and use its complete Evidence; splitting JSON text or trimming Evidence fields does not produce valid workflow input.";
/**
* Strict JSON input keeps rejecting a leading byte-order mark, but names it:
* the parser's own message quotes the invisible U+FEFF as the bad token.
*/
export const JSON_BYTE_ORDER_MARK_MESSAGE =
"JSON input begins with a UTF-8 byte-order mark (EF BB BF), which strict JSON input does not accept. Save the file as UTF-8 without a byte-order mark.";
/** Decode JSON bytes without confusing a runtime string limit with malformed input. */
export const parseUtf8Json = (
bytes: Uint8Array,
@@ -77,5 +84,7 @@ export const parseUtf8Json = (
cause,
};
}
if (text.startsWith("\uFEFF"))
return { ok: false, error: JSON_BYTE_ORDER_MARK_MESSAGE, cause: undefined };
return safeParseJson(text);
};
@@ -2,6 +2,8 @@ import { expect, it } from "vitest";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
import { createEvidence, parseEvidence } from "../../domain/evidence.js";
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
import {
analysisViewJavaScriptAnalysisWithSource,
analysisViewJavaScriptEvidence,
@@ -9,6 +11,96 @@ import {
} from "../../../tests/fixtures/analysisView.js";
import { inspectAnalysisView } from "./AnalysisViewService.js";
it.each(["/fixtures/unknown.exe", ""])(
"preserves recorded empty native identity fields: path=%j",
(path) => {
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const parent = createEvidence(
{ path, format: "pe", sha256: "c".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: {},
result: {
...original,
procedure: {
...original.procedure,
address: "",
body: { available: false, reason: "Not recorded" },
},
},
},
);
const result = inspectAnalysisView({
source: { kind: "inline", evidence: parent },
view: {
kind: "native",
facet: "procedure",
offset: 0,
limit: 64,
},
});
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
procedure_address: "",
artifact: { path },
item: { address: "" },
});
expect(result.value.locations).toEqual(
path.length > 0 ? [{ kind: "artifact-path", path }] : [],
);
},
);
it("projects a small native view from an authenticated >10 MiB retained dossier", () => {
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const parent = createEvidence(
{ path: "/fixtures/large.exe", format: "pe", sha256: "c".repeat(64) },
{ id: "ghidra", name: "Ghidra", version: "12.1.4" },
{
operation: "analyze_function",
parameters: { address: "0x401000" },
result: { ...original, pseudocode: "X".repeat(11 * 1024 * 1024) },
limitations: ["Synthetic fixture"],
},
);
const input = {
source: {
kind: "retained-evidence" as const,
evidence_id: parent.evidence_id,
},
view: {
kind: "native" as const,
facet: "pseudocode" as const,
offset: 0,
limit: 128,
},
};
const view = inspectAnalysisView(input, (id) =>
id === parent.evidence_id ? parent : undefined,
);
if (!view.ok) throw view.error;
expect(view.value.evidence_links).toEqual([parent.evidence_id]);
expect(view.value.normalized_result).toMatchObject({
kind: "native",
parent_operation: "analyze_function",
parent_evidence_id: parent.evidence_id,
procedure_address: "0x401000",
artifact: { path: "/fixtures/large.exe", sha256: "c".repeat(64) },
coverage: { total: 11 * 1024 * 1024, examined: 128, next_offset: 128 },
});
expect(view.value.locations).toEqual([
{ kind: "artifact-path", path: "/fixtures/large.exe" },
{ kind: "address", address: "0x401000" },
]);
expect(JSON.stringify(view.value).length).toBeLessThan(12000);
expect(JSON.stringify(parent).length).toBeGreaterThan(10 * 1024 * 1024);
expect(inspectAnalysisView(input, () => undefined)).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
});
it("projects inline layout Evidence and retains a derived view record", () => {
const parent = analysisViewLayoutEvidence();
const result = inspectAnalysisView({
@@ -53,6 +53,13 @@ export const inspectAnalysisViewValidated = (
operation: parent.operation,
normalizedResult: parent.normalized_result,
limitations: parent.limitations,
artifact:
parent.subject === null
? null
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
},
input.view,
);
@@ -126,7 +133,16 @@ const createAnalysisViewEvidence = (
confidence: "derived",
authority: parent.authority,
limitations: result.limitations,
locations: [{ kind: "artifact-path", path: result.artifact.path }],
locations: [
...(result.artifact.path.length > 0
? [{ kind: "artifact-path" as const, path: result.artifact.path }]
: []),
...(result.kind === "native" &&
result.procedure_address !== null &&
result.procedure_address.length > 0
? [{ kind: "address" as const, address: result.procedure_address }]
: []),
],
evidenceLinks: [parent.evidence_id],
});
};
@@ -5,6 +5,7 @@ import {
BINARY_LAYOUT_TEST_PROVIDER,
} from "../../../tests/fixtures/binaryDiagnostics/layout.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { parseEvidence } from "../../domain/evidence.js";
import { err, ok } from "../../domain/result.js";
it.each([
@@ -28,6 +29,19 @@ it.each([
},
);
it("records the decoded layout once in its Evidence", async () => {
const layout = binaryLayoutFixture();
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(layout)),
});
const result = await service.inspect({ path: layout.artifact.path });
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(layout);
expect(evidence.raw_result).toBeNull();
});
it("preserves a provider's actionable unsupported reason", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"fixture-layout",
@@ -78,7 +78,8 @@ export class BinaryLayoutService {
operation: OPERATION,
parameters: input.data,
result: value,
rawResult: value,
// The decoded report is the only representation; do not repeat it.
rawResult: null,
confidence: "observed",
limitations: value.limitations,
locations: [{ kind: "artifact-path", path: value.artifact.path }],
@@ -24,6 +24,7 @@ it("labels an envelope containing debugger-derived maps as derived", async () =>
const evidence = parseEvidence(result.value);
expect(evidence.confidence).toBe("derived");
expect(evidence.normalized_result).toEqual(fixture);
expect(evidence.raw_result).toBeNull();
});
it.each([
@@ -83,7 +83,8 @@ export class RecordedCrashService {
operation: OPERATION,
parameters: input.data,
result: value,
rawResult: value,
// The decoded report is the only representation; do not repeat it.
rawResult: null,
confidence:
value.debugger.status === "available" ? "derived" : "observed",
limitations: value.limitations,
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
import { compactStringIdentityKey } from "../../domain/compactStringIdentity.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
import type { JavaScriptStaticAnalysis } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -162,16 +163,15 @@ const addEndpoint = (
const source =
sourceNodeFor(context, input.file.path, input.value.module_key) ??
input.asset;
const key = compactStringIdentityKey(input.value.value);
const label = `${input.value.kind} endpoint`;
const node = context.accumulator.addNode({
kind: "endpoint",
identity: artifactLocalIdentity(
input.file.sha256,
input.value.kind,
input.value.value,
),
identity: artifactLocalIdentity(input.file.sha256, input.value.kind, key),
observations: [
{
label: input.value.value,
label:
input.value.value.length <= label.length ? input.value.value : label,
properties: {
endpoint_kind: input.value.kind,
value: input.value.value,
@@ -1,3 +1,4 @@
import { compactStringIdentityKey } from "../../domain/compactStringIdentity.js";
import { createJavaScriptSemanticGraphUnknown } from "../../domain/javascript/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
import type {
@@ -21,7 +22,7 @@ export const projectSemanticEvents = (
const eventKey =
operation.eventName === null
? operation.eventId
: `${operation.emitterKey}\u0000${operation.eventName}`;
: `${operation.emitterKey}\u0000${compactStringIdentityKey(operation.eventName)}`;
const event =
eventNodes.get(eventKey) ?? addEventNode(context, operation, eventKey);
if (event === null) continue;
@@ -59,7 +60,11 @@ const addEventNode = (
kind: "event",
roleKey: `event:${eventKey}`,
location: operation.eventName === null ? operation.location : null,
label: operation.eventName,
label:
operation.eventName === null ||
operation.eventName.length <= "event".length
? operation.eventName
: "event",
functionNodeId: null,
properties: {
emitter_key: operation.emitterKey,
@@ -78,7 +83,9 @@ const addListenerNode = (
label:
operation.eventName === null
? operation.method
: `${operation.method}:${operation.eventName}`,
: operation.eventName.length <= "listener".length
? `${operation.method}:${operation.eventName}`
: `${operation.method}:listener`,
functionNodeId:
operation.ownerCallableId === null
? null
@@ -175,7 +175,21 @@ export const createJavaScriptSemanticGraphProjection =
): Value => {
bindSemanticGraphApplicationNodes(state, applicationGraph);
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const relations = [...state.relations.values()];
const unknowns = [...state.unknowns.values()];
type Family = (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number];
const retainedByFamily = new Map<Family, number>();
const unknownIdsByFamily = new Map<Family, string[]>();
for (const relation of relations) {
const family = JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation];
retainedByFamily.set(family, (retainedByFamily.get(family) ?? 0) + 1);
}
for (const unknown of unknowns) {
const identifiers = unknownIdsByFamily.get(unknown.family);
if (identifiers === undefined)
unknownIdsByFamily.set(unknown.family, [unknown.unknown_id]);
else identifiers.push(unknown.unknown_id);
}
const graph = factory({
schema: "JavaScriptSemanticRelationGraph",
root_artifact_sha256: rootArtifactSha256,
@@ -183,7 +197,7 @@ export const createJavaScriptSemanticGraphProjection =
root_node_ids: [...state.roots],
evidence_contexts: state.evidenceContexts.contexts,
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
relations,
fingerprints,
unknowns,
coverage: {
@@ -204,15 +218,9 @@ export const createJavaScriptSemanticGraphProjection =
families: JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map((family) => ({
family,
status: semanticFamilyStatus(family),
retained_relations: [...state.relations.values()].filter(
(relation) =>
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation.relation] ===
family,
).length,
retained_relations: retainedByFamily.get(family) ?? 0,
omitted_relations: truncatedFiles > 0 ? null : 0,
unknown_ids: unknowns
.filter((unknown) => unknown.family === family)
.map(({ unknown_id: identifier }) => identifier),
unknown_ids: unknownIdsByFamily.get(family) ?? [],
})),
},
limitations: [
@@ -137,7 +137,11 @@ const addRequestNode = (
kind: operation.kind === "request" ? "request" : "response",
roleKey: operation.requestId,
location: operation.location,
label: operation.endpoint ?? operation.method,
label:
operation.endpoint !== null &&
operation.endpoint.length <= operation.method.length
? operation.endpoint
: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
@@ -2,6 +2,7 @@ import {
semanticContainer,
semanticPropertyPointer,
} from "../../domain/javascript/javascriptSemanticSlots.js";
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import type { JavaScriptSemanticBinding } from "../../domain/javascript/javascriptSemanticIr.js";
import type {
JavaScriptSemanticProperty,
@@ -153,16 +154,27 @@ const addLiteralNode = (
binding: JavaScriptSemanticBinding,
value: string | number | boolean | null,
role: string,
) =>
retainSemanticGraphNode(context.state, context.file, {
) => {
const encodedValue = JSON.stringify(value);
const valueDigest = `value-sha256:${digestCanonicalValue(value, "Semantic literal")}`;
const valueKey =
encodedValue.length <= valueDigest.length ? encodedValue : valueDigest;
const stringLabel = "string literal";
return retainSemanticGraphNode(context.state, context.file, {
kind: "literal",
roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`,
// Identity needs an exact value commitment, not another payload copy.
// Keep the complete literal in properties for queries and Evidence export.
roleKey: `literal:${binding.bindingId}:${role}:${valueKey}`,
location: binding.definitions[0]?.location ?? null,
label: JSON.stringify(value),
label:
typeof value === "string" && encodedValue.length > stringLabel.length
? stringLabel
: encodedValue,
functionNodeId:
context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null,
properties: { value },
});
};
/** Create one canonical slot for a root binding and exact static property path. */
export const semanticPropertySlot = (
@@ -6,6 +6,7 @@ import {
captureProcessScenarioFile,
projectProcessCliError,
} from "./ProcessCli.js";
import { JSON_BYTE_ORDER_MARK_MESSAGE } from "../Utf8JsonInput.js";
const roots: string[] = [];
afterEach(async () => {
@@ -87,4 +88,14 @@ describe("process CLI input diagnostics", () => {
}),
});
});
it("names a leading byte-order mark instead of quoting it as a token", async () => {
const path = join(await fixture(), "scenario.json");
await writeFile(path, '\uFEFF{"executable":"/bin/echo"}');
expect(await captureProcessScenarioFile(path)).toEqual({
error: "Process command failed",
category: "invalid_input",
message: `Process input file is not valid UTF-8 JSON: ${path} (${JSON_BYTE_ORDER_MARK_MESSAGE}). Repair the file, then try again.`,
});
});
});
+3
View File
@@ -19,6 +19,7 @@ import { createProgressReporter } from "../ProgressReporter.js";
import { captureProcessScenario } from "../../process/capture/ProcessHarness.js";
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
import { JSON_BYTE_ORDER_MARK_MESSAGE } from "../Utf8JsonInput.js";
/** Safe process-command failure returned to the CLI adapter. */
export interface ProcessCliErrorOutput {
@@ -191,6 +192,8 @@ const readJson = async (path: string): Promise<unknown> => {
fatal: true,
ignoreBOM: true,
}).decode(bytes);
if (text.startsWith("\uFEFF"))
throw new Error(JSON_BYTE_ORDER_MARK_MESSAGE);
const parsed: unknown = JSON.parse(text);
return parsed;
} catch (cause: unknown) {
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import {
annotateEnglishUnicodeCaseCollisions,
ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION,
} from "./ArtifactPaths.js";
const NOTE =
"a case-insensitive destination cannot store both. This comparison is not a filesystem observation.";
const annotate = (paths: readonly string[]) => {
const occurrences = paths.map((logical_path) => ({
logical_path,
limitations: [] as string[],
}));
const limitation = annotateEnglishUnicodeCaseCollisions(occurrences);
return {
limitation,
byPath: new Map(
occurrences.map(({ logical_path, limitations }) => [
logical_path,
limitations,
]),
),
};
};
describe("English Unicode case collisions", () => {
it("names the other spelling of a colliding file", () => {
const { limitation, byPath } = annotate([".", "Main.js", "main.js", "x"]);
expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION);
expect(byPath.get("Main.js")).toEqual([
`Logical path Main.js collides under English (en-US) Unicode case folding with main.js; ${NOTE}`,
]);
expect(byPath.get("main.js")).toEqual([
`Logical path main.js collides under English (en-US) Unicode case folding with Main.js; ${NOTE}`,
]);
expect(byPath.get("x")).toEqual([]);
});
it("records a directory collision once at the diverging segment", () => {
const { byPath } = annotate([
"res/Foo",
"res/Foo/a.txt",
"res/foo",
"res/foo/b.txt",
]);
expect(byPath.get("res/Foo")).toEqual([
`Logical path res/Foo collides under English (en-US) Unicode case folding with res/foo; ${NOTE}`,
]);
expect(byPath.get("res/foo/b.txt")).toEqual([
`Logical path res/foo/b.txt is under res/foo, which collides under English (en-US) Unicode case folding with res/Foo; ${NOTE}`,
]);
});
it("counts further spellings, each of which is its own occurrence", () => {
const { byPath } = annotate(["A.txt", "a.txt", "a.TXT"]);
expect(byPath.get("a.txt")).toEqual([
`Logical path a.txt collides under English (en-US) Unicode case folding with A.txt and 1 other spelling; ${NOTE}`,
]);
});
it("stays linear for large case-variant subtrees", () => {
const count = 5_000;
const paths = Array.from({ length: count }, (_, index) => [
`Foo/a${String(index)}.txt`,
`foo/b${String(index)}.txt`,
]).flat();
const { byPath } = annotate(paths);
for (const path of paths) {
const limitations = byPath.get(path) ?? [];
expect(limitations).toHaveLength(1);
expect(limitations[0]?.length).toBeLessThan(300);
}
});
it("walks names with more components than the call stack holds", () => {
const deep = Array.from({ length: 30_000 }, () => "a").join("/");
const { byPath } = annotate([deep, `${deep}/X`, `${deep}/x`]);
expect(byPath.get(`${deep}/X`)).toHaveLength(1);
expect(byPath.get(deep)).toEqual([]);
});
});
+182 -11
View File
@@ -1,9 +1,24 @@
import { posix } from "node:path";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
const DRIVE_OR_UNC = /^(?:[A-Za-z]:|\\|\/\/)/u;
/**
* English Unicode case folding used only to describe logical names a
* case-insensitive destination might collapse. It is not a filesystem case table.
*/
const ENGLISH_UNICODE_CASE_NOTE =
"This comparison is not a filesystem observation.";
/** Inventory limitation when logical names collide under English Unicode case folding. */
export const ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION = `Logical archive names collide under English (en-US) Unicode case folding; a case-insensitive destination cannot store both spellings. ${ENGLISH_UNICODE_CASE_NOTE}`;
/** User-facing prefix for a destination that cannot keep two logical spellings. */
export const DESTINATION_CASE_COLLISION_PREFIX =
"Destination filesystem cannot store both ";
/** Normalize an untrusted logical archive path without touching filesystem. */
export const normalizeArtifactPath = (input: string): string => {
if (
@@ -30,7 +45,7 @@ export const normalizeArtifactPath = (input: string): string => {
return normalized;
};
/** Reject exact, Unicode-normalized, case-folded, and prefix collisions. */
/** Reject exact and same-spelling prefix collisions. Case-distinct names stay distinct. */
export class ArtifactPathRegistry {
readonly #root: PathTrieNode = { kind: undefined, children: new Map() };
@@ -43,16 +58,10 @@ export class ArtifactPathRegistry {
"path",
`Artifact prefix conflict: ${path}`,
);
const foldedPart = part.toLocaleLowerCase("en-US");
let child = node.children.get(foldedPart);
if (child !== undefined && child.spelling !== part)
throw new ArtifactReaderFailure(
"path",
`Artifact path collision: ${path} differs only in case from ${[...parts.slice(0, index), child.spelling].join("/")}`,
);
let child = node.children.get(part);
if (child === undefined) {
child = { spelling: part, kind: undefined, children: new Map() };
node.children.set(foldedPart, child);
child = { kind: undefined, children: new Map() };
node.children.set(part, child);
}
node = child;
if (index === parts.length - 1) {
@@ -73,7 +82,169 @@ export class ArtifactPathRegistry {
}
interface PathTrieNode {
readonly spelling?: string;
kind: "file" | "directory" | "symlink" | "slice" | undefined;
readonly children: Map<string, PathTrieNode>;
}
interface CaseNode {
readonly bySpelling: Map<string, CaseNode>;
readonly spellingsByFold: Map<string, string[]>;
readonly terminals: string[];
}
const emptyCaseNode = (): CaseNode => ({
bySpelling: new Map(),
spellingsByFold: new Map(),
terminals: [],
});
const englishCaseFold = (part: string): string =>
part.toLocaleLowerCase("en-US");
/**
* Record English (en-US) Unicode case collisions on each affected occurrence.
* Returns the inventory limitation when any logical names collide.
*/
export const annotateEnglishUnicodeCaseCollisions = (
occurrences: readonly {
readonly logical_path: string;
limitations: string[];
}[],
): string | undefined => {
const collisions = englishUnicodeCaseCollisions(
occurrences.map(({ logical_path }) => logical_path),
);
if (collisions.size === 0) return undefined;
for (const occurrence of occurrences)
for (const collision of collisions.get(occurrence.logical_path) ?? [])
occurrence.limitations.push(
caseCollisionLimitation(occurrence.logical_path, collision),
);
return ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION;
};
/** One logical path segment whose spelling folds to another sibling's. */
interface CaseCollision {
/** Logical path through the colliding segment. */
readonly prefix: string;
/** First other sibling spelling, as a logical path, in code-point order. */
readonly other: string;
/** Count of further sibling spellings, each its own occurrence. */
readonly additional: number;
}
const caseCollisionLimitation = (
path: string,
{ prefix, other, additional }: CaseCollision,
): string => {
const others =
additional === 0
? other
: `${other} and ${String(additional)} other spelling${additional === 1 ? "" : "s"}`;
const subject =
prefix === path
? `Logical path ${path} collides`
: `Logical path ${path} is under ${prefix}, which collides`;
return `${subject} under English (en-US) Unicode case folding with ${others}; a case-insensitive destination cannot store both. ${ENGLISH_UNICODE_CASE_NOTE}`;
};
/**
* Name the directory-listing spelling that differs from the requested segment
* only by English (en-US) Unicode case. Exact matches are the same logical name.
*/
export const destinationCaseCollisionMessage = (
requestedPath: string,
existingNames: readonly string[],
): string | undefined => {
const slash = requestedPath.lastIndexOf("/");
const segment = slash < 0 ? requestedPath : requestedPath.slice(slash + 1);
if (existingNames.includes(segment)) return undefined;
const folded = englishCaseFold(segment);
const existing = existingNames
.filter((name) => englishCaseFold(name) === folded)
.sort(compareUnicodeCodePoints)[0];
if (existing === undefined) return undefined;
const parent = slash < 0 ? "" : requestedPath.slice(0, slash + 1);
return `${DESTINATION_CASE_COLLISION_PREFIX}${requestedPath} and ${parent}${existing}; inventory retains both logical names.`;
};
const englishUnicodeCaseCollisions = (
paths: readonly string[],
): ReadonlyMap<string, readonly CaseCollision[]> => {
const root = emptyCaseNode();
for (const path of paths) {
if (path.length === 0 || path === ".") continue;
let node = root;
for (const part of path.split("/")) {
const folded = englishCaseFold(part);
const spellings = node.spellingsByFold.get(folded);
if (spellings === undefined) node.spellingsByFold.set(folded, [part]);
else if (!spellings.includes(part)) spellings.push(part);
let child = node.bySpelling.get(part);
if (child === undefined) {
child = emptyCaseNode();
node.bySpelling.set(part, child);
}
node = child;
}
node.terminals.push(path);
}
// A collision is recorded once, at the segment where spellings diverge, and
// shared down the subtree. Pairing every descendant of one spelling with
// every descendant of another grew quadratically with the subtree sizes.
// The walk is iterative because a ZIP name can hold more components than
// the call stack allows.
const collisions = new Map<string, readonly CaseCollision[]>();
const pending: {
readonly node: CaseNode;
readonly prefix: string | undefined;
readonly chain: CollisionChain | undefined;
}[] = [{ node: root, prefix: undefined, chain: undefined }];
for (let item = pending.pop(); item !== undefined; item = pending.pop()) {
const { node, prefix, chain } = item;
if (chain !== undefined)
for (const path of node.terminals)
collisions.set(path, collisionsAlong(chain));
for (const spellings of node.spellingsByFold.values())
spellings.sort(compareUnicodeCodePoints);
for (const [spelling, child] of node.bySpelling) {
const childPrefix =
prefix === undefined ? spelling : `${prefix}/${spelling}`;
const spellings =
node.spellingsByFold.get(englishCaseFold(spelling)) ?? [];
const other = spellings[0] === spelling ? spellings[1] : spellings[0];
pending.push({
node: child,
prefix: childPrefix,
chain:
other === undefined
? chain
: {
collision: {
prefix: childPrefix,
other: prefix === undefined ? other : `${prefix}/${other}`,
additional: spellings.length - 2,
},
parent: chain,
},
});
}
}
return collisions;
};
/** Collisions on one path, linked from the deepest segment to the root. */
interface CollisionChain {
readonly collision: CaseCollision;
readonly parent: CollisionChain | undefined;
}
const collisionsAlong = (chain: CollisionChain): CaseCollision[] => {
const collisions: CaseCollision[] = [];
let link: CollisionChain | undefined = chain;
while (link !== undefined) {
collisions.push(link.collision);
link = link.parent;
}
return collisions.reverse();
};
+7 -14
View File
@@ -194,10 +194,8 @@ class ArtifactClient implements AnalysisClient {
this.target.sourcePath ?? this.target.path,
result.manifest,
),
locations: result.artifacts.map(({ relative_path: path }) => ({
kind: "artifact-path" as const,
path,
})),
// Each extracted file's path is already in artifacts.
locations: [],
}),
);
}
@@ -211,10 +209,8 @@ class ArtifactClient implements AnalysisClient {
this.target.sourcePath ?? this.target.path,
result.manifest,
),
locations: result.occurrences.map(({ logical_path: path }) => ({
kind: "artifact-path" as const,
path,
})),
// Each occurrence's logical path is already in the result.
locations: [],
}),
);
} catch (cause: unknown) {
@@ -323,17 +319,14 @@ class ArtifactClient implements AnalysisClient {
this.target.sourcePath ?? this.target.path,
inventory.manifest,
);
const locations = inventory.occurrences.map(({ logical_path: path }) => ({
kind: "artifact-path" as const,
path,
}));
const inventoryEvidence = createEvidence(subject, ARTIFACT_GRAPH_PROVIDER, {
operation: "inventory_artifact",
parameters: inventoryParameters,
result: inventory,
rawResult: null,
limitations: inventory.limitations,
locations,
// The nested inventory already names every occurrence's logical path.
locations: [],
});
const result = createArtifactInspection(inventoryEvidence);
await options?.progress?.report({
@@ -347,7 +340,7 @@ class ArtifactClient implements AnalysisClient {
rawResult: null,
limitations: result.limitations,
subject,
locations,
locations: [],
}),
);
}
+33 -2
View File
@@ -4,6 +4,7 @@ import {
lstat,
mkdir,
open,
readdir,
realpath,
rm,
type FileHandle,
@@ -14,6 +15,7 @@ import { streamChunkToBuffer } from "./StreamBytes.js";
import {
ArtifactPathRegistry,
destinationCaseCollisionMessage,
normalizeArtifactPath,
} from "./ArtifactPaths.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
@@ -134,7 +136,8 @@ export class SafeOutputTree {
constants.O_WRONLY |
constants.O_NOFOLLOW,
0o600,
).catch((cause: unknown) => {
).catch(async (cause: unknown) => {
await throwIfDestinationCaseCollision(dirname(destination), path, cause);
throw new ArtifactReaderFailure(
"path",
`Could not exclusively create extraction path: ${path}`,
@@ -245,17 +248,28 @@ export class SafeOutputTree {
if (fileName === undefined)
throw new ArtifactReaderFailure("path", "Invalid extraction path");
let current = this.#outputRoot;
let logicalParent = "";
for (const part of parts) {
const parentDirectory = current;
const logicalPath =
logicalParent.length === 0 ? part : `${logicalParent}/${part}`;
current = join(current, part);
let created = true;
await mkdir(current, { mode: 0o700 }).catch((cause: unknown) => {
if (!isAlreadyExists(cause)) throw cause;
created = false;
});
if (!created)
await throwIfDestinationCaseCollision(parentDirectory, logicalPath);
const metadata = await lstat(current);
if (!metadata.isDirectory() || metadata.isSymbolicLink())
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
await throwIfDestinationCaseCollision(parentDirectory, logicalPath);
throw new ArtifactReaderFailure(
"path",
`Unsafe extraction parent: ${relativePath}`,
);
}
logicalParent = logicalPath;
}
return join(current, fileName);
}
@@ -330,6 +344,23 @@ const isNotFound = (cause: unknown): boolean =>
const isAlreadyExists = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
/** Fail when this directory already holds another spelling of the requested segment. */
const throwIfDestinationCaseCollision = async (
parentDirectory: string,
logicalPath: string,
cause?: unknown,
): Promise<void> => {
const names = await readdir(parentDirectory).catch(() => undefined);
if (names === undefined) return;
const message = destinationCaseCollisionMessage(logicalPath, names);
if (message === undefined) return;
throw new ArtifactReaderFailure(
"path",
message,
cause === undefined ? undefined : { cause },
);
};
const abortIfNeeded = (signal?: AbortSignal): void => {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
@@ -147,10 +147,45 @@ const estimateXmlPlistExpansion = (
return decodedSourceBytes * 2 + elementCount * 128;
};
/** Count every expanded binary-plist reference before calling plist.parseBinary. */
const estimateBinaryPlistExpansion = (
/** Resource a binary plist preflight found over its budget, or a malformed reference cycle. */
export type BinaryPlistExpansionFailure = "cycle" | "depth" | "expansion";
const interfaceBuilderBudgetFailure = (
_kind: BinaryPlistExpansionFailure,
message: string,
): Error =>
new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
message,
);
/** How a caller names and reports binary plist expansion failures. */
export interface BinaryPlistExpansionOptions {
/** Budget named in failure messages. */
readonly budget?: string;
/** Error for budget, depth, and reference-cycle failures. */
readonly fail?: (kind: BinaryPlistExpansionFailure, message: string) => Error;
/**
* Structural bounds: "strict" keeps objects and the offset table before the
* trailer; "decoder" admits exactly what plist.parseBinary can read, so
* expansion is bounded without rejecting archives that decoder accepts.
*/
readonly bounds?: "strict" | "decoder";
}
/**
* Count every expanded binary-plist reference before calling plist.parseBinary,
* which recurses on each reference and copies shared containers. Malformed
* structure throws TypeError; budget, depth, and cycle failures use `fail`.
*/
export const estimateBinaryPlistExpansion = (
bytes: Buffer,
maxBytes: number,
{
budget = "the aggregate Interface Builder decode budget",
fail = interfaceBuilderBudgetFailure,
bounds = "strict",
}: BinaryPlistExpansionOptions = {},
): number => {
if (bytes.length < 40)
throw new TypeError("binary plist trailer is truncated");
@@ -172,20 +207,19 @@ const estimateBinaryPlistExpansion = (
const objectCount = readInteger(trailer + 8, 8);
const topObject = readInteger(trailer + 16, 8);
const offsetTable = readInteger(trailer + 24, 8);
const tableEnd = bounds === "strict" ? trailer : bytes.length;
const objectsEnd = bounds === "strict" ? offsetTable : bytes.length;
if (
objectCount < 1 ||
topObject < 0 ||
topObject >= objectCount ||
offsetTable < 8 ||
offsetTable + objectCount * offsetSize > trailer
offsetTable + objectCount * offsetSize > tableEnd
)
throw new TypeError("binary plist trailer or object table is invalid");
let estimate = bytes.length * 2 + objectCount * 16;
if (estimate > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist object table exceeds the aggregate Interface Builder decode budget",
);
throw fail("expansion", `binary plist object table exceeds ${budget}`);
const active = new Set<number>();
const pending: Array<{ object: number; depth: number; exit: boolean }> = [
@@ -201,26 +235,20 @@ const estimateBinaryPlistExpansion = (
}
pendingObjectCount -= 1;
if (entry.depth > 128)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist nesting exceeds the aggregate Interface Builder decode budget",
);
throw fail("depth", `binary plist nesting exceeds ${budget}`);
if (active.has(entry.object))
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist reference cycle exceeds the aggregate Interface Builder decode budget",
);
throw fail("cycle", `binary plist reference cycle exceeds ${budget}`);
estimate += 96;
if (estimate > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist reference expansion exceeds the aggregate Interface Builder decode budget",
throw fail(
"expansion",
`binary plist reference expansion exceeds ${budget}`,
);
const offset = readInteger(
offsetTable + entry.object * offsetSize,
offsetSize,
);
if (offset < 8 || offset >= offsetTable)
if (offset < 8 || offset >= objectsEnd)
throw new TypeError("binary plist object offset is invalid");
const marker = bytes[offset] ?? 0;
const type = marker >> 4;
@@ -234,31 +262,31 @@ const estimateBinaryPlistExpansion = (
const integerSize = 1 << (extMarker & 0x0f);
size = readInteger(cursor, integerSize);
cursor += integerSize;
if (size < 0 || cursor > offsetTable)
if (size < 0 || cursor > objectsEnd)
throw new TypeError("binary plist extended object size is invalid");
}
if (type === 4 || type === 5 || type === 6) {
const byteLength = type === 6 ? size * 2 : size;
if (cursor + byteLength > offsetTable)
if (cursor + byteLength > objectsEnd)
throw new TypeError("binary plist scalar object is truncated");
estimate += type === 4 ? size + 4 * Math.ceil(size / 3) : byteLength * 2;
if (estimate > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist scalar expansion exceeds the aggregate Interface Builder decode budget",
throw fail(
"expansion",
`binary plist scalar expansion exceeds ${budget}`,
);
continue;
}
if (type !== 10 && type !== 13) continue;
const childCount = type === 13 ? size * 2 : size;
const refsEnd = cursor + childCount * referenceSize;
if (!Number.isSafeInteger(refsEnd) || refsEnd > offsetTable)
if (!Number.isSafeInteger(refsEnd) || refsEnd > objectsEnd)
throw new TypeError("binary plist reference table is truncated");
const availableNodes = Math.floor((maxBytes - estimate) / 96);
if (childCount > availableNodes - pendingObjectCount)
throw new InterfaceBuilderDecodeBudgetExceeded(
"aggregate_decode_budget_exhausted",
"binary plist reference expansion exceeds the aggregate Interface Builder decode budget",
throw fail(
"expansion",
`binary plist reference expansion exceeds ${budget}`,
);
active.add(entry.object);
pending.push({ object: entry.object, depth: entry.depth, exit: true });
@@ -103,3 +103,88 @@ describe("inert keyed archive decoding", () => {
);
});
});
/** Encode a bplist00 whose objects reference each other by index. */
const binaryPlist = (objects: readonly Buffer[]): Buffer => {
const header = Buffer.from("bplist00");
const offsets: number[] = [];
let position = header.length;
for (const object of objects) {
offsets.push(position);
position += object.length;
}
const table = Buffer.alloc(objects.length * 4);
offsets.forEach((offset, index) => table.writeUInt32BE(offset, index * 4));
const trailer = Buffer.alloc(32);
trailer[6] = 4;
trailer[7] = 2;
trailer.writeBigUInt64BE(BigInt(objects.length), 8);
trailer.writeBigUInt64BE(0n, 16);
trailer.writeBigUInt64BE(BigInt(position), 24);
return Buffer.concat([header, ...objects, table, trailer]);
};
const plistArray = (references: readonly number[]): Buffer => {
const bytes = Buffer.alloc(1 + references.length * 2);
bytes[0] = 0xa0 | references.length;
references.forEach((reference, index) =>
bytes.writeUInt16BE(reference, 1 + index * 2),
);
return bytes;
};
const plistString = (value: string): Buffer =>
Buffer.concat([Buffer.from([0x50 | value.length]), Buffer.from(value)]);
// {"$archiver": "NSKeyedArchiver", "$top": {"root": UID 1}, "$objects": object 8}
const keyedRoot = (payload: readonly Buffer[]): Buffer =>
binaryPlist([
Buffer.from([0xd3, 0, 1, 0, 3, 0, 4, 0, 2, 0, 8, 0, 5]),
plistString("$archiver"),
Buffer.concat([
Buffer.from([0x5f, 0x10, 15]),
Buffer.from("NSKeyedArchiver"),
]),
plistString("$objects"),
plistString("$top"),
Buffer.from([0xd1, 0, 6, 0, 7]),
plistString("root"),
Buffer.from([0x80, 1]),
...payload,
]);
describe("binary plist reference preflight", () => {
const selection = { offset: 0, limit: 10 };
it("reports a reference cycle as malformed, not as an oversized archive", () => {
expect(() =>
decodeKeyedArchiveBytes(keyedRoot([plistArray([8])]), selection),
).toThrow(
new TypeError(
"binary plist object references form a cycle, which a property list cannot represent",
),
);
});
it("rejects exponential shared-container expansion before decoding", () => {
// Forty levels of [next, next] expand to 2^40 leaves in a few hundred bytes.
const levels = Array.from({ length: 40 }, (_, index) =>
plistArray([9 + index, 9 + index]),
);
expect(() =>
decodeKeyedArchiveBytes(
keyedRoot([...levels, plistString("x")]),
selection,
),
).toThrow(RangeError);
});
it("decodes shared leaf references", () => {
const decoded = decodeKeyedArchiveBytes(
keyedRoot([plistArray([9, 9, 9]), plistString("$null")]),
selection,
);
expect(decoded.objects.map(({ id, value }) => [id, value])).toEqual([
[0, "$null"],
[1, "$null"],
[2, "$null"],
]);
});
});
+17
View File
@@ -28,8 +28,11 @@ import { ArtifactReaderFailure } from "../ArtifactReader.js";
import type { ArtifactEntry } from "../ArtifactReader.js";
import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";
import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";
const MAX_BYTES = 64 * 1024 * 1024;
/** Decoded representation budget, the same 8:1 ratio Interface Builder uses. */
const MAX_DECODE_BYTES = 8 * MAX_BYTES;
/** Parse inert plist bytes, preserving data and dates with explicit typed values. */
export const decodeKeyedArchiveBytes = (
@@ -45,6 +48,20 @@ export const decodeKeyedArchiveBytes = (
);
const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";
const xmlText = binary ? undefined : decodeXmlPlistText(bytes);
// plist.parseBinary recurses on every object reference and copies shared
// containers, so a few hundred bytes can exhaust memory or the stack.
// RangeError reports a resource limit; a reference cycle is malformed.
if (binary)
estimateBinaryPlistExpansion(bytes, MAX_DECODE_BYTES, {
budget: "the keyed archive decode budget",
fail: (kind, message) =>
kind === "cycle"
? new TypeError(
"binary plist object references form a cycle, which a property list cannot represent",
)
: new RangeError(message),
bounds: "decoder",
});
const parsed = binary
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
: parseXmlPropertyList(xmlText ?? "");
@@ -249,16 +249,14 @@ export const createArtifactEdges = (
rootArtifactId;
const semantic = {
parent_artifact_id: parentArtifactId,
child_artifact_id: occurrence.artifact_id,
relation:
occurrence.entry_kind === "slice"
? ("slice-of" as const)
: relationFor(occurrence.logical_path),
occurrence_id: occurrence.occurrence_id,
logical_path: occurrence.logical_path,
};
edges.push({
edge_id: artifactEdgeId(semantic),
edge_id: artifactEdgeId(semantic, occurrence),
...semantic,
producer: occurrence.entry_kind === "slice" ? (producer ?? null) : null,
ordinal: edges.length,
+16 -7
View File
@@ -73,12 +73,12 @@ export const scanCanonicalArtifactInventory = async (
try {
if (reader instanceof AsarArtifactReader)
await reader.prepareContainer(rootDigest?.sha256, options.signal);
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
ownedReaders,
options.signal,
integrity,
);
const {
nodes,
occurrences,
pendingContradictions,
caseCollisionLimitation,
} = await scanReader(reader, ownedReaders, options.signal, integrity);
outcome = {
kind: "completed",
snapshot: await buildInventorySnapshot({
@@ -91,6 +91,7 @@ export const scanCanonicalArtifactInventory = async (
nodes,
occurrences,
pendingContradictions,
caseCollisionLimitation,
}),
};
} catch (cause: unknown) {
@@ -130,6 +131,7 @@ interface SnapshotBuildInput {
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
readonly caseCollisionLimitation: string | undefined;
}
const buildInventorySnapshot = async (
@@ -202,7 +204,12 @@ const buildInventorySnapshot = async (
edges: orderedEdges,
provenance: reader?.provenance() ?? [],
integrity_contradictions: integrityContradictions,
limitations: buildLimitations(rootFormat, reader, integrityContradictions),
limitations: buildLimitations(
rootFormat,
reader,
integrityContradictions,
input.caseCollisionLimitation,
),
};
};
@@ -310,8 +317,10 @@ const buildLimitations = (
rootFormat: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
integrityContradictions: readonly IntegrityContradiction[],
caseCollisionLimitation: string | undefined,
): string[] => [
...inventoryLimitations(rootFormat, reader),
...(caseCollisionLimitation === undefined ? [] : [caseCollisionLimitation]),
...(integrityContradictions.length === 0
? []
: [
+14 -2
View File
@@ -1,6 +1,7 @@
import { isAbsolute } from "node:path";
import {
annotateEnglishUnicodeCaseCollisions,
ArtifactPathRegistry,
normalizeArtifactPath,
} from "../ArtifactPaths.js";
@@ -64,10 +65,16 @@ export const scanReader = async (
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
readonly pendingContradictions: PendingIntegrityContradiction[];
readonly caseCollisionLimitation: string | undefined;
}> => {
const { nodes, occurrences, pendingContradictions } = emptyScan();
if (reader === undefined)
return { nodes, occurrences, pendingContradictions };
return {
nodes,
occurrences,
pendingContradictions,
caseCollisionLimitation: undefined,
};
const context: ScanContext = {
reader,
signal,
@@ -90,7 +97,12 @@ export const scanReader = async (
context.occurrenceByPath,
context.expandedContainerIds,
)?.occurrence_id ?? null;
return { nodes, occurrences, pendingContradictions };
return {
nodes,
occurrences,
pendingContradictions,
caseCollisionLimitation: annotateEnglishUnicodeCaseCollisions(occurrences),
};
};
const visitArtifactEntries = async (
+21 -1
View File
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { expect, it } from "vitest";
import { historicalHar } from "../../../tests/fixtures/historicalHar.js";
import { decodeHarCapture } from "./HarCapture.js";
import { decodeHarCapture, decodeHarText } from "./HarCapture.js";
it.each([
{ values: [] },
@@ -558,3 +558,23 @@ it.each([
});
},
);
it("ignores one leading byte-order mark, as HAR 1.2 requires of readers", () => {
const text = JSON.stringify(historicalHar());
const body = Buffer.from(text, "utf8");
const marked = Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), body]);
expect(decodeHarText(marked)).toBe(text);
expect(decodeHarCapture(decodeHarText(marked), [])).toEqual(
decodeHarCapture(decodeHarText(body), []),
);
// A second mark is content, not an encoding signature.
expect(() =>
decodeHarCapture(
decodeHarText(Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), marked])),
[],
),
).toThrow("HAR is malformed JSON.");
expect(() => decodeHarText(Buffer.from([0x7b, 0xff, 0x7d]))).toThrow(
"HAR is not valid UTF-8 JSON.",
);
});
+14
View File
@@ -1,4 +1,5 @@
import { createHash } from "node:crypto";
import { TextDecoder } from "node:util";
import { isSafeNumber, LosslessNumber } from "lossless-json";
import { parseHarJson } from "./HarJson.js";
import type { JsonValue } from "../../domain/jsonValue.js";
@@ -25,6 +26,19 @@ type Projection = Pick<
"reported" | "numeric_literals" | "binary_fields" | "redactions"
>;
/**
* Decode retained HAR bytes as UTF-8. HAR 1.2 lets writers emit a byte-order
* mark and requires readers to ignore it, so one leading BOM is skipped.
*/
export const decodeHarText = (bytes: Uint8Array): string => {
try {
// ignoreBOM: false (the default) is what skips the mark; true keeps it.
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
} catch {
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
}
};
/** Decode a retained HAR with exact numeric lexemes and unchanged upstream schema validation. */
export const decodeHarCapture = (
text: string,
+5 -11
View File
@@ -1,10 +1,9 @@
import { readFile, writeFile } from "node:fs/promises";
import { TextDecoder } from "node:util";
import { z } from "zod";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { WEB_NETWORK_CAPTURE_LIMITS } from "../../domain/webNetworkCapture.js";
import { CaptureFormatError } from "./CaptureFormatError.js";
import { decodeHarCapture } from "./HarCapture.js";
import { decodeHarCapture, decodeHarText } from "./HarCapture.js";
const requestSchema = z.strictObject({
snapshot_path: z.string(),
@@ -23,17 +22,12 @@ const main = async (): Promise<void> => {
request.snapshot_path,
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
);
let text: string;
try {
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
snapshot.bytes,
);
} catch {
throw new CaptureFormatError("format", "HAR is not valid UTF-8 JSON.");
}
reply = {
ok: true,
value: decodeHarCapture(text, request.sensitive_values),
value: decodeHarCapture(
decodeHarText(snapshot.bytes),
request.sensitive_values,
),
};
} catch (cause: unknown) {
reply =
+1 -1
View File
@@ -18,7 +18,7 @@ export const registerAnalysisViewCommands = (
): void => {
cli.command(CLI_COMMANDS.inspectAnalysisView, {
description:
"Project a selected view of completed layout or JavaScript application Evidence JSON",
"Project a selected view of completed layout, JavaScript application or native function Evidence JSON",
args: z.object({
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
}),
+15 -3
View File
@@ -4,16 +4,27 @@ import { bufferedJsonParts, jsonParts } from "../domain/jsonSerialization.js";
type JsonOutputFormat = "json" | "jsonl";
/** Write ordinary JSON without constructing a document-sized string. */
/**
* Write ordinary JSON without constructing a document-sized string.
*
* `json` is indented for a terminal reader. Piped or redirected output, which
* agents and scripts consume, is compact: indentation adds no information and
* measured 16-45% more model tokens on real results. The value is identical.
*/
export const writeJsonOutput = async (
value: unknown,
destination: Writable,
format: JsonOutputFormat = "json",
): Promise<void> => {
for (const part of bufferedJsonParts(jsonOutputParts(value, format)))
for (const part of bufferedJsonParts(
jsonOutputParts(value, format, isTerminal(destination)),
))
await writePart(destination, part);
};
const isTerminal = (destination: Writable): boolean =>
"isTTY" in destination && destination.isTTY === true;
const writePart = (destination: Writable, part: string): Promise<void> =>
new Promise((resolve, reject) => {
const onError = (cause: unknown): void => reject(cause);
@@ -39,6 +50,7 @@ const writePart = (destination: Writable, part: string): Promise<void> =>
export function* jsonOutputParts(
value: unknown,
format: JsonOutputFormat,
pretty = true,
): Generator<string> {
if (format === "jsonl" && Array.isArray(value)) {
for (const item of value) {
@@ -47,6 +59,6 @@ export function* jsonOutputParts(
}
return;
}
yield* jsonParts(value, format === "json");
yield* jsonParts(value, pretty && format === "json");
yield "\n";
}
+3 -1
View File
@@ -2,7 +2,6 @@ import { Cli } from "incur";
import { z } from "zod";
import { captureBrowserScenario } from "./application/BrowserScenarioCaptureService.js";
import { createBrowserScenarioProvider } from "./composition/browserScenario.js";
import { CLI_COMMANDS } from "./cliCommandNames.js";
import { parseCliJsonInput, resolveCliJsonPaths } from "./cliJsonInput.js";
import { logCliCommand } from "./cliLogging.js";
@@ -44,6 +43,9 @@ export const registerBrowserScenarioCommands = (
projectInputIssues(scenario.error.issues, input.value),
),
);
// Load Playwright only for this command, not during CLI startup.
const { createBrowserScenarioProvider } =
await import("./composition/browserScenario.js");
const result = await captureBrowserScenario(
createBrowserScenarioProvider(environment),
scenario.data,
+25 -5
View File
@@ -8,6 +8,7 @@ import streamValues from "stream-json/streamers/stream-values.js";
import { withRegularFile } from "./application/RegularFileRead.js";
import {
JSON_BYTE_ORDER_MARK_MESSAGE,
JSON_INPUT_RESOURCE_REMEDIATION,
parseUtf8Json,
} from "./application/Utf8JsonInput.js";
@@ -211,12 +212,22 @@ async function* decodedChunks(
prefix?: Uint8Array,
): AsyncGenerator<string> {
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
let leading = true;
const checked = (text: string): string => {
if (leading && text.length > 0) {
leading = false;
if (text.startsWith("\uFEFF")) throw new JsonByteOrderMarkError();
}
return text;
};
if (prefix !== undefined)
for (let offset = 0; offset < prefix.length; offset += READ_CHUNK_BYTES) {
signal?.throwIfAborted();
yield decoder.decode(prefix.subarray(offset, offset + READ_CHUNK_BYTES), {
stream: true,
});
yield checked(
decoder.decode(prefix.subarray(offset, offset + READ_CHUNK_BYTES), {
stream: true,
}),
);
}
const bytes = Buffer.allocUnsafe(READ_CHUNK_BYTES);
while (true) {
@@ -224,9 +235,18 @@ async function* decodedChunks(
const read = await handle.read(bytes, 0, bytes.length, null);
signal?.throwIfAborted();
if (read.bytesRead === 0) break;
yield decoder.decode(bytes.subarray(0, read.bytesRead), { stream: true });
yield checked(
decoder.decode(bytes.subarray(0, read.bytesRead), { stream: true }),
);
}
yield checked(decoder.decode());
}
/** A streamed JSON file begins with a byte-order mark; reported as invalid JSON. */
class JsonByteOrderMarkError extends SyntaxError {
constructor() {
super(JSON_BYTE_ORDER_MARK_MESSAGE);
}
yield decoder.decode();
}
const readPrefix = async (
+2
View File
@@ -5,11 +5,13 @@ import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
import { ghidraStartupTimeoutSchema } from "./ghidraStartupTimeout.js";
import { mcpInputSchemaProfileSchema } from "./mcpInputSchemaProfile.js";
import { mcpResponseBudgetSchema } from "./mcpResponseBudget.js";
const environmentSchema = z.object({
REA_ANALYSIS_PROVIDER: analysisProviderSelectorSchema.default("auto"),
REA_MCP_MAX_RESPONSE_BYTES: mcpResponseBudgetSchema.optional(),
REA_MCP_INPUT_SCHEMA_PROFILE: mcpInputSchemaProfileSchema.optional(),
REA_IDA_MCP_CONFIG: z
.string()
.min(1)
+38
View File
@@ -0,0 +1,38 @@
import { z } from "zod";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
// Moonshot's function-calling API rejects requests while any single tool
// parameters schema exceeds its literal serialized size cap. Community
// measurements bound the cap between ~13.7 KB (accepted) and ~15 KB
// (rejected); 13 KiB leaves margin under the lower bound. See
// https://github.com/morluto/rea/issues/1484 for the measured evidence.
export const COMPACT_INPUT_SCHEMA_BUDGET_BYTES = 13 * 1024;
export const mcpInputSchemaProfileSchema = z.enum(["full", "compact"]);
const profileConstraint =
'REA_MCP_INPUT_SCHEMA_PROFILE must be "full" (default) or "compact". The compact profile advertises input schemas without nested annotation prose for providers that cap each tool schema\'s serialized size.';
export type McpInputSchemaProfile = z.infer<typeof mcpInputSchemaProfileSchema>;
/** Parse the advertised input schema presentation selection. */
export const parseMcpInputSchemaProfile = (
value: string | undefined,
): Result<McpInputSchemaProfile | undefined, ConfigurationError> => {
if (value === undefined) return ok(undefined);
const parsed = mcpInputSchemaProfileSchema.safeParse(value);
return parsed.success
? ok(parsed.data)
: err(
new ConfigurationError(profileConstraint, {
settings: [
{
setting: "REA_MCP_INPUT_SCHEMA_PROFILE",
constraint: profileConstraint,
},
],
}),
);
};
+3
View File
@@ -50,6 +50,9 @@ export const parseConfig = (
...(env.REA_MCP_MAX_RESPONSE_BYTES === undefined
? {}
: { mcpMaxResponseBytes: env.REA_MCP_MAX_RESPONSE_BYTES }),
...(env.REA_MCP_INPUT_SCHEMA_PROFILE === undefined
? {}
: { mcpInputSchemaProfile: env.REA_MCP_INPUT_SCHEMA_PROFILE }),
analysisProvider: env.REA_ANALYSIS_PROVIDER,
...(env.REA_IDA_MCP_CONFIG === undefined
? {}
+3
View File
@@ -2,8 +2,11 @@ import type { LogLevel } from "../logger.js";
import type { ReferenceSourcePolicy } from "../domain/referenceSourcePolicy.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import type { McpInputSchemaProfile } from "./mcpInputSchemaProfile.js";
export interface AppConfig {
readonly mcpMaxResponseBytes?: number;
readonly mcpInputSchemaProfile?: McpInputSchemaProfile;
readonly analysisProvider: AnalysisProviderSelector;
readonly idaMcpConfigPath?: string;
readonly ghidraInstallDir: string | undefined;
+17 -2
View File
@@ -8,14 +8,14 @@ import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
const RETAINED_EXAMPLE_ID = `ev_${"a".repeat(64)}`;
/** Selected views of already completed layout and JavaScript analysis Evidence. */
/** Selected views of already completed layout, JavaScript and native function Evidence. */
export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
{
name: "inspect_analysis_view",
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
"Inspect a selected view of completed binary-layout or JavaScript application Evidence without repeating analysis. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page with a positive limit. Module pages contain JavaScript assets, bundled modules and source modules; use node_id when paths are ambiguous or unavailable. Returns selected facts inline with artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the retained Evidence when needed.",
"Inspect selected views of completed binary-layout, JavaScript application or native analyze_function Evidence without repeating analysis. Use an exact same-session retained evidence_id or portable inline Evidence. Select a summary, layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Native views select procedure, pseudocode, assembly, basic blocks, comments, callers/callees, references, unresolved calls, referenced strings/names, native API and high-pcode. Use nonnegative offset and a positive caller-selected limit (defaults 0 and 64); pseudocode uses UTF-16 code units, other native pages use rows. Returns artifact identity, parent Evidence ID, a distinct view digest, coverage, limitations and unknowns. Actual serialized size determines MCP transport admission; choose a smaller page or export the complete retained Evidence if needed.",
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
@@ -43,6 +43,21 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
},
},
},
{
title: "Page native high-pcode operations from retained Evidence",
input: {
source: {
kind: "retained-evidence",
evidence_id: RETAINED_EXAMPLE_ID,
},
view: {
kind: "native",
facet: "value_flow_operations",
offset: 0,
limit: 32,
},
},
},
{
title: "Page module identities from retained application Evidence",
input: {
+1 -1
View File
@@ -63,7 +63,7 @@ const artifact = <
export const ARTIFACT_TOOL_CONTRACTS = [
artifact(
"inspect_artifact",
"Inspect an active archive or application package in one call. Returns the complete content-addressed artifact graph, source Evidence, observations, relationships, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.",
"Inspect an active archive or application package in one call. Returns the complete content-addressed artifact graph once, as the nested inventory Evidence, with root and integrity observations, integrity contradictions, hypotheses, unexplored branches, limitations, and next probes inline. Read-only DMG mounting is used automatically on supported macOS hosts. Integrity mismatches fail by default; record-and-continue keeps mismatches explicitly untrusted. It does not extract files; use extract_artifact to materialize its regular contents.",
artifactInventoryInputSchema,
),
artifact(
+314
View File
@@ -0,0 +1,314 @@
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, it } from "vitest";
import { compactAdvertisedInputSchema } from "./compactInputSchema.js";
const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
const repeatedObservation = {
type: "object",
properties: {
captured_url: { type: "string", minLength: 1 },
captured_at: { type: "string", minLength: 1 },
status_code: { type: "integer", minimum: 100, maximum: 599 },
headers: {
type: "object",
additionalProperties: { type: "string" },
minProperties: 1,
},
body_digest: { type: "string", minLength: 64, maxLength: 64 },
},
required: ["captured_url", "captured_at", "status_code"],
additionalProperties: false,
} as const;
const annotatedSchema = {
type: "object",
description: "Root group guidance stays.",
properties: {
query: {
type: "string",
description: "Field guidance leaves.",
examples: ["seed"],
default: "seed",
title: "Query",
minLength: 1,
},
limits: {
type: "object",
description: "Nested guidance leaves.",
properties: {
max_results: {
type: "integer",
description: "Leaves.",
minimum: 1,
maximum: 500,
default: 50,
},
},
required: ["max_results"],
additionalProperties: false,
},
},
required: ["query"],
dependentRequired: { limits: ["query"] },
additionalProperties: false,
} as const;
const oversizedPairSchema = (): Record<string, unknown> => {
const deepStructure = {
type: "object",
description: "Nested guidance that leaves.",
properties: Object.fromEntries(
Array.from({ length: 40 }, (_, index) => [
`field_${index}`,
{ type: "string", minLength: 1, description: `Field ${index}` },
]),
),
required: Array.from({ length: 40 }, (_, index) => `field_${index}`),
additionalProperties: false,
};
return {
type: "object",
description: "Provide a complete capture pair.",
properties: {
before: structuredClone(deepStructure),
after: structuredClone(deepStructure),
},
required: ["before", "after"],
additionalProperties: false,
};
};
describe("compact advertised input schema", () => {
it("drops nested annotation prose while keeping validation keywords", () => {
const { schema, presentation } = compactAdvertisedInputSchema(
structuredClone(annotatedSchema),
13 * 1024,
);
expect(presentation).toBe("inline");
expect(schema.description).toBe("Root group guidance stays.");
const query = (schema.properties as Record<string, unknown>)
.query as Record<string, unknown>;
expect(query).toEqual({ type: "string", minLength: 1 });
const limits = (schema.properties as Record<string, unknown>)
.limits as Record<string, unknown>;
expect(limits.description).toBeUndefined();
expect(limits.required).toEqual(["max_results"]);
expect(schema.dependentRequired).toEqual({ limits: ["query"] });
expect(schema.required).toEqual(["query"]);
});
it("keeps annotation-shaped keys inside literal const and enum data", () => {
const literalMode = {
description: "saved data",
default: { keep: "me" },
};
const { schema } = compactAdvertisedInputSchema(
{
type: "object",
properties: {
mode: { enum: [literalMode] },
pinned: { const: { description: "literal" } },
},
},
13 * 1024,
);
const properties = schema.properties as Record<string, unknown>;
expect((properties.mode as Record<string, unknown>).enum).toEqual([
literalMode,
]);
expect((properties.pinned as Record<string, unknown>).const).toEqual({
description: "literal",
});
});
it("inlines local references without changing validation or literal data", () => {
const original = {
type: "object",
$defs: { "observation/~": structuredClone(repeatedObservation) },
properties: {
before: { $ref: "#/$defs/observation~1~0" },
after: { $ref: "#/$defs/observation~1~0" },
literal: { const: { $ref: "saved data", $defs: { keep: true } } },
},
required: ["before", "after"],
additionalProperties: false,
};
const { schema, presentation } = compactAdvertisedInputSchema(
original,
13312,
);
expect(presentation).toBe("inline");
expect(schema.$defs).toBeUndefined();
const ajv = new Ajv2020({ strict: false });
const canonical = ajv.compile(original);
const compact = ajv.compile(schema);
const observation = {
captured_url: "https://example.com",
captured_at: "now",
status_code: 200,
};
for (const input of [
{ before: observation, after: observation },
{ before: observation, after: { ...observation, status_code: 99 } },
{
before: observation,
after: observation,
literal: original.properties.literal.const,
},
])
expect(compact(input)).toBe(canonical(input));
});
it("keeps unconstrained JSON values explicit for client type inference", () => {
const { schema } = compactAdvertisedInputSchema(
{
type: "object",
properties: { normalized_result: {}, literal: { const: {} } },
},
13312,
);
const properties = schema.properties as Record<string, unknown>;
expect(properties.normalized_result).toEqual({
type: ["null", "boolean", "object", "array", "number", "string"],
});
expect(properties.literal).toEqual({ const: {} });
const validate = new Ajv2020({ strict: false }).compile(schema);
for (const normalized_result of [null, true, {}, [], 42, "result"])
expect(validate({ normalized_result })).toBe(true);
});
it("preserves independent validation constraints on reference siblings", () => {
const original = {
type: "object",
$defs: { text: { type: "string", minLength: 3 } },
properties: {
query: { $ref: "#/$defs/text", minLength: 1, maxLength: 5 },
},
};
const { schema } = compactAdvertisedInputSchema(original, 13312);
const validate = new Ajv2020({ strict: false }).compile(schema);
expect(validate({ query: "a" })).toBe(false);
expect(validate({ query: "abc" })).toBe(true);
expect(validate({ query: "abcdef" })).toBe(false);
});
});
describe("compact input schema budget and reduction", () => {
it("budgets repeated-reference expansion before materializing it", () => {
const definitions: Record<string, unknown> = {
leaf: structuredClone(repeatedObservation),
};
for (let index = 0; index < 30; index++) {
const $ref = `#/$defs/${index === 0 ? "leaf" : `level${index - 1}`}`;
definitions[`level${index}`] = {
type: "object",
properties: { left: { $ref }, right: { $ref } },
};
}
const { schema, presentation } = compactAdvertisedInputSchema(
{
type: "object",
$defs: definitions,
properties: { tree: { $ref: "#/$defs/level29" } },
},
1024,
);
expect(presentation).toBe("reduced");
expect(serializedBytes(schema)).toBeLessThanOrEqual(1024);
expect(schema.properties).toEqual({ tree: { type: "object" } });
});
it("retains referenced object, array and nullable types in reduced inputs", () => {
const original = {
type: "object",
$defs: {
pair: oversizedPairSchema(),
observations: {
type: "array",
items: structuredClone(repeatedObservation),
},
nullable: { anyOf: [{ type: "string" }, { type: "null" }] },
},
properties: {
capture: { $ref: "#/$defs/pair", description: "Complete capture." },
observations: { $ref: "#/$defs/observations" },
label: { $ref: "#/$defs/nullable" },
},
};
const { schema, presentation } = compactAdvertisedInputSchema(
original,
1024,
);
expect(presentation).toBe("reduced");
expect(schema.properties).toEqual({
capture: { type: "object", description: "Complete capture." },
observations: { type: "array" },
label: { type: ["string", "null"] },
});
const validate = new Ajv2020({ strict: false }).compile(schema);
expect(validate({ capture: {}, observations: [], label: null })).toBe(true);
expect(validate({ capture: {}, observations: [], label: "capture" })).toBe(
true,
);
expect(validate({ capture: "{}", observations: [], label: null })).toBe(
false,
);
});
it("reduces structurally oversized schemas to the shallow property presentation", () => {
const compacted = compactAdvertisedInputSchema(oversizedPairSchema(), 1024);
expect(compacted.presentation).toBe("reduced");
expect(serializedBytes(compacted.schema)).toBeLessThanOrEqual(1024);
expect(compacted.schema.type).toBe("object");
expect(compacted.schema.description).toContain(
"Provide a complete capture pair.",
);
expect(compacted.schema.description).toContain(
"compact input schema profile",
);
const properties = compacted.schema.properties as Record<string, unknown>;
expect(properties.before).toEqual({
type: "object",
description: "Nested guidance that leaves.",
});
expect(properties.after).toEqual(properties.before);
expect(compacted.schema.required).toEqual(["before", "after"]);
});
it("produces deterministic output for equal input", () => {
const schema = {
type: "object",
properties: {
before: structuredClone(repeatedObservation),
after: structuredClone(repeatedObservation),
},
};
expect(compactAdvertisedInputSchema(schema, 13 * 1024)).toEqual(
compactAdvertisedInputSchema(structuredClone(schema), 13 * 1024),
);
});
it("keeps inline presentations under the measured provider budget", () => {
const { schema, presentation } = compactAdvertisedInputSchema(
{
type: "object",
description: "Group guidance.",
properties: {
before: structuredClone(repeatedObservation),
after: structuredClone(repeatedObservation),
normalization: {
type: "object",
description: "Rules.",
properties: { rules: { type: "array", items: { type: "string" } } },
},
},
},
13312,
);
expect(presentation).toBe("inline");
expect(serializedBytes(schema)).toBeLessThanOrEqual(13312);
});
});
+311
View File
@@ -0,0 +1,311 @@
import {
schemaArrays,
schemaChildren,
schemaMaps,
} from "./inputSchemaPresentation.js";
// Kimi expands schema-local references before sending tools to Moonshot.
// Compact advertisements must fit after expansion, independently of client
// reference handling. Canonical server-side validation remains unchanged.
/** Annotation keys that carry guidance but no validation semantics. */
const annotationKeys = new Set(["description", "examples", "default", "title"]);
/** Keys whose values are literal data, never nested schemas to rewrite. */
const dataKeys = new Set(["const", "enum", "examples", "default"]);
const definitionKeys = new Set(["$defs", "definitions"]);
// An empty schema accepts every JSON value. Kimi otherwise infers string.
const jsonValueTypes = [
"null",
"boolean",
"object",
"array",
"number",
"string",
];
export type AdvertisedInputSchemaPresentation = "inline" | "reduced";
export interface CompactedInputSchema {
readonly schema: Record<string, unknown>;
readonly presentation: AdvertisedInputSchemaPresentation;
}
const isSchemaObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const serializedBytes = (value: unknown): number =>
Buffer.byteLength(JSON.stringify(value), "utf8");
/** Rewrite every schema-valued position; literal data stays opaque. */
const rebuildSchemaPositions = (
node: unknown,
rebuild: (child: unknown) => unknown,
): unknown => {
if (Array.isArray(node)) return node.map((child) => rebuild(child));
if (!isSchemaObject(node)) return node;
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(node)) {
if (dataKeys.has(key)) {
out[key] = value;
continue;
}
if (schemaMaps.has(key) && isSchemaObject(value)) {
out[key] = Object.fromEntries(
Object.entries(value).map(([name, child]) => [name, rebuild(child)]),
);
continue;
}
if (schemaArrays.has(key) && Array.isArray(value)) {
out[key] = value.map((child) => rebuild(child));
continue;
}
if (schemaChildren.has(key)) {
out[key] = Array.isArray(value)
? value.map((child) => rebuild(child))
: rebuild(value);
continue;
}
out[key] = value;
}
return out;
};
/**
* Drop annotation prose from every subschema while preserving all validation
* keywords. The root keeps its own description because the root-union
* projection encodes accepted input groups there; the root's echoed literal
* examples leave with the rest of the annotation prose.
*/
const stripAnnotations = (
schema: Record<string, unknown>,
): Record<string, unknown> => {
const rebuilt = rebuildSchemaPositions(
schema,
stripChildAnnotations,
) as Record<string, unknown>;
const out: Record<string, unknown> = {};
for (const [key, value] of Object.entries(rebuilt)) {
if (annotationKeys.has(key) && key !== "description") continue;
out[key] = value;
}
return out;
};
const stripChildAnnotations = (child: unknown): unknown => {
const rebuilt = rebuildSchemaPositions(child, stripChildAnnotations);
if (!isSchemaObject(rebuilt)) return rebuilt;
const kept: Record<string, unknown> = {};
for (const [key, value] of Object.entries(rebuilt))
if (!annotationKeys.has(key)) kept[key] = value;
return kept;
};
const resolveLocalReference = (
root: Record<string, unknown>,
reference: string,
): unknown => {
if (reference === "#") return root;
if (!reference.startsWith("#/")) return undefined;
let value: unknown = root;
for (const token of reference.slice(2).split("/")) {
const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
if (!isSchemaObject(value) || !Object.hasOwn(value, key)) return undefined;
value = value[key];
}
return value;
};
/** Stop serialization at the budget before allocating an expanded schema. */
const inlineWithinBudget = (
root: Record<string, unknown>,
budgetBytes: number,
): Record<string, unknown> | undefined => {
let resolved = true;
function* serialize(
value: unknown,
position: "schema" | "map" | "data",
active: ReadonlySet<string>,
): Generator<string> {
if (Array.isArray(value)) {
yield "[";
for (const [index, child] of value.entries()) {
if (index > 0) yield ",";
yield* serialize(child, position, active);
}
yield "]";
} else if (isSchemaObject(value)) {
if (position === "schema" && Object.keys(value).length === 0) {
yield JSON.stringify({ type: jsonValueTypes });
return;
}
if (position === "schema" && typeof value.$ref === "string") {
const target = resolveLocalReference(root, value.$ref);
if (target === undefined || active.has(value.$ref)) {
resolved = false;
return;
}
const { $ref, ...siblings } = value;
// Reference siblings are independent constraints in draft 2020-12.
// Merging their keys into the target would overwrite validation rules.
yield* serialize(
Object.keys(siblings).length === 0
? target
: { allOf: [target, siblings] },
"schema",
new Set([...active, $ref]),
);
return;
}
yield "{";
let first = true;
for (const [key, child] of Object.entries(value)) {
if (position === "schema" && definitionKeys.has(key)) continue;
if (!first) yield ",";
first = false;
yield JSON.stringify(key) + ":";
const childPosition =
position === "map"
? "schema"
: position === "schema" && schemaMaps.has(key)
? "map"
: position === "schema" &&
(schemaArrays.has(key) || schemaChildren.has(key))
? "schema"
: "data";
yield* serialize(child, childPosition, active);
}
yield "}";
} else {
yield JSON.stringify(value);
}
}
const chunks: string[] = [];
let bytes = 0;
for (const chunk of serialize(root, "schema", new Set())) {
bytes += Buffer.byteLength(chunk, "utf8");
if (bytes > budgetBytes || !resolved) return undefined;
chunks.push(chunk);
}
return resolved
? (JSON.parse(chunks.join("")) as Record<string, unknown>)
: undefined;
};
/** Preserve every possible type, including referenced and nullable unions. */
const detectedTypes = (
schema: unknown,
root: Record<string, unknown>,
active: ReadonlySet<string> = new Set(),
): readonly string[] | undefined => {
if (!isSchemaObject(schema)) return undefined;
if (typeof schema.$ref === "string") {
if (active.has(schema.$ref)) return undefined;
return detectedTypes(
resolveLocalReference(root, schema.$ref),
root,
new Set([...active, schema.$ref]),
);
}
if (typeof schema.type === "string") return [schema.type];
if (
Array.isArray(schema.type) &&
schema.type.every((type) => typeof type === "string")
)
return schema.type;
const alternatives = Array.isArray(schema.anyOf)
? schema.anyOf
: Array.isArray(schema.oneOf)
? schema.oneOf
: [];
if (alternatives.length === 0) return undefined;
const types = alternatives.map((branch) =>
detectedTypes(branch, root, active),
);
if (types.some((type) => type === undefined)) return undefined;
return [...new Set(types.flatMap((type) => type ?? []))];
};
const REDUCED_ANNOTATION =
"Advertised in reduced form by the compact input schema profile; the server still validates complete canonical inputs.";
/**
* Present only the root property shape with per-property guidance. Used for
* schemas whose validation structure alone exceeds the compact budget; the
* canonical schema still rejects malformed calls server-side.
*/
const reduceToShallowProperties = (
schema: Record<string, unknown>,
): Record<string, unknown> => {
const properties = isSchemaObject(schema.properties) ? schema.properties : {};
const description = [
typeof schema.description === "string" ? schema.description : undefined,
REDUCED_ANNOTATION,
]
.filter((text) => text !== undefined)
.join(" ");
const $schema =
typeof schema.$schema === "string" ? { $schema: schema.$schema } : {};
const shallow = Object.fromEntries(
Object.entries(properties).map(([name, value]) => {
const types = detectedTypes(value, schema);
const type = types?.length === 1 ? types[0] : types;
const description =
isSchemaObject(value) && typeof value.description === "string"
? { description: value.description }
: {};
return [
name,
{ ...(type === undefined ? {} : { type }), ...description },
];
}),
);
return {
...$schema,
type: "object",
description,
properties: shallow,
...(Array.isArray(schema.required)
? { required: [...schema.required] }
: {}),
...(typeof schema.minProperties === "number"
? { minProperties: schema.minProperties }
: {}),
...(isSchemaObject(schema.dependentRequired)
? { dependentRequired: { ...schema.dependentRequired } }
: {}),
...(schema.additionalProperties === false
? { additionalProperties: false }
: {}),
};
};
/**
* Render an advertised input schema within a per-schema byte budget for
* providers that validate the literal serialized schema size. Validation
* keywords and the canonical contract are preserved; only
* annotation prose and, for structurally oversized schemas, nested
* validation detail leave the advertised form.
*/
export const compactAdvertisedInputSchema = (
schema: Record<string, unknown>,
budgetBytes: number,
): CompactedInputSchema => {
const inline = inlineWithinBudget(stripAnnotations(schema), budgetBytes);
if (inline !== undefined) return { schema: inline, presentation: "inline" };
const reduced = reduceToShallowProperties(schema);
if (serializedBytes(reduced) <= budgetBytes)
return { schema: reduced, presentation: "reduced" };
// A future contract with an extreme root-property count still advertises
// an honest, budget-fitting shape instead of an oversized one.
return {
schema: reduceToShallowProperties({
type: "object",
description:
(typeof schema.description === "string"
? `${schema.description} `
: "") + REDUCED_ANNOTATION,
}),
presentation: "reduced",
};
};
+13 -13
View File
@@ -1,6 +1,6 @@
import { isDeepStrictEqual } from "node:util";
const schemaMaps = new Set([
export const schemaMaps = new Set([
"$defs",
"definitions",
"properties",
@@ -8,8 +8,8 @@ const schemaMaps = new Set([
"dependentSchemas",
"dependencies",
]);
const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
const schemaChildren = new Set([
export const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
export const schemaChildren = new Set([
"items",
"additionalItems",
"contains",
@@ -59,7 +59,7 @@ const referencedDescription = (
const describeSchema = (
schema: unknown,
root: Readonly<Record<string, unknown>>,
describeProperty: (property: string) => string,
describeProperty: (property: string) => string | undefined,
): unknown => {
if (!isObject(schema)) return schema;
return Object.fromEntries(
@@ -70,16 +70,16 @@ const describeSchema = (
Object.fromEntries(
Object.entries(value).map(([name, child]) => {
const described = describeSchema(child, root, describeProperty);
if (key !== "properties" || !isObject(described))
return [name, described];
const description =
referencedDescription(root, described) ??
describeProperty(name);
return [
name,
key === "properties" && isObject(described)
? {
...described,
description:
referencedDescription(root, described) ??
describeProperty(name),
}
: described,
description === undefined
? described
: { ...described, description },
];
}),
),
@@ -223,7 +223,7 @@ const flattenRootObjectUnion = (
/** Describe canonical input fields and present the root as one object. */
export const presentInputJsonSchema = (
root: Record<string, unknown>,
describeProperty: (property: string) => string,
describeProperty: (property: string) => string | undefined,
): Record<string, unknown> => {
const flattened = flattenRootObjectUnion(root);
const described = describeSchema(flattened, flattened, describeProperty);
+6 -1
View File
@@ -97,9 +97,14 @@ describe("advertised input references", () => {
before: { description: "Exact byte range in the selected artifact." },
after: { description: "Exact byte range in the selected artifact." },
metadata: { default: literal, examples: [literal] },
constructor: { description: "Value for constructor." },
},
});
// Inherited object keys never supply a description.
expect(inline).not.toHaveProperty([
"properties",
"constructor",
"description",
]);
const ajv =
target === "draft-2020-12"
? new Ajv2020({ strict: false })
@@ -1,11 +1,69 @@
import { Ajv } from "ajv";
import { Ajv2020 } from "ajv/dist/2020.js";
import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
import { expect, it } from "vitest";
import { z } from "zod";
import { toolContract } from "./toolContracts.js";
import { toolOutputSchemaWithMetadata } from "./toolSchemaMetadata.js";
it("keeps dialect-specific validators distinct after JSON schema serialization", () => {
const contract = {
...toolContract("binary_session"),
outputSchema: z.strictObject({ value: z.number().int().min(1).max(8) }),
};
const output = toolOutputSchemaWithMetadata(contract);
const provider = new AjvJsonSchemaValidator();
for (const target of ["draft-2020-12", "draft-07"] as const) {
const projected = output["~standard"].jsonSchema.output({ target });
const parsed = z
.record(z.string(), z.unknown())
.parse(JSON.parse(JSON.stringify(projected)));
const validate = provider.getValidator(parsed);
expect(validate({ value: 8 }).valid).toBe(true);
expect(validate({ value: 9 }).valid).toBe(false);
expect(validate({ value: 1.5 }).valid).toBe(false);
}
});
it("preserves explicit schema identity and relative reference resolution", () => {
const value = z.string();
const canonical = z.strictObject({ value });
const contract = {
...toolContract("binary_session"),
outputSchema: canonical,
};
const projected = toolOutputSchemaWithMetadata(contract)[
"~standard"
].jsonSchema.output({
target: "draft-2020-12",
libraryOptions: {
override: (context: {
readonly zodSchema: unknown;
readonly jsonSchema: Record<string, unknown>;
}) => {
if (context.zodSchema !== value) return;
delete context.jsonSchema.type;
context.jsonSchema.$ref = "child.json";
},
},
});
const ajv = new Ajv2020({ strict: false });
ajv.addSchema({ $id: "child.json", type: "string", minLength: 3 });
const validate = ajv.compile(projected);
expect(validate({ value: "abc" })).toBe(true);
expect(validate({ value: "ab" })).toBe(false);
const identified = toolOutputSchemaWithMetadata({
...contract,
outputSchema: canonical.meta({ $id: "https://example.test/result" }),
})["~standard"].jsonSchema.output({ target: "draft-2020-12" });
expect(identified.$id).toBe("https://example.test/result");
const explicit = ajv.compile(identified);
expect(explicit({ value: "abc" })).toBe(true);
expect(explicit({ value: 1 })).toBe(false);
});
it.each(["draft-2020-12", "draft-07"] as const)(
"preserves refined numeric bounds and strict repeated objects through %s references",
(target) => {
+86 -6
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import type { ToolContract } from "./toolContractTypes.js";
import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
addresses: "Ordered provider-normalized procedure addresses to analyze.",
@@ -69,20 +70,95 @@ export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
},
);
/** Share repeated output definitions without changing canonical validation. */
/** Share output definitions and content-bound validator identities on the wire. */
export const toolOutputSchemaWithMetadata = <Contract extends ToolContract>(
contract: Contract,
): Contract["outputSchema"] =>
withAdvertisedJsonSchema(
contract.outputSchema,
"output",
(project) => (options) =>
project({
(project) => (options) => {
const shared = project({
...options,
libraryOptions: { reused: "ref", ...options.libraryOptions },
}),
});
// An explicit ID owns the reference base. Relative external references
// also depend on that base, so leave those projections unchanged.
if ("$id" in shared || hasRelativeSchemaReference(shared)) return shared;
return {
...shared,
$id: `urn:rea:tool-output:sha256:${digestCanonicalValue(
{ target: options.target, schema: shared },
"Tool output schema",
)}`,
};
},
);
/**
* Apply a wire-presentation transform to one schema's advertised input
* projection. The wrapper preserves the schema's own parser and standard
* metadata, so both Zod registrations and plain standard schemas keep their
* canonical validation while only the advertised JSON changes.
*/
export const transformAdvertisedInputJsonSchema = <Schema>(
schema: Schema,
transform: (projected: Record<string, unknown>) => Record<string, unknown>,
): Schema => {
const standard = Reflect.get(schema as object, "~standard");
if (!isSchemaRecord(standard)) return schema;
const jsonSchema = Reflect.get(standard, "jsonSchema");
if (!isSchemaRecord(jsonSchema)) return schema;
const project = Reflect.get(jsonSchema, "input");
if (typeof project !== "function") return schema;
const byTarget = new Map<string, Record<string, unknown>>();
const transformedInput = (options: unknown): unknown => {
const target = Reflect.get(options as object, "target");
if (typeof target === "string") {
const cached = byTarget.get(target);
if (cached !== undefined) return cached;
}
const projected = (project as (options: unknown) => unknown)(options);
const transformed = isSchemaRecord(projected)
? transform(projected)
: projected;
if (typeof target === "string" && isSchemaRecord(transformed))
byTarget.set(target, transformed);
return transformed;
};
return {
...(schema as object),
"~standard": {
...standard,
jsonSchema: { ...jsonSchema, input: transformedInput },
},
} as Schema;
};
const hasRelativeSchemaReference = (
schema: Record<string, unknown>,
): boolean => {
const pending: unknown[] = [schema];
const visited = new WeakSet<object>();
while (pending.length > 0) {
const current = pending.pop();
if (current === null || typeof current !== "object" || visited.has(current))
continue;
visited.add(current);
for (const [key, value] of Object.entries(current)) {
if (
["$id", "$ref", "$dynamicRef", "$recursiveRef"].includes(key) &&
typeof value === "string" &&
!value.startsWith("#") &&
!URL.canParse(value)
)
return true;
if (value !== null && typeof value === "object") pending.push(value);
}
}
return false;
};
const withAdvertisedJsonSchema = <Schema extends z.ZodType>(
canonical: Schema,
io: "input" | "output",
@@ -128,7 +204,10 @@ const memoizeByTarget = (
};
};
const fallbackPropertyDescription = (property: string): string => {
const isSchemaRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const fallbackPropertyDescription = (property: string): string | undefined => {
const explicit = Object.hasOwn(PROPERTY_DESCRIPTIONS, property)
? PROPERTY_DESCRIPTIONS[property]
: undefined;
@@ -156,5 +235,6 @@ const fallbackPropertyDescription = (property: string): string => {
return `Local filesystem ${words} selected for this operation.`;
if (property.startsWith("is_") || property.startsWith("has_"))
return `Whether ${words}.`;
return `Value for ${words}.`;
// A generic sentence would only restate the property name in every schema.
return undefined;
};
+20 -3
View File
@@ -191,7 +191,7 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
const standardMessage = standardErrorMessage(error._tag);
if (standardMessage !== undefined) return standardMessage;
if (error instanceof ArtifactOperationError)
return artifactMessage(error.operation, error.reason);
return artifactMessage(error.operation, error.reason, error.detail);
if (error instanceof EvidenceReferenceError)
return error.reason === "missing"
? `Evidence ${error.evidenceId} is not retained in this session. Supply complete inline Evidence, re-run its producer, or import its bundle before using this reference.`
@@ -329,13 +329,13 @@ const START_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
const artifactMessage = (
operation: ArtifactOperationError["operation"],
reason: ArtifactOperationError["reason"],
detail?: string,
): string => {
if (reason === "cancelled")
return "Artifact operation was cancelled. Start it again when ready.";
if (reason === "limit")
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
if (reason === "path")
return "Artifact contains an unsafe or conflicting internal path. Inspect the reported path and correct the artifact before retrying.";
if (reason === "path") return artifactPathMessage(detail);
if (reason === "unavailable")
return "Artifact processing is unavailable for the current target or host. Check artifact support and required tools.";
if (reason === "integrity" && operation === "analyze_javascript_application")
@@ -345,6 +345,23 @@ const artifactMessage = (
return "Artifact could not be read or written. Check file access and try again.";
};
const artifactPathMessage = (detail: string | undefined): string => {
// Kept in step with DESTINATION_CASE_COLLISION_PREFIX. Domain does not import
// the artifact adapter that produces the detail.
if (
detail !== undefined &&
detail.startsWith("Destination filesystem cannot store both ")
)
return detail;
if (
detail !== undefined &&
(detail.startsWith("Artifact path is absolute or unsafe:") ||
detail.startsWith("Artifact path is not normalized:"))
)
return "Artifact contains an unsafe internal path. Inspect the reported path and correct the artifact before retrying.";
return "Artifact contains a conflicting internal path. Inspect the reported path before retrying.";
};
const evidenceFileMessage = ({
operation,
reason,
+242 -13
View File
@@ -1,6 +1,8 @@
import { expect, it } from "vitest";
import { resolveJavaScriptSourceMapReference } from "../javascript/javascriptSourceMapPaths.js";
import { functionDossierSchema } from "../hopperValues.js";
import { ghidraFunctionDossier } from "../ghidraValues.fixture.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
import {
analysisViewBindJavaScriptGraphs,
@@ -48,21 +50,248 @@ const javascriptParent = (
limitations: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE.limitations,
});
it("accepts caller-selected page sizes and rejects malformed bounds", () => {
const input = {
source: { kind: "retained-evidence", evidence_id: `ev_${"a".repeat(64)}` },
view: { kind: "page", collection: "sections", offset: 0, limit: 500 },
};
expect(inspectAnalysisViewInputSchema.safeParse(input).success).toBe(true);
for (const limit of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1])
expect(
inspectAnalysisViewInputSchema.safeParse({
...input,
view: { ...input.view, limit },
}).success,
).toBe(false);
const nativeParent = (
result: unknown = ghidraFunctionDossier(),
): AnalysisViewParent => ({
evidenceId: "ev_" + "b".repeat(64),
operation: "analyze_function",
normalizedResult: result,
limitations: ["Retained provider limitation"],
artifact: { path: "/fixtures/example.exe", sha256: "a".repeat(64) },
});
it("projects native procedure and bounded assembly and high-pcode with exact parent identity", () => {
const parent = nativeParent();
const procedure = projectAnalysisView(parent, {
kind: "native",
facet: "procedure",
offset: 0,
limit: 64,
});
if (!procedure.ok) throw procedure.error;
expect(procedure.value).toMatchObject({
kind: "native",
parent_operation: "analyze_function",
artifact: parent.artifact,
item: { address: "0x401000" },
});
expect(procedure.value.view_digest).not.toBe(parent.evidenceId.slice(3));
const assembly = projectAnalysisView(parent, {
kind: "native",
facet: "assembly",
offset: 0,
limit: 1,
});
if (!assembly.ok) throw assembly.error;
expect(assembly.value).toMatchObject({
coverage: { examined: 1, total: 2, next_offset: 1 },
item: ["0x401000: CALL 0x401020"],
});
const flow = projectAnalysisView(parent, {
kind: "native",
facet: "value_flow_operations",
offset: 0,
limit: 1,
});
if (!flow.ok) throw flow.error;
expect(flow.value).toMatchObject({ item: [{ opcode: "COPY" }] });
});
it("rejects invalid native parents, unsupported source operations and singleton offsets", () => {
const view = {
kind: "native",
facet: "assembly",
offset: 0,
limit: 4,
} as const;
expect(projectAnalysisView(nativeParent({}), view)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(
projectAnalysisView({ ...nativeParent(), artifact: null }, view),
).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(projectAnalysisView(layoutParent(), view)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(projectAnalysisView(javascriptParent(), view)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(
projectAnalysisView(nativeParent(), {
kind: "native",
facet: "procedure",
offset: 1,
limit: 2,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
});
it("preserves native API limitations and unavailable residual unknowns", () => {
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const view = {
kind: "native",
facet: "procedure",
offset: 0,
limit: 64,
} as const;
const unavailable = projectAnalysisView(
nativeParent({
...original,
native_api: {
available: false,
reason: "No decompiler",
residual_unknowns: ["Calling convention unresolved"],
},
}),
view,
);
if (!unavailable.ok) throw unavailable.error;
expect(unavailable.value.unknowns).toContain("Calling convention unresolved");
const available = projectAnalysisView(nativeParent(), view);
if (!available.ok) throw available.error;
if (!original.native_api?.available) throw new Error("expected API fixture");
expect(available.value.limitations).toEqual(
expect.arrayContaining(original.native_api.limitations),
);
});
it("pages every retained dossier collection and the native API record", () => {
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const page = (
facet:
| "basic_blocks"
| "comments"
| "unresolved_calls"
| "referenced_strings"
| "referenced_names",
result: unknown = original,
) => {
const view = projectAnalysisView(nativeParent(result), {
kind: "native",
facet,
offset: 0,
limit: 64,
});
if (!view.ok) throw view.error;
return view.value;
};
expect(page("basic_blocks")).toMatchObject({
item: original.basic_blocks,
coverage: { total: original.basic_blocks.length, exhausted: true },
});
expect(page("referenced_strings")).toMatchObject({
item: original.referenced_strings,
});
expect(
page("comments", {
...original,
comments: [{ address: "0x401000", kind: "comment", text: "entry" }],
}),
).toMatchObject({ item: [{ text: "entry" }] });
expect(page("referenced_names")).toMatchObject({ coverage: { total: 0 } });
const { unresolved_calls: _omitted, ...withoutUnresolved } = original;
expect(
page("unresolved_calls", {
...withoutUnresolved,
native_value_flow: {
available: false,
reason: "No high p-code",
limitations: [],
},
}),
).toMatchObject({ item: { available: false, reason: "not recorded" } });
const api = projectAnalysisView(nativeParent(), {
kind: "native",
facet: "native_api",
offset: 0,
limit: 64,
});
if (!api.ok) throw api.error;
expect(api.value).toMatchObject({
item: original.native_api,
coverage: { status: "complete-within-view" },
});
});
it("reports the malformed native dossier field", () => {
const result = projectAnalysisView(
nativeParent({
...functionDossierSchema.parse(ghidraFunctionDossier()),
pseudocode: 12,
}),
{
kind: "native",
facet: "pseudocode",
offset: 0,
limit: 64,
},
);
expect(result).toMatchObject({
ok: false,
error: {
issues: expect.arrayContaining([
expect.objectContaining({
path: ["source", "normalized_result", "pseudocode"],
}),
]),
},
});
});
it("native pseudocode pages do not split surrogate pairs", () => {
const original = functionDossierSchema.parse(ghidraFunctionDossier());
const parent = nativeParent({ ...original, pseudocode: "ab😀cd" });
expect(
projectAnalysisView(parent, {
kind: "native",
facet: "pseudocode",
offset: 3,
limit: 2,
}),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const safe = projectAnalysisView(parent, {
kind: "native",
facet: "pseudocode",
offset: 2,
limit: 3,
});
if (!safe.ok) throw safe.error;
expect(safe.value).toMatchObject({
item: { text: "😀c", unit: "utf16-code-units" },
coverage: { examined: 3, next_offset: 5 },
});
});
it.each([
{ kind: "page", collection: "sections", offset: 0, limit: 500 },
{ kind: "native", facet: "assembly", offset: 0, limit: 500 },
])(
"accepts caller-selected page sizes and rejects malformed bounds: $kind",
(view) => {
const input = {
source: {
kind: "retained-evidence",
evidence_id: `ev_${"a".repeat(64)}`,
},
view,
};
expect(inspectAnalysisViewInputSchema.safeParse(input).success).toBe(true);
for (const limit of [0, -1, 0.5, Infinity, Number.MAX_SAFE_INTEGER + 1])
expect(
inspectAnalysisViewInputSchema.safeParse({
...input,
view: { ...input.view, limit },
}).success,
).toBe(false);
},
);
it("projects layout summary, facet, item, and stable pages", () => {
const parent = layoutParent();
const layout = analysisViewLayoutFixture();
+66 -3
View File
@@ -12,6 +12,7 @@ import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { binaryLayoutSchema } from "../native/binaryLayout.js";
import { functionDossierSchema } from "../hopperValues.js";
import {
parseOwnedJavaScriptApplicationAnalysisSteps,
type JavaScriptApplicationAnalysisResult,
@@ -19,6 +20,7 @@ import {
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { projectBinaryLayoutView } from "./binaryLayoutView.js";
import { projectJavaScriptApplicationView } from "./javascriptApplicationView.js";
import { projectNativeFunctionView } from "./nativeFunctionView.js";
/** Public name of the selected-view workflow. */
export const INSPECT_ANALYSIS_VIEW_OPERATION = "inspect_analysis_view" as const;
@@ -73,12 +75,41 @@ const pageViewSchema = z.strictObject({
limit: z.number().int().positive(),
});
/** Bounded native function facets of already authenticated analyze_function Evidence. */
const nativeViewSchema = z.strictObject({
kind: z.literal("native"),
facet: z.enum([
"procedure",
"pseudocode",
"assembly",
"basic_blocks",
"comments",
"callers",
"callees",
"incoming_references",
"outgoing_references",
"unresolved_calls",
"referenced_strings",
"referenced_names",
"native_api",
"value_flow_summary",
"value_flow_operations",
"value_flow_def_use",
"value_flow_effects",
"value_flow_parameters",
"value_flow_parameter_uses",
]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
/** Caller-selected projection of already completed analysis Evidence. */
export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
summaryViewSchema,
facetViewSchema,
itemViewSchema,
pageViewSchema,
nativeViewSchema,
]);
/** Inline Evidence or an exact same-session retained reference. */
@@ -108,7 +139,9 @@ const coverageSchema = z.strictObject({
});
const artifactSchema = z.strictObject({
path: z.string().min(1),
path: z
.string()
.describe("Exact recorded artifact path, including an empty string."),
sha256: digestSchema,
});
@@ -150,6 +183,7 @@ const viewResultBase = {
parent_operation: z.enum([
"inspect_binary_layout",
"analyze_javascript_application",
"analyze_function",
]),
parent_digest: digestSchema,
view_digest: digestSchema,
@@ -185,6 +219,13 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
items: z.array(jsonValueSchema),
...viewResultBase,
}),
z.strictObject({
kind: z.literal("native"),
view: nativeViewSchema,
procedure_address: z.string().nullable(),
item: jsonValueSchema,
...viewResultBase,
}),
]);
export type AnalysisViewRequest = z.output<typeof analysisViewRequestSchema>;
@@ -200,6 +241,7 @@ export interface AnalysisViewParent {
readonly operation: string;
readonly normalizedResult: unknown;
readonly limitations: readonly string[];
readonly artifact?: { readonly path: string; readonly sha256: string } | null;
}
/** Construct a typed input failure for one selected-view constraint. */
@@ -216,7 +258,11 @@ export type UnsignedAnalysisView =
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "facet" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "item" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "page" }>, "view_digest">;
| Omit<Extract<AnalysisViewResult, { readonly kind: "page" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "native" }>,
"view_digest"
>;
/** Attach the content digest that must change when projected bytes change. */
export const sealAnalysisView = (
@@ -261,7 +307,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} is not inspect_binary_layout or analyze_javascript_application.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} is not inspect_binary_layout, analyze_javascript_application or analyze_function.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -327,5 +373,22 @@ export const projectAnalysisView = (
);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "analyze_function") {
const native = functionDossierSchema.safeParse(parent.normalizedResult);
if (!native.success)
return err(
analysisInputErrorFromIssues(
INSPECT_ANALYSIS_VIEW_OPERATION,
native.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: native.error },
),
);
const projected = projectNativeFunctionView(parent, native.data, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
return err(unsupportedParent(parent));
};
@@ -152,6 +152,10 @@ export const projectBinaryLayoutView = (
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
const shared = parentFields(parent, layout);
if (view.kind === "native")
return err(
layoutIncompatible("Native views require analyze_function Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -243,6 +243,10 @@ export const projectJavaScriptApplicationView = (
): Result<UnsignedAnalysisView, AnalysisError> => {
const shared = parentFields(parent, analysis);
const modules = moduleEntries(analysis.graph.nodes);
if (view.kind === "native")
return err(
jsIncompatible("Native views require analyze_function Evidence."),
);
if (view.kind === "summary")
return ok({
kind: "summary",
@@ -0,0 +1,222 @@
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import type { FunctionDossier } from "../hopperValues.js";
import { jsonValueSchema } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewCoverage,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
type Artifact = { readonly path: string; readonly sha256: string };
const viewError = (message: string): AnalysisError =>
analysisViewInputError([
{ path: ["view"], reason: "invalid_value", message },
]);
const parentFields = (
parent: AnalysisViewParent,
dossier: FunctionDossier,
artifact: Artifact,
) => {
const flow = dossier.native_value_flow;
const api = dossier.native_api;
const unknowns: string[] = [];
if (flow === null) unknowns.push("native_value_flow was not recorded");
else if (!flow.available)
unknowns.push("native_value_flow unavailable: " + flow.reason);
else if (flow.truncated)
unknowns.push(
"native_value_flow is truncated; omitted observations remain unknown",
);
if (api === null) unknowns.push("native_api was not recorded");
else if (!api.available)
unknowns.push(
"native_api unavailable: " + api.reason,
...api.residual_unknowns,
);
return {
parent_evidence_id: parent.evidenceId,
parent_operation: "analyze_function" as const,
parent_digest: parent.evidenceId.slice(3),
procedure_address: dossier.procedure.address,
artifact,
limitations: uniqueSorted([
...parent.limitations,
...dossier.limitations,
...(flow?.limitations ?? []),
...(api?.available ? api.limitations : []),
]),
unknowns: uniqueSorted(unknowns),
};
};
const pseudocodePage = (
body: string,
offset: number,
limit: number,
): Result<
{
readonly item: { readonly text: string; readonly unit: "utf16-code-units" };
readonly coverage: AnalysisViewCoverage;
},
AnalysisError
> => {
const start = Math.min(offset, body.length);
const high = (n: number) => n >= 0xd800 && n <= 0xdbff;
const low = (n: number) => n >= 0xdc00 && n <= 0xdfff;
if (
start > 0 &&
start < body.length &&
high(body.charCodeAt(start - 1)) &&
low(body.charCodeAt(start))
)
return err(viewError("Pseudocode offset splits a UTF-16 surrogate pair."));
let end = Math.min(start + limit, body.length);
if (
end > start &&
end < body.length &&
high(body.charCodeAt(end - 1)) &&
low(body.charCodeAt(end))
)
end--;
if (end === start && start < body.length)
return err(
viewError(
"Increase pseudocode limit to include the next complete Unicode character.",
),
);
return ok({
item: { text: body.slice(start, end), unit: "utf16-code-units" },
coverage: pageViewCoverage(start, end - start, body.length),
});
};
const nativeRows = (
dossier: FunctionDossier,
facet: Exclude<
Extract<AnalysisViewRequest, { readonly kind: "native" }>["facet"],
"procedure" | "pseudocode" | "native_api" | "value_flow_summary"
>,
): readonly unknown[] | undefined => {
const sourceFlow = dossier.native_value_flow;
const flow = sourceFlow?.available ? sourceFlow : undefined;
return {
assembly: dossier.assembly,
basic_blocks: dossier.basic_blocks,
comments: dossier.comments,
callers: dossier.callers,
callees: dossier.callees,
incoming_references: dossier.incoming_references,
outgoing_references: dossier.outgoing_references,
unresolved_calls: dossier.unresolved_calls,
referenced_strings: dossier.referenced_strings,
referenced_names: dossier.referenced_names,
value_flow_operations: flow?.operations,
value_flow_def_use: flow?.def_use,
value_flow_effects: flow?.effects,
value_flow_parameters: flow?.parameters,
value_flow_parameter_uses: flow?.parameter_uses,
}[facet];
};
/** Project bounded native function facets from complete retained Evidence without reanalysis. */
export const projectNativeFunctionView = (
parent: AnalysisViewParent,
dossier: FunctionDossier,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "native")
return err(viewError("analyze_function Evidence requires a native view."));
const artifact = parent.artifact;
if (!artifact)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Native function Evidence requires an artifact-bound subject.",
},
]),
);
const common = parentFields(parent, dossier, artifact);
const singleton = (item: unknown): UnsignedAnalysisView => ({
kind: "native",
view,
item: jsonValueSchema.parse(item),
coverage: completeWithinViewCoverage(1, 1),
...common,
});
const flow = dossier.native_value_flow;
if (
view.facet === "procedure" ||
view.facet === "native_api" ||
view.facet === "value_flow_summary"
) {
if (view.offset !== 0)
return err(viewError("Singleton native facets require offset 0."));
if (view.facet === "procedure") return ok(singleton(dossier.procedure));
if (view.facet === "native_api")
return ok(
singleton(
dossier.native_api ?? { available: false, reason: "not recorded" },
),
);
const status =
flow === null
? { available: false, reason: "not recorded" }
: !flow.available
? { available: false, reason: flow.reason }
: {
available: true,
provenance: flow.provenance,
truncated: flow.truncated,
omitted_operations_lower_bound:
flow.omitted_operations_lower_bound,
known_omitted_inputs: flow.known_omitted_inputs,
known_omitted_edges: flow.known_omitted_edges,
operations: flow.operations.length,
def_use: flow.def_use.length,
effects: flow.effects.length,
parameters: flow.parameters.length,
parameter_uses: flow.parameter_uses.length,
};
return ok(singleton(status));
}
if (view.facet === "pseudocode") {
const page = pseudocodePage(dossier.pseudocode, view.offset, view.limit);
return page.ok
? ok({ kind: "native", view, ...page.value, ...common })
: page;
}
const rows = nativeRows(dossier, view.facet);
if (rows === undefined)
return ok(
singleton({
available: false,
// Only value-flow facets inherit the value-flow failure reason; an
// older dossier simply has no unresolved_calls record.
reason:
view.facet.startsWith("value_flow_") && flow?.available === false
? flow.reason
: "not recorded",
}),
);
const items = rows.slice(view.offset, view.offset + view.limit);
return ok({
kind: "native",
view,
item: jsonValueSchema.parse(items),
coverage: pageViewCoverage(view.offset, items.length, rows.length),
...common,
});
};
+9 -28
View File
@@ -125,6 +125,8 @@ export const projectAndroidApplication = (
"Manifest, resource, signing, and bytecode semantics require a dedicated Android provider; this projection reports exact inventory paths and hashes only.",
"Runtime families are inferred from inventory formats and paths; filename suffixes do not establish valid DEX or JVM class bytes.",
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
"A bridge basis is inferred from the native path and is repeated for every managed component.",
"ZIP inventory cannot see the APK Signing Block, so an empty signing array does not mean the APK is unsigned.",
...(bridgeProjection.coverage.status === "partial"
? [
`Bridge candidate pairs exceeded the projection safety budget; ${bridgeProjection.coverage.omitted_candidates} hypotheses are omitted. Component arrays still include every component from the supplied inventory pages.`,
@@ -157,23 +159,12 @@ export const projectAndroidApplication = (
};
const classify = (all: readonly Component[]) => ({
manifests: all.filter(
({ path, format }) =>
format === "android-manifest" ||
/(?:^|\/)AndroidManifest\.xml$/u.test(path),
),
resources: all.filter(
({ path, format }) =>
format === "android-resources" || /(?:^|\/)resources\.arsc$/u.test(path),
),
dex: all.filter(
({ path, format }) =>
format === "dex" || /(?:^|\/)[^/]+\.dex$/iu.test(path),
),
jvm_classes: all.filter(
({ path, format }) =>
format === "jvm-class" || /(?:^|\/)[^/]+\.class$/iu.test(path),
manifests: all.filter(({ path }) =>
/(?:^|\/)AndroidManifest\.xml$/u.test(path),
),
resources: all.filter(({ path }) => /(?:^|\/)resources\.arsc$/u.test(path)),
dex: all.filter(({ path }) => /(?:^|\/)[^/]+\.dex$/iu.test(path)),
jvm_classes: all.filter(({ path }) => /(?:^|\/)[^/]+\.class$/iu.test(path)),
native_libraries: all.filter(
({ path, format }) =>
format === "elf" || /(?:^|\/)lib\/[^/]+\/[^/]+\.so$/iu.test(path),
@@ -189,19 +180,9 @@ const runtimeFamilies = (all: readonly Component[]) => {
const families = new Set<
AndroidApplicationProjectionResult["runtime_families"][number]
>();
if (
all.some(
({ path, format }) =>
format === "dex" || path.toLowerCase().endsWith(".dex"),
)
)
if (all.some(({ path }) => path.toLowerCase().endsWith(".dex")))
families.add("dalvik-art");
if (
all.some(
({ path, format }) =>
format === "jvm-class" || path.toLowerCase().endsWith(".class"),
)
)
if (all.some(({ path }) => path.toLowerCase().endsWith(".class")))
families.add("java-kotlin");
if (all.some(({ format }) => format === "elf")) families.add("native");
if (all.some(({ format }) => format === "javascript-bundle"))
@@ -509,3 +509,75 @@ describe("AppKit keyed archive connectors", () => {
expect(to).toEqual(expect.arrayContaining(["objc_selector", "unknown"]));
});
});
it("names the archive once per evidence record", () => {
const relativePath = "Views/Main.storyboardc/scene.nib/objects.nib";
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath,
archiveSha256: hash,
documentKind: "storyboard_scene",
raw: {
"com.apple.ibtool.document.objects": {
controller: { customClass: "StoreViewController" },
next: { customClass: "BuildViewController" },
},
"com.apple.ibtool.document.connections": {
controller: [
{ type: "segue", identifier: "showBuild", destinationId: "next" },
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
const evidence = [...result.graph.nodes, ...result.graph.edges].flatMap(
(item) => item.evidence,
);
expect(new Set(evidence.map(({ artifact_path }) => artifact_path))).toEqual(
new Set([relativePath]),
);
expect(evidence.map(({ description }) => description)).toEqual(
expect.arrayContaining([
"compiled document",
"object controller",
"segue showBuild",
]),
);
expect(
evidence.filter(({ description }) => description.includes(relativePath)),
).toEqual([]);
});
it("states each object's class, label, and ID once", () => {
const { objects } = parseInterfaceBuilderRecords({
"com.apple.ibtool.document.objects": {
"7": {
customClass: "NSButton",
label: "Start",
objectID: "7",
nibValues: { NSContents: "Start" },
},
button: { class: "UIButton", title: "Build", objectID: "authored" },
},
});
expect(objects).toEqual([
expect.objectContaining({
id: "7",
class_name: "NSButton",
name: "Start",
attributes: { nibValues: { NSContents: "Start" } },
}),
expect.objectContaining({
id: "button",
class_name: "UIButton",
name: "Build",
// Values that differ from the canonical fields stay as authored.
attributes: { class: "UIButton", title: "Build", objectID: "authored" },
}),
]);
});
+3 -1
View File
@@ -72,7 +72,9 @@ export const buildInterfaceBuilderAnalysis = (input: {
const evidenceFor = (description: string) => [
{
kind: "interface_builder_resource" as const,
description: `${document.relativePath}: ${description}`,
// artifact_path names the archive; repeating it here cost a path per
// node and edge.
description,
location: { address: null, file_offset: null },
artifact_path: document.relativePath,
artifact_sha256: document.archiveSha256,
@@ -71,13 +71,23 @@ export const parseInterfaceBuilderRecords = (
attributes["name"],
className,
);
// class_name, name, and id already carry these values; repeating them in
// attributes doubled them on every graph node.
const carried = new Set<string>();
if (attributes["customClass"] === className) carried.add("customClass");
if (attributes["label"] === label) carried.add("label");
if (attributes["objectID"] === id) carried.add("objectID");
objects.push(
objectNode.parse({
id,
kind: classifyObject(className),
class_name: className,
name: label ?? id,
attributes: jsonSafeRecord(attributes),
attributes: jsonSafeRecord(
Object.fromEntries(
Object.entries(attributes).filter(([key]) => !carried.has(key)),
),
),
}),
);
}
+7 -6
View File
@@ -350,19 +350,20 @@ const relationsByPath = (
inventory.occurrences.map((item) => [item.occurrence_id, item]),
);
for (const edge of inventory.edges) {
const path = edge.logical_path ?? ".";
const values = output.get(path);
const occurrence = occurrences.get(edge.occurrence_id);
// An incomplete inventory can omit the occurrence that names the child.
if (occurrence?.artifact_id === null || occurrence === undefined) continue;
const path = occurrence.logical_path;
const values = output.get(path);
const projection: RelationProjection = {
parent_logical_path:
occurrence?.parent_occurrence_id === null ||
occurrence?.parent_occurrence_id === undefined
occurrence.parent_occurrence_id === null
? null
: (occurrences.get(occurrence.parent_occurrence_id)?.logical_path ??
null),
child_artifact_id: edge.child_artifact_id,
child_artifact_id: occurrence.artifact_id,
relation: edge.relation,
logical_path: edge.logical_path,
logical_path: occurrence.logical_path,
producer: edge.producer,
};
if (values === undefined) output.set(path, [projection]);
+4 -3
View File
@@ -151,12 +151,14 @@ export const integrityContradictionSchema = z.object({
limitations: z.array(z.string()).min(1),
});
/** Parent-child derivation relation between two content-addressed artifacts. */
/**
* Parent-child derivation relation between two content-addressed artifacts.
* The child artifact and its logical path are those of the edge's occurrence.
*/
const artifactEdgeSchema = z.object({
edge_id: edgeIdSchema,
ordinal: z.number().int().min(0),
parent_artifact_id: artifactIdSchema,
child_artifact_id: artifactIdSchema,
relation: z.enum([
"contains",
"extracts",
@@ -167,7 +169,6 @@ const artifactEdgeSchema = z.object({
"derived-from",
]),
occurrence_id: occurrenceIdSchema,
logical_path: boundedRelativePathSchema.nullable(),
producer: artifactCommandSchema.nullable(),
});
+17 -10
View File
@@ -71,14 +71,21 @@ export const artifactContradictionId = (input: {
"Artifact",
)}`;
/** Identify an edge by its semantic relationship and exact occurrence. */
/**
* Identify an edge by its semantic relationship and exact occurrence. The
* child artifact and logical path come from that occurrence.
*/
export const artifactEdgeId = (
semantic: Pick<
ArtifactEdge,
| "parent_artifact_id"
| "child_artifact_id"
| "relation"
| "occurrence_id"
| "logical_path"
>,
): string => `edge_${digestCanonicalValue(semantic, "Artifact")}`;
edge: Pick<ArtifactEdge, "parent_artifact_id" | "relation" | "occurrence_id">,
occurrence: Pick<ArtifactOccurrence, "artifact_id" | "logical_path">,
): string =>
`edge_${digestCanonicalValue(
{
parent_artifact_id: edge.parent_artifact_id,
child_artifact_id: occurrence.artifact_id,
relation: edge.relation,
occurrence_id: edge.occurrence_id,
logical_path: occurrence.logical_path,
},
"Artifact",
)}`;
+3 -56
View File
@@ -16,30 +16,12 @@ const artifactIdSchema = prefixedDigestSchema("art");
const inspectionObservationSchema = z.strictObject({
observation_id: prefixedDigestSchema("aio"),
kind: z.enum(["root-manifest", "artifact", "occurrence", "integrity"]),
kind: z.enum(["root-manifest", "integrity"]),
subject: textSchema,
value: jsonValueSchema,
evidence_id: evidenceIdSchema,
});
const inspectionRelationshipSchema = z.strictObject({
relationship_id: prefixedDigestSchema("air"),
relation: z.enum([
"contains",
"extracts",
"slice-of",
"embeds",
"loads",
"maps-source",
"derived-from",
]),
source_artifact_id: artifactIdSchema,
target_artifact_id: artifactIdSchema,
occurrence_id: prefixedDigestSchema("occ"),
logical_path: textSchema.nullable(),
evidence_id: evidenceIdSchema,
});
const inspectionHypothesisSchema = z.strictObject({
hypothesis_id: prefixedDigestSchema("aih"),
statement: textSchema,
@@ -97,7 +79,6 @@ export const artifactInspectionResultSchema = z.strictObject({
)
.min(1),
observations: z.array(inspectionObservationSchema),
derived_relationships: z.array(inspectionRelationshipSchema),
hypotheses: z.array(inspectionHypothesisSchema),
contradictions: z.array(inspectionContradictionSchema),
unexplored_branches: z.array(unexploredBranchSchema),
@@ -107,8 +88,6 @@ export const artifactInspectionResultSchema = z.strictObject({
substeps_completed: z.literal(1),
observations_retained: z.number().int().min(0),
observations_omitted: z.number().int().min(0),
relationships_retained: z.number().int().min(0),
relationships_omitted: z.number().int().min(0),
hypotheses_retained: z.number().int().min(0),
hypotheses_omitted: z.number().int().min(0),
unexplored_branches_retained: z.number().int().min(0),
@@ -136,10 +115,6 @@ export const createArtifactInspection = (
inventory,
inventoryEvidence.evidence_id,
);
const relationships = allRelationships(
inventory,
inventoryEvidence.evidence_id,
);
const hypotheses = allHypotheses(inventory, inventoryEvidence.evidence_id);
const nextProbes = probesFor(inventory);
const branches = allUnexploredBranches(
@@ -149,14 +124,12 @@ export const createArtifactInspection = (
);
const retained = {
observations,
relationships,
hypotheses,
branches,
probes: nextProbes,
};
const omissions = {
observations: 0,
relationships: 0,
hypotheses: 0,
branches: 0,
probes: 0,
@@ -184,7 +157,6 @@ export const createArtifactInspection = (
},
],
observations: retained.observations,
derived_relationships: retained.relationships,
hypotheses: retained.hypotheses,
contradictions: contradictions(inventory, inventoryEvidence.evidence_id),
unexplored_branches: retained.branches,
@@ -194,8 +166,6 @@ export const createArtifactInspection = (
substeps_completed: 1 as const,
observations_retained: retained.observations.length,
observations_omitted: omissions.observations,
relationships_retained: retained.relationships.length,
relationships_omitted: omissions.relationships,
hypotheses_retained: retained.hypotheses.length,
hypotheses_omitted: omissions.hypotheses,
unexplored_branches_retained: retained.branches.length,
@@ -224,6 +194,8 @@ const parseInventoryEvidence = (input: unknown): Evidence => {
return evidence;
};
// Artifact, occurrence, and edge records stay in the nested inventory Evidence;
// restating each one here would repeat the complete graph in every result.
const allObservations = (
inventory: ArtifactInventoryResult,
evidenceId: string,
@@ -234,12 +206,6 @@ const allObservations = (
inventory.manifest,
evidenceId,
),
...inventory.nodes.map((node) =>
observation("artifact", node.artifact_id, node, evidenceId),
),
...inventory.occurrences.map((occurrence) =>
observation("occurrence", occurrence.occurrence_id, occurrence, evidenceId),
),
...inventory.integrity_contradictions.map((value) =>
observation("integrity", value.contradiction_id, value, evidenceId),
),
@@ -263,25 +229,6 @@ const observation = (
};
};
const allRelationships = (
inventory: ArtifactInventoryResult,
evidenceId: string,
): ArtifactInspectionResult["derived_relationships"] =>
inventory.edges.map((edge) => {
const semantic = {
relation: edge.relation,
source_artifact_id: edge.parent_artifact_id,
target_artifact_id: edge.child_artifact_id,
occurrence_id: edge.occurrence_id,
logical_path: edge.logical_path,
evidence_id: evidenceId,
};
return {
relationship_id: `air_${digestCanonicalValue(semantic, "Artifact inspection")}`,
...semantic,
};
});
const allHypotheses = (
inventory: ArtifactInventoryResult,
evidenceId: string,
+13 -12
View File
@@ -211,8 +211,14 @@ const validateCompleteInventory = (inventory: InventorySet): void => {
);
for (const occurrence of inventory.occurrences)
validateOccurrence(occurrence, inventory, nodeIds, occurrenceIds);
const occurrencesById = new Map(
inventory.occurrences.map((occurrence) => [
occurrence.occurrence_id,
occurrence,
]),
);
for (const edge of inventory.edges)
validateEdge(edge, nodeIds, occurrenceIds);
validateEdge(edge, nodeIds, occurrencesById);
for (const contradiction of inventory.integrityContradictions) {
if (
!nodeIds.has(contradiction.parent_artifact_id) ||
@@ -273,22 +279,17 @@ const validateOccurrence = (
const validateEdge = (
edge: ArtifactInventoryResult["edges"][number],
nodeIds: ReadonlySet<string>,
occurrenceIds: ReadonlySet<string>,
occurrences: ReadonlyMap<string, ArtifactOccurrence>,
): void => {
const occurrence = occurrences.get(edge.occurrence_id);
if (
!nodeIds.has(edge.parent_artifact_id) ||
!nodeIds.has(edge.child_artifact_id) ||
!occurrenceIds.has(edge.occurrence_id)
occurrence?.artifact_id === null ||
occurrence === undefined ||
!nodeIds.has(occurrence.artifact_id)
)
throw new TypeError("Artifact edge references a missing graph member");
const semantic = {
parent_artifact_id: edge.parent_artifact_id,
child_artifact_id: edge.child_artifact_id,
relation: edge.relation,
occurrence_id: edge.occurrence_id,
logical_path: edge.logical_path,
};
if (edge.edge_id !== artifactEdgeId(semantic))
if (edge.edge_id !== artifactEdgeId(edge, occurrence))
throw new TypeError("Artifact edge ID does not match its identity");
};
+10
View File
@@ -0,0 +1,10 @@
import { digestCanonicalValue } from "./canonicalDigest.js";
/** Retain short exact string keys or commit their value in a reserved digest namespace. */
export const compactStringIdentityKey = (value: string): string => {
const prefix = "value-sha256:";
const digestKey = `${prefix}${digestCanonicalValue(value, "String identity")}`;
return value.length <= digestKey.length && !value.startsWith(prefix)
? value
: digestKey;
};
+18 -1
View File
@@ -35,7 +35,23 @@ const projectIssue = (
typeof part === "string" || typeof part === "number" ? [part] : [],
);
// Branch issue paths are relative to the union; branches often agree.
if (issue.code === "invalid_union")
if (issue.code === "invalid_union") {
// Unmatched discriminators and ambiguous unions have no branch issues.
// Keep their outer failure instead of flattening it into an empty list.
if (issue.errors.length === 0) {
const expected =
"options" in issue ? issue.options?.filter(isSafeExpected) : undefined;
return [
{
path,
reason:
valueAtPath(input, path) === undefined
? "missing_argument"
: "invalid_value",
...(expected === undefined ? {} : { expected }),
},
];
}
return uniqueIssues(
issue.errors.flatMap((branch) =>
branch.flatMap((branchIssue) =>
@@ -46,6 +62,7 @@ const projectIssue = (
),
),
);
}
if (issue.code === "invalid_key")
return issue.issues.flatMap((keyIssue) =>
projectIssue(
@@ -12,6 +12,7 @@ import type {
import {
boundedExpression,
collectContextBridgeMembers,
electronCalleeName,
electronStaticValue,
objectProperty,
} from "./electronStaticAnalysisValues.js";
@@ -19,7 +20,6 @@ import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { addLocatedFinding } from "./javascriptStaticAnalysisFindings.js";
import {
argumentNode,
calleeName,
range,
staticPath,
staticPathResolutionContext,
@@ -42,7 +42,7 @@ const inspectBrowserWindow = (
node: t.NewExpression,
context: JavaScriptFindingContext,
): void => {
const name = calleeName(node.callee);
const name = electronCalleeName(node.callee, context);
if (name !== "BrowserWindow" && !name.endsWith(".BrowserWindow")) return;
const options = argumentNode(node.arguments[0]);
const collected = collectWindowOptions(context.source, options);
@@ -165,7 +165,7 @@ const inspectContextBridge = (
node: t.CallExpression,
context: JavaScriptFindingContext,
): void => {
const name = calleeName(node.callee);
const name = electronCalleeName(node.callee, context);
const main =
name === "contextBridge.exposeInMainWorld" ||
name.endsWith(".contextBridge.exposeInMainWorld");
@@ -213,7 +213,7 @@ const inspectUtilityProcess = (
node: t.CallExpression,
context: JavaScriptFindingContext,
): void => {
const name = calleeName(node.callee);
const name = electronCalleeName(node.callee, context);
if (name !== "utilityProcess.fork" && !name.endsWith(".utilityProcess.fork"))
return;
const moduleNode = argumentNode(node.arguments[0]);
@@ -7,6 +7,7 @@ import type {
} from "./electronStaticAnalysisTypes.js";
import {
boundedExpression,
electronCalleeName,
electronStaticValue,
handlerKind,
} from "./electronStaticAnalysisValues.js";
@@ -36,7 +37,7 @@ const inspectIpcCall = (
node: t.CallExpression,
context: JavaScriptFindingContext,
): void => {
const name = calleeName(node.callee);
const name = electronCalleeName(node.callee, context);
const descriptor = ipcDescriptor(name);
if (descriptor === undefined) return;
const channelNode = argumentNode(node.arguments[0]);
@@ -6,7 +6,26 @@ import {
readExactJavaScriptLiteral,
semanticStaticPropertyName,
} from "./javascriptAstValues.js";
import { sourceSlice } from "./javascriptStaticAnalysisHelpers.js";
import { calleeName, sourceSlice } from "./javascriptStaticAnalysisHelpers.js";
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
/** Name a callee, spelling a root renamed from Electron as its export. */
export const electronCalleeName = (
callee: t.Node,
context: JavaScriptFindingContext,
): string => {
const name = calleeName(callee);
let root = callee;
while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) {
if (!t.isNode(root.object)) return name;
root = root.object;
}
if (!t.isIdentifier(root)) return name;
const exported = context.electronBindings?.get(root.start ?? -1);
return exported === undefined
? name
: `${exported}${name.slice(root.name.length)}`;
};
/** Preserve one literal value or the exact inert expression. */
export const electronStaticValue = (
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import {
createJavaScriptApplicationEdge,
createJavaScriptApplicationGraph,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import {
artifactEvidence,
completeCoverage,
fixtureNode,
} from "./javascriptApplicationGraph.fixture.js";
import { compareJavaScriptApplicationVersions } from "./javascriptApplicationVersionComparison.js";
const LEFT_SHA = "a".repeat(64);
const RIGHT_SHA = "b".repeat(64);
const digest = (value: number): string => value.toString(16).padStart(64, "0");
const buildGraph = (
artifactSha: string,
changed: number,
): JavaScriptApplicationGraph => {
const nodes = ["a", "b", "c", "d"].map((name, index) =>
fixtureNode(
"javascript-module",
{
strategy: "canonical-path",
stability: "artifact-version",
artifact_sha256: artifactSha,
path: `${name}.js`,
},
`${name}.js`,
{
structural_fingerprint_sha256: digest(index + 1),
structural_fingerprint_algorithm: "fixture",
source_sha256: digest(index === 1 || index === 3 ? changed : 0),
},
artifactEvidence(artifactSha, `${name}.js`),
),
);
const [a, b] = nodes;
if (a === undefined || b === undefined)
throw new Error("Missing fixture node");
return createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: [a.node_id],
nodes,
edges: [
createJavaScriptApplicationEdge({
source_node_id: a.node_id,
target_node_id: b.node_id,
relation: "imports",
properties: {},
evidence: artifactEvidence(artifactSha, "a.js"),
}),
],
coverage: completeCoverage,
limitations: [],
});
};
describe("application change graph", () => {
it("anchors each changed_from edge to its own right-hand observation", () => {
const left = buildGraph(LEFT_SHA, 1);
const right = buildGraph(RIGHT_SHA, 2);
const result = compareJavaScriptApplicationVersions({
left: {
evidenceId: `ev_${"1".repeat(64)}`,
rootArtifactSha256: LEFT_SHA,
graph: left,
},
right: {
evidenceId: `ev_${"2".repeat(64)}`,
rootArtifactSha256: RIGHT_SHA,
graph: right,
},
leftNativeEvidence: [],
rightNativeEvidence: [],
});
const changedFrom = result.graph.edges.filter(
({ relation }) => relation === "changed_from",
);
expect(changedFrom).toHaveLength(2);
for (const edge of changedFrom) {
const source = right.nodes.find(
({ node_id: id }) => id === edge.source_node_id,
);
const target = left.nodes.find(
({ node_id: id }) => id === edge.target_node_id,
);
expect(source?.observations[0]?.label).toBe(
target?.observations[0]?.label,
);
expect(edge.evidence.artifact).toEqual(
source?.observations[0]?.evidence.artifact,
);
expect(edge.evidence.location).toEqual(
source?.observations[0]?.evidence.location,
);
}
});
});
@@ -53,8 +53,14 @@ export const buildJavaScriptApplicationChangeGraph = (
({ source_node_id: source, target_node_id: target }) =>
retained.has(source) && retained.has(target),
);
const leftById = new Map(
input.left.nodes.map((node) => [node.node_id, node]),
);
const rightById = new Map(
input.right.nodes.map((node) => [node.node_id, node]),
);
const comparisonEdges = input.items.flatMap((item) =>
changedFromEdge(item, input, retained),
changedFromEdge(item, input, retained, leftById, rightById),
);
const candidateEdges = uniqueEdges([...sourceEdges, ...comparisonEdges]);
const rootNodeIds = preferredRoots.filter((nodeId) => retained.has(nodeId));
@@ -104,6 +110,8 @@ const changedFromEdge = (
item: ApplicationVersionComparisonItem,
input: ChangeGraphInput,
retained: ReadonlySet<string>,
leftById: ReadonlyMap<string, ApplicationNode>,
rightById: ReadonlyMap<string, ApplicationNode>,
): ApplicationEdge[] => {
const left = item.left_node_id;
const right = item.right_node_id;
@@ -117,7 +125,12 @@ const changedFromEdge = (
!retained.has(right)
)
return [];
const evidence = comparisonEvidence(item, input);
const evidence = comparisonEvidence(
item,
input,
leftById.get(left),
rightById.get(right),
);
return [
createJavaScriptApplicationEdge({
source_node_id: right,
@@ -138,13 +151,9 @@ const changedFromEdge = (
const comparisonEvidence = (
item: ApplicationVersionComparisonItem,
input: ChangeGraphInput,
left: ApplicationNode | undefined,
right: ApplicationNode | undefined,
): ApplicationGraphEvidence => {
const right = input.right.nodes.find(
({ node_id: id }) => id === item.right_node_id,
);
const left = input.left.nodes.find(
({ node_id: id }) => id === item.left_node_id,
);
const source =
right?.observations[0]?.evidence ?? left?.observations[0]?.evidence;
const complete =
@@ -109,7 +109,7 @@ type FixtureNodeArguments = [
evidence: ApplicationGraphEvidence,
];
const fixtureNode = (
export const fixtureNode = (
...[kind, identity, label, properties, evidence]: FixtureNodeArguments
): FixtureNode =>
createJavaScriptApplicationNode({
@@ -547,6 +547,21 @@ describe("JavaScript Application Graph: source maps and observations", () => {
/Edge identifier/u,
);
});
it("creates exactly the graph the public schema accepts", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
expect(JSON.stringify(graph)).toBe(
JSON.stringify(
javascriptApplicationGraphSchema.parse(structuredClone(graph)),
),
);
const { graph_id: _graphId, ...semantic } = structuredClone(graph);
firstOf(semantic.edges, "edge").edge_id = `jag_edge_${"f".repeat(64)}`;
expect(() => createJavaScriptApplicationGraph(semantic)).toThrow(
/Edge identifier/u,
);
});
});
describe("JavaScript Application Graph: duplicate and orphan rejection", () => {
@@ -304,8 +304,8 @@ const checkNode = (
type GraphRecord = z.infer<typeof javascriptApplicationGraphRecordSchema>;
const checkGraphInvariants = (
graph: GraphRecord,
const checkGraphContent = (
graph: JavaScriptApplicationGraphInput,
context: z.RefinementCtx,
): void => {
sortedUniqueIssue(
@@ -394,7 +394,13 @@ const checkGraphInvariants = (
context,
);
}
};
const checkGraphInvariants = (
graph: GraphRecord,
context: z.RefinementCtx,
): void => {
checkGraphContent(graph, context);
const { graph_id: identifier, ...semantic } = graph;
if (
identifier !==
@@ -411,6 +417,9 @@ const checkGraphInvariants = (
export const javascriptApplicationGraphSchema =
javascriptApplicationGraphRecordSchema.superRefine(checkGraphInvariants);
const javascriptApplicationGraphContentSchema =
javascriptApplicationGraphInputSchema.superRefine(checkGraphContent);
/** Fully validated JavaScript Application Graph. */
export type JavaScriptApplicationGraph = z.infer<
typeof javascriptApplicationGraphSchema
@@ -482,10 +491,11 @@ export const createJavaScriptApplicationGraph = (
},
limitations: uniqueSorted(parsed.limitations),
};
return javascriptApplicationGraphSchema.parse({
...semantic,
graph_id: `jag_${digestCanonicalValue(semantic, "JavaScript Application Graph")}`,
});
const content = javascriptApplicationGraphContentSchema.parse(semantic);
return {
...content,
graph_id: `jag_${digestCanonicalValue(content, "JavaScript Application Graph")}`,
};
};
const validatedImmutableApplicationGraphs = new WeakSet<object>();
@@ -76,6 +76,16 @@ export const semanticStaticPropertyKey = (
return !computed && t.isIdentifier(property) ? property.name : null;
};
/** Read exact consumed object-pattern keys, leaving dynamic keys unknown. */
export const semanticObjectPatternKeys = (
pattern: t.ObjectPattern,
): readonly string[] =>
pattern.properties.flatMap((property) => {
if (t.isRestElement(property)) return [];
const key = semanticStaticPropertyKey(property.key, property.computed);
return key === null ? [] : [key];
});
/**
* Display an exact JavaScript string as nonempty label text. Graph labels and
* artifact-local keys are nonempty, so the legal empty value is shown as `""`;
@@ -590,3 +590,24 @@ describe("property mutations through TypeScript satisfies aliases", () => {
).toEqual({ status: "literal", value: "TOKEN" });
});
});
describe("property mutation collection on minified bundles", () => {
it("records each write to one object without replaying earlier writes", () => {
const writes = Array.from(
{ length: 2000 },
(_, index) => `source.p${index} = ${index};`,
).join(" ");
const start = performance.now();
const value = resultValue(
`const source = { token: "TOKEN" }; ${writes} return [source.token, source.p1999];`,
);
expect(performance.now() - start).toBeLessThan(2000);
expect(value).toMatchObject({
status: "array",
items: [
{ value: { status: "literal", value: "TOKEN" } },
{ value: { status: "unknown" } },
],
});
}, 30000);
});
@@ -9,6 +9,163 @@ const resultValue = (body: string) =>
"result",
).returnSites[0]?.value;
describe("bounded member path propagation", () => {
it("bounds cyclic member paths with no observed container origin", () => {
const branches = Array.from(
{ length: 16 },
(_, index) => `if (flag === ${index}) node = node.m${index};`,
).join(" else ");
const start = performance.now();
const callable = onlyCallable(
analyzeJavaScriptSemantics(
`export function result(seed) { let node=seed; while(node) { ${branches} use(node.state); } return seed.keep; }`,
),
"result",
);
expect(callable.returnSites[0]?.value.status).toBe("unknown");
expect(performance.now() - start).toBeLessThan(2000);
}, 30000);
it("preserves Array prototype effects through an otherwise unknown alias", () => {
expect(
resultValue(
"const values=[1]; const prototype=Array.prototype; prototype[Symbol.iterator]=custom; for(const item of values) { mutate(item); } return values[0];",
)?.status,
).toBe("unknown");
});
it("bounds loops derived from a scalar member while preserving sibling facts", () => {
const branches = Array.from(
{ length: 16 },
(_, index) => `if (flag === ${index}) node = node.m${index};`,
).join(" else ");
const start = performance.now();
expect(
resultValue(
`const source={child:1,keep:{value:3}}; let node=source.child; while(node) { ${branches} use(node.state); } return source.keep.value;`,
),
).toEqual({ status: "literal", value: 3 });
expect(performance.now() - start).toBeLessThan(2000);
}, 30000);
it.each([
["child:external,", "child", "present"],
["", "missing", "unknown-coverage"],
])(
"retains slot presence below an unobserved container: %s",
(property, name, presence) => {
expect(
resultValue(
`const source={${property}keep:3}; const alias=source.${name}; alias.deep.value=2; return source;`,
),
).toMatchObject({
status: "object",
properties: expect.arrayContaining([
{
name,
presence,
value: {
status: "unknown",
reason: "This property may have been mutated.",
},
},
{
name: "keep",
presence: "present",
value: { status: "literal", value: 3 },
},
]),
});
},
);
it.each([
["use(node);", "m0.value", "unknown"],
["node.value = 2;", "m0.value", "unknown"],
["node.value = 2;", "mode", "literal"],
])(
"bounds a loop that reassigns one reference through many members: %s seed.%s",
(effect, read, status) => {
const branches = Array.from(
{ length: 9 },
(_, index) => `if (flag === ${index}) node = node.m${index};`,
).join(" else ");
const start = performance.now();
const value = resultValue(
`const seed = { mode: "initial", m0: { value: 1 } }; let node = seed; while (node) { ${branches} ${effect} } return seed.${read};`,
);
expect(performance.now() - start).toBeLessThan(2000);
expect(value?.status).toBe(status);
},
30000,
);
it.each([
["const alias = flag ? owner.child : owner; alias.value = 2;", "value"],
["const alias = flag ? owner : owner.child; alias.value = 2;", "value"],
["const alias = flag ? owner.child : owner; alias[key] = 2;", "value"],
[
"const alias = flag ? owner.child : owner; alias.child = 2;",
"child.value",
],
[
"let alias = owner; let i = 0; while (i++ < 1) { alias = flag ? alias.child : alias; alias.value = 2; }",
"value",
],
])(
"keeps a write that reaches a child through a longer path: %s",
(body, read) => {
expect(
resultValue(
`const shared = { value: 1, child: { value: 1 } }; const owner = { child: shared }; ${body} return shared.${read};`,
)?.status,
).toBe("unknown");
},
);
it.each([
"mutate(source.left, source.right);",
"const alias = flag ? source.left : source.right; mutate(alias);",
"const copy = flag ? [source.left] : [source.right]; mutate(copy);",
"const alias = flag ? source.left : source.right; alias.value = 2;",
])("keeps members outside the mutated paths: %s", (body) => {
expect(
resultValue(
`const source = { left: { value: 1 }, right: { value: 2 }, keep: { value: 3 } }; ${body} return source.keep.value;`,
),
).toEqual({ status: "literal", value: 3 });
});
});
describe("distinct observable mutation paths", () => {
it.each([
["alias.value = 2;", "left"],
["alias.value = 2;", "right"],
["mutate(alias);", "left"],
["mutate(alias);", "right"],
])(
"propagates both conditional paths to shared bindings: %s %s",
(effect, target) => {
expect(
resultValue(
`const left={value:1}; const right={value:2}; const source={left,right}; const alias=flag?source.left:source.right; ${effect} return ${target}.value;`,
)?.status,
).toBe("unknown");
},
);
it.each(["mutate(alias);", "alias.value = 2;"])(
"preserves sibling facts below a shared prefix: %s",
(effect) => {
expect(
resultValue(
`const shared={left:{value:1},right:{value:2},keep:{value:3}}; const source={nested:shared}; const alias=flag?source.nested.left:source.nested.right; ${effect} return shared.keep.value;`,
),
).toEqual({ status: "literal", value: 3 });
},
);
});
describe("reference lifetimes across calls and shallow copies", () => {
it("bounds dynamic destructuring across shared alias branches", () => {
const declarations = Array.from(
@@ -14,7 +14,10 @@ import {
immutableSemanticBindings,
immutableSemanticScopes,
} from "./javascriptSemanticProjection.js";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import {
semanticObjectPatternKeys,
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import type {
JavaScriptSemanticAnalysisState,
JavaScriptSemanticBindingState,
@@ -29,6 +32,7 @@ import {
semanticVariableScope,
} from "./javascriptSemanticState.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { collectSemanticMemberMutations } from "./javascriptSemanticMemberMutations.js";
import {
collectSemanticReturns,
@@ -282,6 +286,92 @@ const resolveGlobalAliasFact = (
return openGlobalFact(name);
};
const ELECTRON_MODULE = /^electron(?:\/(?:common|main|renderer|utility))?$/u;
/**
* Electron export paths for call and construction roots bound to Electron
* under another name, such as esbuild's `import { ipcMain as ipcMain2 }`.
* Keys are root identifier offsets; roots spelled as their export are omitted.
*/
export const classifyParsedJavaScriptElectronBindings = (
file: ParsedJavaScriptSource,
): ReadonlyMap<number, string> => {
const facts = new Map<number, string>();
const state = createState(file.program);
collectDefinitions(file.program, state);
const exportsByBinding = new Map<string, string | null>();
traverseJavaScriptAst(file.program, {
enter: (node) => {
if (
!t.isCallExpression(node) &&
!t.isOptionalCallExpression(node) &&
!t.isNewExpression(node)
)
return;
const root = calleeRoot(node.callee);
if (root === undefined) return;
const binding = resolveSemanticBindingState(state, root, root.name);
if (binding === undefined) return;
let exported = exportsByBinding.get(binding.bindingId);
if (exported === undefined) {
exported = electronExport(binding, state);
exportsByBinding.set(binding.bindingId, exported);
}
if (exported !== null && exported !== root.name)
facts.set(root.start ?? -1, exported);
},
});
return facts;
};
const calleeRoot = (node: t.Node): t.Identifier | undefined => {
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
if (!t.isNode(node.object)) return undefined;
node = node.object;
}
return t.isIdentifier(node) ? node : undefined;
};
// Read import and require origins directly; general value evaluation is
// unnecessary here and costly across large vendor bundles.
const electronExport = (
binding: JavaScriptSemanticBindingState,
state: JavaScriptSemanticAnalysisState,
): string | null => {
const origin = bindingOrigin(binding, state);
return origin !== undefined &&
ELECTRON_MODULE.test(origin.specifier) &&
origin.importedPath.length > 0
? origin.importedPath.join(".")
: null;
};
const bindingOrigin = (
binding: JavaScriptSemanticBindingState,
state: JavaScriptSemanticAnalysisState,
): JavaScriptModuleOrigin | undefined => {
if (binding.directOrigins.length > 0)
return binding.directOrigins.length === 1
? binding.directOrigins[0]
: undefined;
const [initializer] = binding.initializers;
// A var/let declaration permits writes without proving one occurred.
// Require one unconditional initializer and no actual binding writes.
if (
initializer === undefined ||
binding.initializers.length !== 1 ||
binding.definitions.some(({ kind }) => kind === "assignment") ||
state.conditionalInitializers.has(initializer.node)
)
return undefined;
const origin = semanticRequireOrigin(initializer.node, state);
const projection = initializer.projection;
return origin === undefined ||
!projection.every((key): key is string => typeof key === "string")
? undefined
: { ...origin, importedPath: [...origin.importedPath, ...projection] };
};
const createState = (program: t.Program): JavaScriptSemanticAnalysisState => {
const root: JavaScriptSemanticScopeState = {
scopeId: semanticScopeId("program", program),
@@ -565,9 +655,21 @@ const bindAssignment = (
else if (t.isForOfStatement(node) || t.isForInStatement(node))
for (const pattern of t.isVariableDeclaration(node.left)
? node.left.declarations.map(({ id }) => id)
: [node.left])
: [node.left]) {
for (const identifier of assignedPatternIdentifiers(pattern))
addAssignment(identifier, node, scope, state);
if (t.isForOfStatement(node))
// Keep the loop value unknown, but preserve references yielded into
// each bound slot so writes/escapes can reach their iterable origins.
bindPattern({
pattern,
initializer: node,
scope,
state,
mutable: true,
referenceOnly: true,
});
}
};
const assignedPatternIdentifiers = (
@@ -780,7 +882,11 @@ const bindPattern = (input: BindPatternInput): void => {
}
if (t.isIdentifier(pattern)) {
if (referenceOnly) {
const binding = scope.bindings.get(pattern.name);
const binding = resolveSemanticBindingFromScope(
scope,
pattern.name,
state,
);
if (binding !== undefined && initializer !== null)
binding.referenceInitializers.push({
node: initializer,
@@ -864,14 +970,7 @@ const bindPattern = (input: BindPatternInput): void => {
referenceOnly: true,
copyKind: "object-rest",
copyProjectionOffset: projection.length,
copyExcludedKeys: pattern.properties.flatMap((property) => {
if (t.isRestElement(property)) return [];
const key = semanticStaticPropertyKey(
property.key,
property.computed,
);
return key === null ? [] : [key];
}),
copyExcludedKeys: semanticObjectPatternKeys(pattern),
});
} else {
const name = semanticStaticPropertyKey(property.key, property.computed);
@@ -0,0 +1,53 @@
import * as t from "@babel/types";
import { childNodes } from "./javascriptSemanticTraversal.js";
/** One direct return or yield, excluding every nested callable. */
export interface SemanticCallableResultExpression {
readonly node: t.Node | null;
readonly site: t.Node;
readonly kind: "return" | "yield";
readonly delegated: boolean;
}
/** Collect direct result syntax without executing or evaluating a callable. */
export const semanticCallableResultExpressions = (
callable: t.Node,
): readonly SemanticCallableResultExpression[] => {
if (
t.isArrowFunctionExpression(callable) &&
!t.isBlockStatement(callable.body)
)
return [
{
node: callable.body,
site: callable.body,
kind: "return",
delegated: false,
},
];
if (!t.isFunction(callable)) return [];
const output: SemanticCallableResultExpression[] = [];
const pending = childNodes(callable.body).reverse();
while (pending.length > 0) {
const node = pending.pop();
if (node === undefined || t.isFunction(node) || t.isClass(node)) continue;
if (t.isReturnStatement(node)) {
output.push({
node: node.argument ?? null,
site: node,
kind: "return",
delegated: false,
});
}
if (t.isYieldExpression(node))
output.push({
node: node.argument ?? null,
site: node,
kind: "yield",
delegated: node.delegate,
});
for (const child of childNodes(node).reverse()) pending.push(child);
}
return output;
};
@@ -56,6 +56,9 @@ const evidenceContextId = (context: ApplicationGraphEvidenceContext): string =>
/** Graph-scoped owner for canonical provenance shared by semantic facts. */
export class JavaScriptSemanticEvidenceContextRegistry {
readonly #contexts = new Map<string, JavaScriptSemanticEvidenceContext>();
// Facts share a few contexts, so key them by canonical text and hash each
// distinct context once instead of on every fact.
readonly #idsByCanonicalContext = new Map<string, string>();
/** Intern normalized non-location provenance at fact construction. */
intern(
@@ -63,18 +66,21 @@ export class JavaScriptSemanticEvidenceContextRegistry {
): JavaScriptSemanticEvidenceReference {
const normalized = normalizeEvidence(evidence);
const { location, ...context } = normalized;
const canonicalContext = canonicalJson(
context,
"JavaScript semantic graph",
);
const internedId = this.#idsByCanonicalContext.get(canonicalContext);
if (internedId !== undefined) return { context_id: internedId, location };
const contextId = evidenceContextId(context);
const row = { ...context, context_id: contextId };
const existing = this.#contexts.get(contextId);
if (
existing !== undefined &&
canonicalJson(existing, "JavaScript semantic graph") !==
canonicalJson(row, "JavaScript semantic graph")
)
// This canonical context is new, so a row already stored under its
// digest holds different provenance.
if (this.#contexts.has(contextId))
throw new TypeError(
"JavaScript semantic evidence context digest collision",
);
this.#contexts.set(contextId, row);
this.#contexts.set(contextId, { ...context, context_id: contextId });
this.#idsByCanonicalContext.set(canonicalContext, contextId);
return { context_id: contextId, location };
}
@@ -101,6 +107,7 @@ export class JavaScriptSemanticEvidenceContextRegistry {
/** Release interned contexts after the owning graph is finalized. */
clear(): void {
this.#contexts.clear();
this.#idsByCanonicalContext.clear();
}
}
@@ -120,10 +127,6 @@ export const createJavaScriptSemanticGraphNode = (
...parsed,
application_node_ids: uniqueSorted(parsed.application_node_ids),
evidence: evidenceContexts.intern(parsed.evidence),
identifier_strategy: {
strategy: "semantic-content-sha256" as const,
stability: "artifact-version" as const,
},
};
return javaScriptSemanticNodeSchema.parse({
...semantic,
@@ -140,10 +143,6 @@ export const createJavaScriptSemanticGraphRelation = (
const semantic = {
...parsed,
evidence: evidenceContexts.intern(parsed.evidence),
identifier_strategy: {
strategy: "semantic-content-sha256" as const,
stability: "relationship-exact" as const,
},
};
return javaScriptSemanticRelationSchema.parse({
...semantic,
@@ -1,6 +1,7 @@
import { expect, it } from "vitest";
import { z } from "zod";
import { digestCanonicalValue } from "../canonicalDigest.js";
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
import {
JAVASCRIPT_SEMANTIC_NODE_KINDS,
@@ -615,3 +616,42 @@ it.each(invalidGraphCases)(
expect(issues(() => complete(steps))).toEqual(expected);
},
);
it("interns each distinct evidence context once under its content digest", () => {
const registry = new JavaScriptSemanticEvidenceContextRegistry();
const elsewhere: ApplicationGraphEvidence = {
...evidence(),
location: {
available: true,
value: {
kind: "source-range",
source: "other.js",
start: { line: 7, column: 2 },
end: { line: 7, column: 9 },
},
},
};
const first = registry.intern(evidence());
const repeated = registry.intern(elsewhere);
const reordered = registry.intern({
...evidence("inferred"),
limitations: [
"Static reachability does not prove runtime execution.",
"Static reachability does not prove runtime execution.",
],
});
const inferred = registry.intern(evidence("inferred"));
const { location: _location, ...context } = evidence();
expect(repeated.context_id).toBe(first.context_id);
expect(repeated.location).toEqual(elsewhere.location);
expect(reordered.context_id).toBe(inferred.context_id);
expect(inferred.context_id).not.toBe(first.context_id);
expect(first.context_id).toBe(
`jsrg_evidence_${digestCanonicalValue(context, "test")}`,
);
expect(registry.contexts.map(({ context_id }) => context_id)).toEqual(
[first.context_id, inferred.context_id].toSorted(),
);
expect(registry.resolve(repeated)).toEqual(elsewhere);
});
@@ -233,11 +233,9 @@ export const javaScriptSemanticNodeInputSchema = z.strictObject({
export const javaScriptSemanticNodeSchema =
javaScriptSemanticNodeInputSchema.extend({
evidence: javaScriptSemanticEvidenceReferenceSchema,
node_id: semanticNodeIdSchema,
identifier_strategy: z.strictObject({
strategy: z.literal("semantic-content-sha256"),
stability: z.literal("artifact-version"),
}),
node_id: semanticNodeIdSchema.describe(
"SHA-256 of the node kind and identity; stable for one artifact version.",
),
});
/** One directed semantic relationship before its ID is derived. */
@@ -254,11 +252,9 @@ export const javaScriptSemanticRelationInputSchema = z.strictObject({
export const javaScriptSemanticRelationSchema =
javaScriptSemanticRelationInputSchema.extend({
evidence: javaScriptSemanticEvidenceReferenceSchema,
relation_id: semanticRelationIdSchema,
identifier_strategy: z.strictObject({
strategy: z.literal("semantic-content-sha256"),
stability: z.literal("relationship-exact"),
}),
relation_id: semanticRelationIdSchema.describe(
"SHA-256 of the exact relation content, including its evidence reference.",
),
});
/** Reasons semantic analysis can leave an explicit frontier. */
@@ -1,15 +1,23 @@
import * as t from "@babel/types";
import { semanticStaticPropertyKey } from "./javascriptAstValues.js";
import { semanticArrayIndex } from "./javascriptSemanticPropertyPaths.js";
import {
semanticObjectPatternKeys,
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import {
semanticArrayIndex,
type JavaScriptSemanticPropertyPath,
} from "./javascriptSemanticPropertyPaths.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
interface IterationSourceValue {
readonly node: t.Node;
readonly projection: readonly (string | number | null)[];
readonly projection: JavaScriptSemanticPropertyPath;
}
/** An implicit iterator receiver, with guards for destructuring defaults. */
/** An iterator receiver or property reference store, with default guards. */
export interface SemanticIterationSource extends IterationSourceValue {
readonly kind: "iteration" | "reference-store";
readonly mutation: t.Node;
readonly fallbackSources?: readonly IterationSourceValue[];
readonly requiredSources?: readonly IterationSourceValue[];
@@ -30,8 +38,10 @@ const add = (
source: IterationSourceValue,
mutation: t.Node,
guards: SourceGuards,
kind: SemanticIterationSource["kind"] = "iteration",
): void => {
sources.push({
kind,
node: source.node,
projection: source.projection,
mutation,
@@ -66,6 +76,27 @@ const visit = (
guards: SourceGuards = {},
): void => {
const { sources, mutation } = context;
if (t.isMemberExpression(pattern)) {
// Property stores have no lexical alias binding. Preserve the selected
// reference's escape rather than claiming later writes cannot reach it.
if (source !== undefined)
add(
sources,
source.restStartIndex === undefined
? source
: {
node: source.node,
projection: [
...source.projection,
{ excludedKeys: [], startIndex: source.restStartIndex },
],
},
mutation,
guards,
"reference-store",
);
return;
}
if (t.isTSParameterProperty(pattern)) {
visit(context, pattern.parameter, source, guards);
return;
@@ -94,8 +125,29 @@ const visit = (
}
if (t.isObjectPattern(pattern)) {
for (const property of pattern.properties) {
// Object rest creates a fresh object and has no iterable binding pattern.
if (t.isRestElement(property)) continue;
if (t.isRestElement(property)) {
// A rest copy owns its scalar slots; only selected child references
// escape when that fresh copy is stored through a member target.
visit(
context,
property.argument,
source === undefined
? undefined
: {
node: source.node,
projection: [
...source.projection,
{
excludedKeys: [
...new Set(semanticObjectPatternKeys(pattern)),
].sort(compareUnicodeCodePoints),
},
],
},
guards,
);
continue;
}
visit(
context,
property.value,
@@ -134,7 +186,7 @@ const visit = (
visit(context, pattern.argument, undefined, guards);
};
/** Describe implicit iteration sources without deciding their runtime values. */
/** Describe iterator receivers and property reference stores without evaluation. */
export const semanticIterationSources = (
node: t.Node,
parent: t.Node | null,
@@ -143,7 +195,10 @@ export const semanticIterationSources = (
const context = { sources, mutation: node };
if (t.isVariableDeclarator(node) && node.init != null)
visit(context, node.id, { node: node.init, projection: [] });
else if (t.isAssignmentExpression(node) && node.operator === "=")
else if (
t.isAssignmentExpression(node) &&
["=", "||=", "&&=", "??="].includes(node.operator)
)
visit(context, node.left, { node: node.right, projection: [] });
else if (t.isForOfStatement(node)) {
add(sources, { node: node.right, projection: [] }, node, {});
@@ -15,9 +15,12 @@ import {
semanticSlotAtPath,
} from "./javascriptSemanticSlots.js";
import { semanticIterationSources } from "./javascriptSemanticIterationSources.js";
import { semanticCallableResultExpressions } from "./javascriptSemanticCallableResults.js";
import { createSemanticReturnedReferences } from "./javascriptSemanticReturnedReferences.js";
import { semanticMutationInitializers } from "./javascriptSemanticMutationInitializers.js";
import {
semanticArrayIndex,
SemanticPropertyPathCoverage,
semanticPropertyPathKeyMatches,
type JavaScriptSemanticPropertyPath,
} from "./javascriptSemanticPropertyPaths.js";
@@ -42,8 +45,11 @@ export const collectSemanticMemberMutations = (
if (parent !== null) parents.set(node, parent);
},
});
const normalizePath = observableMutationPaths(state);
const returnedReferences = createSemanticReturnedReferences(state);
const recordedEffects = new Set<string>();
const selections = new Map<string, readonly string[]>();
const coveringPaths = new Map<string, SemanticPropertyPathCoverage>();
let arrayIterationUnknown = false;
const pendingReferences: {
readonly initializer: JavaScriptSemanticBindingState["referenceInitializers"][number];
@@ -93,8 +99,10 @@ export const collectSemanticMemberMutations = (
originAt: t.Node | undefined = mutation,
): void => {
const pending = [{ node, path, bindings, originAt }];
while (pending.length > 0) {
const current = pending.pop();
// Visit shallower alias traversals first so their exact prefixes suppress
// longer loop paths before those paths enumerate every assignment order.
for (let cursor = 0; cursor < pending.length; cursor++) {
const current = pending[cursor];
if (current === undefined) break;
const expression = unwrapJavaScriptExpression(current.node).node;
if (t.isIdentifier(expression)) {
@@ -126,10 +134,13 @@ export const collectSemanticMemberMutations = (
if (current.bindings.has(lifetime)) continue;
// Union compatible copied-slot selections at each binding. Carrying every
// combination of exclusions through branch diamonds is exponential.
const selectorIndex = current.path.findIndex(
// Preserve paths that can change observed slots or Array prototype
// effects; canonicalize suffixes that cannot distinguish lattice facts.
let path = normalizePath(binding.bindingId, current.path, effect);
if (path === null) continue;
const selectorIndex = path.findIndex(
(key) => key !== null && typeof key === "object",
);
let path = current.path;
const selector = path[selectorIndex];
if (selector !== null && typeof selector === "object") {
const selectionIdentity = JSON.stringify([
@@ -157,6 +168,25 @@ export const collectSemanticMemberMutations = (
index === selectorIndex ? { ...selector, excludedKeys } : key,
);
}
// Keep an antichain of exact paths. Widening distinct member keys would
// also invalidate unrelated siblings that never reach this effect.
const pathState = JSON.stringify([
binding.bindingId,
effect,
// Short writes stop at owned literal slots, whereas longer writes
// reach shared children. Only equal-depth writes cover one another.
effect === "write" ? path.length : null,
mutation?.start,
mutation?.end,
current.originAt?.start,
current.originAt?.end,
]);
let covering = coveringPaths.get(pathState);
if (covering === undefined) {
covering = new SemanticPropertyPathCoverage();
coveringPaths.set(pathState, covering);
}
if (!covering.retain(path)) continue;
const identity = JSON.stringify([
binding.bindingId,
effect,
@@ -167,8 +197,11 @@ export const collectSemanticMemberMutations = (
current.originAt?.end,
]);
if (recordedEffects.has(identity)) continue;
// A recorded write invalidates the binding to a non-primitive value, so
// only its first write can target a primitive. Re-evaluating it would
// replay every earlier write and make repeated writes superlinear.
const value =
effect === "write"
effect === "write" && binding.mutatedPaths.length === 0
? evaluateSemanticBinding(binding, state)
: undefined;
const primitiveWrite =
@@ -297,7 +330,7 @@ export const collectSemanticMemberMutations = (
bindings: new Set(),
effect: "escape",
originAt: source.mutation,
iterationOnly: true,
iterationOnly: source.kind === "iteration",
});
if (t.isAssignmentExpression(node)) markTarget(node.left, node);
else if (t.isUpdateExpression(node)) markTarget(node.argument, node);
@@ -310,6 +343,8 @@ export const collectSemanticMemberMutations = (
t.isOptionalCallExpression(node) ||
t.isNewExpression(node)
) {
for (const source of returnedReferences(node.callee))
markEscaped(source.node, node, source.projection);
for (const argument of node.arguments)
if (t.isSpreadElement(argument))
deferIterable({
@@ -342,6 +377,19 @@ export const collectSemanticMemberMutations = (
const { initializer } = reference;
if (referenceSourcesInactive(initializer, state))
pendingReferences.push(reference);
else if (t.isForOfStatement(initializer.node))
deferIterable({
node: initializer.node.right,
projection: [],
path: [null, ...reference.path],
fallbackPath: [],
bindings: reference.bindings,
effect: reference.effect,
originAt: initializer.node,
...(reference.mutation === undefined
? {}
: { mutation: reference.mutation }),
});
else if (
initializer.copyKind === "array-rest" &&
initializer.copyProjectionOffset !== undefined
@@ -512,6 +560,11 @@ const referencedValues = (
path: PropertyPath,
effect: ValueEffect,
): readonly ReferencedValue[] => {
if (effect === "escape" && t.isFunction(node))
return semanticCallableResultExpressions(node).flatMap(
({ node, delegated }) =>
node === null ? [] : [{ node, path: delegated ? [null] : [] }],
);
// An initializer owns its slots; only deeper writes can affect shared children.
if (t.isObjectExpression(node) || t.isArrayExpression(node)) {
if (effect === "write" && path.length < 2) return [];
@@ -544,6 +597,241 @@ const referencedValues = (
return [];
};
type MutationObservableOrigin =
| t.ObjectExpression
| t.ArrayExpression
| "ambient"
| "array"
| "array-prototype"
| "opaque";
interface MutationObserverNode {
readonly origins: Set<MutationObservableOrigin>;
readonly sources: Set<MutationObserverNode>;
readonly dependents: Set<MutationObserverNode>;
readonly projections: Map<string, MutationObserverNode>;
readonly read?: {
readonly source: MutationObserverNode;
readonly key: PropertyPath[number];
};
}
const observableMutationPaths = (
state: JavaScriptSemanticAnalysisState,
): ((
bindingId: string,
path: PropertyPath,
effect: ValueEffect,
) => PropertyPath | null) => {
const bindingNodes = new Map<string, MutationObserverNode>();
const expressions = new WeakMap<t.Node, MutationObserverNode>();
const pendingExpressions: {
readonly expression: t.Node;
readonly observer: MutationObserverNode;
}[] = [];
const pending: MutationObserverNode[] = [];
const queued = new Set<MutationObserverNode>();
const schedule = (node: MutationObserverNode): void => {
if (queued.has(node)) return;
queued.add(node);
pending.push(node);
};
const create = (
read?: MutationObserverNode["read"],
): MutationObserverNode => ({
origins: new Set(),
sources: new Set(),
dependents: new Set(),
projections: new Map(),
...(read === undefined ? {} : { read }),
});
const link = (
source: MutationObserverNode,
target: MutationObserverNode,
): void => {
if (target.sources.has(source)) return;
target.sources.add(source);
source.dependents.add(target);
schedule(target);
};
const expressionNode = (node: t.Node): MutationObserverNode => {
const expression = unwrapJavaScriptExpression(node).node;
const existing = expressions.get(expression);
if (existing !== undefined) return existing;
const observer = create();
expressions.set(expression, observer);
pendingExpressions.push({ expression, observer });
return observer;
};
const project = (
source: MutationObserverNode,
path: PropertyPath,
): MutationObserverNode => {
let observer = source;
for (const key of path) {
const identity = JSON.stringify(
key === null || typeof key === "object" ? key : String(key),
);
let selected = observer.projections.get(identity);
if (selected === undefined) {
selected = create({ source: observer, key });
observer.projections.set(identity, selected);
observer.dependents.add(selected);
schedule(selected);
}
observer = selected;
}
return observer;
};
for (const binding of state.bindingsById.values())
bindingNodes.set(binding.bindingId, create());
for (const binding of state.bindingsById.values()) {
const observer = bindingNodes.get(binding.bindingId);
if (observer === undefined) continue;
for (const initializer of binding.initializers)
link(
project(expressionNode(initializer.node), initializer.projection),
observer,
);
// Preserve exact paths where copies, defaults or iteration need their
// reference-specific projections; an opaque origin prevents pruning.
if (binding.referenceInitializers.length > 0)
observer.origins.add("opaque");
for (const initializer of binding.referenceInitializers) {
for (const source of [
initializer,
...(initializer.requiredSources ?? []),
...(initializer.fallbackSources ?? []),
])
link(expressionNode(source.node), observer);
}
}
const settle = (): void => {
while (pendingExpressions.length > 0 || pending.length > 0) {
while (pendingExpressions.length > 0) {
const selected = pendingExpressions.pop();
if (selected === undefined) break;
const { expression, observer } = selected;
if (t.isObjectExpression(expression) || t.isArrayExpression(expression))
observer.origins.add(expression);
else if (t.isIdentifier(expression)) {
const binding = resolveSemanticBindingState(
state,
expression,
expression.name,
);
if (binding !== undefined) {
const origin = bindingNodes.get(binding.bindingId);
if (origin !== undefined) link(origin, observer);
} else if (expression.name === "Array") observer.origins.add("array");
else if (
["globalThis", "global", "window", "self"].includes(expression.name)
)
observer.origins.add("ambient");
} else if (
t.isMemberExpression(expression) ||
t.isOptionalMemberExpression(expression)
)
link(
project(expressionNode(expression.object), [
semanticStaticPropertyKey(
expression.property,
expression.computed,
),
]),
observer,
);
else
for (const reference of referencedValues(expression, [], "escape"))
link(
project(expressionNode(reference.node), reference.path),
observer,
);
schedule(observer);
}
const observer = pending.pop();
if (observer === undefined) continue;
queued.delete(observer);
let changed = false;
const add = (origin: MutationObservableOrigin): void => {
if (observer.origins.has(origin)) return;
observer.origins.add(origin);
changed = true;
};
for (const source of observer.sources)
for (const origin of source.origins) add(origin);
if (observer.read !== undefined) {
const { source, key } = observer.read;
if (key === null || typeof key === "object") {
// Dynamic keys and copied-slot masks retain their original paths.
// Enumerating their exclusion combinations would recreate the growth
// that the mutation collector's selection union already prevents.
if (source.origins.size > 0) add("opaque");
} else
for (const origin of source.origins) {
if (typeof origin === "string") {
if (origin === "array-prototype" || origin === "opaque")
add(origin);
else if (
origin === "ambient" &&
semanticPropertyPathKeyMatches(key, "Array")
)
add("array");
else if (
origin === "array" &&
semanticPropertyPathKeyMatches(key, "prototype")
)
add("array-prototype");
} else {
for (const reference of referencedValues(
origin,
[key],
"escape",
)) {
link(
project(expressionNode(reference.node), reference.path),
observer,
);
if (reference.iterableFallbackPath !== undefined)
link(
project(
expressionNode(reference.node),
reference.iterableFallbackPath,
),
observer,
);
}
}
}
}
if (changed)
for (const dependent of observer.dependents) schedule(dependent);
}
};
settle();
return (bindingId, path, effect) => {
let observer = bindingNodes.get(bindingId);
if (observer === undefined) return path;
if (path.some((key) => key !== null && typeof key === "object"))
return path;
if (effect === "escape") {
observer = project(observer, path);
settle();
return observer.origins.size === 0 ? null : path;
}
if (observer.origins.size === 0) return path.length === 0 ? path : [null];
for (let offset = 0; offset < path.length; offset++) {
const key = path[offset];
if (key === undefined) break;
observer = project(observer, [key]);
settle();
if (observer.origins.size === 0 && offset + 1 < path.length)
return [...path.slice(0, offset + 1), null];
}
return path;
};
};
const objectReferencedValues = (
node: t.ObjectExpression,
path: PropertyPath,
@@ -577,11 +865,11 @@ const objectReferencedValues = (
}
const name = semanticStaticPropertyKey(property.key, property.computed);
if (name !== null && overwritten.has(name)) continue;
if (
t.isObjectProperty(property) &&
(name === null || semanticPropertyPathKeyMatches(key ?? null, name))
)
references.push({ node: property.value, path: remaining });
if (name === null || semanticPropertyPathKeyMatches(key ?? null, name))
references.push({
node: t.isObjectProperty(property) ? property.value : property,
path: remaining,
});
// A prototype setter does not replace an own property from a spread.
if (
name !== null &&
@@ -33,49 +33,89 @@ export const invalidateSemanticEscapedPath = (
: { ...value, items: value.items.map(invalidateChild) };
};
/** Invalidate only slots that an explicit mutation can affect. */
export const invalidateSemanticMutationPath = (
/**
* Invalidate only slots that explicit mutations can affect, as if applying each
* path in order. Paths are grouped per slot so that many writes to one object
* cost one pass over its slots rather than one pass per write.
*/
export const invalidateSemanticMutationPaths = (
value: JavaScriptSemanticValue,
path: JavaScriptSemanticPropertyPath,
paths: readonly JavaScriptSemanticPropertyPath[],
): JavaScriptSemanticValue => {
const [key, ...remaining] = path;
const unknown: JavaScriptSemanticValue = {
status: "unknown",
reason: "This property may have been mutated.",
if (paths.length === 0) return value;
// An unknown key or a replaced value leaves nothing that a later path can
// restore, wherever it occurs in the sequence.
if (
(value.status !== "object" && value.status !== "array") ||
paths.some(([key]) => key === undefined || key === null)
)
return {
status: "unknown",
reason: "This property may have been mutated.",
};
// Writing an array length discards every item known before it.
const reset =
value.status === "array"
? paths.findLastIndex(([key]) => key === "length")
: -1;
const base: typeof value =
reset < 0
? value
: { status: "array", items: [], unknownItems: true, omittedItems: null };
const slots = base.status === "object" ? base.properties : base.items;
const slotsByName = new Map<string, number[]>();
slots.forEach((property, index) => {
const indexes = slotsByName.get(property.name) ?? [];
indexes.push(index);
slotsByName.set(property.name, indexes);
});
const slotPaths = new Map<number, JavaScriptSemanticPropertyPath[]>();
const replacedSlots = new Set<number>();
const select = (index: number, remaining: JavaScriptSemanticPropertyPath) => {
const selected = slotPaths.get(index) ?? [];
selected.push(remaining);
slotPaths.set(index, selected);
if (remaining.length === 0) replacedSlots.add(index);
};
if (key === undefined || key === null) return unknown;
if (value.status === "object" || value.status === "array") {
if (value.status === "array" && key === "length")
return {
status: "array",
items: [],
unknownItems: true,
omittedItems: null,
};
const slots = value.status === "object" ? value.properties : value.items;
const observed = slots.some((property) =>
semanticPropertyPathKeyMatches(key, property.name),
);
const properties = slots.map((property) =>
semanticPropertyPathKeyMatches(key, property.name)
? {
// An added slot is already unknown, so later paths that select it are inert.
const added = new Set<string>();
for (const [key, ...remaining] of paths.slice(reset + 1)) {
if (key === undefined || key === null) continue;
if (typeof key === "object") {
slots.forEach((property, index) => {
if (semanticPropertyPathKeyMatches(key, property.name))
select(index, remaining);
});
continue;
}
const indexes = slotsByName.get(String(key));
if (indexes === undefined) added.add(String(key));
else for (const index of indexes) select(index, remaining);
}
const properties: JavaScriptSemanticProperty[] = slots.map(
(property, index) => {
const selected = slotPaths.get(index);
return selected === undefined
? property
: {
...property,
...(remaining.length === 0
...(replacedSlots.has(index)
? { presence: "unknown-coverage" as const }
: {}),
value: invalidateSemanticMutationPath(property.value, remaining),
}
: property,
);
if (!observed && typeof key !== "object")
properties.push({
name: String(key),
value: unknown,
presence: "unknown-coverage",
});
return value.status === "object"
? { ...value, properties }
: { ...value, items: properties };
}
return unknown;
value: invalidateSemanticMutationPaths(property.value, selected),
};
},
);
for (const name of added)
properties.push({
name,
value: {
status: "unknown",
reason: "This property may have been mutated.",
},
presence: "unknown-coverage",
});
return base.status === "object"
? { ...base, properties }
: { ...base, items: properties };
};
@@ -35,3 +35,89 @@ export const semanticPropertyPathKeyMatches = (
const index = semanticArrayIndex(name);
return index !== null && index >= key.startIndex;
};
interface PropertyPathCoverageNode {
terminal: boolean;
readonly exact: Map<string, PropertyPathCoverageNode>;
readonly selectors: Map<
string,
{
readonly key: JavaScriptSemanticPropertyPath[number];
readonly node: PropertyPathCoverageNode;
}
>;
}
const coverageNode = (): PropertyPathCoverageNode => ({
terminal: false,
exact: new Map(),
selectors: new Map(),
});
/** Index exact effect prefixes without widening distinct member paths. */
export class SemanticPropertyPathCoverage {
readonly #root = coverageNode();
/** Retain a path only when no previously retained prefix covers it. */
retain(path: JavaScriptSemanticPropertyPath): boolean {
const pending = [{ node: this.#root, offset: 0 }];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined) break;
if (current.node.terminal) return false;
const key = path[current.offset];
if (key === undefined) continue;
if (key !== null && typeof key !== "object") {
const exact = current.node.exact.get(String(key));
if (exact !== undefined)
pending.push({ node: exact, offset: current.offset + 1 });
}
for (const selected of current.node.selectors.values()) {
if (keyCovers(selected.key, key))
pending.push({ node: selected.node, offset: current.offset + 1 });
}
}
let node = this.#root;
for (const key of path) {
if (key !== null && typeof key !== "object") {
const name = String(key);
let child = node.exact.get(name);
if (child === undefined) {
child = coverageNode();
node.exact.set(name, child);
}
node = child;
} else {
const identity = JSON.stringify(key);
let selected = node.selectors.get(identity);
if (selected === undefined) {
selected = { key, node: coverageNode() };
node.selectors.set(identity, selected);
}
node = selected.node;
}
}
node.terminal = true;
node.exact.clear();
node.selectors.clear();
return true;
}
}
const keyCovers = (
covering: JavaScriptSemanticPropertyPath[number],
key: JavaScriptSemanticPropertyPath[number],
): boolean => {
if (covering === null) return true;
if (key === null) return false;
if (typeof key !== "object")
return typeof covering === "object"
? semanticPropertyPathKeyMatches(covering, String(key))
: String(covering) === String(key);
return (
typeof covering === "object" &&
covering.excludedKeys.every((name) => key.excludedKeys.includes(name)) &&
(covering.startIndex === undefined ||
(key.startIndex !== undefined && covering.startIndex <= key.startIndex))
);
};
@@ -0,0 +1,213 @@
import * as t from "@babel/types";
import {
semanticStaticPropertyKey,
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
import {
resolveLocalCallables,
type LocalCallableResolution,
} from "./javascriptSemanticCallResolution.js";
import { semanticCallableResultExpressions } from "./javascriptSemanticCallableResults.js";
import {
semanticArrayIndex,
type JavaScriptSemanticPropertyPath,
} from "./javascriptSemanticPropertyPaths.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
} from "./javascriptSemanticState.js";
/** A reference potentially handed to a caller or generator consumer. */
export interface SemanticReturnedReference {
readonly node: t.Node;
readonly projection: JavaScriptSemanticPropertyPath;
}
interface Candidate {
readonly node: t.Node;
readonly path: readonly (string | number | null)[];
readonly bindings: ReadonlySet<string>;
}
/** Resolve local result references conservatively, without claiming call execution. */
export const createSemanticReturnedReferences = (
state: JavaScriptSemanticAnalysisState,
): ((callee: t.Node) => readonly SemanticReturnedReference[]) => {
const callableById = new Map(
state.callables.map((callable) => [callable.callableId, callable]),
);
const bindingCache = new Map<string, LocalCallableResolution>();
const results = new WeakMap<t.Node, readonly SemanticReturnedReference[]>();
return (callee) => {
const existing = results.get(callee);
if (existing !== undefined) return existing;
const functions = new Set<t.Node>();
const resolution = resolveLocalCallables({
node: callee,
state,
callableById,
bindingCache,
seenBindings: new Set(),
});
for (const id of resolution.callableIds) {
const node = state.callableNodesById.get(id);
if (node !== undefined) functions.add(node);
}
const pending: Candidate[] = [
{ node: callee, path: [], bindings: new Set() },
];
for (let cursor = 0; cursor < pending.length; cursor++) {
const item = pending[cursor];
if (item === undefined) break;
const node = unwrapJavaScriptExpression(item.node).node;
if (t.isIdentifier(node)) {
const binding = resolveSemanticBindingState(state, node, node.name);
if (binding === undefined || item.bindings.has(binding.bindingId))
continue;
const bindings = new Set([...item.bindings, binding.bindingId]);
for (const initializer of [
...binding.initializers,
...binding.referenceInitializers,
])
pending.push({
node: initializer.node,
path: [...initializer.projection, ...item.path],
bindings,
});
} else if (
t.isMemberExpression(node) ||
t.isOptionalMemberExpression(node)
) {
const path: (string | number | null)[] = [];
let receiver: t.Node = node;
while (
t.isMemberExpression(receiver) ||
t.isOptionalMemberExpression(receiver)
) {
path.push(
semanticStaticPropertyKey(receiver.property, receiver.computed),
);
receiver = unwrapJavaScriptExpression(receiver.object).node;
}
pending.push({
...item,
node: receiver,
path: [...path.reverse(), ...item.path],
});
} else if (
t.isConditionalExpression(node) ||
t.isLogicalExpression(node)
) {
pending.push(
{
...item,
node: t.isConditionalExpression(node) ? node.consequent : node.left,
},
{
...item,
node: t.isConditionalExpression(node) ? node.alternate : node.right,
},
);
} else if (t.isSequenceExpression(node)) {
const last = node.expressions.at(-1);
if (last !== undefined) pending.push({ ...item, node: last });
} else if (t.isFunction(node) && item.path.length === 0)
functions.add(node);
else if (t.isObjectExpression(node))
selectObjectTargets(node, item, pending);
else if (t.isArrayExpression(node)) {
const [key, ...path] = item.path;
const index =
key === undefined || key === null ? null : semanticArrayIndex(key);
let uncertainOffset = false;
node.elements.forEach((element, offset) => {
if (element === null) return;
if (t.isSpreadElement(element)) {
uncertainOffset = true;
pending.push({
...item,
node: element.argument,
path: [null, ...path],
});
} else if (index === null || uncertainOffset || index === offset)
pending.push({ ...item, node: element, path });
});
} else if (t.isNewExpression(node))
pending.push({ ...item, node: node.callee });
else if (t.isClass(node)) {
const [key, ...path] = item.path;
for (const member of node.body.body) {
if (t.isClassMethod(member)) {
if (
(item.path.length === 0 && member.kind === "constructor") ||
(key !== undefined &&
(key === null ||
semanticStaticPropertyKey(member.key, member.computed) ===
String(key)))
)
pending.push({ ...item, node: member, path });
} else if (
t.isClassProperty(member) &&
member.value !== null &&
member.value !== undefined &&
key !== undefined &&
(key === null ||
semanticStaticPropertyKey(member.key, member.computed) ===
String(key))
)
pending.push({ ...item, node: member.value, path });
}
if (node.superClass !== null && node.superClass !== undefined)
pending.push({ ...item, node: node.superClass });
}
}
const output = [...functions].flatMap((node) => {
const callables = t.isClass(node)
? node.body.body.filter(
(member) =>
t.isClassMethod(member) && member.kind === "constructor",
)
: [node];
return callables.flatMap((callable) =>
semanticCallableResultExpressions(callable).flatMap(
({ node, delegated }) =>
node === null
? []
: [{ node, projection: delegated ? [null] : [] }],
),
);
});
results.set(callee, output);
return output;
};
};
const selectObjectTargets = (
node: t.ObjectExpression,
item: Candidate,
pending: Candidate[],
): void => {
const [key, ...path] = item.path;
let replaced = false;
for (const property of [...node.properties].reverse()) {
if (replaced) break;
if (t.isSpreadElement(property)) {
pending.push({ ...item, node: property.argument });
continue;
}
const name = semanticStaticPropertyKey(property.key, property.computed);
if (
key !== null &&
key !== undefined &&
name !== null &&
name !== String(key)
)
continue;
if (t.isObjectProperty(property))
pending.push({ ...item, node: property.value, path });
else pending.push({ ...item, node: property, path });
if (key !== null && key !== undefined && name === String(key))
replaced = true;
}
};
@@ -26,10 +26,8 @@ import {
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import { semanticReturnCoverage } from "./javascriptSemanticCoverage.js";
import {
childNodes,
traverseJavaScriptAst,
} from "./javascriptSemanticTraversal.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { semanticCallableResultExpressions } from "./javascriptSemanticCallableResults.js";
interface ReturnExpression {
readonly node: t.Node | null;
@@ -123,25 +121,10 @@ const callableNodes = (program: t.Program): Map<string, t.Node> => {
return output;
};
const directReturnExpressions = (callable: t.Node): ReturnExpression[] => {
if (
t.isArrowFunctionExpression(callable) &&
!t.isBlockStatement(callable.body)
)
return [{ node: callable.body, location: range(callable.body) }];
if (!t.isFunction(callable)) return [];
const output: ReturnExpression[] = [];
const visit = (node: t.Node): void => {
if (t.isFunction(node) || t.isClass(node)) return;
if (t.isReturnStatement(node)) {
output.push({ node: node.argument ?? null, location: range(node) });
return;
}
for (const child of childNodes(node)) visit(child);
};
for (const child of childNodes(callable.body)) visit(child);
return output;
};
const directReturnExpressions = (callable: t.Node): ReturnExpression[] =>
semanticCallableResultExpressions(callable)
.filter(({ kind }) => kind === "return")
.map(({ node, site }) => ({ node, location: range(site) }));
const callableIdsForBinding = (
binding: JavaScriptSemanticBindingState,
@@ -10,7 +10,7 @@ import { semanticSlotAtPath } from "./javascriptSemanticSlots.js";
import {
invalidateSemanticEscapedPath,
invalidateSemanticMutationPath,
invalidateSemanticMutationPaths,
} from "./javascriptSemanticMutationValues.js";
import type { JavaScriptBindingProvenance } from "./javascriptSemanticIr.js";
@@ -211,12 +211,11 @@ const evaluateBinding = (
if (isPrimitive(captured)) value = captured;
}
}
const mutated = binding.mutatedPaths.reduce(
invalidateSemanticMutationPath,
value,
);
const projected = binding.escapedPaths.reduce(
(value, escape) =>
let projected = invalidateSemanticMutationPaths(value, binding.mutatedPaths);
for (const escape of binding.escapedPaths) {
// Escapes only invalidate object references; other lattice values survive.
if (projected.status !== "object" && projected.status !== "array") break;
if (
context.capturePoint !== undefined &&
semanticEscapeFollowsCapture(
binding,
@@ -224,10 +223,10 @@ const evaluateBinding = (
escape.node,
context.state.parentsByNode,
)
? value
: invalidateSemanticEscapedPath(value, escape.path),
mutated,
);
)
continue;
projected = invalidateSemanticEscapedPath(projected, escape.path);
}
// Point-local memoization also bounds failed speculative captures. Only a
// primitive result is allowed back into ordinary value evaluation.
if (
@@ -25,9 +25,11 @@ import { finalizeLocatedFindings } from "./javascriptStaticAnalysisFindings.js";
import {
createJavaScriptAnalysisAccumulator,
type JavaScriptAnalysisAccumulator as AnalysisAccumulator,
type JavaScriptFindingContext,
} from "./javascriptStaticAnalysisState.js";
import type { JavaScriptStaticAnalysis } from "./javascriptStaticAnalysisTypes.js";
import {
classifyParsedJavaScriptElectronBindings,
classifyParsedJavaScriptOpenReceivers,
type JavaScriptOpenReceiverFact,
} from "./javascriptSemanticAnalysis.js";
@@ -57,21 +59,24 @@ export const analyzeParsedJavaScriptStaticSource = (
openReceiverFacts?: ReadonlyMap<number, JavaScriptOpenReceiverFact>,
): JavaScriptStaticAnalysis => {
const accumulator = createJavaScriptAnalysisAccumulator(source.length);
traverseStaticSource(source, file, accumulator, openReceiverFacts);
traverseStaticSource(file, {
source,
accumulator,
...(openReceiverFacts === undefined ? {} : { openReceiverFacts }),
electronBindings: classifyParsedJavaScriptElectronBindings(file),
});
addSourceMapDirectives(source, file.comments ?? [], accumulator);
return finalizeStaticAnalysis(source, file, accumulator);
};
const traverseStaticSource = (
source: string,
file: ParsedJavaScriptSource,
accumulator: AnalysisAccumulator,
openReceiverFacts?: ReadonlyMap<number, JavaScriptOpenReceiverFact>,
findings: JavaScriptFindingContext,
): void => {
traverseJavaScriptAst(file, {
enter: (node) => {
accumulator.visitedNodes += 1;
inspectNode(source, node, accumulator, openReceiverFacts);
findings.accumulator.visitedNodes += 1;
inspectNode(node, findings);
return undefined;
},
});
@@ -156,16 +161,10 @@ const finalizeStaticAnalysis = (
};
const inspectNode = (
source: string,
node: t.Node,
accumulator: AnalysisAccumulator,
openReceiverFacts?: ReadonlyMap<number, JavaScriptOpenReceiverFact>,
findings: JavaScriptFindingContext,
): void => {
const findings = {
source,
accumulator,
...(openReceiverFacts === undefined ? {} : { openReceiverFacts }),
};
const { source, accumulator } = findings;
inspectElectronStaticNode(node, findings);
if (t.isCallExpression(node)) {
inspectBundlerRegistration(source, node, accumulator);
@@ -65,6 +65,8 @@ export interface JavaScriptFindingContext {
| "local-indexed-db"
| "local-cache-storage"
>;
/** Electron export paths for renamed call roots, by identifier offset. */
readonly electronBindings?: ReadonlyMap<number, string>;
}
/** Candidate import, require, worker, or service-worker reference. */
+4
View File
@@ -108,6 +108,10 @@ export const processComparisonContract = (
...(scenario.normalization.ports
? { port_normalization_version: "contextual-endpoints-v2" }
: {}),
...(scenario.normalization.patterns.length > 0
? { pattern_normalization_version: "literal-replacements-v1" }
: {}),
rendered_line_format: "trailing-spaces-trimmed-v1",
});
/**

Some files were not shown because too many files have changed in this diff Show More