Compare commits

..
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 c6cda443c1 docs(javascript): state that duplicate unmapped content stays ambiguous
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 03:33:36 +00:00
Kaoru0822andClaude Opus 5.5 e308f35c43 fix(javascript): keep unmapped captured runtime scripts unknown
A captured script whose bytes matched no static digest was reported as
high-confidence unmatched even when no automatic or caller-declared
mapping applied to its location in any static layer. The matcher now
computes mapping presence once while locating candidates and shares one
no-candidate classification between the captured-source and source-free
branches, so an unmapped location stays unknown with
no-authorized-location-mapping and is not counted as unmatched.

Fixes #6061.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 02:20:21 +00:00
118 changed files with 2165 additions and 11751 deletions

No files matched your search

-8
View File
@@ -551,14 +551,6 @@ command, objdump, Rizin and GDB, and the agent environment server
signal-derived status. This describes the current source routing; it is not a
claim that every command or provider runtime has been independently exercised.
Commands with `--evidence_output` select their delivered view, then publish the
complete Evidence bundle atomically. Cancellation before publication leaves no
new file. A publication that has committed can win a later cancellation; the
`cancelled` result then keeps the written path and byte count under
`details.diagnostics.evidence_bundle`. If staging cleanup stays incomplete
after commit, the `cleanup_incomplete` error reports the same file as
`details.published_path` and `details.bytes`.
When the reader of piped output closes early, as `rea ... | head` does, the
CLI stops writing, prints no error and exits `141` (`128 + 13`, the status of a
SIGPIPE-terminated writer). The operation itself may have completed; only its
+4 -3
View File
@@ -108,9 +108,10 @@ nodes. REA evaluates compatible static candidates conservatively:
6. Missing authorization mappings and incomplete or truncated input coverage
remain unknown or truncated rather than becoming absence claims. A runtime
location with no automatic artifact-root or caller-declared mapping into
any layer, and no unique content match, is `unknown` with
`no-authorized-location-mapping`, with or without captured bytes. Only a
mapped location can be `unmatched` with `no-static-content-match`.
any layer, and no content match, is `unknown` with
`no-authorized-location-mapping`, with or without captured bytes; several
content matches remain `ambiguous` under rule 4. Only a mapped location can
be `unmatched` with `no-static-content-match`.
Every successful cross-layer `observed_as` edge has
`authority: cross-layer-reconciliation` and `state: inferred`. The underlying
-12
View File
@@ -65,18 +65,6 @@ API dependency, and independent fixture compiler oracles keep their existing
TypeScript versions.
`npm run build:cached` compiles the CLI/MCP runtime and its packaged skill.
The build also records `dist/mcp-catalog.json` (compact inputs) and
`dist/mcp-catalog-full.json` from the canonical SDK registrations and binds
each to the runtime with its own SHA-256 digest. These are
runtime artifacts, separate from the test catalog below. Default target-free
MCP startup serves its schemas without constructing analysis validators;
the first tool or guided-workflow request materializes the canonical runtime
on that same SDK server. Explicit compact/full input selections preserve
their advertised schemas throughout materialization. Initial-target,
HTTP and output-schema-off startup keep the eager path; source runs without
recorded artifacts also use eager composition. Compare memory both after discovery and after a completed
request; report diagnostic GC separately from normal resident memory.
Turbo's strict task environment preserves caller-selected `GOMAXPROCS`,
`GOMEMLIMIT`, and `UV_THREADPOOL_SIZE` for resource-constrained builds and
checks. These execution controls do not change artifact content, so changing
@@ -6,9 +6,8 @@ import { join, relative } from "node:path";
import { fileURLToPath } from "node:url";
const sha = (value) => createHash("sha256").update(value).digest("hex");
/** Bind a trial to its source checkout and compiled runtime, including deferred assets. */
export const captureRuntimeBinding = async (runtime, kind = "cli") => {
assert.ok(kind === "cli" || kind === "mcp", "Unknown runtime entry");
/** Bind a trial to its source checkout and the compiled CLI actually launched. */
export const captureRuntimeBinding = async (runtime) => {
const root = await realpath(runtime);
const git = (args) =>
execFileSync("git", args, { cwd: root, maxBuffer: 16 * 1024 * 1024 });
@@ -51,16 +50,10 @@ export const captureRuntimeBinding = async (runtime, kind = "cli") => {
files.push(relative(root, path));
}
};
// MCP materializes additional workers and reads build-owned JSON after
// discovery. Bind every compiled JS/JSON asset, rather than only its entry.
await visit(join(root, kind === "mcp" ? "dist" : "dist/cli-runtime"));
await visit(join(root, "dist/cli-runtime"));
assert.ok(
files.includes(
kind === "mcp"
? join("dist", "mcp", "main.js")
: join("dist", "cli-runtime", "cli.js"),
),
"Missing compiled runtime entry",
files.includes(join("dist", "cli-runtime", "cli.js")),
"Missing compiled CLI entry",
);
const hash = createHash("sha256");
let bytes = 0;
@@ -70,23 +63,15 @@ export const captureRuntimeBinding = async (runtime, kind = "cli") => {
hash.update(JSON.stringify([name, value.length, sha(value)]) + "\n");
}
return {
binding_version: kind === "mcp" ? 2 : 1,
binding_version: 1,
root,
node: process.version,
git_revision: gitRevision,
source_diff_sha256: sha(sourceDiff),
untracked_source_sha256: sha(JSON.stringify(untrackedEntries)),
...(kind === "mcp"
? {
compiled_runtime_sha256: hash.digest("hex"),
compiled_runtime_files: files.length,
compiled_runtime_bytes: bytes,
}
: {
compiled_cli_sha256: hash.digest("hex"),
compiled_cli_files: files.length,
compiled_cli_bytes: bytes,
}),
compiled_cli_sha256: hash.digest("hex"),
compiled_cli_files: files.length,
compiled_cli_bytes: bytes,
};
};
@@ -97,10 +82,6 @@ export const assertRuntimeBinding = (actual, expected, mode) => {
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
console.log(
JSON.stringify(
await captureRuntimeBinding(process.argv[2], process.argv[3]),
null,
2,
),
JSON.stringify(await captureRuntimeBinding(process.argv[2]), null, 2),
);
}
@@ -226,8 +226,3 @@ keeps default valid calls and typed refusals while checking full producer
constraints separately. Five isolated suites passed 14 tests across call paths,
ADB start, browser scenarios, source selection and managed analysis. The first
browser attempt failed and remains recorded; no performance cohort changed.
The subsequent [startup audit](mcp-startup.md) extends this harness with
source/bundle bindings and a post-materialization directory check. Its new
measurements are a separate cohort; reproduce this report at its recorded
revision when comparing the original timing and model-session receipts.
@@ -7,10 +7,6 @@ import { parseArgs } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { Ajv2020 } from "ajv/dist/2020.js";
import {
captureRuntimeBinding,
assertRuntimeBinding,
} from "./managed-cli-runtime.mjs";
const { values } = parseArgs({
options: {
@@ -19,68 +15,26 @@ const { values } = parseArgs({
oracle: { type: "string" },
output: { type: "string" },
profile: { type: "string", default: "default" },
phase: { type: "string", default: "analysis" },
cache: { type: "string", default: "cold" },
"cache-root": { type: "string" },
bindings: { type: "string" },
role: { type: "string" },
},
});
assert.ok(["analysis", "discovery"].includes(values.phase));
assert.ok(["cold", "warm"].includes(values.cache));
for (const key of values.phase === "analysis"
? ["runtime", "artifact", "oracle", "output"]
: ["runtime", "output"])
for (const key of ["runtime", "artifact", "oracle", "output"])
assert.ok(
values[key] && resolve(values[key]) === values[key],
`${key} must be absolute`,
);
assert.ok(["default", "full", "compact"].includes(values.profile));
if (values.cache === "warm")
assert.ok(
values["cache-root"] &&
resolve(values["cache-root"]) === values["cache-root"],
);
await mkdir(values.output, { recursive: false });
const hash = (value) => createHash("sha256").update(value).digest("hex");
let oracle;
let artifactSha;
if (values.phase === "analysis") {
oracle = JSON.parse(await readFile(values.oracle, "utf8"));
artifactSha = hash(await readFile(values.artifact));
assert.equal(artifactSha, oracle.artifact_sha256);
}
let expectedBinding;
let bindingBefore;
let auditBeforeMs;
let measurementInputsSha256;
const producerSources = {};
if (values.bindings !== undefined) {
assert.ok(["baseline", "candidate"].includes(values.role));
const inputBytes = await readFile(values.bindings);
measurementInputsSha256 = hash(inputBytes);
const inputs = JSON.parse(inputBytes.toString("utf8"));
for (const name of ["mcp-input-catalog.mjs", "managed-cli-runtime.mjs"]) {
producerSources[name] = hash(
await readFile(new URL(name, import.meta.url)),
);
assert.equal(producerSources[name], inputs.harness_sources_sha256[name]);
}
expectedBinding = inputs.runtime_bindings[values.role];
const start = performance.now();
bindingBefore = await captureRuntimeBinding(values.runtime, "mcp");
auditBeforeMs = performance.now() - start;
assertRuntimeBinding(bindingBefore, expectedBinding, values.role);
}
const oracle = JSON.parse(await readFile(values.oracle, "utf8"));
const artifactSha = hash(await readFile(values.artifact));
assert.equal(artifactSha, oracle.artifact_sha256);
const environment = {
PATH: process.env.PATH,
HOME: values.output,
REA_LOG_LEVEL: "silent",
UV_THREADPOOL_SIZE: "1",
NODE_OPTIONS: "--max-old-space-size=2048",
...(values.cache === "cold"
? { NODE_DISABLE_COMPILE_CACHE: "1" }
: { NODE_COMPILE_CACHE: values["cache-root"] }),
NODE_DISABLE_COMPILE_CACHE: "1",
...(values.profile === "default"
? {}
: { REA_MCP_INPUT_SCHEMA_PROFILE: values.profile }),
@@ -92,29 +46,14 @@ const transport = new StdioClientTransport({
env: environment,
stderr: "pipe",
});
const protocolRequests = {};
const send = transport.send.bind(transport);
transport.send = (...args) => {
const method = args[0].method;
if (typeof method === "string")
protocolRequests[method] = (protocolRequests[method] ?? 0) + 1;
return send(...args);
};
const client = new Client({ name: "rea-catalog-task", version: "1" });
const report = {
profile: values.profile,
phase: values.phase,
cache: values.cache,
cache_root: values["cache-root"] ?? null,
role: values.role,
measurement_inputs_sha256: measurementInputsSha256,
producer_sources_sha256: producerSources,
artifact_sha256: artifactSha,
calls: [],
checks: [],
status: "incomplete",
cleanup_verified: false,
protocol_requests: protocolRequests,
};
const transcript = [];
let stderr = "";
@@ -124,15 +63,6 @@ transport.stderr?.on("data", (value) => {
const began = performance.now();
try {
await client.connect(transport);
report.protocol_era = client.getProtocolEra();
await writeFile(
join(values.output, "server.json"),
JSON.stringify({
info: client.getServerVersion(),
capabilities: client.getServerCapabilities(),
instructions: client.getInstructions(),
}),
);
const catalog = await client.listTools();
assert.equal(catalog.nextCursor, undefined);
const definitions = new Map(catalog.tools.map((tool) => [tool.name, tool]));
@@ -143,145 +73,97 @@ try {
ajv.validateSchema(tool.inputSchema),
`Invalid schema: ${tool.name}`,
);
{
const encoded = JSON.stringify(catalog);
await writeFile(join(values.output, "catalog.json"), encoded);
report.catalog_sha256 = hash(encoded);
}
await writeFile(join(values.output, "catalog.json"), JSON.stringify(catalog));
report.tool_names = [...definitions.keys()];
if (values.phase === "discovery") {
const prompts = await client.listPrompts();
assert.equal(prompts.nextCursor, undefined);
await writeFile(
join(values.output, "prompts.json"),
JSON.stringify(prompts),
const call = async (name, args) => {
const definition = definitions.get(name);
assert.ok(definition, `Missing named tool ${name}`);
const start = performance.now();
const reply = await client.callTool(
{ name, arguments: args },
{ toolDefinition: definition },
);
report.prompts_sha256 = hash(JSON.stringify(prompts));
report.answer = {
tools: report.tool_names,
prompts: prompts.prompts.map((prompt) => prompt.name),
};
report.status = "passed";
} else {
const call = async (name, args) => {
const definition = definitions.get(name);
assert.ok(definition, `Missing named tool ${name}`);
const start = performance.now();
const reply = await client.callTool(
{ name, arguments: args },
{ toolDefinition: definition },
);
report.calls.push({
name,
elapsed_ms: performance.now() - start,
is_error: reply.isError === true,
});
transcript.push({ name, arguments: args, reply });
return reply;
};
const input = {
path: values.artifact,
report.calls.push({
name,
elapsed_ms: performance.now() - start,
is_error: reply.isError === true,
});
transcript.push({ name, arguments: args, reply });
return reply;
};
const input = {
path: values.artifact,
view: {
collection: "packages",
names: ["serde"],
fields: ["name", "version", "kind"],
},
};
const first = await call("inspect_rust_binary", input);
assert.notEqual(first.isError, true);
const selected = first.structuredContent;
assert.ok(selected?.normalized_result?.page);
assert.deepEqual(selected.normalized_result.page.rows, oracle.serde_rows);
assert.equal(selected.subject.digest.sha256, artifactSha);
const parentId = selected.normalized_result.parent_evidence_id;
for (let index = 0; index < 2; index++) {
const reply = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: parentId },
view: {
kind: "rust",
collection: "packages",
names: ["serde"],
fields: ["name", "version", "kind"],
},
};
const first = await call("inspect_rust_binary", input);
assert.notEqual(first.isError, true);
const selected = first.structuredContent;
assert.ok(selected?.normalized_result?.page);
assert.deepEqual(selected.normalized_result.page.rows, oracle.serde_rows);
assert.equal(selected.subject.digest.sha256, artifactSha);
const parentId = selected.normalized_result.parent_evidence_id;
for (let index = 0; index < 2; index++) {
const reply = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: parentId },
view: {
kind: "rust",
collection: "packages",
names: ["serde"],
fields: ["name", "version", "kind"],
},
});
assert.notEqual(reply.isError, true);
assert.deepEqual(
reply.structuredContent.normalized_result.page.rows,
oracle.serde_rows,
);
assert.equal(
reply.structuredContent.normalized_result.parent_evidence_id,
parentId,
);
}
const malformed = await call("inspect_rust_binary", {
path: values.artifact,
view: { collection: "packages", offset: -1 },
});
assert.equal(malformed.isError, true);
report.checks.push(
"Independent package rows and digest; repeated retained identity; canonical negative-offset refusal",
);
const exported = await call("export_evidence_bundle", {
path: join(values.output, "evidence.json"),
});
assert.notEqual(exported.isError, true);
const bundle = JSON.parse(
await readFile(join(values.output, "evidence.json"), "utf8"),
);
const parent = bundle.records.find(
(record) => record.evidence_id === parentId,
);
assert.ok(parent, "Complete original Evidence is retained");
assert.equal(parent.subject.digest.sha256, artifactSha);
assert.notEqual(reply.isError, true);
assert.deepEqual(
parent.normalized_result.auditable_metadata.packages,
oracle.packages,
reply.structuredContent.normalized_result.page.rows,
oracle.serde_rows,
);
assert.deepEqual(
parent.normalized_result.auditable_metadata.dependency_edges,
oracle.edges,
assert.equal(
reply.structuredContent.normalized_result.parent_evidence_id,
parentId,
);
report.parent_evidence_id = parentId;
report.parent_semantic_sha256 = hash(JSON.stringify(parent));
report.answer = oracle.serde_rows;
assert.deepEqual(
await client.listTools(),
catalog,
"Advertisement changed after canonical materialization",
);
report.checks.push(
"Catalog remains identical after canonical materialization",
);
report.status = "passed";
}
const malformed = await call("inspect_rust_binary", {
path: values.artifact,
view: { collection: "packages", offset: -1 },
});
assert.equal(malformed.isError, true);
report.checks.push(
"Independent package rows and digest; repeated retained identity; canonical negative-offset refusal",
);
const exported = await call("export_evidence_bundle", {
path: join(values.output, "evidence.json"),
});
assert.notEqual(exported.isError, true);
const bundle = JSON.parse(
await readFile(join(values.output, "evidence.json"), "utf8"),
);
const parent = bundle.records.find(
(record) => record.evidence_id === parentId,
);
assert.ok(parent, "Complete original Evidence is retained");
assert.equal(parent.subject.digest.sha256, artifactSha);
assert.deepEqual(
parent.normalized_result.auditable_metadata.packages,
oracle.packages,
);
assert.deepEqual(
parent.normalized_result.auditable_metadata.dependency_edges,
oracle.edges,
);
report.parent_evidence_id = parentId;
report.parent_semantic_sha256 = hash(JSON.stringify(parent));
report.answer = oracle.serde_rows;
report.status = "passed";
} finally {
await client.close();
await transport.close();
report.cleanup_verified = transport.pid === null;
assert.ok(report.cleanup_verified);
report.elapsed_ms = performance.now() - began;
if (expectedBinding !== undefined) {
const start = performance.now();
const after = await captureRuntimeBinding(values.runtime, "mcp");
report.runtime_audit_ms = {
before: auditBeforeMs,
after: performance.now() - start,
};
assertRuntimeBinding(after, expectedBinding, values.role);
assert.deepEqual(after, bindingBefore);
assert.equal(
hash(await readFile(values.bindings)),
measurementInputsSha256,
);
for (const [name, digest] of Object.entries(producerSources))
assert.equal(
hash(await readFile(new URL(name, import.meta.url))),
digest,
);
report.runtime_binding = after;
report.runtime_binding_verified = true;
}
await writeFile(
join(values.output, "report.json"),
JSON.stringify(report, null, 2) + "\n",
@@ -1,118 +0,0 @@
"""Verify paired SDK startup/analysis receipts and account for the whole task."""
import argparse
import hashlib
import importlib.util
import json
import statistics
from pathlib import Path
import tiktoken
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('root', type=Path)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
root = args.root
input_bytes = (root / 'measurement-inputs.json').read_bytes()
inputs = json.loads(input_bytes)
expected = inputs['runtime_bindings']
sha = lambda value: hashlib.sha256(value).hexdigest()
compact = lambda value: json.dumps(value, ensure_ascii=False, separators=(',', ':'), allow_nan=False)
encoding = tiktoken.get_encoding('cl100k_base')
count = lambda value: len(encoding.encode(value, disallowed_special=()))
for role in ['baseline', 'candidate']:
assert expected[role]['git_revision'] == inputs[f'{role}_revision']
assert expected[role]['source_diff_sha256'] == sha(b'')
assert expected[role]['untracked_source_sha256'] == sha(b'[]')
assert expected['baseline']['root'] != expected['candidate']['root']
assert expected['baseline']['compiled_runtime_sha256'] != expected['candidate']['compiled_runtime_sha256']
spec = importlib.util.spec_from_file_location('catalog_costs', Path(__file__).with_name('mcp-input-catalog-costs.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
catalogs = {}
identities = {}
rows = []
for case in inputs['cases']:
directory = root / case['case']
report = json.loads((directory / 'report.json').read_text())
assert report['status'] == 'passed' and report['cleanup_verified']
assert report['runtime_binding_verified']
assert report['measurement_inputs_sha256'] == sha(input_bytes)
for name, producer_digest in report['producer_sources_sha256'].items():
assert producer_digest == inputs['harness_sources_sha256'][name]
assert report['runtime_binding'] == expected[case['role']]
for key in ['role', 'cache', 'profile', 'phase']:
assert report[key] == case[key]
raw = (directory / 'catalog.json').read_bytes()
catalog_digest = sha(raw)
assert catalog_digest == report['catalog_sha256']
profile = case['profile']
if profile not in catalogs:
catalog = json.loads(raw)
definitions = [{key: tool[key] for key in ['name', 'description', 'inputSchema']} for tool in catalog['tools']]
catalogs[profile] = {'sha256': catalog_digest, 'tool_count': len(catalog['tools']),
'input_catalog_tokens': count(compact(definitions)),
'raw_catalog_tokens': count(raw.decode()), 'raw_catalog_bytes': len(raw)}
assert catalog_digest == catalogs[profile]['sha256'], 'Directory differs across roles or phases'
transcript = json.loads((directory / 'transcript.json').read_text())
server = json.loads((directory / 'server.json').read_text())
tokens = {'question_and_recipe': count(inputs['questions'][case['phase']] + '\n' + inputs['recipes'][case['phase']]),
'server_instructions': count(server.get('instructions') or ''),
'input_catalog_once': catalogs[profile]['input_catalog_tokens'],
'arguments': sum(count(compact({'name': call['name'], 'arguments': call['arguments']})) for call in transcript),
'text_replies': sum(count(block['text']) for call in transcript for block in call['reply']['content'] if block['type'] == 'text')}
requests = report['protocol_requests']
assert requests['initialize'] == 1
if case['phase'] == 'analysis':
assert len(transcript) == 5 and requests['tools/call'] == 5 and requests['tools/list'] == 2
assert report['artifact_sha256'] == inputs['artifacts'][case['artifact']]['sha256']
identity = (report['parent_evidence_id'], report['parent_semantic_sha256'], sha(compact(report['answer']).encode()))
assert identities.setdefault(case['artifact'], identity) == identity
assert sum(call['is_error'] for call in report['calls']) == 1
else:
assert not transcript and requests.get('tools/call', 0) == 0
assert requests['tools/list'] == 1 and requests['prompts/list'] == 1
prompts = (directory / 'prompts.json').read_bytes()
assert sha(prompts) == report['prompts_sha256']
assert identities.setdefault('prompts', report['prompts_sha256']) == report['prompts_sha256']
tokens['prompt_directory'] = count(prompts.decode())
tokens['whole_task'] = sum(tokens.values())
resource = module.resource(directory)
for name, guard_digest in resource['guard_sources_sha256'].items():
assert guard_digest == inputs['harness_sources_sha256'][name]
del resource['guard_sources_sha256']
row = {**case, 'runtime_binding_sha256': sha(compact(report['runtime_binding']).encode()), 'runtime_audit_ms': report['runtime_audit_ms'],
'catalog_sha256': catalog_digest, 'parent_evidence_id': report.get('parent_evidence_id'),
'parent_semantic_sha256': report.get('parent_semantic_sha256'),
'answer_sha256': sha(compact(report['answer']).encode()), 'tokens_estimated': tokens,
'raw_catalog_result_tokens_all_lists': catalogs[profile]['raw_catalog_tokens'] * requests['tools/list'],
'raw_catalog_result_bytes_all_lists': catalogs[profile]['raw_catalog_bytes'] * requests['tools/list'],
'actual_model_usage': None, 'protocol_era': report['protocol_era'], 'protocol_requests': requests, 'calls': report['calls'],
**resource,
'receipt_sha256': {name: sha((directory / name).read_bytes()) for name in ['report.json', 'catalog.json', 'server.json', 'transcript.json']}}
assert row['catalog_sha256'] == row['receipt_sha256']['catalog.json'] == catalogs[profile]['sha256']
rows.append(row)
assert len(rows) == 72
summary = []
for phase in ['discovery', 'analysis']:
for cache in ['cold', 'warm']:
for profile in ['default', 'full']:
for artifact in ([None] if phase == 'discovery' else ['ripgrep', 'zellij']):
item = {'phase': phase, 'cache': cache, 'profile': profile, 'artifact': artifact}
for role in ['baseline', 'candidate']:
selected = [row for row in rows if all(row[key] == item[key] for key in ['phase', 'cache', 'profile', 'artifact']) and row['role'] == role]
assert len(selected) == 3
item[role] = {metric: {'median': statistics.median(row[metric] for row in selected),
'min': min(row[metric] for row in selected), 'max': max(row[metric] for row in selected)}
for metric in ['wall_seconds', 'cpu_seconds', 'kernel_family_peak_bytes_including_page_cache']}
item[role]['tokens_estimated'] = [row['tokens_estimated']['whole_task'] for row in selected]
summary.append(item)
result = {'status': 'passed', 'tokenizer': f'tiktoken=={tiktoken.__version__}/cl100k_base; estimates, not model usage',
'aggregation_sources_sha256': {path.name: sha(path.read_bytes()) for path in [Path(__file__), Path(spec.origin)]},
'context_scope': 'Question, explicit recipe, server instructions, one complete name/description/input-schema directory, every tool argument and text reply, plus prompt directory for discovery. This projection assumes the client retains a single unchanged directory. Raw catalog result costs include every observed tools/list result separately, with output schemas and without JSON-RPC envelopes. SDK initialization/framing, reasoning and actual model usage are unmeasured. The analysis task includes retained-read, rejection, export/oracle and post-materialization directory checks.',
'cache_scope': 'Cold disables server Node compile cache. Warm enables a prepopulated role/profile-specific cache after one complete analysis priming run. Fresh server/client processes and HOME each trial. Driver compile cache disabled in both cohorts. Cache hit rate and OS page cache are unmeasured; source/runtime audits warm compiled-file pages before startup.',
'resource_scope': 'Whole SDK driver, resource observer and owned REA process family. Includes before/after source-and-all-compiled-JS/JSON binding, SDK schema checks, extra validation calls, bundle export and independent oracle checking. Kernel cgroup peak includes file cache. Build/download/oracle preparation and cache priming excluded. Retained V8 heap and forced-GC diagnostics were not separately measured.',
'measurement_inputs': inputs, 'catalogs': catalogs, 'summary': summary, 'records': rows,
'warmup_receipts': {name: sha((root / name / 'report.json').read_bytes()) for name in [f'warmup-{profile}-{role}' for profile in ['default', 'full'] for role in ['baseline', 'candidate']]}}
args.output.write_text(json.dumps(result, indent=2) + '\n')
print(json.dumps(summary, indent=2))
File diff suppressed because it is too large. Load diff
@@ -1,61 +0,0 @@
# MCP discovery and complete Rust tasks
Target-free stdio discovery previously constructed the canonical analysis runtime before the client could inspect its directory. The candidate records SDK advertisements at build time for default/explicit compact and explicit full inputs. Its first tool, prompt or completion request materializes canonical validators and handlers on the same SDK server. HTTP, output-schema-off, initial-target and unrecorded source runs retain eager composition.
Pinned baseline: [`main@c465ff5a8`](https://github.com/morluto/rea/commit/c465ff5a814b8e1a386fc547cbcd94df5c35f086). Measured candidate: [`04900abbc`](https://github.com/leeguooooo/rea/commit/04900abbcd3c3438fce4af932ff28400fe744a7d). Both use the same main base and locked dependencies. Before/after source and all compiled JS/JSON bindings identify the exact runtime used in every trial. The input manifest and producer scripts are also hashed and checked.
## Real tasks and independent facts
Official Alpine v3.21 packages supply ripgrep 14.1.1-r0 (3,416,168-byte executable) and Zellij 0.40.0-r0 (17,151,864 bytes). Their download URLs, archive/executable digests and aports revisions are retained in [the measurement data](mcp-startup.json). The independent Python ELF/section/zlib/JSON oracle checks 42 packages and 88 dependency edges for ripgrep, and 422 packages and 1,063 edges for Zellij. Serde versions are 1.0.210 and 1.0.137 respectively; the selected package kind remains explicit unknown (`null`). Verification covers embedded static build metadata; execution and runtime reachability remain unverified.
Each analysis task initializes the actual SDK client, lists and validates the input directory, selects serde name/version/kind, reads the exact retained parent twice, verifies canonical rejection of a negative offset, exports and independently checks the complete package/edge inventory, confirms unchanged advertisements after materialization, then closes. All five tool calls and both directory reads are included in the measured task. Discovery tasks initialize, list tools/prompts, validate the input directory and close without an analysis call.
All 72 paired trials and four priming runs passed. Each artifact has identical answers, parent Evidence IDs and complete semantic hashes across roles, profiles and cache modes. Both profiles retain byte-identical directories across baseline/candidate and before/after canonical materialization. The directory contains 213 tools. Complete Evidence is retained and exported through the existing shared workflow.
## Measured cost
Three alternating pairs per condition; table values are medians. Min/max ranges and individual receipts are in [mcp-startup.json](mcp-startup.json). Each cell is baseline → candidate. Kernel process-family peak includes file cache, SDK driver, observer and REA children.
| Task | Cache | Inputs | Wall seconds | Family CPU seconds | Family peak MiB |
| --------- | ----- | ----------------- | ------------: | -----------------: | --------------: |
| Directory | cold | compact (default) | 5.661 → 2.236 | 5.403 → 2.050 | 559.3 → 248.6 |
| Directory | cold | full | 5.256 → 2.337 | 5.040 → 2.175 | 650.9 → 349.1 |
| Directory | warm | compact (default) | 5.056 → 2.236 | 4.800 → 2.015 | 572.8 → 251.4 |
| Directory | warm | full | 4.957 → 2.338 | 4.754 → 2.139 | 672.7 → 349.6 |
| ripgrep | cold | compact (default) | 8.177 → 8.078 | 7.945 → 7.899 | 849.7 → 792.5 |
| zellij | cold | compact (default) | 8.276 → 7.276 | 8.041 → 7.105 | 846.2 → 819.0 |
| ripgrep | cold | full | 8.180 → 7.483 | 8.000 → 7.312 | 846.5 → 794.4 |
| zellij | cold | full | 8.484 → 7.776 | 8.284 → 7.514 | 850.4 → 813.1 |
| ripgrep | warm | compact (default) | 7.976 → 6.879 | 7.739 → 6.678 | 826.8 → 802.6 |
| zellij | warm | compact (default) | 8.285 → 7.472 | 8.019 → 7.254 | 882.1 → 811.4 |
| ripgrep | warm | full | 8.074 → 7.476 | 7.890 → 7.265 | 852.1 → 803.6 |
| zellij | warm | full | 8.382 → 7.479 | 8.151 → 7.293 | 854.3 → 830.0 |
Discovery improves clearly in this cohort. Completed-task changes depend on the workload: default cold ripgrep is approximately unchanged. Initialization moves into the first actual analysis request; its latency must be assessed with the full workflow.
| Default ripgrep first RPC | Baseline ms | Candidate ms |
| ------------------------- | ----------: | -----------: |
| cold | 231.5 | 2532.1 |
| warm | 227.1 | 2118.2 |
Within each profile, advertised context remains identical. Input-directory estimates are 49,670 tokens for default compact and 205,744 for full. Whole-task estimates include the supplied question/recipe, server instructions, directory once, every tool argument and text reply, and the prompt directory in discovery tasks. This projection assumes the client retains one unchanged directory; raw catalog result costs count every observed list result separately, including output schemas. These use tiktoken 0.14.0/cl100k_base; actual model usage, reasoning and SDK initialization/framing are unmeasured.
Linux x64 / AMD EPYC 7B12 / kernel 6.1.0-54-cloud-amd64 / Node 24.18.0, npm 11.16.0. Timed SDK tasks negotiated the legacy protocol era; auto/modern correctness is covered separately by compiled boundary tests. Trials run serially under a 1-CPU quota pinned to CPU 15, 4 GiB hard memory / 3 GiB early stop, no swap and 192 tasks. No resource stop, OOM or remaining payload process was observed. Cold disables server Node compile cache; warm uses a role/profile-specific cache populated by one complete task. Fresh processes and HOME are used each trial. Cache hit rate and OS page cache are unmeasured. Runtime audits warm compiled-file pages and are included in whole-task costs. Builds, downloads, oracle generation and cache priming are preparation outside those costs. Retained V8 heap and forced-GC measurements were not separately collected.
## Ownership and validation
`OwnedMcpServers` seals publication before taking its close snapshot, keeps failed exact close capabilities for retry and serves both eager and deferred paths. Deferred startup still joins servers published before an asynchronous serving handle settles. Post-snapshot and post-close factory calls are refused before allocation. Both production-boundary regressions fail with only the shared guard removed and pass restored.
The moved transport/delivery implementation preserves current complete-error retention, escaped-preview fitting, response/string-limit recovery, target-content provenance and native Evidence continuations. Canonical parsers remain authoritative after lazy binding. Both protocol eras, input/output profile choices, invalid input/output, completion cancellation, partial startup and cleanup retry are exercised.
Aggregation keeps catalog, producer-script and guard-script digests in distinct variables. Before publishing a trial it verifies that the catalog digest matches both its catalog-file receipt and the shared profile identity. Deliberately selecting the guard digest for that field is rejected. Regeneration preserves all measured timing, CPU, memory, context and parent-Evidence values.
Executed local gates: 125 focused tests across 14 files; a repeated 22-case schema/profile subset after the pinned main merge; all six static-check tasks plus architecture guards; builds for both pinned runtimes; six documentation checks and five README consistency tests. HTTP coverage includes the real compiled CLI session/replacement/Host tests. Runtime-binding admission rejects a mismatched compiled graph before MCP launch; aggregation rejects a tampered trial binding. The raw receipts remain in `/tmp/rea-perf-mcp-startup-20261022`, identified by hashes in the data. Real initial-target providers, foreign OS runtime behavior and other providers remain outside this measurement.
## Reproduction
Use the pinned Node/npm toolchain and separate clean baseline/candidate checkouts. Build each with `npm ci` and `npm run build:cached` (the measured workspace shared one locked dependency installation). Acquire and verify the official packages listed in the data, extract the named executables and generate independent oracles with `mcp-input-catalog-oracle.py`.
Capture each checkout with `node experiments/analysis-efficiency/managed-cli-runtime.mjs CHECKOUT mcp`. Construct `measurement-inputs.json` using the recorded schema, updating absolute checkout/artifact/oracle paths and their independently verified bindings. Keep it immutable through a cohort; producer source digests cover `mcp-input-catalog.mjs`, `managed-cli-runtime.mjs`, `resource-run.py` and `resource_payload.py`.
Run `mcp-input-catalog.mjs` through `resource-run.py --observe-payload-exit` with `--runtime`, `--output`, `--bindings`, `--role baseline|candidate`, `--profile default|full`, `--phase discovery|analysis` and `--cache cold|warm`. Analysis also takes `--artifact` and `--oracle`; warm requires a role/profile-specific `--cache-root`. Disable the driver compile cache for both cohorts. Prime each warm role/profile once with the complete ripgrep task. Follow the 72-case order in the data, reversing role order in every second pair. Aggregate with `python mcp-startup-costs.py LAB --output mcp-startup.json` using tiktoken 0.14.0. The aggregator verifies every input/runtime/guard binding and completed receipt before producing summaries.
+2 -2
View File
@@ -305,8 +305,8 @@
"verify:solidity:metadata": "npm run build:cached && node scripts/verify-solidity-metadata.mjs",
"verify:recorded:crash": "npm run build:cached && node scripts/verify-recorded-crash.mjs",
"mcp-catalog:check:built": "node scripts/generate-mcp-tool-catalog.mjs --check",
"compile": "node scripts/clean-build-output.mjs && node scripts/run-typescript.mjs -p tsconfig.build.json && node scripts/record-catalog-digests.mjs && node scripts/record-mcp-catalog.mjs && node scripts/bundle-runtime.mjs",
"compile:termux": "node scripts/clean-build-output.mjs && node --max-old-space-size=3072 node_modules/typescript-termux/lib/tsc.js -p tsconfig.build.json && node scripts/record-catalog-digests.mjs && node scripts/record-mcp-catalog.mjs && node scripts/bundle-runtime.mjs",
"compile": "node scripts/clean-build-output.mjs && node scripts/run-typescript.mjs -p tsconfig.build.json && node scripts/record-catalog-digests.mjs && node scripts/bundle-runtime.mjs",
"compile:termux": "node scripts/clean-build-output.mjs && node --max-old-space-size=3072 node_modules/typescript-termux/lib/tsc.js -p tsconfig.build.json && node scripts/record-catalog-digests.mjs && node scripts/bundle-runtime.mjs",
"artifacts:mcp-catalog": "node scripts/generate-mcp-tool-catalog.mjs",
"artifacts:skills": "node scripts/generate-skill-metadata.mjs",
"artifacts:product-catalog": "node scripts/generate-product-catalog.mjs",
-1
View File
@@ -39,7 +39,6 @@ export const parseDevelopmentTestRequest = (mode, arguments_) => {
// runtime or typecheck prerequisites. Add a consumer here when it reads one.
const artifactConsumers = {
"artifacts:mcp-catalog": [
"tests/boundary/mcp/deferredRuntime.test.ts",
"tests/boundary/mcp/contractPresentation.test.ts",
"tests/boundary/mcp/toolSchemaValidity.test.ts",
],
-119
View File
@@ -1,119 +0,0 @@
import { createHash } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
// Runtime discovery is generated from the same canonical registrations, after
// default identity has been recorded and before bundling. Test catalogs stay separate.
const compiled = resolve(dirname(fileURLToPath(import.meta.url)), "../dist");
const read = (name) => import(pathToFileURL(join(compiled, name)).href);
const [
{ createServer },
{ createBinarySession },
{ parseConfig },
{ silentLogger },
{ PROMPT_CONTRACTS },
] = await Promise.all([
read("server/createServer.js"),
read("composition/binary.js"),
read("config/parseConfig.js"),
read("logger.js"),
read("contracts/promptContracts.js"),
]);
const recordCatalog = async (profile) => {
// Catalog generation is independent of the host account and user configuration.
const home = await mkdtemp(join(tmpdir(), "rea-mcp-catalog-"));
const environment = {
REA_MCP_INPUT_SCHEMA_PROFILE: profile,
HOME: home,
USERPROFILE: home,
XDG_CONFIG_HOME: join(home, "config"),
XDG_CACHE_HOME: join(home, "cache"),
XDG_STATE_HOME: join(home, "state"),
};
const cleanup = [];
let producerFailure;
try {
const config = parseConfig(environment);
if (!config.ok) throw config.error;
const session = createBinarySession(
config.value,
silentLogger,
environment,
);
cleanup.push(async () => {
const closed = await session.close({ retainProviderDocuments: true });
if (!closed.ok) throw closed.error;
});
const server = createServer({ kind: "session", session }, { environment });
cleanup.push(() => server.close());
const client = new Client({ name: "rea-catalog-recorder", version: "1" });
cleanup.push(() => client.close());
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const tools = (await client.listTools()).tools;
const prompts = (await client.listPrompts()).prompts.map((prompt) => {
const contract = PROMPT_CONTRACTS.find(
(candidate) => candidate.name === prompt.name,
);
if (contract === undefined)
throw new Error(`Missing prompt ${prompt.name}`);
return { ...prompt, parameters: contract.arguments };
});
const catalog = {
version: 1,
info: client.getServerVersion(),
capabilities: client.getServerCapabilities(),
instructions: client.getInstructions(),
identity: server.catalogIdentity,
tools,
prompts,
};
const encoded = JSON.stringify(catalog);
const digest = createHash("sha256").update(encoded).digest("hex");
await writeFile(
join(
compiled,
profile === "full" ? "mcp-catalog-full.json" : "mcp-catalog.json",
),
encoded,
);
return digest;
} catch (cause) {
producerFailure = { cause };
throw cause;
} finally {
const results = await Promise.allSettled(
cleanup.reverse().map((close) => Promise.resolve().then(close)),
);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
if (failures.length === 0) {
try {
await rm(home, { recursive: true, force: true });
} catch (cause) {
failures.push(cause);
}
}
if (failures.length > 0)
throw new AggregateError(
producerFailure === undefined
? failures
: [producerFailure.cause, ...failures],
`Catalog cleanup failed; temporary home retained at ${home}`,
);
}
};
const digests = {};
for (const profile of ["compact", "full"])
digests[profile] = await recordCatalog(profile);
await writeFile(
join(compiled, "recordedMcpCatalog.js"),
`/** Recorded from the compiled runtime; do not edit. */\nexport const RECORDED_MCP_CATALOG_SHA256 = ${JSON.stringify(digests)};\n`,
);
+7 -41
View File
@@ -98,60 +98,26 @@ export const deliverAnalysisEvidence = async (
)
: ok(evidence);
if (!delivered.ok) return delivered;
const published = await publishEvidenceDelivery({
bundle,
complete: evidence,
delivered: delivered.value,
outputPath,
operation: evidence.operation,
signal,
});
return published.ok ? ok(published.value.delivered) : published;
};
/** Selected Evidence delivered after its complete bundle was committed. */
export interface PublishedEvidenceDelivery {
readonly delivered: Evidence;
readonly evidenceBundle: PublishedEvidenceFile;
}
/**
* Publish a complete bundle, then deliver Evidence already projected from it.
* Cancellation observed before commit leaves no output and retains the
* complete Evidence. A committed publication wins a later cancellation race;
* its receipt stays in the typed cancellation as diagnostics.evidence_bundle,
* and a cleanup failure after commit keeps its own published receipt.
*/
export const publishEvidenceDelivery = async (input: {
readonly bundle: EvidenceBundle;
readonly complete: Evidence;
readonly delivered: Evidence;
readonly outputPath: string;
readonly operation: string;
readonly signal?: AbortSignal | undefined;
}): Promise<Result<PublishedEvidenceDelivery, AnalysisError>> => {
const { signal, operation } = input;
const written = await persistEvidenceBundleCommand(
input.bundle,
input.outputPath,
bundle,
outputPath,
false,
signal,
operation,
evidence.operation,
);
// Deliver interrupts queued during final publication cleanup before the
// command's signal owner accepts completion and removes its listeners.
await dispatchQueuedInterrupts();
if (!written.ok)
return err(written.error.retainPartialObservation(input.complete));
if (!written.ok) return err(written.error.retainPartialObservation(evidence));
if (signal?.aborted)
return err(
new AnalysisCancelledError(operation, {
new AnalysisCancelledError(evidence.operation, {
cause: signal.reason,
partialObservation: input.delivered,
partialObservation: delivered.value,
diagnostics: { evidence_bundle: { ...written.value } },
}),
);
return ok({ delivered: input.delivered, evidenceBundle: written.value });
return delivered;
};
/** Resolve the caller's exact retained parent from an authenticated portable bundle. */
+7 -2
View File
@@ -9,7 +9,6 @@ import {
RegularFileCleanupFailure,
retryRegularFileCleanup,
} from "./RegularFileRead.js";
import { referenceSourceResourceFailure } from "../reference/ReferenceSourceReaderErrors.js";
import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js";
export type ReferenceSourceVcsInfo =
@@ -60,7 +59,13 @@ export const readReferenceSourceVcs = async (
});
} catch (cause: unknown) {
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err(referenceSourceResourceFailure(cause));
return err({
tag: "reference-source-reader",
code: cause.reason === "cancelled" ? "cancelled" : "io",
message: cause.message,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
}
};
@@ -1,4 +1,3 @@
import { javascriptSourceRangeKey } from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
import type { ElectronCallPath } from "../../domain/javascript/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -11,6 +10,7 @@ import {
import {
addElectronInferenceEdge,
electronFindingSourceNode,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
import {
artifactLocalIdentity,
@@ -191,15 +191,13 @@ const matches = (
path.steps.some(
(step) =>
step.kind === sourceStepKind &&
javascriptSourceRangeKey(step.location) ===
javascriptSourceRangeKey(finding.location),
electronRangeKey(step.location) === electronRangeKey(finding.location),
) &&
(invocation === undefined ||
path.steps.some(
(step) =>
(step.kind === "call" || step.kind === "exposure") &&
javascriptSourceRangeKey(step.location) ===
javascriptSourceRangeKey(invocation),
electronRangeKey(step.location) === electronRangeKey(invocation),
))
);
};
@@ -108,3 +108,23 @@ export const addElectronInferenceEdge = (
}),
});
};
/** Deterministic source-range key for artifact-local graph identities. */
export const electronRangeKey = (range: JavaScriptSourceRange): string =>
`${String(range.start.line)}:${String(range.start.column)}-${String(range.end.line)}:${String(range.end.column)}`;
/** Test exact source-range containment without assuming runtime reachability. */
export const electronRangeContains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,
): boolean =>
comparePoint(outer.start, inner.start) <= 0 &&
comparePoint(outer.end, inner.end) >= 0;
const comparePoint = (
left: JavaScriptSourceRange["start"],
right: JavaScriptSourceRange["start"],
): number =>
left.line === right.line
? left.column - right.column
: left.line - right.line;
@@ -1,7 +1,3 @@
import {
javascriptSourceRangeKey,
javascriptSourceRangeContains,
} from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
import type { ElectronSenderValidationFinding } from "../../domain/javascript/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -25,6 +21,8 @@ import {
addElectronInferenceEdge,
electronFindingSourceNode,
electronObservationIdentity,
electronRangeContains,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
interface IpcGraphState {
@@ -184,7 +182,7 @@ const addHandlerNode = (input: IpcHandlerInput): ApplicationNode => {
identity: artifactLocalIdentity(
file.sha256,
"electron-ipc-handler",
`${finding.side}:${finding.operation}:${finding.channel ?? finding.channel_expression}:${javascriptSourceRangeKey(handlerRange)}`,
`${finding.side}:${finding.operation}:${finding.channel ?? finding.channel_expression}:${electronRangeKey(handlerRange)}`,
),
observations: [
{
@@ -340,7 +338,7 @@ const containingHandler = (
(record) =>
record.file.path === file.path &&
record.finding.handler_location !== null &&
javascriptSourceRangeContains(
electronRangeContains(
record.finding.handler_location,
validation.location,
),
@@ -1,4 +1,3 @@
import { javascriptSourceRangeKey } from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { ElectronNativeAddonBindingFinding } from "../../domain/javascript/electronStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
import {
@@ -14,6 +13,7 @@ import {
addElectronInferenceEdge,
electronFindingSourceNode,
electronObservationIdentity,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
interface NativeBindingInput {
@@ -65,7 +65,7 @@ const addNativeBinding = (input: NativeBindingInput): void => {
value.members,
value.namespace_access ?? null,
value.dynamic_member_access ?? null,
javascriptSourceRangeKey(value.location),
electronRangeKey(value.location),
]),
),
observations: [
@@ -1,4 +1,3 @@
import { javascriptSourceRangeKey } from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { ApplicationNode } from "../../domain/javascript/javascriptApplicationGraphSchemas.js";
import type {
ElectronBrowserWindowFinding,
@@ -22,6 +21,7 @@ import {
addElectronAstEdge,
addElectronInferenceEdge,
electronFindingSourceNode,
electronRangeKey,
} from "./ElectronBoundaryGraphContext.js";
import {
artifactPathResolutionProperties,
@@ -86,11 +86,11 @@ const addBrowserWindow = (
identity: artifactLocalIdentity(
file.sha256,
"electron-browser-window",
javascriptSourceRangeKey(value.location),
electronRangeKey(value.location),
),
observations: [
{
label: `BrowserWindow@${javascriptSourceRangeKey(value.location)}`,
label: `BrowserWindow@${electronRangeKey(value.location)}`,
properties: {
source_path: file.path,
options_status: value.options_status,
@@ -202,7 +202,7 @@ const addContextBridge = (
identity: artifactLocalIdentity(
file.sha256,
"electron-context-bridge",
`${value.world}:${value.api_key ?? value.api_key_expression ?? "[missing]"}:${javascriptSourceRangeKey(value.location)}`,
`${value.world}:${value.api_key ?? value.api_key_expression ?? "[missing]"}:${electronRangeKey(value.location)}`,
),
observations: [
{
@@ -271,7 +271,7 @@ const addUtilityProcess = (
identity: artifactLocalIdentity(
file.sha256,
"electron-utility-process",
`${value.module_path ?? value.module_expression}:${javascriptSourceRangeKey(value.location)}`,
`${value.module_path ?? value.module_expression}:${electronRangeKey(value.location)}`,
),
observations: [
{
@@ -7,10 +7,7 @@ import {
type JavaScriptApplicationAnalysisResult,
parseOwnedJavaScriptApplicationAnalysisSteps,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import {
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
@@ -152,8 +149,13 @@ export const analyzeJavaScriptApplicationValidated = async (
cause,
}),
);
const filesystemFailure = hostFilesystemFailure(cause);
if (filesystemFailure !== undefined) return err(filesystemFailure);
if (
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string" &&
FILESYSTEM_ERROR_CODES.has(cause.code)
)
return err(new ArtifactOperationError(OPERATION, "io"));
return err(
new ProviderAdapterError(JAVASCRIPT_APPLICATION_PROVIDER.id, OPERATION, {
cause,
@@ -206,43 +208,6 @@ const describeResultSchemaFailure = (cause: z.ZodError): string => {
const escapePointerPart = (part: string): string =>
part.replaceAll("~", "~0").replaceAll("/", "~1");
/**
* Project a host filesystem failure that no narrower owner classified. Selected
* input denial is classified at selection; this failure may concern any path,
* including private workspace files, so it keeps the host's own facts rather
* than claiming a selected-read denial.
*/
const hostFilesystemFailure = (cause: unknown): AnalysisError | undefined => {
if (!(cause instanceof Error)) return undefined;
const code: unknown = Reflect.get(cause, "code");
if (typeof code !== "string" || !FILESYSTEM_ERROR_CODES.has(code))
return undefined;
const syscall: unknown = Reflect.get(cause, "syscall");
const path: unknown = Reflect.get(cause, "path");
const facts = {
system_code: code,
...(typeof syscall === "string" ? { syscall } : {}),
...(typeof path === "string" ? { path } : {}),
};
if (code === "EMFILE" || code === "ENFILE")
return new AnalysisResourceConstraintError(
OPERATION,
"capacity",
`Host file-descriptor limit reached (${code})${typeof path === "string" ? ` while accessing ${path}` : ""}`,
facts,
{
cause,
retryable: true,
remediationAction:
"Close unused files or raise the open-file limit for the process or host running REA, then retry.",
},
);
return new ArtifactOperationError(OPERATION, "io", undefined, cause.message, {
cause,
diagnostics: facts,
});
};
const FILESYSTEM_ERROR_CODES = new Set([
"ENOENT",
"EACCES",
@@ -1,4 +1,4 @@
import { constants, type Stats } from "node:fs";
import { constants } from "node:fs";
import { access, lstat, realpath } from "node:fs/promises";
import { setImmediate } from "node:timers/promises";
@@ -91,8 +91,8 @@ export const reconstructJavaScriptArtifact = async (
};
const input = javascriptArtifactReconstructionInputSchema.parse(rawInput);
abortIfNeeded(signal);
const { path, metadata } = await resolveSelectedInput(input.input_path);
const format = selectedFormat(path, metadata, input);
const path = await resolveSelectedInput(input.input_path);
const format = await resolveFormat(path, input);
const snapshot = await scanCanonicalArtifactInventoryInScope(path, {
resourceScope: scope,
signal,
@@ -346,21 +346,13 @@ const OPERATION = "analyze_javascript_application";
/**
* Resolve the caller-selected input. A missing, looping, overlong, or
* unreadable selection is a caller or host-resolution failure, not a damaged
* artifact. A selected directory must also be searchable: without search
* permission its entries can be listed but not inspected, so no entry is
* readable. Other host failures propagate with their errno facts intact.
* artifact.
*/
const resolveSelectedInput = async (
inputPath: string,
): Promise<{ readonly path: string; readonly metadata: Stats }> => {
const resolveSelectedInput = async (inputPath: string): Promise<string> => {
try {
const path = await realpath(inputPath);
const metadata = await lstat(path);
await access(
path,
metadata.isDirectory() ? constants.R_OK | constants.X_OK : constants.R_OK,
);
return { path, metadata };
await access(path, constants.R_OK);
return path;
} catch (cause: unknown) {
const code =
cause instanceof Error && "code" in cause ? String(cause.code) : "";
@@ -397,11 +389,11 @@ const selectedInputResolutionMessage = (
: `Selected input path could not be resolved because symbolic-link traversal looped or exceeded the host limit (ELOOP): ${inputPath}`;
/** The selected input's kind, checked against the caller's requested format. */
const selectedFormat = (
const resolveFormat = async (
path: string,
metadata: Stats,
input: JavaScriptArtifactReconstructionInput,
): "asar" | "directory" => {
): Promise<"asar" | "directory"> => {
const metadata = await lstat(path);
const observed = metadata.isDirectory()
? "directory"
: metadata.isFile() && path.toLowerCase().endsWith(".asar")
@@ -10,10 +10,7 @@ import {
addSemanticGraphUnknown,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
projectSemanticResultBindings,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project literal EventEmitter registrations, removals, and dispatches. */
export const projectSemanticEvents = (
@@ -183,11 +180,18 @@ const projectTimerSchedule = (
relation: "schedules-timer",
resolution: "resolved",
});
projectSemanticResultBindings(
context,
timerNodes.get(operation.timerId),
operation.projectedResultBindings,
);
for (const projected of operation.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: timerNodes.get(operation.timerId),
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
};
const projectTimerCancellation = (
@@ -9,10 +9,7 @@ import {
addSemanticGraphUnknown,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
projectSemanticResultBindings,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
interface ChildUnknownInput {
readonly context: SemanticFlowProjectionContext;
@@ -83,7 +80,18 @@ const projectSpawn = (
relation: "spawns",
resolution: spawn.resolution === "complete" ? "resolved" : "candidate",
});
projectSemanticResultBindings(context, child, spawn.projectedResultBindings);
for (const projected of spawn.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: child,
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
if (spawn.argvCount !== null)
addSemanticGraphRelation(context.state, {
source: callSite,
@@ -1,4 +1,3 @@
import { javascriptSourceRangeKey } from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { z } from "zod";
import type { JavaScriptApplicationGraph } from "../../domain/javascript/javascriptApplicationGraph.js";
import type { JsonValue } from "../../domain/jsonValue.js";
@@ -339,5 +338,7 @@ const applicationLocationKey = (
[
artifactSha256,
path,
range === null ? "artifact-path" : javascriptSourceRangeKey(range),
range === null
? "artifact-path"
: `${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`,
].join("\u0000");
@@ -10,10 +10,7 @@ import {
addSemanticGraphUnknown,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
projectSemanticResultBindings,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
import { semanticResourceLimitReason } from "../../domain/javascript/javascriptSemanticResourceLimits.js";
/** Project environment, argv, file, default, and precedence candidates. */
@@ -182,11 +179,18 @@ const projectRequestConstruction = (
relation: "constructs-request",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
projectSemanticResultBindings(
context,
request,
operation.projectedResultBindings,
);
for (const projected of operation.projectedResultBindings)
addSemanticGraphRelation(context.state, {
source: request,
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
for (const field of operation.fields)
addSemanticGraphRelation(context.state, {
source:
@@ -1,10 +1,6 @@
import { javascriptSourceRangeKey } from "../../domain/javascript/javascriptSourceCoordinates.js";
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
import { javaScriptSemanticNodeId } from "../../domain/javascript/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticIr,
JavaScriptSemanticProjectedResultBinding,
} from "../../domain/javascript/javascriptSemanticIr.js";
import type { JavaScriptSemanticIr } from "../../domain/javascript/javascriptSemanticIr.js";
import { sourceRangesEqual } from "../../domain/javascript/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
@@ -38,26 +34,6 @@ export interface SemanticFlowProjectionContext {
) => JavaScriptSemanticGraphNode | undefined;
}
/** Project result destructuring consistently for timers, child processes, and requests. */
export const projectSemanticResultBindings = (
context: Pick<SemanticFlowProjectionContext, "state" | "bindingNodes">,
source: JavaScriptSemanticGraphNode | undefined,
bindings: readonly JavaScriptSemanticProjectedResultBinding[],
): void => {
for (const projected of bindings)
addSemanticGraphRelation(context.state, {
source,
target: context.bindingNodes.get(projected.bindingId),
relation: "destructures",
resolution:
projected.resolution === "complete" ? "resolved" : "candidate",
properties: {
projection_path: [...projected.projectionPath],
projection_resolution: projected.resolution,
},
});
};
/** Project explicit static Promise/task ownership without runtime claims. */
export const projectSemanticPromises = (
context: SemanticFlowProjectionContext,
@@ -222,6 +198,9 @@ interface ObjectReadIndex {
const objectReadIndexes = new WeakMap<JavaScriptSemanticIr, ObjectReadIndex>();
const objectReadRangeKey = (location: JavaScriptSourceRange): string =>
`${String(location.start.line)}:${String(location.start.column)}:${String(location.end.line)}:${String(location.end.column)}`;
/**
* The object projection owns a member read's occurrence. Index it once per
* file so return and argument flow can connect that expression without
@@ -248,7 +227,7 @@ const objectReadOccurrences = (
}),
);
if (node !== undefined)
nodes.set(javascriptSourceRangeKey(operation.location), node);
nodes.set(objectReadRangeKey(operation.location), node);
}
objectReadIndexes.set(context.ir, { state: context.state, nodes });
return nodes;
@@ -261,7 +240,7 @@ export const semanticObjectReadOccurrence = (
): JavaScriptSemanticGraphNode | undefined =>
location === null
? undefined
: objectReadOccurrences(context).get(javascriptSourceRangeKey(location));
: objectReadOccurrences(context).get(objectReadRangeKey(location));
/** Link direct return expressions to their retained semantic references. */
export const projectSemanticReturnValues = (
@@ -1,8 +1,3 @@
import {
compareJavaScriptSourcePoints,
javascriptSourceRangeContains,
javascriptSourceRangeKey,
} from "../../domain/javascript/javascriptSourceCoordinates.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import type { JavaScriptSemanticGraphNode } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
import { JAVASCRIPT_SEMANTIC_RELATION_FAMILIES } from "../../domain/javascript/javascriptSemanticGraphSchemas.js";
@@ -45,7 +40,7 @@ export const createSemanticCallableOwnerLookup = (
}))
.sort(
(left, right) =>
compareJavaScriptSourcePoints(left.range.start, right.range.start) ||
pointCompare(left.range.start, right.range.start) ||
left.order - right.order,
);
const tree = buildSourceIntervalTree(entries, 0, entries.length);
@@ -59,13 +54,12 @@ export const createSemanticCallableOwnerLookup = (
const current = pending.pop();
if (
current === undefined ||
compareJavaScriptSourcePoints(current.minimumStart, location.start) >
0 ||
compareJavaScriptSourcePoints(current.maximumEnd, location.end) < 0
pointCompare(current.minimumStart, location.start) > 0 ||
pointCompare(current.maximumEnd, location.end) < 0
)
continue;
const candidate = current.entry;
if (javascriptSourceRangeContains(candidate.range, location)) {
if (contains(candidate.range, location)) {
const node = nodes.get(candidate.callableId);
const rank =
best === undefined
@@ -99,15 +93,9 @@ const buildSourceIntervalTree = <Interval extends SourceInterval>(
let minimumEnd = entry.range.end;
let maximumEnd = entry.range.end;
for (const child of [left, right]) {
if (
child !== null &&
compareJavaScriptSourcePoints(child.minimumEnd, minimumEnd) < 0
)
if (child !== null && pointCompare(child.minimumEnd, minimumEnd) < 0)
minimumEnd = child.minimumEnd;
if (
child !== null &&
compareJavaScriptSourcePoints(child.maximumEnd, maximumEnd) > 0
)
if (child !== null && pointCompare(child.maximumEnd, maximumEnd) > 0)
maximumEnd = child.maximumEnd;
}
return {
@@ -132,7 +120,7 @@ export const createSemanticNodeRangeLookup = (
})
.sort(
(left, right) =>
compareJavaScriptSourcePoints(left.range.start, right.range.start) ||
pointCompare(left.range.start, right.range.start) ||
left.order - right.order,
);
const tree = buildSourceIntervalTree(entries, 0, entries.length);
@@ -144,12 +132,11 @@ export const createSemanticNodeRangeLookup = (
const current = pending.pop();
if (
current === undefined ||
compareJavaScriptSourcePoints(current.maximumStart, range.start) < 0 ||
compareJavaScriptSourcePoints(current.minimumEnd, range.end) > 0
pointCompare(current.maximumStart, range.start) < 0 ||
pointCompare(current.minimumEnd, range.end) > 0
)
continue;
if (javascriptSourceRangeContains(range, current.entry.range))
matches.push(current.entry);
if (contains(range, current.entry.range)) matches.push(current.entry);
if (current.left !== null) pending.push(current.left);
if (current.right !== null) pending.push(current.right);
}
@@ -168,15 +155,18 @@ export const createSemanticCallSiteLookup = (
) => JavaScriptSemanticGraphNode | undefined) => {
const identifiers = new Map<string, string>();
for (const call of ir.callSites) {
const key = javascriptSourceRangeKey(call.location);
const key = rangeKey(call.location);
if (!identifiers.has(key)) identifiers.set(key, call.callSiteId);
}
return (range) => {
const identifier = identifiers.get(javascriptSourceRangeKey(range));
const identifier = identifiers.get(rangeKey(range));
return identifier === undefined ? undefined : nodes.get(identifier);
};
};
const rangeKey = (range: JavaScriptSourceRange): string =>
`${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`;
/** Report extractor support without treating missing families as absence. */
export const semanticFamilyStatus = (
family: (typeof JAVASCRIPT_SEMANTIC_RELATION_FAMILIES)[number],
@@ -201,5 +191,17 @@ export const semanticFamilyStatus = (
return "partial";
};
const contains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,
): boolean =>
pointCompare(outer.start, inner.start) <= 0 &&
pointCompare(outer.end, inner.end) >= 0;
const pointCompare = (
left: JavaScriptSourceRange["start"],
right: JavaScriptSourceRange["start"],
): number => left.line - right.line || left.column - right.column;
const positionKey = (range: JavaScriptSourceRange): string =>
`${String(range.start.line).padStart(12, "0")}:${String(range.start.column).padStart(12, "0")}`;
+49 -23
View File
@@ -5,9 +5,6 @@ import type { ExecutionOptions } from "../application/AnalysisProvider.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import {
electronActiveTimelineEventSchema,
electronActiveProcessMetricSchema,
electronActiveWindowSchema,
electronActiveObservationResultSchema,
type ElectronActiveObservationInput,
type ElectronActiveObservationResult,
} from "../domain/javascript/electronActiveObservation.js";
@@ -20,25 +17,49 @@ const OPERATION = "capture_electron_scenario" as const;
const CANCELLED_STATE_READ_TIMEOUT_MS = 5_000;
const GRACE_EXPIRED = Symbol("cancellation grace expired");
const retention = electronActiveObservationResultSchema.shape.retention.shape;
const hookSnapshotSchema = z.strictObject({
events: z.array(electronActiveTimelineEventSchema),
retention_budget_bytes: retention.budget_bytes,
estimated_retained_bytes: retention.estimated_retained_bytes,
event_serialized_byte_upper_bound:
retention.event_serialized_byte_upper_bound,
retained: retention.retained,
dropped: retention.dropped,
dropped_ipc: retention.dropped_ipc,
dropped_runtime: retention.dropped_runtime,
dropped_event_families: retention.dropped_event_families,
dropped_event_roles: retention.dropped_event_roles,
retention_budget_bytes: z.number().int().min(0),
estimated_retained_bytes: z.number().int().min(0),
event_serialized_byte_upper_bound: z.number().int().min(0),
retained: z.number().int().min(0),
dropped: z.number().int().min(0),
dropped_ipc: z.number().int().min(0),
dropped_runtime: z.number().int().min(0),
dropped_event_families: z.array(
z.strictObject({
family: z.string().min(1),
count: z.number().int().min(1),
}),
),
dropped_event_roles: z.array(
z.strictObject({
role: z.string().min(1),
count: z.number().int().min(1),
}),
),
observed: z.number().int().min(0),
observed_ipc: retention.observed_ipc,
observed_runtime: retention.observed_runtime,
observed_ipc: z.number().int().min(0),
observed_runtime: z.number().int().min(0),
hook_error: z.boolean(),
});
const metricSchema = z.strictObject({
pid: z.number().int().min(1),
type: z.string().min(1),
name: z.string().nullable(),
service_name: z.string().nullable(),
});
const windowMetadataSchema = z.strictObject({
window_id: z.string(),
web_contents_id: z.string(),
url: z.string(),
title: z.string(),
visible: z.boolean().nullable(),
destroyed: z.boolean(),
});
type ElectronAction = ElectronActiveObservationInput["actions"][number];
type ElectronActions = ElectronActiveObservationResult["actions"];
@@ -46,10 +67,8 @@ export type ElectronHookSnapshot = z.infer<typeof hookSnapshotSchema>;
export type ElectronHookEvent = z.infer<
typeof electronActiveTimelineEventSchema
>;
export type ElectronMetrics = z.infer<
typeof electronActiveProcessMetricSchema
>[];
type ElectronWindowMetadata = z.infer<typeof electronActiveWindowSchema>;
export type ElectronMetrics = z.infer<typeof metricSchema>[];
type ElectronWindowMetadata = z.infer<typeof windowMetadataSchema>;
type ElectronApplicationState = Awaited<
ReturnType<typeof readApplicationState>
>;
@@ -270,7 +289,14 @@ const emitDeepLink = (
export const readApplicationState = async (
application: ElectronApplication,
): Promise<{
readonly windows: ReadonlyArray<ElectronWindowMetadata>;
readonly windows: ReadonlyArray<{
readonly window_id: string;
readonly web_contents_id: string;
readonly url: string;
readonly title: string;
readonly visible: boolean | null;
readonly destroyed: boolean;
}>;
readonly metrics: ElectronMetrics;
readonly electronVersion: string;
readonly hookSnapshot: ElectronHookSnapshot;
@@ -297,7 +323,7 @@ export const readApplicationState = async (
}),
),
)
.then((value) => z.array(electronActiveWindowSchema).parse(value));
.then((value) => z.array(windowMetadataSchema).parse(value));
const processMetricsPromise: Promise<ElectronMetrics> = application
.evaluate(({ app }) =>
app
@@ -316,7 +342,7 @@ export const readApplicationState = async (
}),
),
)
.then((value) => z.array(electronActiveProcessMetricSchema).parse(value));
.then((value) => z.array(metricSchema).parse(value));
const electronVersionPromise: Promise<string> = application
.evaluate(() => process.versions.electron)
.then((value) => z.string().parse(value));
+40 -35
View File
@@ -4,11 +4,12 @@ import { parseEvidence, type Evidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { ok, type Result } from "../domain/result.js";
import type { Result } from "../domain/result.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { publishEvidenceDelivery } from "../application/EvidenceBundleCommands.js";
import { writeEvidenceBundle } from "../application/EvidenceBundleFiles.js";
import { inspectAnalysisView } from "../application/analysisView/AnalysisViewService.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
@@ -105,7 +106,7 @@ export const publishCliAnalysisEvidence = async (
value: JsonValue,
input: CliEvidenceDelivery,
) => {
const { operation, signal, detail, evidenceOutput } = input;
const { providerId, operation, signal, detail, evidenceOutput } = input;
if (!isEvidence(value)) return value;
const complete = parseEvidence(value);
const inputError = cliEvidenceDeliveryInputError(input);
@@ -114,39 +115,43 @@ export const publishCliAnalysisEvidence = async (
return projectAnalysisError(inputError);
}
if (evidenceOutput === undefined) return complete;
// Project before publication so a view failure cannot commit an
// unreported bundle; publication then owns every post-commit outcome.
const delivered =
detail === "summary"
? inspectAnalysisView({
source: { kind: "inline", evidence: complete },
view: input.view ?? { kind: "summary" },
})
: ok(complete);
if (!delivered.ok)
return projectAnalysisError(
delivered.error.retainPartialObservation(complete),
);
const published = await publishEvidenceDelivery({
bundle: createEvidenceBundle([
...new Map(
[...(input.sourceEvidence ?? []), complete].map((record) => [
record.evidence_id,
record,
const resources = new ArtifactResourceScope();
let receipt: { readonly path: string; readonly bytes: number } | undefined;
const delivered = await finishAnalysisCommand(
async () => {
const written = await writeEvidenceBundle(
createEvidenceBundle([
...new Map(
[...(input.sourceEvidence ?? []), complete].map((record) => [
record.evidence_id,
record,
]),
).values(),
]),
).values(),
]),
complete,
delivered: delivered.value,
outputPath: absoluteCallerPath(evidenceOutput),
absoluteCallerPath(evidenceOutput),
false,
resources,
signal,
);
if (!written.ok) {
if (written.error.partialObservation === undefined)
written.error.retainPartialObservation(complete);
return written;
}
receipt = written.value;
return detail === "summary"
? inspectAnalysisView({
source: { kind: "inline", evidence: complete },
view: input.view ?? { kind: "summary" },
})
: { ok: true as const, value: complete };
},
{ close: () => resources.close() },
providerId,
operation,
signal,
});
if (!published.ok) return projectAnalysisError(published.error);
return detail === "summary"
? {
summary: published.value.delivered,
evidence_bundle: published.value.evidenceBundle,
}
: published.value.delivered;
);
return isEvidence(delivered) && detail === "summary"
? { summary: delivered, evidence_bundle: receipt }
: delivered;
};
+35 -8
View File
@@ -9,7 +9,6 @@ import type { Logger } from "pino";
import {
directAnalysisOptionsFromCli,
nativeOpenOptionFields,
snapshotSelectionOption,
} from "./options.js";
import type { CliInstance } from "./types.js";
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
@@ -39,7 +38,11 @@ const registerOverviewCommands = (
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
): void => {
const overviewOptions = z.object({
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
});
// `analyze` declares the JavaScript integrity policy for its JavaScript
@@ -176,7 +179,11 @@ const registerDecompileCommand = (
.describe(
"Ghidra source-file byte offset; mapped internally to an analysis address",
),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
@@ -259,7 +266,11 @@ const registerXrefsCommand = (
.describe(
"Address or symbol name; use --address=<value> for leading dashes",
),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
@@ -304,7 +315,11 @@ const registerTraceCommand = (
.boolean()
.default(false)
.describe("Match the query with exact letter case"),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
@@ -350,7 +365,11 @@ const registerFunctionCommand = (
.describe(
"Procedure name or address; use --procedure=<value> for leading dashes",
),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
@@ -395,7 +414,11 @@ const registerInstructionsCommand = (
.describe(
"Procedure name or address; use --procedure=<value> for leading dashes",
),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
@@ -452,7 +475,11 @@ const registerSearchCommand = (
.boolean()
.default(false)
.describe("Match the pattern with exact letter case"),
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
+10 -5
View File
@@ -7,7 +7,6 @@ import type { Logger } from "pino";
import {
directAnalysisOptionsFromCli,
nativeOpenOptionFields,
snapshotSelectionOption,
} from "./options.js";
import type { CliInstance } from "./types.js";
@@ -272,9 +271,11 @@ const registerNativeDispatchMetadataCommand = (
.max(20_000)
.default(5_000)
.describe("Maximum symbol records to inspect"),
snapshot: snapshotSelectionOption.describe(
"Load or update the local analysis snapshot",
),
snapshot: z
.string()
.min(1)
.optional()
.describe("Load or update the local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: async ({ args, options }) =>
@@ -359,7 +360,11 @@ const registerNativeApiCommand = (
address: z.string().describe("Procedure name or address"),
}),
options: z.object({
snapshot: snapshotSelectionOption,
snapshot: z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot"),
...nativeOpenOptionFields,
}),
run: ({ args, options }) =>
+5 -2
View File
@@ -11,7 +11,6 @@ import { logCliCommand } from "../cliLogging.js";
import { parseEnvironmentName } from "../config/environmentName.js";
import {
parseMcpHttpEndpoint,
mcpHttpListenerPortSchema,
type McpHttpEndpoint,
} from "../config/mcpHttpEndpoint.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
@@ -365,7 +364,11 @@ export const registerEnvironmentCommands = (
.min(1)
.optional()
.describe("Listener address; default MCP_HOST, else 127.0.0.1"),
port: mcpHttpListenerPortSchema
port: z
.number()
.int()
.min(0)
.max(65535)
.optional()
.describe(
"Listener port; default MCP_PORT, else 0 for an ephemeral port",
+10 -15
View File
@@ -2,7 +2,6 @@ import { inspectGpuCodeObjectsInputSchema } from "../domain/gpu/gpuCodeObjects.j
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { safeParseJson } from "../domain/safeJson.js";
import { z } from "incur";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
@@ -60,23 +59,19 @@ export const registerGpuCommands = (cli: CliInstance, logger: Logger): void => {
for (const name of ["object_ids", "targets", "view"] as const) {
const value = options[name];
if (value === undefined) continue;
const decoded = safeParseJson(value);
if (!decoded.ok) {
try {
selectors[name] = JSON.parse(value);
} catch (cause) {
return projectAnalysisError(
new AnalysisInputError(
"inspect_gpu_code_objects",
{ cause: decoded.cause },
[
{
path: [name],
reason: "invalid_format",
message: `${name} must be valid JSON`,
},
],
),
new AnalysisInputError("inspect_gpu_code_objects", { cause }, [
{
path: [name],
reason: "invalid_format",
message: `${name} must be valid JSON`,
},
]),
);
}
selectors[name] = decoded.value;
}
const rawInput = {
path: absoluteCallerPath(args.path),
+12 -18
View File
@@ -2,7 +2,6 @@ import { inspectModelArtifactInputSchema } from "../domain/model/modelArtifactQu
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { safeParseJson } from "../domain/safeJson.js";
import { z } from "incur";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
@@ -45,26 +44,21 @@ export const registerModelCommands = (
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectModelArtifact, async () => {
const decoded =
options.view === undefined
? { ok: true as const, value: undefined }
: safeParseJson(options.view);
if (!decoded.ok) {
let view: unknown;
try {
view =
options.view === undefined ? undefined : JSON.parse(options.view);
} catch (cause) {
return projectAnalysisError(
new AnalysisInputError(
"inspect_model_artifact",
{ cause: decoded.cause },
[
{
path: ["view"],
reason: "invalid_format",
message: "view must be a JSON model page selection",
},
],
),
new AnalysisInputError("inspect_model_artifact", { cause }, [
{
path: ["view"],
reason: "invalid_format",
message: "view must be a JSON model page selection",
},
]),
);
}
const view = decoded.value;
const selected = inspectModelArtifactInputSchema.safeParse({
path: absoluteCallerPath(args.path),
hash: options.hash,
-7
View File
@@ -26,13 +26,6 @@ export const providerSelectionOption = analysisProviderSelectorSchema
"Bind deep analysis to a provider ID or use deterministic auto selection",
);
/** Optional path to the local analysis snapshot loaded or updated by a command. */
export const snapshotSelectionOption = z
.string()
.min(1)
.optional()
.describe("Load and update a local analysis snapshot");
/** Explicit interpretation for headerless native executable formats. */
export const formatSelectionOption = executableFormatHintSchema
.optional()
+12 -18
View File
@@ -10,7 +10,6 @@ import { inspectRustBinaryRequestSchema } from "../domain/rust/rustBinaryQuery.j
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { safeParseJson } from "../domain/safeJson.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
@@ -45,26 +44,21 @@ export const registerRustCommands = (
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectRustBinary, async () => {
const decoded =
options.view === undefined
? { ok: true as const, value: undefined }
: safeParseJson(options.view);
if (!decoded.ok) {
let view: unknown;
try {
view =
options.view === undefined ? undefined : JSON.parse(options.view);
} catch (cause) {
return projectAnalysisError(
new AnalysisInputError(
"inspect_rust_binary",
{ cause: decoded.cause },
[
{
path: ["view"],
reason: "invalid_format",
message: "view must be a JSON package or edge selection",
},
],
),
new AnalysisInputError("inspect_rust_binary", { cause }, [
{
path: ["view"],
reason: "invalid_format",
message: "view must be a JSON package or edge selection",
},
]),
);
}
const view = decoded.value;
const input = inspectRustBinaryRequestSchema.safeParse({
path: absoluteCallerPath(args.path),
...(options.detail === undefined ? {} : { detail: options.detail }),
+1 -4
View File
@@ -11,15 +11,12 @@ export const DEFAULT_MCP_HTTP_HOST = "127.0.0.1";
/** Port 0 asks the host for an ephemeral port, reported by the listening log line. */
export const DEFAULT_MCP_HTTP_PORT = 0;
/** A listener may request an ephemeral port with 0; connected endpoints may not. */
export const mcpHttpListenerPortSchema = z.number().int().min(0).max(65535);
/** Decimal TCP port text, shared by the `--port` flag and `MCP_PORT`. */
export const mcpHttpPortSchema = z
.string()
.regex(/^(?:0|[1-9]\d*)$/u)
.transform(Number)
.pipe(mcpHttpListenerPortSchema);
.pipe(z.number().int().min(0).max(65535));
const mcpHttpHostSchema = z.string().trim().min(1);
+1 -6
View File
@@ -12,16 +12,11 @@ export const COMPACT_INPUT_SCHEMA_BUDGET_BYTES = 13 * 1024;
export const mcpInputSchemaProfileSchema = z.enum(["full", "compact"]);
/** Resolve the selected advertisement at the configuration boundary. */
export const resolveMcpInputSchemaProfile = (
profile: McpInputSchemaProfile | undefined,
): McpInputSchemaProfile => profile ?? "compact";
/** Select the default compact advertisement, preserving an explicit full choice. */
export const compactPresentationForMcpInputSchemaProfile = (
profile: "full" | "compact" | undefined,
): { readonly budgetBytes: number } | undefined =>
resolveMcpInputSchemaProfile(profile) === "full"
profile === "full"
? undefined
: { budgetBytes: COMPACT_INPUT_SCHEMA_BUDGET_BYTES };
@@ -1,6 +1,5 @@
import { z } from "zod";
import { evidenceSchema } from "../../domain/evidence.js";
import { compareManagedMembersInputSchema } from "../../domain/managed/managedMemberComparison.js";
import { managedNativeVerificationInputSchema } from "../../domain/managed/managedNativeVerificationSchemas.js";
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
@@ -15,13 +14,31 @@ import {
import { toolContractMetadata } from "../toolEffects.js";
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
/** Inputs for comparing two managed observations carried inline. */
export const compareManagedMembersReferenceInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
})
.superRefine((input, context) => {
if (input.left.evidence_id === input.right.evidence_id)
context.addIssue({
code: "custom",
path: ["right"],
message: "Managed member Evidence must be distinct",
});
});
/** Inline Evidence input for importing reconstruction. */
export const managedReconstructionReferenceInputSchema =
managedReconstructionImportInputSchema.extend({
static_members: evidenceSchema,
});
const managedApplicationGraphReferenceFacts = {} as const;
const managedApplicationGraphReferenceShape = z.strictObject({
...managedApplicationGraphReferenceFacts,
managed_artifact: evidenceSchema.optional(),
managed_members: evidenceSchema.optional(),
managed_native_boundaries: evidenceSchema.optional(),
@@ -83,7 +100,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
description:
"Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Signatures compare type operands by name, not by build-local metadata row. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",
kind: "application",
inputSchema: compareManagedMembersInputSchema,
inputSchema: compareManagedMembersReferenceInputSchema,
outputSchema: comparisonOutputSchema,
examples: [
{
+5 -2
View File
@@ -11,7 +11,10 @@ import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
} from "./managed/managedWorkflowExamples.js";
import { managedApplicationGraphReferenceInputSchema } from "./managed/managedWorkflowToolContracts.js";
import {
compareManagedMembersReferenceInputSchema,
managedApplicationGraphReferenceInputSchema,
} from "./managed/managedWorkflowToolContracts.js";
describe("workflow input contracts", () => {
it("rejects application Evidence ID references and duplicate inline records", () => {
@@ -35,7 +38,7 @@ describe("workflow input contracts", () => {
it("rejects duplicate inline managed Evidence records", () => {
expect(
toolContract("compare_managed_members").inputSchema.safeParse({
compareManagedMembersReferenceInputSchema.safeParse({
left: MANAGED_MEMBER_COMPARISON_EXAMPLE.left,
right: MANAGED_MEMBER_COMPARISON_EXAMPLE.left,
}).success,
+11 -2
View File
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { digestCanonicalValue } from "./canonicalDigest.js";
import { jsonObjectSchema, type JsonValue } from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
@@ -63,4 +65,11 @@ export const analysisProfilesEqual = (
const profileDigest = (
profile: z.infer<typeof unsignedAnalysisProfileSchema>,
): string => digestCanonicalValue(profile, "Analysis profile");
): string => createHash("sha256").update(canonicalJson(profile)).digest("hex");
const canonicalJson = (value: JsonValue): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("RFC 8785 canonicalization rejected analysis profile");
return encoded;
};
+9 -8
View File
@@ -100,10 +100,7 @@ import { evidenceSchema, type Evidence } from "../evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import {
binaryLayoutSchema,
safeParseOwnedBinaryLayout,
} from "../native/binaryLayout.js";
import { safeParseOwnedBinaryLayout } from "../native/binaryLayout.js";
import { bundleResourceRootSchema } from "../apple/bundleResourceRoot.js";
import { functionDossierSchema } from "../hopperValues.js";
import {
@@ -383,10 +380,14 @@ const artifactSchema = z.strictObject({
});
const layoutSummarySchema = z.strictObject({
bytes: binaryLayoutSchema.shape.artifact.shape.bytes,
format: binaryLayoutSchema.shape.format,
architecture: binaryLayoutSchema.shape.architecture,
image_type: binaryLayoutSchema.shape.image_type,
bytes: z.number().int().nonnegative(),
format: z.literal("elf"),
architecture: z.strictObject({
machine: z.literal("EM_X86_64"),
bits: z.literal(64),
byte_order: z.literal("little"),
}),
image_type: z.enum(["ET_EXEC", "ET_DYN", "ET_REL"]),
entry: z.strictObject({
reported_value: z.string().min(1),
meaning: z.enum(["linked-virtual-address", "not-applicable", "absent"]),
+2 -2
View File
@@ -10,7 +10,6 @@ import {
} from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { digestCanonicalValue } from "../canonicalDigest.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
import {
applicationInventoryProjectionInputSchema,
@@ -20,6 +19,7 @@ import {
projectedInventoryEntries,
projectedFileComponents,
projectionCoverage,
projectionDigest,
projectionEvidenceIdSchema,
unavailableComponentSchema,
} from "../mobileApplicationGraphProjection.js";
@@ -155,7 +155,7 @@ export const projectAndroidApplication = (
return {
projection: androidApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `adp_${digestCanonicalValue(withoutId, "Android application projection")}`,
projection_id: `adp_${projectionDigest(withoutId, "Android application projection")}`,
}),
sources: evidence,
};
+5 -2
View File
@@ -21,7 +21,6 @@ import {
import { evidenceSchema } from "../evidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { digestCanonicalValue } from "../canonicalDigest.js";
import {
bridgeCandidateCoverageSchema,
projectCartesianCandidates,
@@ -31,6 +30,7 @@ import {
projectedComponentSchema,
projectedInventoryEntries,
projectedFileComponents,
projectionDigest,
unavailableComponentSchema,
type ProjectedInventoryEntry,
} from "../mobileApplicationGraphProjection.js";
@@ -212,7 +212,7 @@ export const projectAppleApplication = (
/** Identify the complete projection, including source Evidence provenance. */
export const appleProjectionId = (projection: unknown): string =>
`aap_${digestCanonicalValue(projection, "Apple application projection")}`;
`aap_${digest(projection)}`;
/**
* AppleDouble sidecars describe neighbouring files and are never components.
@@ -442,3 +442,6 @@ const projectionLimitations = (facts: {
"Bridge candidates are path-based hypotheses, not observed runtime calls.",
"A bridge basis is inferred from the native path and is repeated for every managed component.",
];
const digest = (value: unknown): string =>
projectionDigest(value, "Apple application projection");
+14 -2
View File
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { digestCanonicalValue } from "./canonicalDigest.js";
import { IDENTIFIER_PATTERN } from "./stringPatterns.js";
import {
compareAsciiStrings,
@@ -123,9 +125,19 @@ const completionManifestObjectSchema = z.strictObject({
});
type CompletionManifestValue = z.infer<typeof completionManifestObjectSchema>;
const canonicalJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError(
"RFC 8785 canonicalization rejected completion metadata",
);
return serialized;
};
const computeManifestId = (
manifest: Omit<CompletionManifestValue, "manifest_id">,
): string => `ecm_${digestCanonicalValue(manifest, "Completion metadata")}`;
): string =>
`ecm_${createHash("sha256").update(canonicalJson(manifest)).digest("hex")}`;
const manifestIssues = (
manifest: CompletionManifestValue,
+7 -2
View File
@@ -1,3 +1,6 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { IDENTIFIER_PATTERN } from "./stringPatterns.js";
@@ -6,7 +9,6 @@ import { evidenceSchema } from "./evidence.js";
import { evidenceBundleSchema } from "./evidenceBundle.js";
import { err, ok, type Result } from "./result.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { digestCanonicalValue } from "./canonicalDigest.js";
const conformancePackageIdSchema = prefixedDigestSchema("cp");
@@ -315,5 +317,8 @@ const packageContents = (
});
const computePackageId = (contents: ConformancePackageContents): string => {
return `cp_${digestCanonicalValue(contents, "Conformance package")}`;
const json = canonicalize(contents);
if (json === undefined)
throw new TypeError("Could not canonicalize parsed conformance package");
return `cp_${createHash("sha256").update(json).digest("hex")}`;
};
+16 -2
View File
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { digestCanonicalValue } from "./canonicalDigest.js";
import { IDENTIFIER_PATTERN } from "./stringPatterns.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import {
@@ -77,9 +79,21 @@ const summarize = (
};
};
const canonicalJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError(
"RFC 8785 canonicalization rejected the completion ledger",
);
return serialized;
};
const computeLedgerId = (
records: readonly EvidenceCompletionRecord[],
): string => `ecl_${digestCanonicalValue({ records }, "Completion ledger")}`;
): string =>
`ecl_${createHash("sha256")
.update(canonicalJson({ records }))
.digest("hex")}`;
const ledgerIssues = (
ledger: EvidenceCompletionLedgerValue,
+2 -2
View File
@@ -10,7 +10,6 @@ import {
} from "../artifactInventoryEvidence.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { digestCanonicalValue } from "../canonicalDigest.js";
import { nativeRuntimeConvention } from "../nativeConvention.js";
import {
applicationInventoryProjectionInputSchema,
@@ -20,6 +19,7 @@ import {
projectedInventoryEntries,
projectedFileComponents,
projectionCoverage,
projectionDigest,
projectionEvidenceIdSchema,
unavailableComponentSchema,
} from "../mobileApplicationGraphProjection.js";
@@ -151,7 +151,7 @@ export const projectHarmonyApplication = (
return {
projection: harmonyApplicationProjectionResultSchema.parse({
...withoutId,
projection_id: `hmp_${digestCanonicalValue(withoutId, "HarmonyOS application projection")}`,
projection_id: `hmp_${projectionDigest(withoutId, "HarmonyOS application projection")}`,
}),
sources: evidence,
};
@@ -156,16 +156,14 @@ const ipcEventSchema = electronActiveTimelineEventSchema.extend({
]),
});
/** Process facts shared by the runtime boundary and retained active observation. */
export const electronActiveProcessMetricSchema = z.strictObject({
const processMetricSchema = z.strictObject({
pid: z.number().int().min(1),
type: z.string().min(1),
name: z.string().nullable(),
service_name: z.string().nullable(),
});
/** Window facts shared by the runtime boundary and retained active observation. */
export const electronActiveWindowSchema = z.strictObject({
const windowResultSchema = z.strictObject({
window_id: z.string(),
web_contents_id: z.string(),
url: z.string(),
@@ -225,9 +223,9 @@ export const electronActiveObservationResultSchema = z.strictObject({
cleanup: z.literal("terminated-owned-process"),
}),
actions: z.array(actionResultSchema),
windows: z.array(electronActiveWindowSchema),
windows: z.array(windowResultSchema),
processes: z.strictObject({
items: z.array(electronActiveProcessMetricSchema),
items: z.array(processMetricSchema),
}),
ipc: z.strictObject({
events: z.array(ipcEventSchema),
@@ -1,7 +1,7 @@
import {
createJavaScriptApplicationEdge,
createImmutableJavaScriptApplicationGraphSteps,
mergeJavaScriptApplicationNodes,
createJavaScriptApplicationNode,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import type {
@@ -30,16 +30,22 @@ export interface ApplicationChangeGraphProjection {
export const buildJavaScriptApplicationChangeGraph = (
input: ChangeGraphInput,
): ApplicationChangeGraphProjection => {
const mergedNodes = mergeJavaScriptApplicationNodes(
nodeCandidates(input),
).sort((left, right) =>
compareUnicodeCodePoints(left.node_id, right.node_id),
);
const retained = new Set(mergedNodes.map(({ node_id }) => node_id));
const allNodes = nodeCandidates(input);
const preferredRoots = uniqueSorted([
...input.right.root_node_ids,
...input.left.root_node_ids,
]).filter((nodeId) => retained.has(nodeId));
]).filter((nodeId) => allNodes.has(nodeId));
const orderedNodeIds = uniqueSorted([
...preferredRoots,
...input.items.flatMap(({ left_node_id: left, right_node_id: right }) => [
...(right === null ? [] : [right]),
...(left === null ? [] : [left]),
]),
]);
const retained = new Set(orderedNodeIds);
const mergedNodes = mergeNodes(
orderedNodeIds.flatMap((nodeId) => allNodes.get(nodeId) ?? []),
);
const sourceEdges = uniqueEdges([
...input.left.edges,
...input.right.edges,
@@ -82,7 +88,9 @@ export const buildJavaScriptApplicationChangeGraph = (
return { graph: next.value };
};
const nodeCandidates = (input: ChangeGraphInput): ApplicationNode[] => {
const nodeCandidates = (
input: ChangeGraphInput,
): Map<string, ApplicationNode[]> => {
const required = new Set([
...input.left.root_node_ids,
...input.right.root_node_ids,
@@ -91,9 +99,11 @@ const nodeCandidates = (input: ChangeGraphInput): ApplicationNode[] => {
...(right === null ? [] : [right]),
]),
]);
return [...input.left.nodes, ...input.right.nodes].filter((node) =>
required.has(node.node_id),
);
const output = new Map<string, ApplicationNode[]>();
for (const node of [...input.left.nodes, ...input.right.nodes])
if (required.has(node.node_id))
output.set(node.node_id, [...(output.get(node.node_id) ?? []), node]);
return output;
};
const changedFromEdge = (
@@ -235,6 +245,37 @@ const sourceCoverageLimits = (input: ChangeGraphInput) =>
const combineOmittedCounts = (left: number | null, right: number | null) =>
left === null || right === null ? null : left + right;
const mergeNodes = (nodes: readonly ApplicationNode[]): ApplicationNode[] => {
const groups = new Map<string, ApplicationNode[]>();
for (const node of nodes)
groups.set(node.node_id, [...(groups.get(node.node_id) ?? []), node]);
const merged = [...groups.values()].map((group) => {
const first = group[0];
if (first === undefined)
throw new TypeError("Empty change-graph node group");
const observations = [
...new Map(
group
.flatMap(({ observations: values }) => values)
.map((observation) => [observation.observation_id, observation]),
).values(),
].sort((left, right) =>
compareUnicodeCodePoints(left.observation_id, right.observation_id),
);
return createJavaScriptApplicationNode({
kind: first.kind,
identity: first.identity,
observations: observations.map(
({ observation_id: _id, identifier_strategy: _strategy, ...value }) =>
value,
),
});
});
return merged.sort((left, right) =>
compareUnicodeCodePoints(left.node_id, right.node_id),
);
};
const uniqueEdges = (edges: readonly ApplicationEdge[]): ApplicationEdge[] =>
[...new Map(edges.map((edge) => [edge.edge_id, edge])).values()].sort(
(left, right) => compareUnicodeCodePoints(left.edge_id, right.edge_id),
@@ -4,7 +4,6 @@ import {
createJavaScriptApplicationEdge,
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
mergeJavaScriptApplicationNodes,
javascriptApplicationGraphSchema,
parseJavaScriptApplicationGraph,
serializeJavaScriptApplicationGraph,
@@ -24,58 +23,6 @@ import {
sourceMapReference,
unknownEvidence,
} from "./javascriptApplicationGraph.fixture.js";
it("merges observations by entity identity without changing source nodes", () => {
const evidence = artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "main.js");
const first = contentNode(evidence, { selected: "first" });
const second = contentNode(evidence, { selected: "second" });
const reversedIdentity = {
sha256: APPLICATION_GRAPH_DIGESTS.asar,
stability: "global-exact" as const,
strategy: "content-digest" as const,
};
const merged = mergeJavaScriptApplicationNodes([
first,
{ ...second, identity: reversedIdentity },
first,
]);
expect(merged).toHaveLength(1);
const node = firstOf(merged, "merged node");
expect(node.node_id).toBe(first.node_id);
expect(node.observations.map(({ properties }) => properties)).toEqual(
expect.arrayContaining([{ selected: "first" }, { selected: "second" }]),
);
expect(node.observations).toHaveLength(2);
expect(first.observations).toHaveLength(1);
expect(second.observations).toHaveLength(1);
const graph = graphForNode(node);
expect(parseJavaScriptApplicationGraph(graph)).toEqual(graph);
});
it.each(["kind", "identity"] as const)(
"rejects colliding entity IDs with a different %s before merging observations",
(field) => {
const node = contentNode(
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "main.js"),
);
const conflicting =
field === "kind"
? { ...node, kind: "javascript-asset" as const }
: {
...node,
identity: {
strategy: "content-digest" as const,
stability: "global-exact" as const,
sha256: "f".repeat(64),
},
};
expect(() => mergeJavaScriptApplicationNodes([node, conflicting])).toThrow(
"Colliding JAG node identifiers disagree",
);
expect(node.observations).toHaveLength(1);
},
);
const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
const properties = Object.fromEntries(
Array.from({ length: 1_001 }, (_, index) => [
@@ -502,51 +502,6 @@ export const createJavaScriptApplicationNode = (
});
};
/** Merge authenticated entities, retaining every distinct observation. */
export const mergeJavaScriptApplicationNodes = (
nodes: readonly ApplicationNode[],
): ApplicationNode[] => {
const groups = new Map<
string,
{
node: ApplicationNode;
observations: Map<string, ApplicationNode["observations"][number]>;
}
>();
for (const node of nodes) {
const group = groups.get(node.node_id);
if (group === undefined) {
groups.set(node.node_id, {
node,
observations: new Map(
node.observations.map((observation) => [
observation.observation_id,
observation,
]),
),
});
continue;
}
if (
node.kind !== group.node.kind ||
canonicalJson(node.identity) !== canonicalJson(group.node.identity)
)
throw new TypeError("Colliding JAG node identifiers disagree");
for (const observation of node.observations)
group.observations.set(observation.observation_id, observation);
}
return [...groups.values()].map(({ node, observations }) =>
createJavaScriptApplicationNode({
kind: node.kind,
identity: node.identity,
observations: [...observations.values()].map(
({ observation_id: _id, identifier_strategy: _strategy, ...value }) =>
value,
),
}),
);
};
/** Build one normalized directed relationship and derive its semantic ID. */
export const createJavaScriptApplicationEdge = (
input: unknown,
@@ -1,7 +1,9 @@
import { uniqueSorted } from "../canonicalOrdering.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { canonicalJson } from "../comparisonSemantics.js";
import { digestCanonicalValue } from "../canonicalDigest.js";
import {
canonicalExportShapeValue,
digestExportShapeValue,
} from "./javascriptExportShapeComparisonIdentity.js";
import {
javaScriptExportShapeComparisonResultSchema,
type JavaScriptExportShapeComparisonChange,
@@ -84,7 +86,7 @@ export const compareJavaScriptExportShapes = (
};
return javaScriptExportShapeComparisonResultSchema.parse({
...semantic,
comparison_id: `jesc_${digestCanonicalValue(semantic, "JavaScript export shape comparison")}`,
comparison_id: `jesc_${digestExportShapeValue(semantic)}`,
});
};
@@ -95,17 +97,14 @@ const sortChanges = (
.map((change, index) => ({
change,
index,
sortKey: canonicalJson(
{
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
},
"JavaScript export shape comparison",
),
sortKey: canonicalExportShapeValue({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
}),
}))
.sort(
(left, right) =>
@@ -0,0 +1,22 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
/**
* Canonically encode one export-shape comparison value.
*
* Comparison identifiers hash the full result semantics, including each
* change's presence object and the per-variant property inventories.
*/
export const canonicalExportShapeValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"JavaScript export shape comparison could not canonicalize data",
);
return encoded;
};
/** Derive one deterministic SHA-256 comparison identifier component. */
export const digestExportShapeValue = (value: unknown): string =>
createHash("sha256").update(canonicalExportShapeValue(value)).digest("hex");
@@ -1,5 +1,7 @@
import { canonicalJson } from "../comparisonSemantics.js";
import { digestCanonicalValue } from "../canonicalDigest.js";
import {
canonicalExportShapeValue,
digestExportShapeValue,
} from "./javascriptExportShapeComparisonIdentity.js";
import type {
JavaScriptExportShapeComparisonChange,
JavaScriptExportShapeComparisonResult,
@@ -193,10 +195,7 @@ const discriminantOccurrences = (
const value = literalValue(field);
if (!value.found) continue;
const discriminant = { path: field.path, value: value.value };
const key = canonicalJson(
discriminant,
"JavaScript export shape comparison",
);
const key = canonicalExportShapeValue(discriminant);
const current = output.get(key);
output.set(key, {
discriminant,
@@ -255,8 +254,8 @@ const compareDiscriminants = (
right: Discriminant,
): number =>
compareUnicodeCodePoints(
canonicalJson(left, "JavaScript export shape comparison"),
canonicalJson(right, "JavaScript export shape comparison"),
canonicalExportShapeValue(left),
canonicalExportShapeValue(right),
);
const selectionUnknownChange = (
@@ -386,8 +385,8 @@ const fieldChangeStatus = ({
if (
leftField !== undefined &&
rightField !== undefined &&
canonicalJson(leftField, "JavaScript export shape comparison") ===
canonicalJson(rightField, "JavaScript export shape comparison")
canonicalExportShapeValue(leftField) ===
canonicalExportShapeValue(rightField)
)
return null;
if (leftPresence === "absent" && rightPresence === "absent") return null;
@@ -503,7 +502,7 @@ const changeWithId = (
semantic: Omit<JavaScriptExportShapeComparisonChange, "change_id">,
): JavaScriptExportShapeComparisonChange => ({
...semantic,
change_id: `jesc_change_${digestCanonicalValue(semantic, "JavaScript export shape comparison")}`,
change_id: `jesc_change_${digestExportShapeValue(semantic)}`,
});
const literalValue = (
@@ -8,7 +8,10 @@ import {
parseAtPath,
} from "./javascriptRuntimeReconciliationInputValidation.js";
import { classifyBrowserCompleteness } from "../browserCompleteness.js";
import {
classifyBrowserCompleteness,
type BrowserCompleteness,
} from "../browserCompleteness.js";
import {
electronActiveObservationResultSchema,
type ElectronActiveObservationResult,
@@ -78,10 +81,19 @@ const assertIdentity = (evidence: Evidence): void => {
};
const normalizeInspection = (
result: ElectronActiveObservationResult,
): Extract<
ParsedRuntimeCapture,
{ kind: "electron-active" }
>["inspection"] => ({
): {
readonly target: {
readonly target_id: string;
readonly type: string;
readonly title: string;
readonly attached: boolean;
readonly file_path: string;
};
readonly frames: readonly [];
readonly scripts: { readonly items: readonly [] };
readonly workers: readonly [];
readonly completeness: BrowserCompleteness;
} => ({
target: {
target_id: `electron-active:${digestCanonicalValue(result.application.application_path, "Runtime reconciliation").slice(0, 32)}`,
type: "electron-application",
@@ -1,6 +1,6 @@
import {
createJavaScriptApplicationGraph,
mergeJavaScriptApplicationNodes,
createJavaScriptApplicationNode,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import type {
@@ -39,7 +39,7 @@ export interface ReconciledApplicationGraphProjection {
export const buildReconciledApplicationGraph = (
input: ReconciledGraphInput,
): ReconciledApplicationGraphProjection => {
const merged = mergeJavaScriptApplicationNodes([
const merged = mergeNodes([
...input.layers.flatMap(({ graph }) => graph.nodes),
...input.runtime.nodes,
]);
@@ -210,6 +210,45 @@ const graphCoverage = (
limits: [],
};
const mergeNodes = (nodes: readonly ApplicationNode[]): ApplicationNode[] => {
const grouped = new Map<string, ApplicationNode[]>();
for (const node of nodes) {
const group = grouped.get(node.node_id);
if (group === undefined) grouped.set(node.node_id, [node]);
else group.push(node);
}
const merged = [...grouped.values()].map((group) => {
const first = group[0];
if (first === undefined) throw new TypeError("Empty JAG node group");
if (
group.some(
({ kind, identity }) =>
kind !== first.kind ||
JSON.stringify(identity) !== JSON.stringify(first.identity),
)
)
throw new TypeError("Colliding JAG node identifiers disagree");
const observations = [
...new Map(
group
.flatMap(({ observations: values }) => values)
.map((observation) => [observation.observation_id, observation]),
).values(),
].sort((left, right) =>
compareUnicodeCodePoints(left.observation_id, right.observation_id),
);
return createJavaScriptApplicationNode({
kind: first.kind,
identity: first.identity,
observations: observations.map(
({ observation_id: _id, identifier_strategy: _strategy, ...value }) =>
value,
),
});
});
return merged;
};
const uniqueEdges = (edges: readonly ApplicationEdge[]): ApplicationEdge[] => [
...new Map(edges.map((edge) => [edge.edge_id, edge])).values(),
];
@@ -2,7 +2,6 @@ import * as t from "@babel/types";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticProjectedResultBinding,
JavaScriptSemanticEventOperation,
JavaScriptSemanticTimerOperation,
} from "./javascriptSemanticIr.js";
@@ -19,7 +18,6 @@ import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import { range } from "./javascriptStaticAnalysisHelpers.js";
import {
builtinDataEffectMethod,
dataEffectArgumentBindingId,
dataEffectLiteralString,
dataEffectMemberCallee,
assignedSemanticResultBindings,
@@ -73,7 +71,11 @@ interface TimerCandidate {
readonly kind: JavaScriptSemanticTimerOperation["kind"];
readonly ownerCallableId: string | null;
readonly handleBindingId: string | null;
readonly projectedResultBindings: readonly JavaScriptSemanticProjectedResultBinding[];
readonly projectedResultBindings: readonly {
readonly bindingId: string;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}[];
readonly handleRead: {
readonly origins: readonly t.Node[];
readonly complete: boolean;
@@ -156,7 +158,7 @@ const collectEvent = (
emitterKey: emitter.key,
emitterBindingId: emitter.bindingId,
eventName,
listenerBindingId: dataEffectArgumentBindingId(listenerArgument, state),
listenerBindingId: bindingId(listenerArgument, state),
listenerLocation: t.isNode(listenerArgument)
? range(listenerArgument)
: null,
@@ -262,7 +264,7 @@ const collectTimer = (input: TimerCollectionInput): void => {
handleBindingId:
kind === "schedule"
? scalarAssignedResultBinding(projectedResultBindings)
: dataEffectArgumentBindingId(node.arguments[0], state),
: bindingId(node.arguments[0], state),
projectedResultBindings:
kind === "schedule"
? semanticProjectedBindingFacts(
@@ -349,6 +351,19 @@ const admittedTimerMethod = (
(candidate) => candidate === value,
) ?? null;
const bindingId = (
node:
| t.Expression
| t.SpreadElement
| t.JSXNamespacedName
| t.ArgumentPlaceholder
| undefined,
state: JavaScriptSemanticAnalysisState,
): string | null =>
t.isIdentifier(node)
? (resolveSemanticBindingState(state, node, node.name)?.bindingId ?? null)
: null;
const timerDelay = (candidate: TimerCandidate): number | null => {
if (candidate.kind !== "schedule" || candidate.method === "setImmediate")
return null;
@@ -1,4 +1,3 @@
import { javascriptSourceRangeContains } from "./javascriptSourceCoordinates.js";
import * as t from "@babel/types";
import type {
@@ -271,7 +270,7 @@ const parameterAcceptsArgument = (
if (!t.isFunction(node)) return false;
const parameters = runtimeFunctionParameters(node);
const parameterIndex = parameters.findIndex((parameter) =>
javascriptSourceRangeContains(range(parameter), location),
rangeContains(range(parameter), location),
);
if (parameterIndex === argumentIndex) return true;
return (
@@ -281,5 +280,16 @@ const parameterAcceptsArgument = (
);
};
const rangeContains = (
outer: JavaScriptSemanticArgumentFlow["parameterLocation"],
inner: JavaScriptSemanticArgumentFlow["parameterLocation"],
): boolean =>
(outer.start.line < inner.start.line ||
(outer.start.line === inner.start.line &&
outer.start.column <= inner.start.column)) &&
(outer.end.line > inner.end.line ||
(outer.end.line === inner.end.line &&
outer.end.column >= inner.end.column));
const uniqueCallableIds = (values: readonly string[]): string[] =>
[...new Set(values)].sort(compareUnicodeCodePoints);
@@ -2,7 +2,6 @@ import * as t from "@babel/types";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticProjectedResultBinding,
JavaScriptSemanticChildProcessInteraction,
JavaScriptSemanticChildProcessSpawn,
} from "./javascriptSemanticIr.js";
@@ -50,7 +49,11 @@ interface SpawnCandidate {
readonly method: JavaScriptSemanticChildProcessSpawn["method"];
readonly ownerCallableId: string | null;
readonly resultBindingId: string | null;
readonly projectedResultBindings: readonly JavaScriptSemanticProjectedResultBinding[];
readonly projectedResultBindings: readonly {
readonly bindingId: string;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}[];
}
interface ChildInteractionContext {
@@ -8,10 +8,7 @@ import {
semanticGlobalProcessOrigin,
semanticMutableBuiltinOrigin,
} from "./javascriptSemanticRequireOrigin.js";
import type {
JavaScriptModuleOrigin,
JavaScriptSemanticProjectedResultBinding,
} from "./javascriptSemanticIr.js";
import type { JavaScriptModuleOrigin } from "./javascriptSemanticIr.js";
import {
evaluateSemanticProvenance,
evaluateSemanticProvenanceAtRead,
@@ -38,8 +35,11 @@ import {
unwrapJavaScriptExpression,
} from "./javascriptAstValues.js";
export interface SemanticProjectedBinding extends JavaScriptSemanticProjectedResultBinding {
export interface SemanticProjectedBinding {
readonly bindingId: string;
readonly identifier: t.Identifier;
readonly projectionPath: readonly (string | number | null)[];
readonly resolution: "complete" | "partial";
}
/** Resolve bindings written by the nearest variable or assignment owner. */
@@ -136,7 +136,7 @@ const projectedPatternBindings = (
export const semanticProjectedBindingFacts = (
bindings: readonly SemanticProjectedBinding[],
): JavaScriptSemanticProjectedResultBinding[] =>
): Omit<SemanticProjectedBinding, "identifier">[] =>
bindings.map(({ identifier: _identifier, ...fact }) => fact);
/** Return a scalar owner only for an unprojected identifier result. */
@@ -1,9 +1,18 @@
import { canonicalJson } from "../comparisonSemantics.js";
import canonicalize from "canonicalize";
import {
javaScriptSemanticGraphSchema,
type JavaScriptSemanticGraph,
} from "./javascriptSemanticGraph.js";
const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"JavaScript semantic graph could not canonicalize data",
);
return encoded;
};
/** Parse a stored semantic graph and reject stale IDs. */
export const parseJavaScriptSemanticGraph = (
input: unknown,
@@ -11,7 +20,4 @@ export const parseJavaScriptSemanticGraph = (
/** Serialize a verified semantic graph as canonical JSON. */
export const serializeJavaScriptSemanticGraph = (input: unknown): string =>
canonicalJson(
parseJavaScriptSemanticGraph(input),
"JavaScript semantic graph",
);
canonicalJson(parseJavaScriptSemanticGraph(input));
@@ -1,4 +1,3 @@
import { javascriptSourceRangeKey } from "./javascriptSourceCoordinates.js";
import * as t from "@babel/types";
import type {
@@ -341,7 +340,7 @@ const indexReturnSites = (
): ReadonlyMap<string, string> => {
const output = new Map<string, string>();
for (const site of callable.returnSites) {
const key = javascriptSourceRangeKey(site.location);
const key = returnSiteKey(site.location);
if (!output.has(key)) output.set(key, site.returnSiteId);
}
return output;
@@ -367,7 +366,7 @@ const createReturnSiteLookup = (
returnSiteIds = indexReturnSites(callable);
returnSiteIdsByCallable.set(callableId, returnSiteIds);
}
return returnSiteIds.get(javascriptSourceRangeKey(location)) ?? null;
return returnSiteIds.get(returnSiteKey(location)) ?? null;
};
};
@@ -382,6 +381,11 @@ const indexCallablesById = (
return output;
};
const returnSiteKey = (
location: JavaScriptSemanticPromiseOperation["location"],
): string =>
`${location.start.line}:${location.start.column}:${location.end.line}:${location.end.column}`;
const promiseSources = (
candidate: PromiseCandidate,
candidateByNode: WeakMap<t.Node, PromiseCandidate>,
@@ -1,4 +1,6 @@
import { digestCanonicalValue } from "../canonicalDigest.js";
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type { JavaScriptSemanticGraph } from "./javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "./javascriptSemanticGraphSchemas.js";
@@ -6,30 +8,44 @@ import { uniqueSorted } from "../canonicalOrdering.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { JavaScriptSemanticQueryInput } from "./javascriptSemanticQuerySchemas.js";
/** Canonical JSON used by semantic query commitments and ordering. */
export const canonicalJavaScriptSemanticQueryJson = (
value: unknown,
): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"JavaScript semantic query could not canonicalize data",
);
return encoded;
};
const digest = (value: unknown): string =>
createHash("sha256")
.update(canonicalJavaScriptSemanticQueryJson(value))
.digest("hex");
/** Derive the stable identity for one graph-bound query. */
export const javaScriptSemanticQueryIdentifier = (
graph: JavaScriptSemanticGraph,
input: JavaScriptSemanticQueryInput,
): string => {
const semantic = input;
return `jsrq_${digestCanonicalValue(
{
source_graph_id: graph.graph_id,
...semantic,
allowed_relations:
semantic.allowed_relations === undefined
? undefined
: uniqueSorted(semantic.allowed_relations),
expected:
semantic.expected === null
? null
: {
...semantic.expected,
classes: uniqueSorted(semantic.expected.classes),
},
},
"JavaScript semantic query",
)}`;
return `jsrq_${digest({
source_graph_id: graph.graph_id,
...semantic,
allowed_relations:
semantic.allowed_relations === undefined
? undefined
: uniqueSorted(semantic.allowed_relations),
expected:
semantic.expected === null
? null
: {
...semantic.expected,
classes: uniqueSorted(semantic.expected.classes),
},
})}`;
};
/** Resolve deterministic seed candidates without applying traversal limits. */
@@ -1,28 +1,4 @@
import { z } from "zod";
import type {
JavaScriptSourcePoint,
JavaScriptSourceRange,
} from "./javascriptStaticAnalysisTypes.js";
/** Compare parser coordinates by line, then UTF-16 column. */
export const compareJavaScriptSourcePoints = (
left: JavaScriptSourcePoint,
right: JavaScriptSourcePoint,
): number => left.line - right.line || left.column - right.column;
/** Include equal endpoints without implying runtime reachability. */
export const javascriptSourceRangeContains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,
): boolean =>
compareJavaScriptSourcePoints(outer.start, inner.start) <= 0 &&
compareJavaScriptSourcePoints(outer.end, inner.end) >= 0;
/** Exact artifact-local coordinate key; callers supply the artifact identity. */
export const javascriptSourceRangeKey = (
range: JavaScriptSourceRange,
): string =>
`${range.start.line}:${range.start.column}-${range.end.line}:${range.end.column}`;
const sourcePointSchema = z.strictObject({
line: z.number().int().min(1),
@@ -33,7 +9,11 @@ const sourcePointSchema = z.strictObject({
export const javascriptSourceRangeSchema = z
.strictObject({ start: sourcePointSchema, end: sourcePointSchema })
.superRefine((range, context) => {
if (compareJavaScriptSourcePoints(range.end, range.start) < 0)
if (
range.end.line < range.start.line ||
(range.end.line === range.start.line &&
range.end.column < range.start.column)
)
context.addIssue({
code: "custom",
path: ["end"],
+7 -3
View File
@@ -1,7 +1,6 @@
import { z } from "zod";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
import { safeParseJson } from "./safeJson.js";
const jsonValueTypeSchema = z.enum([
"object",
@@ -134,8 +133,13 @@ export const inferJsonShape = (text: string): JsonShape | null => {
export const parseJsonObject = (
text: string,
): Readonly<Record<string, unknown>> | null => {
const parsed = safeParseJson(text);
return parsed.ok && isRecord(parsed.value) ? parsed.value : null;
let root: unknown;
try {
root = JSON.parse(text);
} catch {
return null;
}
return isRecord(root) ? root : null;
};
/** The JSON type name of one parsed value. */
export const jsonValueType = (value: unknown): JsonValueType => {
+1 -1
View File
@@ -277,7 +277,7 @@ const managedModuleReferenceSchema = z.object({
name: z.string(),
});
export const managedNativeImportSchema = z.object({
const managedNativeImportSchema = z.object({
token: managedMetadataTokenSchema,
row_offset: offsetSchema,
mapping_flags: z.number().int().min(0).max(0xffff),
@@ -4,7 +4,7 @@ import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import {
cliMetadataGuidSchema,
managedNativeImportSchema,
managedMetadataTokenSchema,
} from "./managedArtifact.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
@@ -24,26 +24,27 @@ const nativeSymbolSchema = z.strictObject({
export type NativeSymbol = z.infer<typeof nativeSymbolSchema>;
const verifiedManagedDeclarationSchema = managedNativeImportSchema
.pick({
token: true,
member_token: true,
member_name: true,
import_name: true,
import_scope_name: true,
no_mangle: true,
char_set: true,
call_convention: true,
})
.extend({
import_name: z.string().min(1),
declaration_verification: managedNativeImportSchema.shape.verification,
})
.strict();
const pinvokeVerificationContextShape = {
item_id: prefixedDigestSchema("mnv_pinvoke"),
managed: verifiedManagedDeclarationSchema,
managed: z.strictObject({
token: managedMetadataTokenSchema,
member_token: managedMetadataTokenSchema.nullable(),
member_name: z.string().nullable(),
import_name: z.string().min(1),
import_scope_name: z.string().nullable(),
no_mangle: z.boolean(),
char_set: z.enum(["not-specified", "ansi", "unicode", "auto", "unknown"]),
call_convention: z.enum([
"not-specified",
"winapi",
"cdecl",
"stdcall",
"thiscall",
"fastcall",
"unknown",
]),
declaration_verification: z.literal("managed-declaration-only"),
}),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(textSchema),
};
@@ -1,3 +1,6 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
@@ -138,3 +141,11 @@ export const projectedFileComponents = (
? [component]
: [],
);
/** Digest a canonical JSON projection payload for its stable identifier. */
export const projectionDigest = (value: unknown, label: string): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(`${label} is not canonical JSON`);
return createHash("sha256").update(encoded).digest("hex");
};
+12 -9
View File
@@ -1,3 +1,6 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import {
@@ -20,7 +23,6 @@ import {
} from "./reconstructionCoverageEvaluation.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { digestCanonicalValue } from "./canonicalDigest.js";
import {
offsetDateTimeInstantFromEpochMilliseconds,
offsetDateTimeSchema,
@@ -287,7 +289,7 @@ export const createReconstructionVerifierContract = (
const parsed = verifierContractBaseSchema.parse(input);
return verifierContractSchema.parse({
...parsed,
contract_sha256: digestCanonicalValue(parsed, "Reconstruction coverage"),
contract_sha256: digest(parsed),
});
};
@@ -352,13 +354,7 @@ const validateCoverageReferences = (
indexUnique(workspace.boundaries, "boundary_id");
for (const contract of workspace.verifier_contracts) {
const { contract_sha256: contractSha256, ...base } = contract;
if (
contractSha256 !==
digestCanonicalValue(
verifierContractBaseSchema.parse(base),
"Reconstruction coverage",
)
)
if (contractSha256 !== digest(verifierContractBaseSchema.parse(base)))
throw new TypeError(
`Verifier contract digest is invalid: ${contract.verifier_id}`,
);
@@ -466,3 +462,10 @@ const reasonOrder = (left: ClosureReason, right: ClosureReason): number =>
compositeKey([left.code, left.subject_id]),
compositeKey([right.code, right.subject_id]),
);
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Reconstruction coverage value is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+16 -10
View File
@@ -1,3 +1,6 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { artifactComparisonResultSchema } from "./artifactComparison.js";
@@ -16,7 +19,6 @@ import { functionDossierSchema } from "./hopperValues.js";
import { assessFunctionCallCoverage } from "./functionCallCoverage.js";
import { processCaptureComparisonSchema } from "./process/processComparison.js";
import { parseProcessCapture } from "./process/processCaptureParsing.js";
import { digestCanonicalValue } from "./canonicalDigest.js";
import {
reconstructionClaimResultSchema,
reconstructionSpecificationSchema,
@@ -70,15 +72,12 @@ export const verifyReconstruction = (
);
const output = {
status: failed > 0 ? "fail" : unresolved > 0 ? "unknown" : "pass",
specification_sha256: digestCanonicalValue(
{
...specification,
claims: [...specification.claims].sort((left, right) =>
compareUnicodeCodePoints(left.claim_id, right.claim_id),
),
},
"Reconstruction specification",
),
specification_sha256: digest({
...specification,
claims: [...specification.claims].sort((left, right) =>
compareUnicodeCodePoints(left.claim_id, right.claim_id),
),
}),
summary: {
total: results.length,
passed: count(results, "pass"),
@@ -378,6 +377,13 @@ const classify = (
return "pass";
};
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Specification canonicalization failed");
return createHash("sha256").update(encoded).digest("hex");
};
const count = (
items: readonly ClaimResult[],
status: ClaimResult["status"],
+22 -13
View File
@@ -1,5 +1,7 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { digestCanonicalValue } from "./canonicalDigest.js";
import {
compareUnicodeCodePoints,
compositeKey,
@@ -24,17 +26,18 @@ const stableUnknownId = (
scopeDigest: string | null,
comparisonConclusionScope?: z.infer<typeof comparisonConclusionScopeSchema>,
): string =>
`unk_${digestCanonicalValue(
{
domain: domain.trim(),
question: question.replace(/\s+/gu, " ").trim(),
scope_digest: scopeDigest,
...(comparisonConclusionScope === undefined
? {}
: { comparison_conclusion_scope: comparisonConclusionScope }),
},
"Unknown identity",
)}`;
`unk_${createHash("sha256")
.update(
canonicalJson({
domain: domain.trim(),
question: question.replace(/\s+/gu, " ").trim(),
scope_digest: scopeDigest,
...(comparisonConclusionScope === undefined
? {}
: { comparison_conclusion_scope: comparisonConclusionScope }),
}),
)
.digest("hex")}`;
const probeSchema = z.strictObject({
operation: z.string().min(1),
@@ -382,7 +385,13 @@ const computeRevisionDigest = (
const { revision_digest: _revisionDigest, ...semantic } =
"revision_digest" in value ? value : { ...value, revision_digest: "" };
void _revisionDigest;
return digestCanonicalValue(semantic, "Unknown identity");
return createHash("sha256").update(canonicalJson(semantic)).digest("hex");
};
const canonicalJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined) throw new TypeError("Unknown identity failed");
return serialized;
};
const sortedUnique = (values: readonly string[]): string[] =>
+16 -2
View File
@@ -1,4 +1,6 @@
import { digestCanonicalValue } from "./canonicalDigest.js";
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { artifactComparisonResultSchema } from "./artifactComparison.js";
@@ -236,7 +238,7 @@ const correlate = (
hypothesis: mapping.hypothesis,
} satisfies JsonValue;
return correlationItemSchema.parse({
correlation_id: `cor_${digestCanonicalValue(projection, "Static/runtime correlation")}`,
correlation_id: `cor_${sha256(canonicalJson(projection))}`,
static: { ...mapping.static, ...selectedStatic },
runtime: { ...mapping.runtime, status: runtimeStatus },
side_alignment: mapping.side_alignment,
@@ -409,3 +411,15 @@ const assertUnique = (evidence: readonly Evidence[], label: string): void => {
`Static/runtime correlation rejects duplicate ${label}`,
);
};
const sha256 = (value: string): string =>
createHash("sha256").update(value).digest("hex");
const canonicalJson = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError(
"RFC 8785 canonicalization rejected correlation mapping",
);
return serialized;
};
+6 -5
View File
@@ -9,10 +9,7 @@ import {
} from "./browserDeadline.js";
import { emptyArraySchema } from "./emptyArraySchema.js";
import { inspectWebPageWithSourceInputSchema } from "./browserObservation.js";
import {
webTextArtifactMetadataSchema,
webTextArtifactSchema,
} from "./webContentArtifact.js";
import { webTextArtifactSchema } from "./webContentArtifact.js";
/** Isolated analyzer heap used when max_heap_mb is omitted. */
export const DEFAULT_WEB_BUNDLE_HEAP_MB = 1024;
@@ -301,7 +298,11 @@ const sourceMapSchema = z.union([
}),
]);
const webTextArtifactSummarySchema = webTextArtifactMetadataSchema.extend({
const webTextArtifactSummarySchema = z.object({
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
bytes: z.number().int().min(0),
media_type: z.string().min(1),
charset: z.literal("utf-8"),
text_available: z.literal(true),
});
+8 -10
View File
@@ -2,17 +2,15 @@ import { createHash } from "node:crypto";
import { z } from "zod";
/** Metadata shared by complete and summarized retained web text artifacts. */
export const webTextArtifactMetadataSchema = z.object({
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
bytes: z.number().int().min(0),
media_type: z.string().min(1),
charset: z.literal("utf-8"),
});
/** Self-verifying text artifact used by web-source analysis boundaries. */
export const webTextArtifactSchema = webTextArtifactMetadataSchema
.extend({ text: z.string() })
export const webTextArtifactSchema = z
.object({
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
bytes: z.number().int().min(0),
media_type: z.string().min(1),
charset: z.literal("utf-8"),
text: z.string(),
})
.superRefine((artifact, context) => {
const bytes = Buffer.byteLength(artifact.text);
const digest = createHash("sha256").update(artifact.text).digest("hex");
+19 -13
View File
@@ -1,4 +1,6 @@
import { digestCanonicalValue } from "./canonicalDigest.js";
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
@@ -34,7 +36,7 @@ export const stableWebResources = (
): StableWebResource[] => {
const keyed = resources.map((resource) => ({
...resource,
resource_key: `res_${digestCanonicalValue(resource, "Web inventory")}`,
resource_key: `res_${digest(resource)}`,
}));
return [
...new Map(
@@ -112,19 +114,23 @@ export const createCapturedWebScriptReconciler = (
/** Stable script identity excludes target IDs, CDP script IDs, and timestamps. */
export const stableWebScriptKey = (script: WebInventoryScriptInput): string =>
`scr_${digestCanonicalValue(
{
url: script.url,
cdp_hash: script.cdp_hash,
length: script.length,
is_module: script.is_module,
language: script.language,
source_map_url: script.source_map_url,
},
"Web inventory",
)}`;
`scr_${digest({
url: script.url,
cdp_hash: script.cdp_hash,
length: script.length,
is_module: script.is_module,
language: script.language,
source_map_url: script.source_map_url,
})}`;
const uniqueResourceKeys = (
resources: readonly StableWebResource[],
): string[] =>
[...new Set(resources.map(({ resource_key }) => resource_key))].sort();
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Web inventory value is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
+110 -60
View File
@@ -1,13 +1,12 @@
import { readdir } from "node:fs/promises";
import { open, readdir } from "node:fs/promises";
import type { FileHandle } from "node:fs/promises";
import { join } from "node:path";
import { parseXmlDocument } from "../domain/xmlDocument.js";
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { withArtifactRegularFile } from "../artifacts/ArtifactFileOperation.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import { ConfigurationError } from "../domain/configurationErrors.js";
import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
/** One language definition and the compiler specs it declares. */
@@ -21,6 +20,62 @@ const MAX_LDEFS_BYTES = 4 * 1024 * 1024;
// Processor modules ship under Processors; installed extensions may add more.
const LANGUAGE_ROOTS = ["Ghidra/Processors", "Ghidra/Extensions"] as const;
interface RetainedLanguageFile {
readonly path: string;
readonly owner: OwnedFileHandle<FileHandle>;
}
/** Language definition handles whose close is unconfirmed but retryable. */
const pendingLanguageFileCleanup = new Set<RetainedLanguageFile>();
/**
* Cleanup of one or more language definition handles is unconfirmed. Any
* read failure that preceded it is kept as the primary failure.
*/
export class GhidraLanguageCatalogCleanupError extends Error {
constructor(
readonly paths: readonly string[],
readonly causes: readonly unknown[],
readonly readFailure?: unknown,
) {
super(
`Language definition cleanup is unconfirmed: ${paths.join(", ")}`,
readFailure === undefined ? undefined : { cause: readFailure },
);
}
}
/** Close one owner; retain it only while a later close can still succeed. */
const closeLanguageFile = async (
file: RetainedLanguageFile,
): Promise<unknown> => {
try {
await file.owner.close();
pendingLanguageFileCleanup.delete(file);
return undefined;
} catch (cause: unknown) {
// Descriptor invalidation does not prove that this owner confirmed close.
// Keep even sticky failures in the lifecycle scope so later reads surface
// the unresolved cleanup instead of silently abandoning ownership.
pendingLanguageFileCleanup.add(file);
return cause;
}
};
/** Retry every retained owner before reporting the failures together. */
const retryLanguageFileCleanup = async (): Promise<void> => {
const failed: { readonly path: string; readonly cause: unknown }[] = [];
for (const file of pendingLanguageFileCleanup) {
const cause = await closeLanguageFile(file);
if (cause !== undefined) failed.push({ path: file.path, cause });
}
if (failed.length > 0)
throw new GhidraLanguageCatalogCleanupError(
failed.map(({ path }) => path),
failed.map(({ cause }) => cause),
);
};
/** Parse the `<language>` elements of one `.ldefs` document. */
export const parseGhidraLanguageDefinitions = (
text: string,
@@ -67,66 +122,61 @@ const languageDirectories = async (installDir: string): Promise<string[]> => {
return directories;
};
/**
* Parse one definition before its final close; an oversized file declares
* nothing. The caller's scope owns a descriptor whose close is unconfirmed.
*/
const readLanguageDefinitionFile = (
/** Read at most the catalog limit; undefined marks an oversized file. */
const readLanguageDefinitionFile = async (
path: string,
resources: ArtifactResourceScope,
signal: AbortSignal | undefined,
): Promise<readonly GhidraLanguageDefinition[]> =>
withArtifactRegularFile(
path,
resources,
signal,
async (file) => {
const bytes = await readBoundedFileBytes(file, MAX_LDEFS_BYTES, {
signal,
cancellationFailure: (reason) =>
new RegularFileOperationCancelled(reason),
});
): Promise<Buffer | undefined> => {
await retryLanguageFileCleanup();
const file = { path, owner: new OwnedFileHandle(await open(path, "r")) };
let read:
| { readonly ok: true; readonly bytes: Buffer | undefined }
| { readonly ok: false; readonly cause: unknown };
try {
read = {
ok: true,
bytes: await readBoundedFileBytes(file.owner.handle, MAX_LDEFS_BYTES),
};
} catch (cause: unknown) {
read = { ok: false, cause };
}
const cleanup = await closeLanguageFile(file);
if (cleanup !== undefined)
throw new GhidraLanguageCatalogCleanupError(
[path],
[cleanup],
read.ok ? undefined : read.cause,
);
if (!read.ok) throw read.cause;
return read.bytes;
};
/** Read every language definition shipped by one Ghidra installation. */
export const readGhidraLanguageCatalog = async (
installDir: string,
): Promise<readonly GhidraLanguageDefinition[]> => {
// Surface retained cleanup even when this catalog has no definitions to read.
await retryLanguageFileCleanup();
const definitions: GhidraLanguageDefinition[] = [];
for (const directory of await languageDirectories(installDir)) {
let entries: string[];
try {
entries = await readdir(directory);
} catch {
continue;
}
for (const entry of entries.sort()) {
if (!entry.endsWith(".ldefs")) continue;
const bytes = await readLanguageDefinitionFile(join(directory, entry));
if (bytes === undefined) continue;
// The XML byte owner validates encoding and declaration before syntax
// parsing; a literal U+FFFD cannot diagnose invalid source bytes.
return bytes === undefined
? []
: parseGhidraLanguageDefinitions(decodeXmlPlistText(bytes));
},
"follow",
);
/**
* Read every language definition shipped by one Ghidra installation. Admission
* first retries cleanup the scope retains, so an unconfirmed close blocks reads
* only until that exact owner releases.
*/
export const readGhidraLanguageCatalog = (
installDir: string,
resources: ArtifactResourceScope,
signal?: AbortSignal,
): Promise<readonly GhidraLanguageDefinition[]> =>
resources.run(async () => {
const definitions: GhidraLanguageDefinition[] = [];
for (const directory of await languageDirectories(installDir)) {
let entries: string[];
try {
entries = await readdir(directory);
} catch {
continue;
}
for (const entry of entries.sort()) {
if (!entry.endsWith(".ldefs")) continue;
definitions.push(
...(await readLanguageDefinitionFile(
join(directory, entry),
resources,
signal,
)),
);
}
definitions.push(
...parseGhidraLanguageDefinitions(decodeXmlPlistText(bytes)),
);
}
return definitions;
});
}
return definitions;
};
/**
* Check a configured import language against the installation before launch,
+5 -13
View File
@@ -18,7 +18,6 @@ import {
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { GhidraProvider } from "./GhidraProvider.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
// Abbreviated from Ghidra 12.1.4 Processors/x86/data/languages/x86.ldefs.
const X86_LDEFS = `<?xml version="1.0" encoding="UTF-8"?>
@@ -198,15 +197,10 @@ describe("Ghidra language catalog", () => {
},
{ id: "x86:LE:16:Real Mode", compilerSpecIds: ["default"] },
]);
expect(
await readGhidraLanguageCatalog(installDir, new ArtifactResourceScope()),
).toHaveLength(2);
expect(
await readGhidraLanguageCatalog(
join(installDir, "absent"),
new ArtifactResourceScope(),
),
).toEqual([]);
expect(await readGhidraLanguageCatalog(installDir)).toHaveLength(2);
expect(await readGhidraLanguageCatalog(join(installDir, "absent"))).toEqual(
[],
);
});
it("reads a UTF-8 signed definition beside an unsigned sibling", async () => {
@@ -225,9 +219,7 @@ describe("Ghidra language catalog", () => {
]),
);
await writeFile(join(module("x86"), "x86.ldefs"), X86_LDEFS);
expect(
await readGhidraLanguageCatalog(root, new ArtifactResourceScope()),
).toEqual([
expect(await readGhidraLanguageCatalog(root)).toEqual([
{ id: "probe:LE:32:default", compilerSpecIds: [] },
...parseGhidraLanguageDefinitions(X86_LDEFS),
]);
+25 -8
View File
@@ -40,6 +40,7 @@ import {
} from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import type { Logger } from "pino";
import { GhidraClient } from "./GhidraClient.js";
@@ -54,9 +55,9 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { resolveGhidraAnalysisSeeds } from "./GhidraAnalysisSeeds.js";
import {
admitGhidraLanguageOverride,
GhidraLanguageCatalogCleanupError,
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { ghidraFileFailure } from "./GhidraFileArtifacts.js";
import {
ghidraProcessorUnsupportedReason,
isGhidraPspTarget,
@@ -396,15 +397,31 @@ export class GhidraProvider implements AnalysisProviderCandidate {
if (override !== undefined && installation.status === "available") {
let catalog: Awaited<ReturnType<typeof readGhidraLanguageCatalog>>;
try {
catalog = await readGhidraLanguageCatalog(
installation.installDir,
this.#inspectionResources,
options?.signal,
);
catalog = await readGhidraLanguageCatalog(installation.installDir);
} catch (cause: unknown) {
if (cause instanceof GhidraLanguageCatalogCleanupError)
return err(
new ProviderCleanupError(
"ghidra",
cause.paths,
{
reason: cause.message,
paths: [...cause.paths],
close_failures: cause.causes.map(providerFailureText),
...(cause.readFailure === undefined
? {}
: { read_failure: providerFailureText(cause.readFailure) }),
},
{ operation: "resolve_analysis_profile", cause },
),
);
return err(
ghidraFileFailure(cause, "resolve_analysis_profile", {
setting: "REA_GHIDRA_LANGUAGE_ID",
new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
cause,
diagnostics: {
reason:
"Could not read the installed Ghidra language definitions.",
},
}),
);
}
+46 -20
View File
@@ -8,12 +8,19 @@ import { realpathSync } from "node:fs";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { parseConfig } from "./config/parseConfig.js";
import { createBinarySession } from "./composition/binary.js";
import { createLogger } from "./logger.js";
import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
import type { RuntimeDependencies } from "./main/types.js";
import { runDeferred } from "./main/deferredRuntime.js";
import { RECORDED_MCP_CATALOG_SHA256 } from "./recordedMcpCatalog.js";
import { SERVER_START_FAILED } from "./main/messages.js";
import { openInitialTarget } from "./main/startup.js";
import { startMcpTransport } from "./main/transport.js";
import {
createOptionalObservationFactories,
loadOptionalObservationProviders,
} from "./composition/optionalObservationProviders.js";
import { createToolResultDelivery } from "./server/toolResult.js";
import { createShutdown } from "./main/shutdown.js";
import {
createExitStatus,
latchSignalShutdown,
@@ -46,7 +53,6 @@ const httpRuntimeDependencies = (
const base = runtimeDependencies();
return {
...base,
transport: "http",
setExitCode: exit.set,
serve: async (factory, options) => {
// Loaded here so the default stdio entry never loads the HTTP listener.
@@ -84,7 +90,12 @@ const httpRuntimeDependencies = (
};
};
/** Start discovery without constructing unused analysis validators. */
/**
* Start the long-lived MCP adapter and install idempotent shutdown handlers.
* The adapter owns its BinarySession for the process lifetime; stdin EOF on
* the stdio transport and process signals on either transport close bridge
* resources without assuming ownership of the Hopper app.
*/
export const run = async (
dependencies: RuntimeDependencies = runtimeDependencies(),
): Promise<number> => {
@@ -94,23 +105,38 @@ export const run = async (
dependencies.writeStderr(`${projectAnalysisError(config.error).message}\n`);
return 1;
}
const fullOutputCatalog =
environment.REA_MCP_OUTPUT_SCHEMA_PROFILE === undefined ||
environment.REA_MCP_OUTPUT_SCHEMA_PROFILE === "full";
if (
RECORDED_MCP_CATALOG_SHA256 !== undefined &&
dependencies.transport !== "http" &&
config.value.hopperTargetPath === undefined &&
fullOutputCatalog &&
dependencies.createServer === undefined &&
dependencies.loadOptionalProviders === undefined
) {
return runDeferred({ ...dependencies, env: environment }, config.value);
}
return (await import("./main/eagerRuntime.js")).runEager(
{ ...dependencies, env: environment },
const logger = createLogger("mcp", config.value.logLevel);
const serverLogger = logger.child({ layer: "server" });
const session = createBinarySession(config.value, logger, environment);
const opened = await openInitialTarget(
session,
config.value,
serverLogger,
dependencies.writeStderr,
);
if (!opened.ok) return opened.exitCode;
const transport = await startMcpTransport(dependencies, session, {
logger,
serverLogger,
environment,
delivery: createToolResultDelivery(config.value.mcpMaxResponseBytes),
loadOptionalProviders:
dependencies.loadOptionalProviders ??
(() =>
loadOptionalObservationProviders(
createOptionalObservationFactories(environment),
)),
});
if (!transport.ok) return 1;
createShutdown({
handle: transport.handle,
closeAndroid: transport.closeAndroid,
closeOptionalProviders: transport.closeOptionalProviders,
session,
dependencies,
serverLogger,
});
return 0;
};
/** Run the executable boundary without exposing an unexpected startup cause. */
-26
View File
@@ -1,26 +0,0 @@
/** Own the exact close capabilities of every published SDK instance. */
export class OwnedMcpServers<Server extends { close(): Promise<void> }> {
private readonly servers = new Map<Server, () => Promise<void>>();
private accepting = true;
create(factory: () => Server): Server {
if (!this.accepting) throw new Error("MCP connection is closed");
const server = factory();
const close = server.close.bind(server);
const ownedClose = async (): Promise<void> => {
await close();
this.servers.delete(server);
};
this.servers.set(server, ownedClose);
server.close = ownedClose;
return server;
}
/** Seal publication before snapshotting; failed close capabilities stay owned. */
closeAll(): Promise<PromiseSettledResult<void>[]> {
this.accepting = false;
return Promise.allSettled(
[...this.servers.values()].map((close) => Promise.resolve().then(close)),
);
}
}
-243
View File
@@ -1,243 +0,0 @@
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import {
STDIO_DEFAULT_MAX_BUFFER_SIZE,
type McpRequestContext,
} from "@modelcontextprotocol/server";
import {
RECORDED_MCP_CATALOG_SHA256,
type RecordedMcpCatalog,
} from "../recordedMcpCatalog.js";
import type { AppConfig } from "../config/types.js";
import {
resolveMcpInputSchemaProfile,
type McpInputSchemaProfile,
} from "../config/mcpInputSchemaProfile.js";
import { DeferredEvidenceMcpServer } from "../server/DeferredEvidenceMcpServer.js";
import { ToolResultDelivery } from "../server/ToolResultDelivery.js";
import { createLogger } from "../logger.js";
import { reportMcpShutdownFailure } from "./shutdown.js";
import type { McpServerHandle, RuntimeDependencies } from "./types.js";
import { MCP_CONNECTION_LOST, SERVER_START_FAILED } from "./messages.js";
import { OwnedMcpServers } from "./OwnedMcpServers.js";
/** Verify the build-owned artifact before trusting its exact typed projection. */
const readCatalog = (profile: McpInputSchemaProfile): RecordedMcpCatalog => {
const bytes = readFileSync(
new URL(
profile === "full" ? "../mcp-catalog-full.json" : "../mcp-catalog.json",
import.meta.url,
),
);
if (
createHash("sha256").update(bytes).digest("hex") !==
RECORDED_MCP_CATALOG_SHA256?.[profile]
)
throw new Error(SERVER_START_FAILED);
// The digest binds these bytes to the same compiled producer and SDK converter.
const catalog: unknown = JSON.parse(bytes.toString("utf8"));
if (
typeof catalog !== "object" ||
catalog === null ||
Reflect.get(catalog, "version") !== 1
)
throw new Error(SERVER_START_FAILED);
return catalog as RecordedMcpCatalog;
};
const initializeRuntime = async (
server: DeferredEvidenceMcpServer,
dependencies: RuntimeDependencies,
context: McpRequestContext,
config: AppConfig,
startedAt: string,
): Promise<void> => {
let shutdown: (() => Promise<void>) | undefined;
let closeSession: (() => Promise<void>) | undefined;
let sessionClosed = false;
server.ownRuntimeCleanup(async () => {
if (shutdown !== undefined) return shutdown();
const results = await Promise.allSettled([
server.closePartialRuntime(),
(async () => {
if (!sessionClosed && closeSession !== undefined) {
await closeSession();
sessionClosed = true;
}
})(),
]);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
if (failures.length > 0)
throw new AggregateError(failures, "MCP startup cleanup failed");
});
const [{ runEager }, { createServer }] = await Promise.all([
import("./eagerRuntime.js"),
import("../server/createServer.js"),
]);
const result = await runEager(
{
...dependencies,
registerShutdown: () => () => undefined,
captureShutdown: (close) => {
shutdown = close;
},
createServer: (source, options) => {
if (source.kind === "session")
closeSession = async () => {
const result = await source.session.close({
retainProviderDocuments: true,
});
if (!result.ok) throw result.error;
};
return createServer(source, {
...options,
mcpServer: server,
startedAt,
});
},
serve: (factory) => {
let close: (() => Promise<void>) | undefined;
server.materialize(() => {
const configured = factory(context);
if (configured !== server) throw new Error(SERVER_START_FAILED);
close = configured.close.bind(configured);
});
return { close: () => close?.() ?? Promise.resolve() };
},
},
config,
);
if (result !== 0 || shutdown === undefined)
throw new Error(SERVER_START_FAILED);
};
/** Own every SDK-created server, including discarded discovery instances. */
export const runDeferred = async (
dependencies: RuntimeDependencies,
config: AppConfig,
): Promise<number> => {
const serverLogger = createLogger("mcp", config.logLevel).child({
layer: "server",
});
const profile = resolveMcpInputSchemaProfile(config.mcpInputSchemaProfile);
let firstCatalog: RecordedMcpCatalog | undefined = readCatalog(profile);
const servers = new OwnedMcpServers<DeferredEvidenceMcpServer>();
let handle: McpServerHandle | undefined;
let attempt: Promise<void> | undefined;
let unregister: () => void = () => undefined;
let closing = false;
let finishServing!: () => void;
const serving = new Promise<void>((resolve) => {
finishServing = resolve;
});
const close = (): Promise<void> => {
closing = true;
attempt ??= Promise.resolve()
.then(async () => {
// A transport published after shutdown begins is still ours to close.
await serving;
const ownedHandle = handle;
const handleResults = Promise.allSettled([
...(ownedHandle === undefined
? []
: [
Promise.resolve()
.then(() => ownedHandle.close())
.then(() => {
handle = undefined;
}),
]),
]);
// Servers published before the serving handle settles join this owner;
// closeAll seals further publication before taking its snapshot.
const [handles, instances] = await Promise.all([
handleResults,
servers.closeAll(),
]);
const failures = [...handles, ...instances].flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
if (failures.length > 0)
throw new AggregateError(failures, "MCP cleanup failed");
unregister();
})
.catch((cause) => {
attempt = undefined;
throw cause;
});
return attempt;
};
const requestClose = () => {
void close().catch((cause) =>
reportMcpShutdownFailure(cause, dependencies, serverLogger),
);
};
try {
// Keep cleanup reachable even if serve creates a server and then throws.
unregister = dependencies.registerShutdown(requestClose);
dependencies.captureShutdown?.(close);
try {
handle = await dependencies.serve(
(context) => {
const server = servers.create(() => {
const catalog = firstCatalog ?? readCatalog(profile);
firstCatalog = undefined;
const startedAt = new Date().toISOString();
const server = new DeferredEvidenceMcpServer(
catalog,
new ToolResultDelivery(
config.mcpMaxResponseBytes ?? STDIO_DEFAULT_MAX_BUFFER_SIZE,
),
(target) =>
initializeRuntime(
target,
dependencies,
context,
config,
startedAt,
).catch((cause) => {
dependencies.setExitCode(1);
throw cause;
}),
);
return server;
});
const previous = server.server.onclose;
server.server.onclose = () => {
previous?.();
requestClose();
};
return server;
},
{
onerror: () => {
serverLogger.error(MCP_CONNECTION_LOST);
dependencies.writeStderr(`${MCP_CONNECTION_LOST}\n`);
},
},
);
} finally {
finishServing();
}
} catch (cause) {
finishServing();
serverLogger.error(
{ error: cause instanceof Error ? cause.message : String(cause) },
SERVER_START_FAILED,
);
try {
await close();
} catch (cleanupCause) {
throw new AggregateError(
[cause, cleanupCause],
"MCP startup and cleanup failed",
);
}
dependencies.writeStderr(`${SERVER_START_FAILED}\n`);
return 1;
}
if (closing) await close();
return 0;
};
-70
View File
@@ -1,70 +0,0 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import type { AppConfig } from "../config/types.js";
import { ok } from "../domain/result.js";
import { parseConfig } from "../config/parseConfig.js";
import { createBinarySession } from "../composition/binary.js";
import { createLogger } from "../logger.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { RuntimeDependencies } from "./types.js";
import { openInitialTarget } from "./startup.js";
import { startMcpTransport } from "./transport.js";
import {
createOptionalObservationFactories,
loadOptionalObservationProviders,
} from "../composition/optionalObservationProviders.js";
import { createToolResultDelivery } from "../server/toolResult.js";
import { createShutdown } from "./shutdown.js";
/**
* Start the long-lived MCP adapter and install idempotent shutdown handlers.
* The adapter owns its BinarySession for the process lifetime; EOF and process
* signals close bridge resources without assuming ownership of the Hopper app.
*/
export const runEager = async (
dependencies: RuntimeDependencies,
selectedConfig?: AppConfig,
): Promise<number> => {
const environment = snapshotEnvironment(dependencies.env);
const config =
selectedConfig === undefined
? parseConfig(environment)
: ok(selectedConfig);
if (!config.ok) {
dependencies.writeStderr(`${projectAnalysisError(config.error).message}\n`);
return 1;
}
const logger = createLogger("mcp", config.value.logLevel);
const serverLogger = logger.child({ layer: "server" });
const session = createBinarySession(config.value, logger, environment);
const opened = await openInitialTarget(
session,
config.value,
serverLogger,
dependencies.writeStderr,
);
if (!opened.ok) return opened.exitCode;
const transport = await startMcpTransport(dependencies, session, {
logger,
serverLogger,
environment,
delivery: createToolResultDelivery(config.value.mcpMaxResponseBytes),
loadOptionalProviders:
dependencies.loadOptionalProviders ??
(() =>
loadOptionalObservationProviders(
createOptionalObservationFactories(environment),
)),
});
if (!transport.ok) return 1;
const shutdown = createShutdown({
handle: transport.handle,
closeAndroid: transport.closeAndroid,
closeOptionalProviders: transport.closeOptionalProviders,
session,
dependencies,
serverLogger,
});
dependencies.captureShutdown?.(shutdown.shutdown);
return 0;
};
+5 -2
View File
@@ -2,7 +2,6 @@ import { Help, z } from "incur";
import {
MCP_HTTP_PORT_CONSTRAINT,
mcpHttpListenerPortSchema,
mcpHttpPortSchema,
} from "../config/mcpHttpEndpoint.js";
@@ -19,7 +18,11 @@ const MCP_HTTP_OPTIONS = z.object({
.min(1)
.optional()
.describe("Listener address; default MCP_HOST, else 127.0.0.1"),
port: mcpHttpListenerPortSchema
port: z
.number()
.int()
.min(0)
.max(65535)
.optional()
.describe("Listener port; default MCP_PORT, else 0 for an ephemeral port"),
help: z.boolean().optional().describe("Show help"),
+9 -18
View File
@@ -78,30 +78,21 @@ export const createShutdown = (input: {
};
const requestShutdown = (): void => {
shutdown().catch((cause: unknown) => {
reportMcpShutdownFailure(cause, dependencies, serverLogger);
serverLogger.debug(
{ failure_cause: describeShutdownFailure(cause) },
"MCP shutdown rejected",
);
dependencies.setExitCode(1);
serverLogger.error(MCP_SHUTDOWN_FAILED);
dependencies.writeStderr(`${MCP_SHUTDOWN_FAILED}\n`);
if (cause instanceof AnalysisError)
dependencies.writeStderr(`${projectAnalysisError(cause).message}\n`);
});
};
unregisterShutdown = dependencies.registerShutdown(requestShutdown);
return { shutdown, request: requestShutdown };
};
/** Preserve the same diagnostics for eager and deferred runtime owners. */
export const reportMcpShutdownFailure = (
cause: unknown,
dependencies: Pick<RuntimeDependencies, "writeStderr" | "setExitCode">,
serverLogger: Logger,
): void => {
serverLogger.debug(
{ failure_cause: describeShutdownFailure(cause) },
"MCP shutdown rejected",
);
dependencies.setExitCode(1);
serverLogger.error(MCP_SHUTDOWN_FAILED);
dependencies.writeStderr(`${MCP_SHUTDOWN_FAILED}\n`);
if (cause instanceof AnalysisError)
dependencies.writeStderr(`${projectAnalysisError(cause).message}\n`);
};
const describeShutdownFailure = (
cause: unknown,
): Readonly<Record<string, JsonValue>> =>
+30 -23
View File
@@ -8,7 +8,6 @@ import { StreamableHttpListenError } from "../server/http/streamableHttpListenEr
import type { ToolResultDelivery } from "../server/toolResult.js";
import type { McpServerHandle, RuntimeDependencies } from "./types.js";
import type { OptionalProviderLoadResult } from "../application/OptionalObservationProviders.js";
import { OwnedMcpServers } from "./OwnedMcpServers.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import {
MCP_CONNECTION_LOST,
@@ -63,9 +62,11 @@ export const startMcpTransport = async (
);
}
const androidProviders: AndroidAnalysisPort[] = [];
const servers = new OwnedMcpServers<ReturnType<typeof createServer>>();
const servers = new Set<ReturnType<typeof createServer>>();
const closeServers = async (): Promise<void> => {
const results = await servers.closeAll();
const results = await Promise.allSettled(
[...servers].map((server) => server.close()),
);
const failures = results.flatMap((result) =>
result.status === "rejected" ? [result.reason] : [],
);
@@ -109,26 +110,32 @@ export const startMcpTransport = async (
let handle: McpServerHandle;
try {
handle = await dependencies.serve(
() =>
servers.create(() => {
// The SDK can discard a discovery probe and construct a replacement server.
const android = createAndroidAnalysisProvider(
serverContext.environment,
);
androidProviders.push(android);
const server = (dependencies.createServer ?? createServer)(
{ kind: "session", session },
{
logger: serverContext.logger,
environment: serverContext.environment,
delivery: serverContext.delivery,
...optionalProviders,
optionalObservationProviderOwner: "caller",
androidAnalysis: android,
},
);
return server;
}),
() => {
// The SDK can discard a discovery probe and construct a replacement server.
const android = createAndroidAnalysisProvider(
serverContext.environment,
);
androidProviders.push(android);
const server = (dependencies.createServer ?? createServer)(
{ kind: "session", session },
{
logger: serverContext.logger,
environment: serverContext.environment,
delivery: serverContext.delivery,
...optionalProviders,
optionalObservationProviderOwner: "caller",
androidAnalysis: android,
},
);
// The SDK can discard a server even when its provider cleanup failed.
servers.add(server);
const closeServer = server.close.bind(server);
server.close = async () => {
await closeServer();
servers.delete(server);
};
return server;
},
{
onerror: () => {
serverLogger.error(MCP_CONNECTION_LOST);
-3
View File
@@ -23,9 +23,6 @@ export type McpServe = (
) => McpServerHandle | Promise<McpServerHandle>;
export interface RuntimeDependencies {
/** HTTP keeps the eager runtime; deferred materialization is stdio-only. */
readonly transport?: "stdio" | "http";
readonly captureShutdown?: (shutdown: () => Promise<void>) => void;
readonly env: NodeJS.ProcessEnv;
readonly serve: McpServe;
readonly writeStderr: (text: string) => void;
@@ -1,240 +0,0 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { afterEach, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
type OwnedProcessGroup,
type ProcessCleanupResult,
type ProcessIdentityObservation,
type ProcessOwnershipHost,
type ProcessTableEntry,
} from "./ProcessOwnership.js";
import { ProcessOwnershipEvidenceOwner } from "./ProcessOwnershipEvidence.js";
import { ProviderProcessSupervisor } from "./ProviderProcess.js";
const JAVA = "/usr/lib/jvm/java-21-openjdk-amd64/bin/java";
const ownership = (): OwnedProcessGroup => ({
runId: "run-6134",
leaderPid: 910,
processGroupId: 910,
expectedParentPid: 17,
expectedCommand: JAVA,
sweepTokenOwnedProcesses: true,
evidenceOwner: new ProcessOwnershipEvidenceOwner(),
});
const launcherRow = (command: string): ProcessTableEntry => ({
pid: 910,
parentPid: 17,
processGroupId: 910,
state: "R",
command,
});
const nativeIdentity = (
lifecycle: "non-zombie" | "exiting",
): ProcessIdentityObservation => ({
state: "readable",
identity: "linux-starttime:4242",
lifecycle: { state: "observed", lifecycle },
relation: { state: "observed", parentPid: 17, processGroupId: 910 },
});
/** A launcher child whose exit the supervisor observes only when the test says so. */
const launcherChild = () => {
const child = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null,
signalCode: null,
kill: vi.fn(() => false),
});
let exited = false;
return {
child,
get exited() {
return exited;
},
exit() {
exited = true;
child.emit("exit", 0, null);
child.stdout.end();
child.stderr.end();
child.emit("close", 0, null);
},
};
};
/** Linux-like host: the launcher row stays listed until the child exits. */
const hostFor = (
launcher: ReturnType<typeof launcherChild>,
row: ProcessTableEntry,
lifecycle?: "non-zombie" | "exiting",
): ProcessOwnershipHost => {
const host: ProcessOwnershipHost = {
platform: "linux",
listProcesses: vi.fn(async () => (launcher.exited ? [] : [row])),
environment: vi.fn(async () => ({ REA_PROCESS_RUN_ID: "run-6134" })),
signalGroup: vi.fn(),
};
if (lifecycle === undefined) return host;
return {
...host,
processIdentities: vi.fn(async (rows: readonly ProcessTableEntry[]) => {
const observation: ProcessIdentityObservation = launcher.exited
? { state: "absent", reason: "not-found-in-caller-pid-namespace" }
: nativeIdentity(lifecycle);
return new Map(rows.map(({ pid }) => [pid, observation] as const));
}),
};
};
const supervise = (
launcher: ReturnType<typeof launcherChild>,
host: ProcessOwnershipHost,
) => {
const results: ProcessCleanupResult[] = [];
const supervisor = new ProviderProcessSupervisor({
process: launcher.child,
ownsProcessLifetime: true,
ownership: ownership(),
cleanup: async () => {
const result = await cleanupOwnedProcessGroup(ownership(), host);
results.push(result);
return result;
},
});
return { supervisor, results };
};
afterEach(() => {
vi.restoreAllMocks();
});
it("re-verifies after the launcher's own exit settles an exiting procps row", async () => {
const launcher = launcherChild();
const host = hostFor(launcher, launcherRow("[java]"));
const { supervisor, results } = supervise(launcher, host);
// The JVM finishes tearing down only after the single table refresh.
vi.mocked(host.listProcesses).mockImplementation(async () => {
if (launcher.exited) return [];
setTimeout(() => launcher.exit(), 20);
return [launcherRow("[java]")];
});
await expect(supervisor.stop()).resolves.toEqual({
status: "verified-cleanup",
});
expect(results).toEqual([
{
cleaned: false,
reason: `owned launcher command identity did not match (observed=[java]; expected=${JAVA})`,
},
{ cleaned: true, signaled: false },
]);
expect(host.signalGroup).not.toHaveBeenCalled();
expect(launcher.child.kill).not.toHaveBeenCalled();
});
it("re-verifies after native exit-in-progress outlasts the settlement deadline", async () => {
const launcher = launcherChild();
const host = hostFor(launcher, launcherRow("[java]"), "exiting");
const { supervisor, results } = supervise(launcher, host);
const exitTimer = setTimeout(() => launcher.exit(), 1_200);
try {
await expect(supervisor.stop({ killGraceMs: 2_000 })).resolves.toEqual({
status: "verified-cleanup",
});
} finally {
clearTimeout(exitTimer);
}
expect(results).toEqual([
{ cleaned: false, reason: "owned launcher exit could not be confirmed" },
{ cleaned: true, signaled: false },
]);
expect(host.signalGroup).not.toHaveBeenCalled();
});
it.each([
["identityless", undefined],
["native", "non-zombie"],
] as const)(
"keeps a still-live mismatched %s launcher incomplete without signaling",
async (_host, lifecycle) => {
const launcher = launcherChild();
const host = hostFor(launcher, launcherRow("/usr/bin/other"), lifecycle);
const { supervisor, results } = supervise(launcher, host);
const started = performance.now();
const stopped = await supervisor.stop({ killGraceMs: 50 });
expect(performance.now() - started).toBeGreaterThanOrEqual(45);
expect(stopped).toEqual({
status: "incomplete",
reason: `owned launcher command identity did not match (observed=/usr/bin/other; expected=${JAVA})`,
cleanupResult: results[0],
});
expect(results).toHaveLength(1);
expect(host.signalGroup).not.toHaveBeenCalled();
expect(launcher.child.kill).not.toHaveBeenCalled();
supervisor.dispose();
},
);
it("does not repeat verification without new launcher exit evidence", async () => {
const launcher = launcherChild();
const cleanup = vi.fn(async (): Promise<ProcessCleanupResult> => ({
cleaned: false,
reason: "process table could not be inspected: spawn EPERM",
}));
const supervisor = new ProviderProcessSupervisor({
process: launcher.child,
ownsProcessLifetime: true,
ownership: ownership(),
cleanup,
});
launcher.exit();
const started = performance.now();
await expect(supervisor.stop()).resolves.toMatchObject({
status: "incomplete",
reason: "process table could not be inspected: spawn EPERM",
});
expect(cleanup).toHaveBeenCalledOnce();
expect(performance.now() - started).toBeLessThan(500);
});
it("retains the post-exit verification failure for a later owned retry", async () => {
const launcher = launcherChild();
const outcomes: ProcessCleanupResult[] = [
{ cleaned: false, reason: "owned launcher exit could not be confirmed" },
{
cleaned: false,
reason: "process ownership could not be revalidated for PID 911: EACCES",
},
{ cleaned: true, signaled: true },
];
const cleanup = vi.fn(async (): Promise<ProcessCleanupResult> => {
const next = outcomes.shift();
if (next === undefined) throw new Error("unexpected cleanup attempt");
if (cleanup.mock.calls.length === 1) setTimeout(() => launcher.exit(), 10);
return next;
});
const supervisor = new ProviderProcessSupervisor({
process: launcher.child,
ownsProcessLifetime: true,
ownership: ownership(),
cleanup,
});
await expect(supervisor.stop()).resolves.toMatchObject({
status: "incomplete",
reason: "process ownership could not be revalidated for PID 911: EACCES",
});
expect(cleanup).toHaveBeenCalledTimes(2);
await expect(supervisor.stop()).resolves.toEqual({
status: "verified-cleanup",
});
expect(cleanup).toHaveBeenCalledTimes(3);
});
+13 -22
View File
@@ -225,14 +225,6 @@ export type ProviderProcessStopResult =
readonly cleanupResult?: ProcessCleanupFailure;
};
const incompleteCleanup = (
failure: ProcessCleanupFailure,
): ProviderProcessStopResult => ({
status: "incomplete",
reason: failure.reason,
cleanupResult: failure,
});
/**
* Spawn a provider in an owned Windows job or dedicated POSIX process group.
*
@@ -683,24 +675,23 @@ export class ProviderProcessSupervisor {
try {
if (!this.launch.ownsProcessLifetime) return { status: "not-owned" };
if (this.launch.cleanup !== undefined) {
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
const exitObservedBeforeCleanup = this.#exitObservation !== undefined;
const cleanup = await this.#ownedCleanup(options.cleanupResult);
if (!cleanup.cleaned) {
// Process tables can show the launcher mid-exit until verification
// gives up. The supervisor's own exit observation is positive proof
// that verification lacked, so verify again only after it arrives.
if (exitObservedBeforeCleanup || !(await this.waitForExit(graceMs)))
return incompleteCleanup(cleanup);
const settled = await this.launch.cleanup();
return settled.cleaned
? { status: "verified-cleanup" }
: incompleteCleanup(settled);
}
if (!cleanup.cleaned)
return {
status: "incomplete",
reason: cleanup.reason,
cleanupResult: cleanup,
};
const graceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
const retried = await this.launch.cleanup();
if (!retried.cleaned) return incompleteCleanup(retried);
if (!retried.cleaned)
return {
status: "incomplete",
reason: retried.reason,
cleanupResult: retried,
};
if (await this.waitForExit(graceMs))
return { status: "verified-cleanup" };
return {
-27
View File
@@ -1,27 +0,0 @@
import type {
Implementation,
Prompt,
ServerCapabilities,
Tool,
} from "@modelcontextprotocol/server";
import type { createCatalogIdentity } from "./catalogIdentity.js";
import type { PromptArgumentContract } from "./contracts/promptContracts.js";
import type { McpInputSchemaProfile } from "./config/mcpInputSchemaProfile.js";
/** Build-owned discovery data; canonical validators remain the runtime authority. */
export interface RecordedMcpCatalog {
readonly version: 1;
readonly info: Implementation;
readonly capabilities: ServerCapabilities;
readonly instructions: string;
readonly identity: ReturnType<typeof createCatalogIdentity>;
readonly tools: readonly Tool[];
readonly prompts: readonly (Prompt & {
readonly parameters: Readonly<Record<string, PromptArgumentContract>>;
})[];
}
/** Replaced after compilation by the recorder; source runs use eager composition. */
export const RECORDED_MCP_CATALOG_SHA256:
| Readonly<Record<McpInputSchemaProfile, string>>
| undefined = undefined;
+7 -2
View File
@@ -19,7 +19,6 @@ import {
noFollowOpenSupported,
prepareRoot,
} from "./ReferenceSourceReaderValidate.js";
import { referenceSourceResourceFailure } from "./ReferenceSourceReaderErrors.js";
const PATH_RACE_LIMITATION =
"Path identity is revalidated around operations; Node lacks portable descriptor-relative openat traversal, so a syscall-boundary pathname race remains.";
@@ -34,7 +33,13 @@ export const readReferenceSource = async (
return await resources.run(() => readSource(root, resources, options));
} catch (cause: unknown) {
if (!(cause instanceof ArtifactReaderFailure)) throw cause;
return err(referenceSourceResourceFailure(cause));
return err({
tag: "reference-source-reader",
code: cause.reason === "cancelled" ? "cancelled" : "io",
message: cause.message,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
}
};
@@ -1,4 +1,3 @@
import type { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type {
ReferenceSourceEntry,
ReferenceSourceFailureCode,
@@ -17,17 +16,6 @@ export const failure = (
export const cancelled = (): ReferenceSourceReaderError =>
failure("cancelled", "Reference source traversal cancelled");
/** Project resource failures into the reference-source error contract. */
export const referenceSourceResourceFailure = (
cause: ArtifactReaderFailure,
): ReferenceSourceReaderError => ({
tag: "reference-source-reader",
code: cause.reason === "cancelled" ? "cancelled" : "io",
message: cause.message,
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
cause,
});
export const safeSize = (size: bigint): number | undefined => {
const value = Number(size);
return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
@@ -1,343 +0,0 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { Tool, ServerContext } from "@modelcontextprotocol/server";
import { afterEach, expect, it, vi } from "vitest";
import { z } from "zod";
import type { RecordedMcpCatalog } from "../recordedMcpCatalog.js";
import { DeferredEvidenceMcpServer } from "./DeferredEvidenceMcpServer.js";
import { ToolResultDelivery } from "./ToolResultDelivery.js";
import { promptArgumentsSchema } from "./promptArguments.js";
const barrier = () => {
let release!: () => void;
const promise = new Promise<void>((resolve) => {
release = resolve;
});
return { promise, release };
};
const input = z.strictObject({ n: z.number().int().nonnegative().default(3) });
const output = z.strictObject({ n: z.number().int() });
const parameters = {
document: {
description: "Document name",
required: true,
completion: "document" as const,
},
};
const catalog: RecordedMcpCatalog = {
version: 1,
info: { name: "deferred-fixture", version: "1" },
instructions: "Fixture",
capabilities: {
tools: { listChanged: true },
prompts: { listChanged: true },
completions: {},
},
identity: {
counts: { cli_commands: 0, mcp_tools: 1, mcp_prompts: 1 },
digests: {
tools_sha256: "fixture",
prompts_sha256: "fixture",
combined_sha256: "fixture",
},
},
tools: [
{
name: "fixture",
inputSchema: z.toJSONSchema(input, {
io: "input",
}) as Tool["inputSchema"],
outputSchema: z.toJSONSchema(output),
},
],
prompts: [
{
name: "explain",
title: "Explain",
description: "Explain a document",
arguments: [
{ name: "document", description: "Document name", required: true },
],
parameters,
},
],
};
const cleanups: Array<() => Promise<unknown>> = [];
afterEach(async () => {
while (cleanups.length > 0) await cleanups.pop()?.();
});
const fixture = async (
options: {
readonly hold?: ReturnType<typeof barrier>;
readonly failClose?: () => boolean;
readonly failLoad?: boolean;
readonly invalidOutput?: boolean;
readonly failAfterTool?: boolean;
} = {},
) => {
const started = barrier();
const calls = vi.fn<(n: number, context: ServerContext) => void>();
const closed = vi.fn();
let loads = 0;
const server = new DeferredEvidenceMcpServer(
catalog,
new ToolResultDelivery(1024 * 1024),
async (target) => {
loads++;
target.ownRuntimeCleanup(async () => {
closed();
if (options.failClose?.()) throw new Error("cleanup denied");
await target.closePartialRuntime();
});
started.release();
await options.hold?.promise;
if (options.failLoad) throw new Error("PRIVATE startup cause");
target.materialize(() => {
target.registerTool(
"fixture",
{ inputSchema: input, outputSchema: output },
async (args, context) => {
calls(args.n, context);
return {
content: [],
structuredContent: {
n: options.invalidOutput ? "invalid" : args.n,
},
};
},
);
if (options.failAfterTool)
throw new Error("PRIVATE partial startup failure");
const completion = target.bindPromptCompletion({
complete: async () => ["Example"],
});
target.registerCanonicalPrompt(
"explain",
{
title: "Explain",
description: "Explain a document",
argsSchema: promptArgumentsSchema(
{ arguments: parameters },
completion,
),
},
async (args) => ({
messages: [
{
role: "user",
content: { type: "text", text: String(args.document) },
},
],
}),
);
});
},
);
const client = new Client({ name: "deferred-fixture-client", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
cleanups.push(async () => {
await client.close();
await server.close();
});
return {
server,
client,
serverTransport,
started,
calls,
closed,
loads: () => loads,
};
};
it("discovers without initialization, then shares one canonical runtime and preserves request metadata", async () => {
const hold = barrier();
const f = await fixture({ hold });
const before = await f.client.listTools();
expect(before.tools).toEqual(catalog.tools);
expect((await f.client.listPrompts()).prompts).toEqual(
catalog.prompts.map(({ parameters: _parameters, ...prompt }) => prompt),
);
expect(f.loads()).toBe(0);
const changed = vi.fn();
f.client.setNotificationHandler("notifications/tools/list_changed", changed);
const a = f.client.callTool({
name: "fixture",
arguments: {},
_meta: { caller: "retained" },
});
await f.started.promise;
const b = f.client.callTool({ name: "fixture", arguments: { n: 7 } });
hold.release();
expect((await a).structuredContent).toEqual({ n: 3 });
expect((await b).structuredContent).toEqual({ n: 7 });
expect(f.loads()).toBe(1);
expect(f.calls.mock.calls[0]?.[1].mcpReq._meta?.caller).toBe("retained");
expect(await f.client.listTools()).toEqual(before);
expect(changed).not.toHaveBeenCalled();
const invalid = await f.client.callTool({
name: "fixture",
arguments: { n: 1.5 },
});
expect(invalid.isError).toBe(true);
expect(f.calls).toHaveBeenCalledTimes(2);
});
it("preserves output validation after deferred registration", async () => {
const f = await fixture({ invalidOutput: true });
const result = await f.client.callTool({ name: "fixture", arguments: {} });
expect(result.isError).toBe(true);
});
it("initializes through prompt retrieval or completion without an internal client", async () => {
const f = await fixture();
expect(
(
await f.client.complete({
ref: { type: "ref/prompt", name: "explain" },
argument: { name: "document", value: "Ex" },
})
).completion.values,
).toEqual(["Example"]);
expect(
(
await f.client.getPrompt({
name: "explain",
arguments: { document: "Example" },
})
).messages[0]?.content,
).toEqual({ type: "text", text: "Example" });
expect(f.loads()).toBe(1);
});
it("retrieves a prompt as the first operation", async () => {
const f = await fixture();
const result = await f.client.getPrompt({
name: "explain",
arguments: { document: "Example" },
});
expect(result.messages).toHaveLength(1);
expect(f.loads()).toBe(1);
});
it("does not execute a tool cancelled while canonical loading is pending", async () => {
const hold = barrier();
const f = await fixture({ hold });
const cancelled = barrier();
const previous = f.serverTransport.onmessage;
f.serverTransport.onmessage = (message, extra) => {
previous?.(message, extra);
if ("method" in message && message.method === "notifications/cancelled")
cancelled.release();
};
const controller = new AbortController();
const pending = f.client.callTool(
{ name: "fixture", arguments: {} },
{ signal: controller.signal },
);
const rejected = expect(pending).rejects.toBeDefined();
await f.started.promise;
controller.abort();
await cancelled.promise;
hold.release();
await rejected;
await f.server.ensureRuntime();
expect(f.calls).not.toHaveBeenCalled();
expect(
(await f.client.callTool({ name: "fixture", arguments: {} })).isError,
).not.toBe(true);
});
it("keeps an independent caller alive when its peer cancels during shared loading", async () => {
const hold = barrier();
const f = await fixture({ hold });
const secondRequest = barrier();
const cancelled = barrier();
let toolCalls = 0;
const previous = f.serverTransport.onmessage;
f.serverTransport.onmessage = (message, extra) => {
previous?.(message, extra);
if (
"method" in message &&
message.method === "tools/call" &&
++toolCalls === 2
)
secondRequest.release();
if ("method" in message && message.method === "notifications/cancelled")
cancelled.release();
};
const controller = new AbortController();
const a = f.client
.callTool({ name: "fixture", arguments: {} }, { signal: controller.signal })
.catch(() => undefined);
await f.started.promise;
const b = f.client.callTool({ name: "fixture", arguments: { n: 8 } });
await secondRequest.promise;
controller.abort();
await cancelled.promise;
hold.release();
await a;
expect((await b).structuredContent).toEqual({ n: 8 });
expect(f.calls).toHaveBeenCalledTimes(1);
expect(f.loads()).toBe(1);
});
it("joins late initialization during close and prevents target execution", async () => {
const hold = barrier();
const f = await fixture({ hold });
const pending = f.client
.callTool({ name: "fixture", arguments: {} })
.catch(() => undefined);
await f.started.promise;
const closing = f.server.close();
hold.release();
await closing;
await pending;
expect(f.calls).not.toHaveBeenCalled();
expect(f.closed).toHaveBeenCalledTimes(1);
await expect(f.server.ensureRuntime()).rejects.toThrow("closed");
});
it("retains failed cleanup for retry without loading a replacement runtime", async () => {
let denied = true;
const f = await fixture({ failClose: () => denied });
await f.client.callTool({ name: "fixture", arguments: {} });
await expect(f.server.close()).rejects.toThrow("cleanup");
await expect(f.server.ensureRuntime()).rejects.toThrow("closed");
denied = false;
await f.server.close();
expect(f.closed).toHaveBeenCalledTimes(2);
expect(f.loads()).toBe(1);
});
it("keeps startup failures redacted and owns partial cleanup", async () => {
const f = await fixture({ failLoad: true });
const result = await f.client.callTool({ name: "fixture", arguments: {} });
expect(result.isError).toBe(true);
expect(JSON.stringify(result)).not.toContain("PRIVATE");
await f.server.close();
expect(f.closed).toHaveBeenCalledTimes(1);
});
it("closes an unused instance without constructing the runtime", async () => {
const f = await fixture();
await f.client.listTools();
await f.server.close();
expect(f.loads()).toBe(0);
expect(f.closed).not.toHaveBeenCalled();
});
it("never executes a partially registered handler after initialization fails", async () => {
const f = await fixture({ failAfterTool: true });
const first = await f.client.callTool({ name: "fixture", arguments: {} });
const retry = await f.client.callTool({ name: "fixture", arguments: {} });
expect(first.isError).toBe(true);
expect(retry.isError).toBe(true);
expect(f.calls).not.toHaveBeenCalled();
expect(f.loads()).toBe(1);
await f.server.close();
expect(f.closed).toHaveBeenCalledTimes(1);
});
-321
View File
@@ -1,321 +0,0 @@
import type {
RegisteredTool,
RegisteredPrompt,
StandardSchemaWithJSON,
ToolCallback,
PromptCallback,
} from "@modelcontextprotocol/server";
import type { PromptCompletionSource } from "./promptCompletion.js";
import type { RecordedMcpCatalog } from "../recordedMcpCatalog.js";
import type { ToolResultDelivery } from "./toolResult.js";
import {
EvidenceMcpServerCore,
currentMcpRequestSignal,
type StandardToolRegistration,
} from "./EvidenceMcpServerCore.js";
import { promptArgumentsSchema } from "./promptArguments.js";
import { SERVER_START_FAILED } from "../main/messages.js";
type ToolConfig = StandardToolRegistration;
type InputCallback = ToolCallback<StandardSchemaWithJSON>;
interface DeferredTool {
readonly registered: RegisteredTool;
readonly input: Record<string, unknown>;
readonly output: Record<string, unknown> | undefined;
callback?: InputCallback;
}
interface DeferredPrompt {
readonly registered: RegisteredPrompt;
callback?: PromptCallback<StandardSchemaWithJSON>;
}
/** Borrow the build-owned wire projection while retaining the canonical parser. */
const recordedProjection = (
schema: StandardSchemaWithJSON,
projection: Record<string, unknown>,
): StandardSchemaWithJSON => ({
"~standard": {
...schema["~standard"],
jsonSchema: { input: () => projection, output: () => projection },
},
});
/** One SDK server, with async canonical validation installed on first use. */
export class DeferredEvidenceMcpServer extends EvidenceMcpServerCore {
private readonly tools = new Map<string, DeferredTool>();
private readonly prompts = new Map<string, DeferredPrompt>();
private loading: Promise<void> | undefined;
private closing = false;
private closeAttempt: Promise<void> | undefined;
private protocolClosed = false;
private runtimeClosed = false;
private runtimeCleanup: (() => Promise<void>) | undefined;
private partialClose: (() => Promise<void>) | undefined;
private materializing = false;
private readonly protocolClose = () => super.close();
constructor(
catalog: RecordedMcpCatalog,
delivery: ToolResultDelivery,
private readonly initialize: (
server: DeferredEvidenceMcpServer,
) => Promise<void>,
) {
super(
catalog.info,
{
capabilities: catalog.capabilities,
instructions: catalog.instructions,
},
undefined,
delivery,
undefined,
false,
catalog.identity,
);
for (const tool of catalog.tools) {
const { name, inputSchema, outputSchema, ...metadata } = tool;
let binding: DeferredTool;
const input: StandardSchemaWithJSON = {
"~standard": {
version: 1,
vendor: "rea",
jsonSchema: { input: () => inputSchema, output: () => inputSchema },
validate: async (value) => {
await this.ensureRuntime();
const canonical = binding.registered.inputSchema;
if (canonical === undefined || canonical === input)
throw new Error(SERVER_START_FAILED);
return canonical["~standard"].validate(value);
},
},
};
const output: StandardSchemaWithJSON | undefined =
outputSchema === undefined
? undefined
: {
"~standard": {
version: 1,
vendor: "rea",
jsonSchema: {
input: () => outputSchema,
output: () => outputSchema,
},
validate: async (value) => {
await this.ensureRuntime();
const canonical = binding.registered.outputSchema;
if (canonical === undefined || canonical === output)
throw new Error(SERVER_START_FAILED);
return canonical["~standard"].validate(value);
},
},
};
const registered = super.bindTool(
name,
{
...metadata,
inputSchema: input,
...(output === undefined ? {} : { outputSchema: output }),
} as StandardToolRegistration,
(async (args, ctx) => {
await this.ensureRuntime();
ctx.mcpReq.signal.throwIfAborted();
if (binding.callback === undefined)
throw new Error(SERVER_START_FAILED);
return binding.callback(args, ctx);
}) as InputCallback,
);
binding = { registered, input: inputSchema, output: outputSchema };
this.tools.set(name, binding);
}
const completion = {
complete: async (
...args: Parameters<
NonNullable<typeof this.promptCompletion>["complete"]
>
) => {
await this.ensureRuntime();
currentMcpRequestSignal()?.throwIfAborted();
if (this.promptCompletion === undefined)
throw new Error(SERVER_START_FAILED);
return this.promptCompletion.complete(...args);
},
};
for (const prompt of catalog.prompts) {
const { name, parameters, title, description } = prompt;
let binding: DeferredPrompt;
const argsSchema = promptArgumentsSchema(
{ arguments: parameters },
completion,
);
const registered = super.registerCanonicalPrompt(
name,
{
...(title === undefined ? {} : { title }),
...(description === undefined ? {} : { description }),
argsSchema,
},
async (args, ctx) => {
await this.ensureRuntime();
ctx.mcpReq.signal.throwIfAborted();
if (binding.callback === undefined)
throw new Error(SERVER_START_FAILED);
return binding.callback(args, ctx);
},
);
binding = { registered };
this.prompts.set(name, binding);
}
}
ensureRuntime(): Promise<void> {
if (this.closing)
return Promise.reject(new Error("MCP connection is closed"));
this.loading ??= Promise.resolve()
.then(() => this.initialize(this))
.catch(() => {
throw new Error(SERVER_START_FAILED);
});
return this.loading;
}
/** Register an awaitable cleanup capability before runtime startup can fail. */
ownRuntimeCleanup(close: () => Promise<void>): void {
this.runtimeCleanup = close;
}
/** Canonical composition may wrap close; retain that exact cleanup capability. */
materialize(build: () => void): void {
const ownedClose = this.close.bind(this);
this.materializing = true;
this.close = this.protocolClose;
try {
build();
if (this.tools.size !== 0 || this.prompts.size !== 0)
throw new Error("MCP catalog does not match runtime registrations");
} finally {
this.partialClose = this.close.bind(this);
this.close = ownedClose;
this.materializing = false;
}
}
closePartialRuntime(): Promise<void> {
return this.partialClose?.() ?? Promise.resolve();
}
protected override bindTool(
name: string,
config: ToolConfig,
callback: ToolCallback<StandardSchemaWithJSON | undefined>,
): RegisteredTool {
const binding = this.tools.get(name);
if (
!this.materializing ||
binding === undefined ||
config.inputSchema === undefined ||
(config.outputSchema === undefined) !== (binding.output === undefined)
)
throw new Error("Unexpected MCP runtime registration");
const canonical = callback as InputCallback;
const guarded: InputCallback = async (args, ctx) => {
ctx.mcpReq.signal.throwIfAborted();
await this.ensureRuntime();
ctx.mcpReq.signal.throwIfAborted();
return canonical(args, ctx);
};
binding.callback = guarded;
const { inputSchema: _input, outputSchema: _output, ...metadata } = config;
binding.registered.update({
...metadata,
paramsSchema: recordedProjection(config.inputSchema, binding.input),
...(config.outputSchema === undefined || binding.output === undefined
? {}
: {
outputSchema: recordedProjection(
config.outputSchema,
binding.output,
),
}),
callback: guarded,
});
this.tools.delete(name);
return binding.registered;
}
override registerCanonicalPrompt<Args extends StandardSchemaWithJSON>(
name: string,
config: { title?: string; description?: string; argsSchema: Args },
callback: PromptCallback<Args>,
): RegisteredPrompt {
const binding = this.prompts.get(name);
if (!this.materializing || binding === undefined)
throw new Error("Unexpected MCP runtime prompt");
const canonical = callback as PromptCallback<StandardSchemaWithJSON>;
binding.callback = async (args, ctx) => {
ctx.mcpReq.signal.throwIfAborted();
await this.ensureRuntime();
ctx.mcpReq.signal.throwIfAborted();
return canonical(args, ctx);
};
binding.registered.update<StandardSchemaWithJSON>({
...config,
callback: binding.callback,
});
this.prompts.delete(name);
return binding.registered;
}
override bindPromptCompletion(
completion: PromptCompletionSource,
): PromptCompletionSource {
return super.bindPromptCompletion({
complete: async (...args) => {
await this.ensureRuntime();
currentMcpRequestSignal()?.throwIfAborted();
return completion.complete(...args);
},
});
}
override sendToolListChanged(): void {
if (!this.materializing) super.sendToolListChanged();
}
override sendPromptListChanged(): void {
if (!this.materializing) super.sendPromptListChanged();
}
override close(): Promise<void> {
this.closing = true;
this.closeAttempt ??= Promise.resolve()
.then(() => this.finishClose())
.catch((cause) => {
this.closeAttempt = undefined;
throw cause;
});
return this.closeAttempt;
}
private async finishClose(): Promise<void> {
const errors: unknown[] = [];
if (!this.protocolClosed) {
try {
await this.protocolClose();
this.protocolClosed = true;
} catch (cause) {
errors.push(cause);
}
}
await this.loading?.catch(() => undefined);
if (!this.runtimeClosed && this.runtimeCleanup !== undefined) {
try {
await this.runtimeCleanup();
this.runtimeClosed = true;
} catch (cause) {
errors.push(cause);
}
}
if (errors.length > 0)
throw new AggregateError(errors, "MCP runtime cleanup failed");
}
}
+627 -32
View File
@@ -1,48 +1,643 @@
import type {
Implementation,
McpServerOptions,
import { AsyncLocalStorage } from "node:async_hooks";
import {
isCallToolResult,
isJSONRPCErrorResponse,
isJSONRPCRequest,
isJSONRPCNotification,
isJSONRPCResultResponse,
type CallToolResult,
type Implementation,
type Icon,
type JSONRPCMessage,
type McpServerOptions,
type RegisteredTool,
type RequestId,
type ScopeChallengeHandler,
type StandardSchemaWithJSON,
type ToolAnnotations,
type ToolCallback,
type Transport,
type TransportSendOptions,
} from "@modelcontextprotocol/server";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import {
presentAdvertisedInputSchema,
type CompactInputSchemaPresentation,
} from "../contracts/compactInputSchema.js";
import {
FULL_CATALOG_IDENTITY,
createCatalogIdentity,
} from "../catalogIdentity.js";
import type { ToolResultDelivery } from "./toolResult.js";
import { transformAdvertisedInputJsonSchema } from "../contracts/toolSchemaMetadata.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
EvidenceMcpServerCore,
type CompactInputSchemaPresentation,
} from "./EvidenceMcpServerCore.js";
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import {
mcpResponseOverflowProjection,
type ToolResultDelivery,
} from "./toolResult.js";
import { toolReturnsTargetContent } from "../contracts/toolEffects.js";
import {
carriesTargetContentMarker,
encodeToolResult,
measureMcpResultWithinBudget,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";
import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js";
export {
forgetPendingMcpRequest,
type CompactInputSchemaPresentation,
} from "./EvidenceMcpServerCore.js";
export type { CompactInputSchemaPresentation } from "../contracts/compactInputSchema.js";
const currentRequestSignal = new AsyncLocalStorage<AbortSignal>();
/** Signal for the completion request currently being dispatched by the SDK. */
export const currentMcpRequestSignal = (): AbortSignal | undefined =>
currentRequestSignal.getStore();
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
const standard = Reflect.get(value, "~standard");
if (typeof standard !== "object" || standard === null) return false;
const jsonSchema = Reflect.get(standard, "jsonSchema");
return (
typeof jsonSchema === "object" &&
jsonSchema !== null &&
Reflect.get(jsonSchema, "input") !== undefined
);
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Recognize the SDK's argument diagnostic after its wire size is checked. */
const sdkInputValidationDiagnostic = (
text: string | undefined,
tool: string | undefined,
): string | undefined => {
if (text === undefined || tool === undefined) return undefined;
const prefix = `Input validation error: Invalid arguments for tool ${tool}`;
if (!text.startsWith(prefix) || text[prefix.length] !== ":") return undefined;
const diagnostic = text.slice(prefix.length + 1).trimStart();
return diagnostic.length === 0 ? undefined : diagnostic;
};
/** Replace the tool payload after the SDK codec while retaining its envelope. */
const replaceToolResultPayload = (
original: CallToolResult,
replacement: CallToolResult,
): CallToolResult => {
const {
content: _content,
structuredContent: _structuredContent,
isError: _isError,
_meta,
...envelope
} = original;
return {
...envelope,
...replacement,
...(_meta === undefined && replacement._meta === undefined
? {}
: { _meta: { ..._meta, ...replacement._meta } }),
};
};
/** Remove only client-facing output schemas; SDK registrations stay canonical. */
const omitOutputSchemasFromToolsList = (
message: JSONRPCMessage,
requestId: RequestId,
): JSONRPCMessage => {
if (
!isJSONRPCResultResponse(message) ||
message.id !== requestId ||
!isRecord(message.result) ||
!Array.isArray(message.result.tools)
)
return message;
return {
...message,
result: {
...message.result,
tools: message.result.tools.map((tool: unknown) => {
if (!isRecord(tool)) return tool;
const { outputSchema: _outputSchema, ...advertisedTool } = tool;
return advertisedTool;
}),
},
} as JSONRPCMessage;
};
/** Release every transport-owned reference for a cancelled/completed request. */
export const forgetPendingMcpRequest = (
pendingTools: Map<RequestId, string>,
pendingToolLists: Set<RequestId>,
pendingCompletions: Map<RequestId, AbortController>,
id: RequestId,
): void => {
pendingTools.delete(id);
pendingToolLists.delete(id);
pendingCompletions.get(id)?.abort();
pendingCompletions.delete(id);
};
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServer extends RequestTrackingMcpServer {
readonly catalogIdentity: ReturnType<typeof createCatalogIdentity>;
private readonly compactPresentation:
| CompactInputSchemaPresentation
| undefined;
/** Canonical composition retains the constructor's existing identity defaults. */
export class EvidenceMcpServer extends EvidenceMcpServerCore {
constructor(
info: Implementation,
options: McpServerOptions,
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
delivery: ToolResultDelivery,
private readonly recordEvidence:
| EvidenceWriter["recordEvidence"]
| undefined,
readonly delivery: ToolResultDelivery,
compactPresentation: CompactInputSchemaPresentation | undefined = undefined,
omitOutputSchemas = false,
identity?: ReturnType<typeof createCatalogIdentity>,
private readonly omitOutputSchemas = false,
) {
super(
info,
options,
recordEvidence,
delivery,
compactPresentation,
omitOutputSchemas,
identity ??
(compactPresentation === undefined && !omitOutputSchemas
? FULL_CATALOG_IDENTITY
: createCatalogIdentity(
compactPresentation,
omitOutputSchemas ? "off" : "full",
)),
super(info, options);
this.compactPresentation =
compactPresentation === undefined
? undefined
: { budgetBytes: compactPresentation.budgetBytes };
this.catalogIdentity =
this.compactPresentation === undefined && !this.omitOutputSchemas
? FULL_CATALOG_IDENTITY
: createCatalogIdentity(
this.compactPresentation,
this.omitOutputSchemas ? "off" : "full",
);
}
/**
* Compact advertised input schemas and optionally omit output-schema
* advertisements. Canonical parsers and contracts remain registered; the
* output-schema-off path validates successful structured results locally.
* The signatures mirror the SDK's registrations so call sites keep their
* inferred handler argument types.
*/
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
const budget = this.compactPresentation?.budgetBytes;
const inputSchema =
budget !== undefined &&
config !== undefined &&
hasAdvertisedInputJsonSchema(config.inputSchema)
? transformAdvertisedInputJsonSchema(
config.inputSchema as Parameters<
typeof transformAdvertisedInputJsonSchema
>[0],
(projected) =>
presentAdvertisedInputSchema(projected, { budgetBytes: budget }),
)
: undefined;
const registeredConfig =
inputSchema === undefined ? config : { ...config, inputSchema };
return super.registerTool(
name,
registeredConfig as never,
callback as never,
);
}
/** Preserve the SDK transport lifecycle while retaining oversized errors. */
override connect(transport: Transport): Promise<void> {
return super.connect(
new ErrorEvidenceTransport(
transport,
this.recordEvidence,
this.delivery,
this.omitOutputSchemas,
),
);
}
}
class ErrorEvidenceTransport implements Transport {
onclose: Transport["onclose"];
onerror: Transport["onerror"];
onmessage: Transport["onmessage"];
readonly hasPerRequestStream?: boolean;
private readonly pendingTools = new Map<RequestId, string>();
private readonly pendingToolLists = new Set<RequestId>();
private readonly pendingCompletions = new Map<RequestId, AbortController>();
constructor(
private readonly transport: Transport,
private readonly recordEvidence:
| EvidenceWriter["recordEvidence"]
| undefined,
private readonly delivery: ToolResultDelivery,
private readonly omitOutputSchemas: boolean,
) {
if (transport.hasPerRequestStream !== undefined)
this.hasPerRequestStream = transport.hasPerRequestStream;
transport.onmessage = (message, extra) => {
if (
isJSONRPCRequest(message) &&
message.method === "tools/call" &&
typeof message.params?.["name"] === "string"
)
this.pendingTools.set(message.id, message.params["name"]);
if (isJSONRPCRequest(message) && message.method === "tools/list")
this.pendingToolLists.add(message.id);
if (isJSONRPCRequest(message) && message.method === "completion/complete")
this.pendingCompletions.set(message.id, new AbortController());
// The SDK suppresses replies after cancellation, so send() cannot release
// this bookkeeping. Keep transport authentication outside retained data.
if (
isJSONRPCNotification(message) &&
message.method === "notifications/cancelled"
) {
const id = message.params?.["requestId"];
if (typeof id === "string" || typeof id === "number")
forgetPendingMcpRequest(
this.pendingTools,
this.pendingToolLists,
this.pendingCompletions,
id,
);
}
const completion =
isJSONRPCRequest(message) && message.method === "completion/complete"
? this.pendingCompletions.get(message.id)
: undefined;
if (completion === undefined) this.onmessage?.(message, extra);
else
currentRequestSignal.run(completion.signal, () =>
this.onmessage?.(message, extra),
);
};
transport.onerror = (error) => this.onerror?.(error);
transport.onclose = () => {
this.pendingTools.clear();
this.pendingToolLists.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
this.onclose?.();
};
}
get sessionId(): string | undefined {
return this.transport.sessionId;
}
set sessionId(value: string | undefined) {
this.transport.sessionId = value;
}
start(): Promise<void> {
return this.transport.start();
}
async close(): Promise<void> {
try {
await this.transport.close();
} finally {
this.pendingTools.clear();
this.pendingToolLists.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
}
}
setProtocolVersion(version: string): void {
this.transport.setProtocolVersion?.(version);
}
setSupportedProtocolVersions(versions: string[]): void {
this.transport.setSupportedProtocolVersions?.(versions);
}
async send(
message: JSONRPCMessage,
options?: TransportSendOptions,
): Promise<void> {
const id =
"id" in message &&
(typeof message.id === "string" || typeof message.id === "number")
? message.id
: undefined;
const tool = id === undefined ? undefined : this.pendingTools.get(id);
const omitToolSchemas =
this.omitOutputSchemas &&
id !== undefined &&
this.pendingToolLists.has(id);
try {
const recovered = this.recoverProtocolError(message, tool);
const advertised = omitToolSchemas
? omitOutputSchemasFromToolsList(recovered, id)
: recovered;
if (
isJSONRPCResultResponse(advertised) &&
isCallToolResult(advertised.result) &&
advertised.result.isError === true
) {
// Keep the complete typed JSON in content. Error projections are not
// success outputSchema data; oversized recovery must consume their
// private structured carrier before it is removed from the wire.
const { structuredContent: _diagnostic, ...result } = advertised.result;
// Errors the SDK builds itself (input validation, a thrown handler)
// bypass ToolResultDelivery; mark them for target-content tools too.
const marked =
tool !== undefined &&
toolReturnsTargetContent(tool) &&
!carriesTargetContentMarker(result)
? {
...result,
_meta: { ...result._meta, ...TARGET_CONTENT_RESULT_META },
}
: result;
await this.transport.send({ ...advertised, result: marked }, options);
} else await this.transport.send(advertised, options);
} finally {
if (!isJSONRPCRequest(message) && id !== undefined) {
forgetPendingMcpRequest(
this.pendingTools,
this.pendingToolLists,
this.pendingCompletions,
id,
);
}
}
}
private recoverError(
message: JSONRPCMessage,
tool: string | undefined,
): JSONRPCMessage {
if (
!isJSONRPCResultResponse(message) ||
!isCallToolResult(message.result) ||
message.result.isError !== true
)
return message;
const budget = this.delivery.resultBudgetBytes;
// Count the provenance marker exactly as the projected error did, and keep
// it on the replacement: the retained original may hold target content.
const targetContent =
carriesTargetContentMarker(message.result) ||
(tool !== undefined && toolReturnsTargetContent(tool));
// SDK validation failures have no structured carrier. Size their existing
// text-only result without serializing the complete JSON-RPC message.
const isStructured = message.result.structuredContent !== undefined;
const structured = isStructured
? jsonObjectSchema.parse(message.result.structuredContent)
: undefined;
const sdkResultWithMarker =
!isStructured &&
targetContent &&
!carriesTargetContentMarker(message.result)
? {
...message.result,
_meta: {
...message.result._meta,
...TARGET_CONTENT_RESULT_META,
},
}
: message.result;
const sdkDiagnostic = !isStructured
? message.result.content.find((item) => item.type === "text")?.text
: undefined;
let encoded =
structured !== undefined
? encodeToolResult(structured, budget, "error-text", targetContent)
: measureMcpResultWithinBudget(sdkResultWithMarker, budget);
const normalized = encoded.ok
? this.normalizeSdkValidationError(
message,
tool,
targetContent,
sdkInputValidationDiagnostic(sdkDiagnostic, tool),
)
: undefined;
if (
normalized !== undefined &&
isJSONRPCResultResponse(normalized) &&
isCallToolResult(normalized.result)
) {
// The structured diagnostic is a private carrier removed before sending.
// Measure the actual wire result, including its preserved SDK metadata.
const { structuredContent, ...wireResult } = normalized.result;
encoded =
normalized.result.content.length === 0
? encodeToolResult(
jsonObjectSchema.parse(structuredContent),
budget,
"error-text",
targetContent,
)
: measureMcpResultWithinBudget(wireResult, budget);
if (encoded.ok) return normalized;
// JSON escaping and recovery fields can exceed the budget even when
// the original SDK result fits. Retain that original before replacing it.
}
if (encoded.ok) return message;
const operation = tool ?? "mcp_tool_error";
const originalResult = jsonObjectSchema.parse(message.result);
const retainedResult = structured ?? originalResult;
const originalError = isStructured
? analysisErrorProjectionSchema.safeParse(structured?.["error"])
: undefined;
// Retain the complete original response, including SDK validation text.
// The SDK error contains its rendered issue, not a separate argument bag;
// transport authentication and caller arguments are never added here.
const evidence = createEvidence(
undefined,
{ id: "rea-mcp", name: "REA MCP delivery", version: "1" },
{
operation: "mcp_tool_error",
parameters: { tool_name: operation },
result:
sdkDiagnostic === undefined
? retainedResult
: {
boundary: "sdk-input-validation",
diagnostic_preview: sdkDiagnostic.slice(0, 256),
diagnostic_truncated: sdkDiagnostic.length > 256,
},
rawResult: originalResult,
},
);
const recorded = this.recordEvidence?.(evidence);
const retained = recorded !== undefined && recorded.ok;
const projected = mcpResponseOverflowProjection({
completed: false,
constraint: encoded.constraint,
effectiveResponseBytes: this.delivery.maximumResponseBytes,
nextStep: retained
? "Export the retained original error through export_evidence_bundle to a caller-selected path. The connection remains usable."
: encoded.constraint === "string-length"
? "The original error could not be retained by this server. Use complete CLI JSON output when the analysis completed. Repeating the unchanged MCP call fails the same way."
: "The original error could not be retained by this server. Restart REA with a larger REA_MCP_MAX_RESPONSE_BYTES and a matching client receive buffer, then retry.",
});
const replacement = this.transportConstraintResult(
operation,
projected.reason,
projected.remediationAction,
{
boundary: "mcp-response",
...(originalError?.success
? { original_error_code: originalError.data.code }
: {}),
result_budget_bytes: budget,
response_bytes_at_least: encoded.bytesAtLeast,
constraint: encoded.constraint,
...(sdkDiagnostic === undefined
? {}
: {
diagnostic_preview: sdkDiagnostic.slice(0, 256),
diagnostic_truncated: sdkDiagnostic.length > 256,
}),
...(retained
? {
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
}
: { retention: recorded === undefined ? "unavailable" : "failed" }),
...(recorded !== undefined && !recorded.ok
? { retention_error: projectAnalysisError(recorded.error) }
: {}),
},
targetContent,
);
return {
...message,
result: replaceToolResultPayload(message.result, replacement),
};
}
/**
* Encode a transport-constraint error inside the MCP text budget.
* The complete SDK diagnostic stays in retained Evidence. Its character
* preview can still expand past the budget when quotes and backslashes are
* escaped into that text, so shorten only the preview and keep the reference.
*/
private transportConstraintResult(
operation: string,
reason: string,
remediationAction: string,
limits: Readonly<Record<string, JsonValue>>,
targetContent: boolean,
): CallToolResult {
const deliver = (
reportedLimits: Readonly<Record<string, JsonValue>>,
): CallToolResult =>
this.delivery.toErrorToolResult(
new AnalysisResourceConstraintError(
operation,
"transport",
reason,
reportedLimits,
{ remediationAction },
),
targetContent,
);
const delivered = deliver(limits);
const preview = limits.diagnostic_preview;
if (delivered.content.length > 0 || typeof preview !== "string")
return delivered;
let low = 0;
let high = preview.length - 1;
let fitted: CallToolResult | undefined;
let fittedLength = -1;
while (low <= high) {
const length = Math.floor((low + high) / 2);
const candidate = deliver({
...limits,
diagnostic_preview: preview.slice(0, length),
diagnostic_truncated: true,
});
if (candidate.content.length > 0) {
fitted = candidate;
fittedLength = length;
low = length + 1;
} else high = length - 1;
}
if (fitted !== undefined && fittedLength > 0) return fitted;
const { diagnostic_preview: _preview, ...withoutPreview } = limits;
const omitted = deliver({
...withoutPreview,
diagnostic_truncated: preview.length > 0,
});
return omitted.content.length > 0 || fitted === undefined
? omitted
: fitted;
}
private normalizeSdkValidationError(
message: JSONRPCMessage,
tool: string | undefined,
targetContent: boolean,
diagnostic: string | undefined,
): JSONRPCMessage | undefined {
if (
tool === undefined ||
diagnostic === undefined ||
!isJSONRPCResultResponse(message) ||
!isCallToolResult(message.result)
)
return undefined;
const error = new AnalysisInputError(
tool,
{
userMessage: `The arguments for MCP tool ${tool} do not match its advertised input schema.`,
},
[{ path: [], reason: "invalid_value", message: diagnostic }],
);
const result = this.delivery.toErrorToolResult(error, targetContent);
return {
...message,
result: replaceToolResultPayload(message.result, result),
};
}
private recoverProtocolError(
message: JSONRPCMessage,
tool: string | undefined,
): JSONRPCMessage {
const recovered = this.recoverError(message, tool);
if (
!isJSONRPCErrorResponse(recovered) ||
tool === undefined ||
recovered.error.code !== -32602 ||
recovered.error.message !== `Tool ${tool} not found`
)
return recovered;
return {
...recovered,
error: {
...recovered.error,
message:
"The requested MCP tool is not advertised by this REA server. Call tools/list, select an advertised tool, and retry; do not repeat the unknown tool name.",
},
};
}
}
-699
View File
@@ -1,699 +0,0 @@
import { AsyncLocalStorage } from "node:async_hooks";
import {
isCallToolResult,
isJSONRPCErrorResponse,
isJSONRPCRequest,
isJSONRPCNotification,
isJSONRPCResultResponse,
type CallToolResult,
type Implementation,
type Icon,
type JSONRPCMessage,
type McpServerOptions,
type RegisteredTool,
type RegisteredPrompt,
type PromptCallback,
type RequestId,
type ScopeChallengeHandler,
type StandardSchemaWithJSON,
type ToolAnnotations,
type ToolCallback,
type Transport,
type TransportSendOptions,
} from "@modelcontextprotocol/server";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import {
presentAdvertisedInputSchema,
type CompactInputSchemaPresentation,
} from "../contracts/compactInputSchema.js";
import type { createCatalogIdentity } from "../catalogIdentity.js";
import { transformAdvertisedInputJsonSchema } from "../contracts/toolSchemaMetadata.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import {
AnalysisInputError,
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { createEvidence } from "../domain/evidence.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import {
mcpResponseOverflowProjection,
type ToolResultDelivery,
} from "./ToolResultDelivery.js";
import { toolReturnsTargetContent } from "../contracts/toolEffects.js";
import {
carriesTargetContentMarker,
encodeToolResult,
measureMcpResultWithinBudget,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";
import { RequestTrackingMcpServer } from "./RequestTrackingMcpServer.js";
export type { CompactInputSchemaPresentation } from "../contracts/compactInputSchema.js";
const currentRequestSignal = new AsyncLocalStorage<AbortSignal>();
/** Signal for the completion request currently being dispatched by the SDK. */
export const currentMcpRequestSignal = (): AbortSignal | undefined =>
currentRequestSignal.getStore();
/** A Zod schema whose standard interface exposes a JSON Schema projection. */
const hasAdvertisedInputJsonSchema = (value: unknown): boolean => {
if (typeof value !== "object" || value === null) return false;
const standard = Reflect.get(value, "~standard");
if (typeof standard !== "object" || standard === null) return false;
const jsonSchema = Reflect.get(standard, "jsonSchema");
return (
typeof jsonSchema === "object" &&
jsonSchema !== null &&
Reflect.get(jsonSchema, "input") !== undefined
);
};
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
/** Recognize the SDK's argument diagnostic after its wire size is checked. */
const sdkInputValidationDiagnostic = (
text: string | undefined,
tool: string | undefined,
): string | undefined => {
if (text === undefined || tool === undefined) return undefined;
const prefix = `Input validation error: Invalid arguments for tool ${tool}`;
if (!text.startsWith(prefix) || text[prefix.length] !== ":") return undefined;
const diagnostic = text.slice(prefix.length + 1).trimStart();
return diagnostic.length === 0 ? undefined : diagnostic;
};
/** Replace the tool payload after the SDK codec while retaining its envelope. */
const replaceToolResultPayload = (
original: CallToolResult,
replacement: CallToolResult,
): CallToolResult => {
const {
content: _content,
structuredContent: _structuredContent,
isError: _isError,
_meta,
...envelope
} = original;
return {
...envelope,
...replacement,
...(_meta === undefined && replacement._meta === undefined
? {}
: { _meta: { ..._meta, ...replacement._meta } }),
};
};
/** Remove only client-facing output schemas; SDK registrations stay canonical. */
const omitOutputSchemasFromToolsList = (
message: JSONRPCMessage,
requestId: RequestId,
): JSONRPCMessage => {
if (
!isJSONRPCResultResponse(message) ||
message.id !== requestId ||
!isRecord(message.result) ||
!Array.isArray(message.result.tools)
)
return message;
return {
...message,
result: {
...message.result,
tools: message.result.tools.map((tool: unknown) => {
if (!isRecord(tool)) return tool;
const { outputSchema: _outputSchema, ...advertisedTool } = tool;
return advertisedTool;
}),
},
} as JSONRPCMessage;
};
/** Release every transport-owned reference for a cancelled/completed request. */
export const forgetPendingMcpRequest = (
pendingTools: Map<RequestId, string>,
pendingToolLists: Set<RequestId>,
pendingCompletions: Map<RequestId, AbortController>,
id: RequestId,
): void => {
pendingTools.delete(id);
pendingToolLists.delete(id);
pendingCompletions.get(id)?.abort();
pendingCompletions.delete(id);
};
import type { PromptCompletionSource } from "./promptCompletion.js";
/** Standard-schema registration boundary shared with deferred SDK bindings. */
export interface StandardToolRegistration {
readonly title?: string;
readonly description?: string;
readonly inputSchema?: StandardSchemaWithJSON;
readonly outputSchema?: StandardSchemaWithJSON;
readonly annotations?: ToolAnnotations;
readonly icons?: Icon[];
readonly scopeChallenge?: ScopeChallengeHandler;
readonly _meta?: Record<string, unknown>;
}
/** Bind oversized MCP error recovery to this server's Evidence ledger. */
export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
private identity: ReturnType<typeof createCatalogIdentity> | undefined;
/** Composition supplies identity without importing the canonical schema graph. */
get catalogIdentity(): ReturnType<typeof createCatalogIdentity> {
if (this.identity === undefined)
throw new Error("MCP catalog identity has not been configured");
return this.identity;
}
/** Attach the process-owned session only after lazy runtime construction. */
attachRuntime(
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
delivery: ToolResultDelivery,
identity: ReturnType<typeof createCatalogIdentity>,
): void {
if (
this.identity !== undefined &&
this.identity.digests.combined_sha256 !== identity.digests.combined_sha256
)
throw new Error("MCP catalog identity does not match runtime");
this.recordEvidence = recordEvidence;
this.delivery = delivery;
this.identity = identity;
}
protected promptCompletion: PromptCompletionSource | undefined;
bindPromptCompletion(
completion: PromptCompletionSource,
): PromptCompletionSource {
this.promptCompletion = completion;
return completion;
}
registerCanonicalPrompt<Args extends StandardSchemaWithJSON>(
name: string,
config: { title?: string; description?: string; argsSchema: Args },
callback: PromptCallback<Args>,
): RegisteredPrompt {
return super.registerPrompt(name, config, callback);
}
private readonly compactPresentation:
| CompactInputSchemaPresentation
| undefined;
constructor(
info: Implementation,
options: McpServerOptions,
private recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
public delivery: ToolResultDelivery,
compactPresentation: CompactInputSchemaPresentation | undefined = undefined,
private readonly omitOutputSchemas = false,
identity?: ReturnType<typeof createCatalogIdentity>,
) {
super(info, options);
this.compactPresentation =
compactPresentation === undefined
? undefined
: { budgetBytes: compactPresentation.budgetBytes };
this.identity = identity;
}
/**
* Compact advertised input schemas and optionally omit output-schema
* advertisements. Canonical parsers and contracts remain registered; the
* output-schema-off path validates successful structured results locally.
* The signatures mirror the SDK's registrations so call sites keep their
* inferred handler argument types.
*/
override registerTool<
OutputArgs extends StandardSchemaWithJSON,
InputArgs extends StandardSchemaWithJSON | undefined = undefined,
>(
name: string,
config: {
title?: string;
description?: string;
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler;
_meta?: Record<string, unknown>;
},
callback: ToolCallback<InputArgs>,
): RegisteredTool {
const budget = this.compactPresentation?.budgetBytes;
const inputSchema =
budget !== undefined &&
config !== undefined &&
hasAdvertisedInputJsonSchema(config.inputSchema)
? transformAdvertisedInputJsonSchema(
config.inputSchema as Parameters<
typeof transformAdvertisedInputJsonSchema
>[0],
(projected) =>
presentAdvertisedInputSchema(projected, { budgetBytes: budget }),
)
: undefined;
const registeredConfig =
inputSchema === undefined ? config : { ...config, inputSchema };
return this.bindTool(name, registeredConfig as never, callback as never);
}
protected bindTool(
name: string,
config: StandardToolRegistration,
callback: ToolCallback<StandardSchemaWithJSON | undefined>,
): RegisteredTool {
return super.registerTool(name, config as never, callback as never);
}
/** Preserve the SDK transport lifecycle while retaining oversized errors. */
override connect(transport: Transport): Promise<void> {
return super.connect(
new ErrorEvidenceTransport(
transport,
() => this.recordEvidence,
() => this.delivery,
this.omitOutputSchemas,
),
);
}
}
class ErrorEvidenceTransport implements Transport {
onclose: Transport["onclose"];
onerror: Transport["onerror"];
onmessage: Transport["onmessage"];
readonly hasPerRequestStream?: boolean;
private readonly pendingTools = new Map<RequestId, string>();
private readonly pendingToolLists = new Set<RequestId>();
private readonly pendingCompletions = new Map<RequestId, AbortController>();
private get recordEvidence(): EvidenceWriter["recordEvidence"] | undefined {
return this.currentEvidenceWriter();
}
private get delivery(): ToolResultDelivery {
return this.currentDelivery();
}
constructor(
private readonly transport: Transport,
private readonly currentEvidenceWriter: () =>
| EvidenceWriter["recordEvidence"]
| undefined,
private readonly currentDelivery: () => ToolResultDelivery,
private readonly omitOutputSchemas: boolean,
) {
if (transport.hasPerRequestStream !== undefined)
this.hasPerRequestStream = transport.hasPerRequestStream;
transport.onmessage = (message, extra) => {
if (
isJSONRPCRequest(message) &&
message.method === "tools/call" &&
typeof message.params?.["name"] === "string"
)
this.pendingTools.set(message.id, message.params["name"]);
if (isJSONRPCRequest(message) && message.method === "tools/list")
this.pendingToolLists.add(message.id);
if (isJSONRPCRequest(message) && message.method === "completion/complete")
this.pendingCompletions.set(message.id, new AbortController());
// The SDK suppresses replies after cancellation, so send() cannot release
// this bookkeeping. Keep transport authentication outside retained data.
if (
isJSONRPCNotification(message) &&
message.method === "notifications/cancelled"
) {
const id = message.params?.["requestId"];
if (typeof id === "string" || typeof id === "number")
forgetPendingMcpRequest(
this.pendingTools,
this.pendingToolLists,
this.pendingCompletions,
id,
);
}
const completion =
isJSONRPCRequest(message) && message.method === "completion/complete"
? this.pendingCompletions.get(message.id)
: undefined;
if (completion === undefined) this.onmessage?.(message, extra);
else
currentRequestSignal.run(completion.signal, () =>
this.onmessage?.(message, extra),
);
};
transport.onerror = (error) => this.onerror?.(error);
transport.onclose = () => {
this.pendingTools.clear();
this.pendingToolLists.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
this.onclose?.();
};
}
get sessionId(): string | undefined {
return this.transport.sessionId;
}
set sessionId(value: string | undefined) {
this.transport.sessionId = value;
}
start(): Promise<void> {
return this.transport.start();
}
async close(): Promise<void> {
try {
await this.transport.close();
} finally {
this.pendingTools.clear();
this.pendingToolLists.clear();
for (const completion of this.pendingCompletions.values())
completion.abort();
this.pendingCompletions.clear();
}
}
setProtocolVersion(version: string): void {
this.transport.setProtocolVersion?.(version);
}
setSupportedProtocolVersions(versions: string[]): void {
this.transport.setSupportedProtocolVersions?.(versions);
}
async send(
message: JSONRPCMessage,
options?: TransportSendOptions,
): Promise<void> {
const id =
"id" in message &&
(typeof message.id === "string" || typeof message.id === "number")
? message.id
: undefined;
const tool = id === undefined ? undefined : this.pendingTools.get(id);
const omitToolSchemas =
this.omitOutputSchemas &&
id !== undefined &&
this.pendingToolLists.has(id);
try {
const recovered = this.recoverProtocolError(message, tool);
const advertised = omitToolSchemas
? omitOutputSchemasFromToolsList(recovered, id)
: recovered;
if (
isJSONRPCResultResponse(advertised) &&
isCallToolResult(advertised.result) &&
advertised.result.isError === true
) {
// Keep the complete typed JSON in content. Error projections are not
// success outputSchema data; oversized recovery must consume their
// private structured carrier before it is removed from the wire.
const { structuredContent: _diagnostic, ...result } = advertised.result;
// Errors the SDK builds itself (input validation, a thrown handler)
// bypass ToolResultDelivery; mark them for target-content tools too.
const marked =
tool !== undefined &&
toolReturnsTargetContent(tool) &&
!carriesTargetContentMarker(result)
? {
...result,
_meta: { ...result._meta, ...TARGET_CONTENT_RESULT_META },
}
: result;
await this.transport.send({ ...advertised, result: marked }, options);
} else await this.transport.send(advertised, options);
} finally {
if (!isJSONRPCRequest(message) && id !== undefined) {
forgetPendingMcpRequest(
this.pendingTools,
this.pendingToolLists,
this.pendingCompletions,
id,
);
}
}
}
private recoverError(
message: JSONRPCMessage,
tool: string | undefined,
): JSONRPCMessage {
if (
!isJSONRPCResultResponse(message) ||
!isCallToolResult(message.result) ||
message.result.isError !== true
)
return message;
const budget = this.delivery.resultBudgetBytes;
// Count the provenance marker exactly as the projected error did, and keep
// it on the replacement: the retained original may hold target content.
const targetContent =
carriesTargetContentMarker(message.result) ||
(tool !== undefined && toolReturnsTargetContent(tool));
// SDK validation failures have no structured carrier. Size their existing
// text-only result without serializing the complete JSON-RPC message.
const isStructured = message.result.structuredContent !== undefined;
const structured = isStructured
? jsonObjectSchema.parse(message.result.structuredContent)
: undefined;
const sdkResultWithMarker =
!isStructured &&
targetContent &&
!carriesTargetContentMarker(message.result)
? {
...message.result,
_meta: {
...message.result._meta,
...TARGET_CONTENT_RESULT_META,
},
}
: message.result;
const sdkDiagnostic = !isStructured
? message.result.content.find((item) => item.type === "text")?.text
: undefined;
let encoded =
structured !== undefined
? encodeToolResult(structured, budget, "error-text", targetContent)
: measureMcpResultWithinBudget(sdkResultWithMarker, budget);
const normalized = encoded.ok
? this.normalizeSdkValidationError(
message,
tool,
targetContent,
sdkInputValidationDiagnostic(sdkDiagnostic, tool),
)
: undefined;
if (
normalized !== undefined &&
isJSONRPCResultResponse(normalized) &&
isCallToolResult(normalized.result)
) {
// The structured diagnostic is a private carrier removed before sending.
// Measure the actual wire result, including its preserved SDK metadata.
const { structuredContent, ...wireResult } = normalized.result;
encoded =
normalized.result.content.length === 0
? encodeToolResult(
jsonObjectSchema.parse(structuredContent),
budget,
"error-text",
targetContent,
)
: measureMcpResultWithinBudget(wireResult, budget);
if (encoded.ok) return normalized;
// JSON escaping and recovery fields can exceed the budget even when
// the original SDK result fits. Retain that original before replacing it.
}
if (encoded.ok) return message;
const operation = tool ?? "mcp_tool_error";
const originalResult = jsonObjectSchema.parse(message.result);
const retainedResult = structured ?? originalResult;
const originalError = isStructured
? analysisErrorProjectionSchema.safeParse(structured?.["error"])
: undefined;
// Retain the complete original response, including SDK validation text.
// The SDK error contains its rendered issue, not a separate argument bag;
// transport authentication and caller arguments are never added here.
const evidence = createEvidence(
undefined,
{ id: "rea-mcp", name: "REA MCP delivery", version: "1" },
{
operation: "mcp_tool_error",
parameters: { tool_name: operation },
result:
sdkDiagnostic === undefined
? retainedResult
: {
boundary: "sdk-input-validation",
diagnostic_preview: sdkDiagnostic.slice(0, 256),
diagnostic_truncated: sdkDiagnostic.length > 256,
},
rawResult: originalResult,
},
);
const recorded = this.recordEvidence?.(evidence);
const retained = recorded !== undefined && recorded.ok;
const projected = mcpResponseOverflowProjection({
completed: false,
constraint: encoded.constraint,
effectiveResponseBytes: this.delivery.maximumResponseBytes,
nextStep: retained
? "Export the retained original error through export_evidence_bundle to a caller-selected path. The connection remains usable."
: encoded.constraint === "string-length"
? "The original error could not be retained by this server. Use complete CLI JSON output when the analysis completed. Repeating the unchanged MCP call fails the same way."
: "The original error could not be retained by this server. Restart REA with a larger REA_MCP_MAX_RESPONSE_BYTES and a matching client receive buffer, then retry.",
});
const replacement = this.transportConstraintResult(
operation,
projected.reason,
projected.remediationAction,
{
boundary: "mcp-response",
...(originalError?.success
? { original_error_code: originalError.data.code }
: {}),
result_budget_bytes: budget,
response_bytes_at_least: encoded.bytesAtLeast,
constraint: encoded.constraint,
...(sdkDiagnostic === undefined
? {}
: {
diagnostic_preview: sdkDiagnostic.slice(0, 256),
diagnostic_truncated: sdkDiagnostic.length > 256,
}),
...(retained
? {
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
}
: { retention: recorded === undefined ? "unavailable" : "failed" }),
...(recorded !== undefined && !recorded.ok
? { retention_error: projectAnalysisError(recorded.error) }
: {}),
},
targetContent,
);
return {
...message,
result: replaceToolResultPayload(message.result, replacement),
};
}
/**
* Encode a transport-constraint error inside the MCP text budget.
* The complete SDK diagnostic stays in retained Evidence. Its character
* preview can still expand past the budget when quotes and backslashes are
* escaped into that text, so shorten only the preview and keep the reference.
*/
private transportConstraintResult(
operation: string,
reason: string,
remediationAction: string,
limits: Readonly<Record<string, JsonValue>>,
targetContent: boolean,
): CallToolResult {
const deliver = (
reportedLimits: Readonly<Record<string, JsonValue>>,
): CallToolResult =>
this.delivery.toErrorToolResult(
new AnalysisResourceConstraintError(
operation,
"transport",
reason,
reportedLimits,
{ remediationAction },
),
targetContent,
);
const delivered = deliver(limits);
const preview = limits.diagnostic_preview;
if (delivered.content.length > 0 || typeof preview !== "string")
return delivered;
let low = 0;
let high = preview.length - 1;
let fitted: CallToolResult | undefined;
let fittedLength = -1;
while (low <= high) {
const length = Math.floor((low + high) / 2);
const candidate = deliver({
...limits,
diagnostic_preview: preview.slice(0, length),
diagnostic_truncated: true,
});
if (candidate.content.length > 0) {
fitted = candidate;
fittedLength = length;
low = length + 1;
} else high = length - 1;
}
if (fitted !== undefined && fittedLength > 0) return fitted;
const { diagnostic_preview: _preview, ...withoutPreview } = limits;
const omitted = deliver({
...withoutPreview,
diagnostic_truncated: preview.length > 0,
});
return omitted.content.length > 0 || fitted === undefined
? omitted
: fitted;
}
private normalizeSdkValidationError(
message: JSONRPCMessage,
tool: string | undefined,
targetContent: boolean,
diagnostic: string | undefined,
): JSONRPCMessage | undefined {
if (
tool === undefined ||
diagnostic === undefined ||
!isJSONRPCResultResponse(message) ||
!isCallToolResult(message.result)
)
return undefined;
const error = new AnalysisInputError(
tool,
{
userMessage: `The arguments for MCP tool ${tool} do not match its advertised input schema.`,
},
[{ path: [], reason: "invalid_value", message: diagnostic }],
);
const result = this.delivery.toErrorToolResult(error, targetContent);
return {
...message,
result: replaceToolResultPayload(message.result, result),
};
}
private recoverProtocolError(
message: JSONRPCMessage,
tool: string | undefined,
): JSONRPCMessage {
const recovered = this.recoverError(message, tool);
if (
!isJSONRPCErrorResponse(recovered) ||
tool === undefined ||
recovered.error.code !== -32602 ||
recovered.error.message !== `Tool ${tool} not found`
)
return recovered;
return {
...recovered,
error: {
...recovered.error,
message:
"The requested MCP tool is not advertised by this REA server. Call tools/list, select an advertised tool, and retry; do not repeat the unknown tool name.",
},
};
}
}
-250
View File
@@ -1,250 +0,0 @@
import type { CallToolResult } from "@modelcontextprotocol/server";
import { STDIO_DEFAULT_MAX_BUFFER_SIZE } from "@modelcontextprotocol/server";
import type { ToolContract } from "../contracts/toolContractTypes.js";
import type { Evidence } from "../domain/evidence.js";
import {
projectAnalysisError,
type AnalysisErrorProjection,
} from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
import { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import {
MCP_TRANSPORT_EVIDENCE_DISCOVERY,
MCP_TRANSPORT_EVIDENCE_EXPORT,
} from "../domain/analysisErrorPresentation.js";
import {
nodeStringCeilingRecovery,
stdioResponseBudgetRecovery,
} from "../config/mcpResponseBudget.js";
import {
encodeToolResult,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
TARGET_CONTENT_RESULT_META,
} from "./toolResultEncoding.js";
/** Project a response-budget refusal without labeling REA's reserved string limit as Node's ceiling. */
export const mcpResponseOverflowProjection = (input: {
readonly completed: boolean;
readonly constraint: "receive-buffer" | "string-length";
readonly effectiveResponseBytes: number;
readonly nextStep: string;
}): { readonly reason: string; readonly remediationAction: string } => {
const facts =
input.constraint === "string-length"
? nodeStringCeilingRecovery(
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
)
: stdioResponseBudgetRecovery(
input.effectiveResponseBytes,
MCP_RESULT_STRING_LIMIT,
NODE_MAX_STRING_LENGTH,
);
const summary =
input.constraint === "string-length"
? input.completed
? "The operation completed, but its complete MCP response exceeds REA's reserved single-string limit."
: "The tool failed, but its complete error response exceeds REA's reserved single-string limit."
: input.completed
? "The operation completed, but its complete MCP response exceeds the stdio response budget. The analysis result was not truncated."
: "The tool failed, but its complete error response exceeds the MCP response budget.";
return {
reason: `${summary} ${facts} ${input.nextStep}`,
remediationAction: `${input.nextStep} ${facts}`,
};
};
/**
* A summary projection has already used `detail: "summary"`.
* Export still writes the retained bundle outside one MCP frame.
*/
const evidenceBundleSummary = (value: JsonValue): boolean => {
const payload =
typeof value === "object" &&
value !== null &&
!Array.isArray(value) &&
"result" in value
? value.result
: value;
return (
typeof payload === "object" &&
payload !== null &&
!Array.isArray(payload) &&
payload.kind === "evidence-bundle-summary"
);
};
/** Immutable encoding and recovery policy shared by one MCP server. */
export class ToolResultDelivery {
readonly maximumResponseBytes: number;
readonly resultBudgetBytes: number;
constructor(
maximumResponseBytes: number,
private readonly nativeContinuation: (
evidence: Evidence,
) => Readonly<Record<string, JsonValue>> = () => ({}),
) {
this.maximumResponseBytes = maximumResponseBytes;
this.resultBudgetBytes = maximumResponseBytes - 1024;
Object.freeze(this);
}
/** Serialize a plain application result or its actionable error. */
toCallToolResult(
result: Result<JsonValue, AnalysisError>,
contract: ToolContract,
): CallToolResult {
return result.ok
? this.successResult(
contract.kind === "session" ? { result: result.value } : result.value,
contract,
)
: this.toErrorToolResult(result.error, contract.returnsTargetContent);
}
/** Deliver Evidence using the producer's explicit recording acknowledgment. */
toEvidenceToolResult(
evidence: Evidence,
contract: ToolContract,
recorded: Result<unknown, AnalysisError> | undefined,
): CallToolResult {
return recorded !== undefined && !recorded.ok
? this.toErrorToolResult(recorded.error, contract.returnsTargetContent)
: this.successResult(evidence, contract, {
evidence_id: evidence.evidence_id,
...(recorded === undefined
? {}
: {
evidence_reference: {
kind: "retained-evidence",
evidence_id: evidence.evidence_id,
},
...this.nativeContinuation(evidence),
}),
});
}
/**
* Project an error without allocating oversized repeated MCP text.
* `targetContent` is the failing tool's `returnsTargetContent`: a failure
* can carry target-derived text (a message, captured output, or a partial
* observation), so it is marked exactly like that tool's successful results.
*/
toErrorToolResult(
error: AnalysisError,
targetContent: boolean,
): CallToolResult {
return this.projectedErrorResult(
projectAnalysisError(error),
targetContent,
);
}
/** Deliver the original failure with the producer-acknowledged partial Evidence reference. */
toRecordedPartialErrorToolResult(
error: AnalysisError,
evidenceId: string,
recorded: Result<unknown, AnalysisError>,
targetContent: boolean,
): CallToolResult {
if (!recorded.ok) return this.toErrorToolResult(error, targetContent);
const projected = projectAnalysisError(error);
return this.projectedErrorResult(
{
...projected,
details: {
...projected.details,
partial_observation: {
kind: "retained-evidence",
evidence_id: evidenceId,
},
},
},
targetContent,
);
}
private projectedErrorResult(
projected: AnalysisErrorProjection,
targetContent: boolean,
): CallToolResult {
const structuredContent = { error: projected };
// Errors reach the wire as text only; the structured copy is a private
// carrier the transport removes after its own budget check.
const encoded = encodeToolResult(
structuredContent,
this.resultBudgetBytes,
"error-text",
targetContent,
);
// The transport retains an oversized projected error before replacing it
// with a recoverable delivery constraint, using this same budget.
return {
content: encoded.ok ? [{ type: "text", text: encoded.text }] : [],
structuredContent,
isError: true,
...(targetContent ? { _meta: TARGET_CONTENT_RESULT_META } : {}),
};
}
private successResult(
value: JsonValue,
contract: ToolContract,
recovery: Readonly<Record<string, JsonValue>> = {},
): CallToolResult {
const encoded = encodeToolResult(
value,
this.resultBudgetBytes,
"structured-and-text",
contract.returnsTargetContent,
);
if (encoded.ok)
return {
content: [{ type: "text", text: encoded.text }],
structuredContent: value,
...(contract.returnsTargetContent
? { _meta: TARGET_CONTENT_RESULT_META }
: {}),
};
const retainedEvidence = recovery.evidence_reference !== undefined;
const nextStep =
recovery.continuation !== undefined
? "Call inspect_analysis_view with the supplied continuation arguments to read retained analysis. Follow coverage.next_offset for subsequent pages; reduce the page limit if needed, or export the complete retained Evidence."
: retainedEvidence
? "Export retained evidence to consume the complete analysis, or use complete CLI JSON output."
: contract.name === "get_evidence_bundle"
? evidenceBundleSummary(value)
? MCP_TRANSPORT_EVIDENCE_EXPORT
: MCP_TRANSPORT_EVIDENCE_DISCOVERY
: "Use complete CLI JSON output to consume the analysis.";
const projected = mcpResponseOverflowProjection({
completed: true,
constraint: encoded.constraint,
effectiveResponseBytes: this.maximumResponseBytes,
nextStep,
});
return this.toErrorToolResult(
new AnalysisResourceConstraintError(
contract.name,
"transport",
projected.reason,
{
boundary: "mcp-response",
default_receive_buffer_bytes: STDIO_DEFAULT_MAX_BUFFER_SIZE,
result_budget_bytes: this.resultBudgetBytes,
max_string_code_units: MCP_RESULT_STRING_LIMIT,
response_bytes_at_least: encoded.bytesAtLeast,
response_code_units_at_least: encoded.codeUnitsAtLeast,
constraint: encoded.constraint,
...recovery,
},
{ remediationAction: projected.remediationAction },
),
contract.returnsTargetContent,
);
}
}
+7 -30
View File
@@ -48,7 +48,6 @@ import { FridaInstrumentationManager } from "../frida/FridaInstrumentationManage
import { registerFridaTools } from "./registerFridaTools.js";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import { createCatalogIdentity } from "../catalogIdentity.js";
import { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import {
createToolResultDelivery,
@@ -162,10 +161,6 @@ const RECOVERY_INSTRUCTIONS =
"Recovery: For invalid arguments, read the connected tool's input schema (refresh tools/list if stale), fix the reported fields and do not repeat the unchanged call. A returned REA provider_timeout is a server/provider deadline: follow its remediation and reuse accessible partial Evidence. A host error such as 'timed out awaiting tools/call' without a REA result is a client deadline, not proof that work or cleanup stopped. Do not repeat the unchanged analysis. Increase the host's tool deadline with execution/cleanup/delivery headroom; when configuration is not editable, report the required setting (Codex: mcp_servers.<server>.tool_timeout_sec, seconds). Server analysis_timeout_ms, when advertised, is a separate millisecond budget; raising it cannot fix a shorter client deadline. Session state does not establish completion of every target-free operation.";
export interface CreateServerOptions {
/** Preserve the connection's creation time when materializing its runtime. */
readonly startedAt?: string;
/** Existing SDK server whose deferred registrations are being materialized. */
readonly mcpServer?: EvidenceMcpServer;
readonly environment?: Readonly<NodeJS.ProcessEnv>;
readonly delivery?: ToolResultDelivery;
readonly packetCapture?: PacketCaptureService;
@@ -303,10 +298,6 @@ const createMcpServer = (
delivery,
compactPresentation,
omitOutputSchemas,
createCatalogIdentity(
compactPresentation,
omitOutputSchemas ? "off" : "full",
),
);
/**
@@ -370,28 +361,14 @@ export const createServer = (
webModuleTrace,
javascriptRecovery,
};
const startedAt = options.startedAt ?? new Date().toISOString();
const startedAt = new Date().toISOString();
const logger = options.logger ?? silentLogger;
const server =
options.mcpServer ??
createMcpServer(
session,
delivery,
selectCompactInputSchemaPresentation(environment),
omitOutputSchemas,
);
if (options.mcpServer !== undefined) {
server.attachRuntime(
session === undefined
? undefined
: (evidence) => session.recordEvidence(evidence),
delivery,
createCatalogIdentity(
selectCompactInputSchemaPresentation(environment),
omitOutputSchemas ? "off" : "full",
),
);
}
const server = createMcpServer(
session,
delivery,
selectCompactInputSchemaPresentation(environment),
omitOutputSchemas,
);
const gdbSessions = new GdbSessionManager({
environment: providerEnvironment,
});
-36
View File
@@ -1,36 +0,0 @@
import { completable } from "@modelcontextprotocol/server";
import { z } from "zod";
import type {
PromptArgumentContract,
PromptContract,
} from "../contracts/promptContracts.js";
import type { PromptCompletionSource } from "./promptCompletion.js";
export const promptArgumentsSchema = (
contract: Pick<PromptContract, "arguments">,
completion: PromptCompletionSource,
) => {
const shape: Record<string, z.ZodType> = {};
for (const [name, argument] of Object.entries(contract.arguments))
shape[name] = argumentSchema(argument, completion);
return z.object(shape);
};
const argumentSchema = (
argument: PromptArgumentContract,
completion: PromptCompletionSource,
): z.ZodType => {
const value = z
.string()
.min(1)
.refine((value) => value.trim().length > 0)
.describe(argument.description);
const kind = argument.completion;
const completed =
kind === undefined
? value
: completable(value, async (partial, context) => [
...(await completion.complete(kind, partial, context)),
]);
return argument.required ? completed : completed.optional();
};
+1 -1
View File
@@ -8,7 +8,7 @@ import { parseProcessCaptureEvidence } from "../application/process/ProcessEvide
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import type { PromptCompletionKind } from "../contracts/promptContracts.js";
import { addressedValueSchema } from "../domain/native/nativeInventory.js";
import { currentMcpRequestSignal } from "./EvidenceMcpServerCore.js";
import { currentMcpRequestSignal } from "./EvidenceMcpServer.js";
import { parseArtifactInventoryEvidence } from "../domain/artifactInventoryEvidence.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more