mirror of
https://github.com/morluto/rea.git
synced 2026-10-26 17:35:11 +00:00
perf(go): summarize build identity and query retained metadata (#5524)
Add opt-in Go build summaries and selected retained metadata pages while preserving complete Evidence and source identity. Validated with 258 focused tests, full static/docs checks, real CLI/SDK workflows and native metadata oracles. CI baseline remediation assertions reproduce on unmodified main; fail-fast cancels two other shards. Owner authorized bypass with those coverage limits recorded in PR #5524. Fixes #5499.
This commit is contained in:
1 parent
e52a71602d
commit
c2858d2aa0
27 files changed
+3212
-59
No files matched your search
@@ -19,6 +19,56 @@ requires an absolute filesystem path and preserves that exact selection:
|
||||
}
|
||||
```
|
||||
|
||||
For build identity and counts, select `detail: "summary"`. MCP retains the same
|
||||
complete Evidence and returns `normalized_result.parent_evidence_id`. Read
|
||||
selected dependency versions without reopening the file:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "inspect_analysis_view",
|
||||
"arguments": {
|
||||
"source": {
|
||||
"kind": "retained-evidence",
|
||||
"evidence_id": "ev_<parent digest>"
|
||||
},
|
||||
"view": {
|
||||
"kind": "go",
|
||||
"collection": "dependencies",
|
||||
"paths": ["golang.org/x/crypto"],
|
||||
"fields": ["path", "version", "replacement"],
|
||||
"offset": 0,
|
||||
"limit": 10
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Go views support `dependencies` (exact `paths`) and `settings` (exact `keys`),
|
||||
optional original `indices`, field selection, and pagination. Filters intersect;
|
||||
empty filter arrays select no rows and `fields: []` returns only row identity.
|
||||
Each row keeps its original `index`, scoped to the parent Evidence and collection;
|
||||
duplicate module paths and setting keys keep distinct indices. Page offsets
|
||||
count matching records. Exhausting retained rows does not establish complete
|
||||
runtime dependencies. Original bytes, unknown lines and all complete metadata
|
||||
remain in the parent and can be exported as an Evidence bundle.
|
||||
|
||||
One-shot CLI summaries save complete Evidence before returning the projection:
|
||||
|
||||
```bash
|
||||
rea inspect-go-binary ./application --detail summary --evidence_output ./go-evidence.json --json
|
||||
```
|
||||
|
||||
`--evidence_output` is required for CLI summary delivery and never overwrites an
|
||||
existing file. The default CLI/MCP reply remains complete.
|
||||
|
||||
[Measured workflows](../experiments/analysis-efficiency/go-build-views.md) include
|
||||
catalog repetition and extra calls. Identity/count questions benefit from a
|
||||
single summary. In the tested Codex full-catalog configuration, a compound
|
||||
question about identity and one dependency uses fewer tokens in captured request JSON with
|
||||
one complete inspection than with a summary followed by a lookup. The complete
|
||||
reply remains useful for that initial question; retained views support later
|
||||
selected reads. Token figures are serialization estimates, not model usage.
|
||||
|
||||
## Observations
|
||||
|
||||
The inline Evidence result contains the artifact path, SHA-256, byte length,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Count verified Go tasks; tokenizer estimates are not model usage or billing."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import tiktoken
|
||||
|
||||
|
||||
def compact(value):
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def inspect(path, encoding):
|
||||
report = json.loads((path / "report.json").read_text())
|
||||
catalog = json.loads((path / "catalog.json").read_text())
|
||||
transcript = json.loads((path / "transcript.json").read_text())
|
||||
log = path.with_suffix(".log")
|
||||
scope = next(json.loads(line) for line in reversed(log.read_text().splitlines())
|
||||
if line.startswith('{"resource_scope":'))
|
||||
observed = scope.get("payload_resource_observation") or {}
|
||||
events = observed.get("resource_events", {})
|
||||
memory = events.get("memory.events", {})
|
||||
verified = (report["status"] == "observed"
|
||||
and not report["cleanup_failures"] and not report["receipt_failures"]
|
||||
and scope["abort"] is None
|
||||
and scope.get("payload_resource_observation_verified") is True
|
||||
and observed.get("payload_cleanup_verified") is True
|
||||
and observed.get("payload_exit_code") == 0
|
||||
and all(memory.get(key) == 0 for key in ["high", "max", "oom", "oom_kill"])
|
||||
and events.get("pids.events", {}).get("max") == 0)
|
||||
count = lambda value: len(encoding.encode(value, disallowed_special=()))
|
||||
inputs = count(compact([{key: tool[key] for key in ["name", "description", "inputSchema"]}
|
||||
for tool in catalog["tools"]]))
|
||||
arguments = sum(count(compact({"name": event["name"], "arguments": event["input"]}))
|
||||
for event in transcript)
|
||||
replies = sum(count(block["text"]) for event in transcript
|
||||
for block in event["reply"]["content"] if block["type"] == "text")
|
||||
cpu = observed.get("cpu_stat", {}).get("usage_usec")
|
||||
return {"case": path.name, "completed_with_verified_cleanup": verified,
|
||||
"mode": report["mode"], "warm_diagnostic": report["warm_diagnostic"],
|
||||
"answer": report["answer"], "parent_evidence_id": report["parent_evidence_id"],
|
||||
"artifact_sha256": report["artifact_sha256"],
|
||||
"complete_result_sha256": report["complete_result_file_sha256"],
|
||||
"calls": report["calls"], "wall_seconds": scope["elapsed_seconds"],
|
||||
"cpu_seconds": None if cpu is None else cpu / 1e6,
|
||||
"kernel_family_peak_bytes": observed.get("memory_peak_bytes"),
|
||||
"events_at_payload_exit": events,
|
||||
"final_whole_scope_events": scope.get("resource_events_final"),
|
||||
"token_proxy": {"input_catalog": inputs, "arguments": arguments,
|
||||
"text_replies": replies, "combined": inputs + arguments + replies,
|
||||
"complete_transport_catalog": count(compact(catalog))},
|
||||
"sha256": {file.name: hashlib.sha256(file.read_bytes()).hexdigest()
|
||||
for file in [path / "report.json", path / "catalog.json",
|
||||
path / "transcript.json", log]}}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("cases", type=Path, nargs="+")
|
||||
args = parser.parse_args()
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
records = [inspect(path, encoding) for path in args.cases]
|
||||
receipt = {"tiktoken": tiktoken.__version__, "encoding": encoding.name,
|
||||
"actual_model_usage": None,
|
||||
"projection": "All discovered input schemas once, plus every call's arguments and text replies, including export. Full transport catalog counted separately; no model turn or host injection measured.",
|
||||
"recordings": records}
|
||||
args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n")
|
||||
assert all(record["completed_with_verified_cleanup"] for record in records)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Pin a completed Go report only after checking native build text and file bytes."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--evidence", type=Path, required=True)
|
||||
parser.add_argument("--input", type=Path, required=True)
|
||||
parser.add_argument("--go", type=Path, required=True)
|
||||
parser.add_argument("--dependency", required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
source = args.input.read_bytes()
|
||||
evidence = json.loads(args.evidence.read_text())
|
||||
if "records" in evidence:
|
||||
evidence = next(record for record in evidence["records"]
|
||||
if record["operation"] == "inspect_go_binary"
|
||||
and record["parameters"] == {"path": str(args.input)})
|
||||
report = evidence["normalized_result"]
|
||||
info = report["build_info"]
|
||||
digest = hashlib.sha256(source).hexdigest()
|
||||
assert report["artifact"] == {"path": str(args.input), "sha256": digest,
|
||||
"bytes": len(source)}
|
||||
native = subprocess.check_output(
|
||||
[str(args.go), "version", "-m", str(args.input)], text=True)
|
||||
lines = native.splitlines()
|
||||
assert info["go_version"] == lines[0].rsplit(" ", 1)[1]
|
||||
text = "\n".join(line.removeprefix("\t") for line in lines[1:]) + "\n"
|
||||
assert info["module_text"] == text
|
||||
for name in ["version", "module"]:
|
||||
location = info[name + "_location"]
|
||||
key = ("go_version" if name == "version" else "module") + "_bytes_base64"
|
||||
assert source[location["offset"]:location["offset"] + location["bytes"]] == base64.b64decode(info[key])
|
||||
# Module identity columns are literal tab-separated fields. Preserve empty
|
||||
# sums, development versions, original ordering and local replacements.
|
||||
dependencies = []
|
||||
main_module = None
|
||||
previous = None
|
||||
for line in text.splitlines():
|
||||
columns = line.split("\t")
|
||||
tag = columns[0]
|
||||
if tag not in ["dep", "mod", "=>"]:
|
||||
continue
|
||||
assert len(columns) in [3, 4], columns
|
||||
item = {"path": columns[1], "version": columns[2],
|
||||
"sum": columns[3] if len(columns) == 4 else None}
|
||||
if tag == "=>":
|
||||
assert previous is not None
|
||||
previous["replacement"] = item
|
||||
else:
|
||||
item["replacement"] = None
|
||||
previous = item
|
||||
if tag == "mod":
|
||||
main_module = item
|
||||
else:
|
||||
dependencies.append(item)
|
||||
assert info["module"]["main"] == main_module
|
||||
assert info["module"]["dependencies"] == dependencies
|
||||
answer = {"go_version": info["go_version"], "main": main_module,
|
||||
"runtime_dependencies": "unknown",
|
||||
"dependencies": [{"index": index, **item}
|
||||
for index, item in enumerate(dependencies)
|
||||
if item["path"] == args.dependency]}
|
||||
complete = args.output.with_suffix(".complete-result.json")
|
||||
complete.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
receipt = {"artifact_sha256": digest, "dependency_path": args.dependency,
|
||||
"dependency_count": len(dependencies), "answer": answer,
|
||||
"complete_result_path": str(complete.resolve()),
|
||||
"native_text_sha256": hashlib.sha256(native.encode()).hexdigest(),
|
||||
"native_go_path": str(args.go),
|
||||
"native_go_sha256": hashlib.sha256(args.go.read_bytes()).hexdigest()}
|
||||
args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,195 @@
|
||||
# Selected Go build metadata
|
||||
|
||||
Addresses [#5499](https://github.com/morluto/rea/issues/5499). A compiler/main-module
|
||||
identity question previously required the complete Go report, including raw framed
|
||||
bytes, base64, module text and every parsed dependency. Opt-in `detail: summary`
|
||||
retains the same complete parent and returns identity, source ranges, counts and
|
||||
explicit unknowns. Default complete delivery remains compatible.
|
||||
|
||||
`inspect_analysis_view` reuses that parent for `kind: go`, collection
|
||||
`dependencies` or `settings`. Exact paths/keys and original indices intersect;
|
||||
fields select columns, while every row keeps its original index. Pagination
|
||||
counts matching rows in producer order, including duplicate module paths. The
|
||||
view never reopens a target or reparses module text. Unknown lines and original
|
||||
bytes remain in the complete parent. CLI summaries save that parent in a new
|
||||
Evidence bundle before returning their projection.
|
||||
|
||||
Only immutable authenticated Evidence results reuse schema validation, keyed
|
||||
by their object identity for the Evidence lifetime. Mutable inline results are
|
||||
validated on each call. Subject identity is checked separately on every view.
|
||||
There is no live-file cache. Only page rows are projected; inherited messages
|
||||
use the existing bounded, deduplicating view-message owner.
|
||||
|
||||
## Question and independent checks
|
||||
|
||||
The main artifact is the official GitHub CLI v2.102.0 Linux amd64 release:
|
||||
42,086,560 bytes, SHA-256
|
||||
`7469124f706944133d6a169691dd1c6c3511b12e85878d255e044e2948df4c9b`.
|
||||
The archive digest matches its official GitHub asset metadata. Its embedded
|
||||
compiler is `go1.27.1`, main module `github.com/cli/cli/v2@v2.102.0`, and it has
|
||||
165 parsed dependency records. The selected `golang.org/x/crypto@v0.57.0` record
|
||||
keeps original index 152. These are embedded observations, not authentication
|
||||
of the compiler, supply chain or runtime behavior.
|
||||
|
||||
Native `go version -m` independently matches module text, main identity and all
|
||||
165 dependency identities in original order. Original file ranges match the
|
||||
reported compiler and framed module bytes. Before/after exports have identical
|
||||
complete normalized results and parent Evidence identity. The small real case
|
||||
is the installed 12,366,352-byte Go tool: embedded `go1.23.5`, no decoded main
|
||||
module and zero retained dependencies, with dependency coverage still unknown.
|
||||
REA reads both inputs without executing them. The installed Go tool also runs
|
||||
as the trusted native verifier; the downloaded GitHub CLI binary is never
|
||||
executed.
|
||||
|
||||
Timing baseline is main `ee12d517a25d34853d40e31fc039c7d1576c60e1`. Packaged runtimes
|
||||
and source patch are pinned in the [receipt](go-build-views.json); later changes
|
||||
do not relabel these timings. Node 24.18.0/npm 11.16.0, MCP SDK 2.3.1, Linux
|
||||
x86-64. Fresh processes use unflushed OS caches; the SDK controller pre-reads
|
||||
the input for verification. These are not disk-cold measurements.
|
||||
|
||||
## Actual client context, including every request
|
||||
|
||||
The [wire driver](go-build-wire.py) starts actual Codex app-server 0.163.0 with a
|
||||
fresh account/workspace and a loopback deterministic Responses SSE backend.
|
||||
It starts a scripted turn and real MCP calls, with **no AI inference or paid
|
||||
service**. All 210 tools remain discovered/advertised. Full input/output
|
||||
profiles are explicit, and each relevant tool has a 30,000-token output budget
|
||||
so complete JSON is delivered without retries or truncation. This does not
|
||||
qualify another client's defaults or a real model's reasoning/schema acceptance.
|
||||
|
||||
All original facts and parent identities match the native oracle. Export cases
|
||||
also verify the complete parent. The [counter](go-build-wire-costs.py) counts
|
||||
**every captured request**, including repeated schemas and accumulated tool
|
||||
outputs, using `tiktoken 0.12.0` / `cl100k_base` on compact request JSON. These are
|
||||
serialization-token proxies; actual model rendering, usage and cache billing
|
||||
remain unmeasured.
|
||||
|
||||
| Completed question | Requests before → after | Whole request JSON proxy before → after |
|
||||
| ------------------------------------------------------ | ----------------------: | --------------------------------------: |
|
||||
| Compiler, main module and dependency count | 2 → 2 | 158,529 → 123,368 (22.2% less) |
|
||||
| Compiler, main module and one selected dependency | 2 → 3 | 158,538 → 186,812 (17.8% more) |
|
||||
| Same selected dependency question plus Evidence export | 3 → 4 | 256,342 → 250,352 (2.3% less) |
|
||||
|
||||
The actual REA namespace costs 51,821 → 51,983 proxy tokens **per request**.
|
||||
An extra round can outweigh a smaller reply. Summary is useful when identity
|
||||
and counts already answer the question; complete delivery remains useful for
|
||||
an initial compound question. Retained views provide selected follow-up facts,
|
||||
without a claim that every such composition saves total context.
|
||||
|
||||
One recording per cell: identity wall/CPU/family peak is
|
||||
6.970 s / 6.331 s / 861.5 MiB before and 7.069 s / 6.457 s / 857.0 MiB after.
|
||||
Compound answer-only is 6.973 / 6.333 / 865.0 before and 6.969 / 6.348 / 861.6
|
||||
after. Export is 7.175 / 6.537 / 866.7 before and 7.274 / 6.568 / 872.6 after.
|
||||
These scripted-client observations establish no universal latency or memory
|
||||
gain, and do not measure model inference time.
|
||||
|
||||
## Direct SDK task and cold/warm costs
|
||||
|
||||
The [SDK driver](go-build-views.mjs) discovers all tools, answers the compound
|
||||
question, verifies exact facts and exports complete Evidence. Before: one
|
||||
complete inspection and export. After: summary, selected dependency and export.
|
||||
For the zero-dependency small case, the summary avoids an unnecessary empty
|
||||
query. Two repetitions alternate version/target order. All 208 other named
|
||||
catalog definitions agree; only Go inspection and the retained-view tool change.
|
||||
|
||||
| Input | Whole wall s before → after | Family CPU s before → after | Kernel family peak MiB before → after |
|
||||
| ---------- | --------------------------- | --------------------------- | ------------------------------------- |
|
||||
| GitHub CLI | 4.855–4.952 → 6.370–6.564 | 4.682–4.725 → 6.175–6.400 | 671.2–680.1 → 846.4–868.7 |
|
||||
| Go tool | 4.349–4.351 → 4.250–4.450 | 4.093–4.140 → 4.092–4.179 | 548.4–548.6 → 544.3–555.6 |
|
||||
|
||||
Cold selected-query calls take 1.719–1.751 s in the SDK task, including its
|
||||
output-schema validation. A separate warm diagnostic takes 1.712 s for the first
|
||||
query and 32.86 ms for the repeat in one session; both the client validator and
|
||||
retained facts are warm. This is not a paired whole-task speedup. The complete
|
||||
warm diagnostic is separately recorded, not mixed into the eight matched runs.
|
||||
|
||||
The [SDK counter](go-build-view-costs.py) counts the discovered input catalog
|
||||
once plus all arguments and text replies, including export: 229,183 → 195,643
|
||||
for GitHub CLI and 194,854 → 194,724 for the small case. Catalog cost grows
|
||||
193,192 → 193,652. This catalog-once projection is **not** the actual host
|
||||
exchange above; omitting repeated schemas would hide the compound-task penalty.
|
||||
|
||||
All qualified recordings use one CPU, a 4 GiB hard/3 GiB early family memory
|
||||
boundary, no swap and 192 tasks. Verified payload exits are zero, only the
|
||||
observer remains, and observed memory/task resource events are zero. Kernel
|
||||
family peaks include attributed file cache. Final whole-scope counters are
|
||||
unavailable. Release acquisition, oracle preparation and compilation are outside
|
||||
the timed tasks. An initial symlink input was correctly refused; qualification
|
||||
explicitly selects its regular target. One development static check was stopped
|
||||
by the host-available-memory guard, with owned cleanup verified and no observed
|
||||
OOM; the unchanged guard succeeded after headroom recovered.
|
||||
|
||||
## Coverage and reproduction
|
||||
|
||||
Executed: 10 files / 202 tests covering existing Go readers, mappings, provider,
|
||||
CLI/MCP and Rust readers, plus selected rows, duplicate paths, empty filters,
|
||||
identity-only fields, malformed/mutable parents, source conflicts, bounded
|
||||
messages and unavailable metadata. Actual CLI complete output is identical
|
||||
before/after; summary bundles retain that exact parent, and file-based CLI
|
||||
selected queries match the native oracle. Full `npm run check` passed.
|
||||
After rebasing onto main `c374c2fe7`, the 202 focused tests, full
|
||||
`npm run check` and `npm run docs:check` (including five README consistency
|
||||
tests) pass again. A real SDK selected query and complete export also pass
|
||||
against that rebuilt runtime, retaining the original parent identity and all
|
||||
165 dependencies. These checks do not relabel the frozen timing cohort.
|
||||
|
||||
A review found that a transcript-write failure could skip the SDK driver's
|
||||
cleanup. The shared finalizer now closes owned resources before publishing the
|
||||
optional transcript and records publication failures separately. All 11 receipt
|
||||
failure tests pass. A real selected SDK task and full export pass again; the
|
||||
same task with an injected transcript-write failure exits 1, preserves its
|
||||
answer and failure receipt, and verifies that the process family was cleaned.
|
||||
These qualification runs do not replace the frozen performance measurements.
|
||||
|
||||
A second review found that a valid external parent could disagree with its
|
||||
report's architecture. Go domain now owns the existing architecture-to-subject
|
||||
mapping; both Evidence production and every Go view use it. The view checks
|
||||
mapped architecture as well as path, digest and format, including `null` for
|
||||
unrecognized report names. All 213 focused tests pass, including authenticated
|
||||
inline/file conflicts and known-alias/unknown-architecture cases.
|
||||
|
||||
Initial CI also exposed two existing baseline failures. On unmodified `c374c2fe7`,
|
||||
`src/cliJsonPaths.test.ts` has the same three URL-message assertion failures.
|
||||
The duplication gate is already above its 3.5% threshold: 31,737 / 899,602 lines
|
||||
(3.52789%) on baseline versus 31,748 / 900,474 (3.52570%) on the initial PR head.
|
||||
These were reproduced separately with the pinned toolchain, bounded resources
|
||||
and verified cleanup; this PR leaves those unrelated failures unchanged.
|
||||
|
||||
Final qualification rebased onto main `cf5194f68`, preserving its new IL2CPP
|
||||
view contract alongside the Go additions. All 258 tests in 12 files pass,
|
||||
including 32 IL2CPP view tests and the now-fixed CLI path assertions. Full
|
||||
`npm run check`, `npm run docs:check` plus five README tests, and the real SDK
|
||||
selected query/full export pass again. Complete parent identity and all 165
|
||||
dependencies remain exact. Duplication now passes: baseline 31,644 / 904,778
|
||||
lines (3.49743%), PR 31,612 / 905,740 (3.49018%), against 3.5%.
|
||||
One latest-main build was guard-stopped during a host-memory dip; its owned
|
||||
scope was verified inactive with zero OOM events, then the unchanged guard's
|
||||
retry passed. These results qualify the rebased source, not new task timings.
|
||||
|
||||
The broader metadata audit also read three real Rust binaries. Alpine ripgrep
|
||||
14.1.1-r0's original `.dep-v0` matches native `readelf` coordinates and independent
|
||||
zlib/JSON decoding: 42 packages, 88 indexed edges, root index 33. The other two
|
||||
have no dependency section, which remains unknown coverage. Compiler-path
|
||||
inferences in all three match native read-only ranges and original byte offsets;
|
||||
they remain inferences. These fast metadata reads did not justify a Rust cache.
|
||||
The Alpine archive is pinned by observed SHA-256; APK signatures were not checked.
|
||||
Real provider verification here covers Linux ELF; PE/Mach-O use authored fixtures.
|
||||
|
||||
To reproduce, use built baseline/candidate runtimes and the pinned public input.
|
||||
Create a baseline complete CLI Evidence JSON, then pin the independent oracle:
|
||||
|
||||
```sh
|
||||
python3 experiments/analysis-efficiency/go-build-view-oracle.py \
|
||||
--evidence /tmp/baseline-evidence.json --input /absolute/gh \
|
||||
--go /absolute/go --dependency golang.org/x/crypto --output /tmp/go-oracle.json
|
||||
```
|
||||
|
||||
Run `go-build-views.mjs` with absolute `--runtime`, `--input`, `--oracle` and
|
||||
new `--output` directories, and `--mode complete` or `selected`, under
|
||||
`resource-run.py --observe-payload-exit`. `--warm` adds a separate diagnostic.
|
||||
The wire driver additionally requires pinned `--codex` and `--node`, and takes
|
||||
`--question identity --mode complete|summary` or
|
||||
`--question dependency --mode complete|selected`; `--export` adds export.
|
||||
All wire recordings require the same resource guard for owned-scope cleanup.
|
||||
Counter scripts take `--output` and recording directories, with their guard
|
||||
logs at the same path plus `.log`. Both counters require `tiktoken==0.12.0`.
|
||||
@@ -0,0 +1,228 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { finished } from "node:stream/promises";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { parseArgs } from "node:util";
|
||||
import { createRetainedQueryCaller } from "./retained-query-calls.mjs";
|
||||
import { finalizeRetainedQueryReceipt } from "./retained-query-finalization.mjs";
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
runtime: { type: "string" },
|
||||
input: { type: "string" },
|
||||
oracle: { type: "string" },
|
||||
output: { type: "string" },
|
||||
mode: { type: "string" },
|
||||
warm: { type: "boolean", default: false },
|
||||
},
|
||||
});
|
||||
for (const key of ["runtime", "input", "oracle", "output"])
|
||||
assert.equal(values[key], resolve(values[key]));
|
||||
assert.ok(["complete", "selected"].includes(values.mode));
|
||||
const oracle = JSON.parse(await readFile(values.oracle, "utf8"));
|
||||
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
const bytes = await readFile(values.input);
|
||||
assert.equal(sha256(bytes), oracle.artifact_sha256);
|
||||
const require = createRequire(join(values.runtime, "package.json"));
|
||||
const { Client } = await import(
|
||||
pathToFileURL(require.resolve("@modelcontextprotocol/client"))
|
||||
);
|
||||
const { StdioClientTransport } = await import(
|
||||
pathToFileURL(require.resolve("@modelcontextprotocol/client/stdio"))
|
||||
);
|
||||
await mkdir(values.output, { mode: 0o700 });
|
||||
const account = await mkdtemp(join(tmpdir(), "rea-go-build-views-"));
|
||||
const report = {
|
||||
question:
|
||||
"Report compiler, main module and the selected embedded dependency; preserve complete original Evidence.",
|
||||
mode: values.mode,
|
||||
warm_diagnostic: values.warm,
|
||||
calls: [],
|
||||
artifact_sha256: oracle.artifact_sha256,
|
||||
};
|
||||
const client = new Client({ name: "rea-go-build-views", version: "1" });
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [join(values.runtime, "scripts/rea.mjs"), "mcp"],
|
||||
env: {
|
||||
HOME: account,
|
||||
PATH: process.env.PATH,
|
||||
NODE_OPTIONS: "--max-old-space-size=2048",
|
||||
UV_THREADPOOL_SIZE: "1",
|
||||
REA_LOG_LEVEL: "silent",
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
const serverLog = createWriteStream(join(values.output, "server.log"));
|
||||
const serverLogFinished = finished(serverLog);
|
||||
serverLogFinished.catch(() => {});
|
||||
transport.stderr?.pipe(serverLog);
|
||||
const transcript = [];
|
||||
const call = createRetainedQueryCaller(client, (receipt, event) => {
|
||||
report.calls.push(receipt);
|
||||
transcript.push(event);
|
||||
});
|
||||
async function result(name, input, phase = name) {
|
||||
const reply = await call(name, input, phase);
|
||||
assert.ok(!reply.isError, JSON.stringify(reply));
|
||||
assert.ok(reply.structuredContent);
|
||||
assert.equal(reply.content.length, 1);
|
||||
assert.equal(reply.content[0].type, "text");
|
||||
assert.deepEqual(JSON.parse(reply.content[0].text), reply.structuredContent);
|
||||
return reply.structuredContent;
|
||||
}
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const catalog = await client.listTools();
|
||||
assert.equal(catalog.nextCursor, undefined);
|
||||
report.catalog_tools = catalog.tools.length;
|
||||
await writeFile(join(values.output, "catalog.json"), JSON.stringify(catalog));
|
||||
const definitions = new Map(catalog.tools.map((tool) => [tool.name, tool]));
|
||||
const original = client.callTool.bind(client);
|
||||
client.callTool = (input, options) =>
|
||||
original(input, {
|
||||
...options,
|
||||
timeout: 60000,
|
||||
toolDefinition: definitions.get(input.name),
|
||||
});
|
||||
const inspected = await result(
|
||||
"inspect_go_binary",
|
||||
{
|
||||
path: values.input,
|
||||
...(values.mode === "selected" ? { detail: "summary" } : {}),
|
||||
},
|
||||
"inspection:first",
|
||||
);
|
||||
let answer;
|
||||
if (values.mode === "complete") {
|
||||
report.parent_evidence_id = inspected.evidence_id;
|
||||
const info = inspected.normalized_result.build_info;
|
||||
assert.ok(info);
|
||||
answer = {
|
||||
go_version: info.go_version,
|
||||
main: info.module.main,
|
||||
runtime_dependencies: "unknown",
|
||||
dependencies: info.module.dependencies.flatMap((row, index) =>
|
||||
row.path === oracle.dependency_path ? [{ index, ...row }] : [],
|
||||
),
|
||||
};
|
||||
} else {
|
||||
const summary = inspected.normalized_result;
|
||||
assert.equal(summary.kind, "summary");
|
||||
report.parent_evidence_id = summary.parent_evidence_id;
|
||||
assert.equal(summary.source_coverage.runtime_dependencies, "unknown");
|
||||
assert.equal(
|
||||
summary.summary.build_info.module.available_counts.dependencies,
|
||||
oracle.dependency_count,
|
||||
);
|
||||
const input = {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: report.parent_evidence_id,
|
||||
},
|
||||
view: {
|
||||
kind: "go",
|
||||
collection: "dependencies",
|
||||
paths: [oracle.dependency_path],
|
||||
fields: ["path", "version", "sum", "replacement"],
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
},
|
||||
};
|
||||
let dependencies = [];
|
||||
if (summary.summary.build_info.module.available_counts.dependencies > 0) {
|
||||
const selected = await result(
|
||||
"inspect_analysis_view",
|
||||
input,
|
||||
"retained-query:first",
|
||||
);
|
||||
assert.equal(selected.normalized_result.coverage.exhausted, true);
|
||||
assert.equal(
|
||||
selected.normalized_result.source_coverage.runtime_dependencies,
|
||||
"unknown",
|
||||
);
|
||||
dependencies = selected.normalized_result.page.rows;
|
||||
if (values.warm) {
|
||||
const warm = await result(
|
||||
"inspect_analysis_view",
|
||||
input,
|
||||
"retained-query:warm-diagnostic",
|
||||
);
|
||||
assert.deepEqual(warm, selected);
|
||||
}
|
||||
}
|
||||
answer = {
|
||||
go_version: summary.summary.build_info.go_version,
|
||||
main: summary.summary.build_info.module.main,
|
||||
runtime_dependencies: "unknown",
|
||||
dependencies,
|
||||
};
|
||||
}
|
||||
assert.deepEqual(answer, oracle.answer);
|
||||
report.answer = answer;
|
||||
await result("export_evidence_bundle", {
|
||||
path: join(values.output, "evidence.json"),
|
||||
});
|
||||
const bundle = JSON.parse(
|
||||
await readFile(join(values.output, "evidence.json"), "utf8"),
|
||||
);
|
||||
const parent = bundle.records.find(
|
||||
(e) => e.evidence_id === report.parent_evidence_id,
|
||||
);
|
||||
assert.ok(parent);
|
||||
assert.equal(parent.operation, "inspect_go_binary");
|
||||
assert.deepEqual(parent.parameters, { path: values.input });
|
||||
assert.equal(
|
||||
parent.normalized_result.artifact.sha256,
|
||||
oracle.artifact_sha256,
|
||||
);
|
||||
// The pre-change normalized result was independently checked against native
|
||||
// go version -m and its file-backed bytes before pinning this exact JSON.
|
||||
const expected = JSON.parse(
|
||||
await readFile(oracle.complete_result_path, "utf8"),
|
||||
);
|
||||
assert.deepEqual(parent.normalized_result, expected);
|
||||
assert.equal(
|
||||
parent.normalized_result.build_info.module.dependencies.length,
|
||||
oracle.dependency_count,
|
||||
);
|
||||
for (const name of ["version", "module"]) {
|
||||
const info = parent.normalized_result.build_info;
|
||||
const location = info[name + "_location"];
|
||||
const encoded =
|
||||
info[(name === "version" ? "go_version" : "module") + "_bytes_base64"];
|
||||
assert.deepEqual(
|
||||
bytes.subarray(location.offset, location.offset + location.bytes),
|
||||
Buffer.from(encoded, "base64"),
|
||||
);
|
||||
}
|
||||
assert.equal(sha256(await readFile(values.input)), oracle.artifact_sha256);
|
||||
report.oracle_file_sha256 = sha256(await readFile(values.oracle));
|
||||
report.complete_result_file_sha256 = sha256(
|
||||
await readFile(oracle.complete_result_path),
|
||||
);
|
||||
report.status = "observed";
|
||||
} catch (cause) {
|
||||
report.status = "failed";
|
||||
report.failure = String(cause?.stack ?? cause);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (
|
||||
!(await finalizeRetainedQueryReceipt({
|
||||
report,
|
||||
client,
|
||||
transport,
|
||||
account,
|
||||
serverLog,
|
||||
serverLogFinished,
|
||||
output: values.output,
|
||||
transcript,
|
||||
}))
|
||||
)
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Count entire captured Codex request sequences, without claiming model usage."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import tiktoken
|
||||
|
||||
|
||||
def compact(value):
|
||||
return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def request_text(body):
|
||||
pieces = []
|
||||
if isinstance(body.get("instructions"), str):
|
||||
pieces.append(body["instructions"])
|
||||
for item in body.get("input", []):
|
||||
kind = item.get("type")
|
||||
if kind == "function_call_output":
|
||||
pieces.append(item["output"])
|
||||
elif kind == "function_call":
|
||||
pieces.append(item["arguments"])
|
||||
elif kind == "message" or "role" in item:
|
||||
for part in item.get("content", []):
|
||||
if isinstance(part, dict) and isinstance(part.get("text"), str):
|
||||
pieces.append(part["text"])
|
||||
return pieces
|
||||
|
||||
|
||||
def inspect(root, encoding):
|
||||
report = json.loads((root / "report.json").read_text())
|
||||
assert (report["status"] == "passed" and not report["cleanup_failures"]
|
||||
and report["appserver_exit_code"] == 0)
|
||||
requests = json.loads((root / "model-requests.json").read_text())
|
||||
whole, namespaces, texts = [], [], []
|
||||
count = lambda value: len(encoding.encode(value, disallowed_special=()))
|
||||
for event in requests:
|
||||
body = event["body"]
|
||||
whole.append(count(compact(body)))
|
||||
namespace = next(tool for tool in body["tools"]
|
||||
if tool.get("type") == "namespace"
|
||||
and tool["name"] == "mcp__rea_audit")
|
||||
namespaces.append(count(compact(namespace)))
|
||||
texts.append(sum(count(piece) for piece in request_text(body)))
|
||||
log = root.with_suffix(".log")
|
||||
scope = next(json.loads(line) for line in reversed(log.read_text().splitlines())
|
||||
if line.startswith('{"resource_scope":'))
|
||||
observed = scope["payload_resource_observation"]
|
||||
assert (scope["abort"] is None and scope["payload_resource_observation_verified"]
|
||||
and observed["payload_cleanup_verified"] and observed["payload_exit_code"] == 0)
|
||||
memory = observed["resource_events"]["memory.events"]
|
||||
assert all(memory[key] == 0 for key in ["high", "max", "oom", "oom_kill"])
|
||||
assert observed["resource_events"]["pids.events"]["max"] == 0
|
||||
return {"case": root.name, "question": report["question_kind"],
|
||||
"request_count": len(requests), "whole_request_json_proxy": whole,
|
||||
"whole_request_json_proxy_sum": sum(whole),
|
||||
"rea_namespace_json_proxy": namespaces,
|
||||
"rea_namespace_json_proxy_sum": sum(namespaces),
|
||||
"unescaped_instruction_and_input_text_proxy": texts,
|
||||
"rea_namespace_plus_text_proxy_sum": sum(namespaces) + sum(texts),
|
||||
"wall_seconds": scope["elapsed_seconds"],
|
||||
"family_cpu_seconds": observed["cpu_stat"]["usage_usec"] / 1e6,
|
||||
"family_peak_mib": observed["memory_peak_bytes"] / 2**20,
|
||||
"completed_with_verified_cleanup": True,
|
||||
"sha256": {file.name: hashlib.sha256(file.read_bytes()).hexdigest()
|
||||
for file in [root / "report.json", root / "model-requests.json",
|
||||
root / "transcript.json", log]}}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("cases", type=Path, nargs="+")
|
||||
args = parser.parse_args()
|
||||
encoding = tiktoken.get_encoding("cl100k_base")
|
||||
receipt = {"actual_model_usage": None,
|
||||
"backend": "deterministic local Responses SSE; no AI inference or paid service; not a model-quality or billing test",
|
||||
"client": "Codex app-server 0.163.0", "tiktoken": tiktoken.__version__,
|
||||
"encoding": encoding.name,
|
||||
"records": [inspect(root, encoding) for root in args.cases]}
|
||||
args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,292 @@
|
||||
"""Actual Codex wire capture with a deterministic local SSE backend; no AI inference."""
|
||||
import argparse
|
||||
import http.server
|
||||
import threading
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
import traceback
|
||||
import subprocess
|
||||
|
||||
|
||||
async def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--runtime", type=Path, required=True)
|
||||
parser.add_argument("--codex", type=Path, required=True)
|
||||
parser.add_argument("--node", type=Path, required=True)
|
||||
parser.add_argument("--input-profile", choices=["full", "compact"], default="full")
|
||||
parser.add_argument("--output-profile", choices=["full", "off"], default="full")
|
||||
parser.add_argument("--input", type=Path, required=True)
|
||||
parser.add_argument("--oracle", type=Path, required=True)
|
||||
parser.add_argument("--expected-tools", type=int, default=210)
|
||||
parser.add_argument("--mode", choices=["complete", "selected", "summary"], required=True)
|
||||
parser.add_argument("--export", action="store_true")
|
||||
parser.add_argument("--question", choices=["identity", "dependency"], default="dependency")
|
||||
args = parser.parse_args()
|
||||
assert args.question != "identity" or args.mode != "selected"
|
||||
assert args.mode != "summary" or args.question == "identity"
|
||||
oracle=json.loads(args.oracle.read_text())
|
||||
target=str(args.input)
|
||||
assert args.input.is_absolute() and args.oracle.is_absolute() and args.output.is_absolute()
|
||||
assert hashlib.sha256(args.input.read_bytes()).hexdigest()==oracle["artifact_sha256"]
|
||||
def delivered(pieces):
|
||||
assert isinstance(pieces,str) and pieces.startswith("Wall time: "), pieces[:300]
|
||||
_,sep,payload=pieces.partition("Output:\n");assert sep
|
||||
value=json.loads(payload)
|
||||
return value["result"] if "result" in value and "normalized_result" not in value else value
|
||||
def outputs_of(body):
|
||||
return {item["call_id"]:delivered(item["output"]) for item in body.get("input",[]) if item.get("type")=="function_call_output"}
|
||||
steps=1+(args.mode=="selected")+args.export
|
||||
args.output.mkdir(mode=0o700)
|
||||
audit_home = args.output / "account"
|
||||
codex_state = audit_home / ".codex"
|
||||
mcp_home = audit_home / "mcp"
|
||||
workspace = audit_home / "workspace"
|
||||
for directory in [codex_state, mcp_home, workspace]:
|
||||
directory.mkdir(parents=True)
|
||||
captured = []
|
||||
class Capture(http.server.BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
def do_POST(self):
|
||||
size = int(self.headers["Content-Length"])
|
||||
assert 0 < size <= 16 * 1024 * 1024
|
||||
assert self.headers.get("Content-Encoding", "identity") == "identity"
|
||||
body = json.loads(self.rfile.read(size))
|
||||
captured.append({"path": self.path, "body": body})
|
||||
(args.output / "model-requests.json").write_text(json.dumps(captured) + "\n")
|
||||
index = len(captured)
|
||||
names = [t.get("name", "") for ns in body.get("tools", []) if ns.get("type") == "namespace" and ns.get("name") == "mcp__rea_audit" for t in ns.get("tools", [])]
|
||||
assert index <= steps+1
|
||||
response_id=f"resp_local_{index}"
|
||||
if index <= steps:
|
||||
previous=outputs_of(body)
|
||||
if index==1:
|
||||
operation="inspect_go_binary";arguments={"path":target}
|
||||
if args.mode!="complete":arguments["detail"]="summary"
|
||||
elif args.mode=="selected" and index==2:
|
||||
parent=previous["call_local_1"]["normalized_result"]["parent_evidence_id"]
|
||||
operation="inspect_analysis_view";arguments={"source":{"kind":"retained-evidence","evidence_id":parent},"view":{"kind":"go","collection":"dependencies","paths":[oracle["dependency_path"]],"fields":["path","version","sum","replacement"],"offset":0,"limit":64}}
|
||||
else:
|
||||
operation="export_evidence_bundle";arguments={"path":str(args.output/"evidence.json")}
|
||||
selected=[name for name in names if name.endswith(operation)];assert len(selected)==1
|
||||
item={"type":"function_call","id":f"fc_local_{index}","call_id":f"call_local_{index}","name":selected[0],"namespace":"mcp__rea_audit","arguments":json.dumps(arguments),"status":"completed"}
|
||||
else:
|
||||
item={"type":"message","id":"msg_local_done","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Scripted local Go metadata query complete.","annotations":[]}]}
|
||||
base = {"id": response_id, "object": "response", "model": body.get("model"), "status": "completed", "output": [item]}
|
||||
events = [
|
||||
{"type": "response.created", "response": {**base, "status": "in_progress", "output": []}},
|
||||
{"type": "response.output_item.added", "output_index": 0, "item": {**item, "status": "in_progress"}},
|
||||
{"type": "response.output_item.done", "output_index": 0, "item": item},
|
||||
{"type": "response.completed", "response": base},
|
||||
]
|
||||
wire = "".join("event: " + e["type"] + "\ndata: " + json.dumps(e) + "\n\n" for e in events).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Content-Length", str(len(wire)))
|
||||
self.end_headers()
|
||||
self.wfile.write(wire)
|
||||
endpoint = http.server.HTTPServer(("127.0.0.1", 0), Capture)
|
||||
endpoint_thread = threading.Thread(target=endpoint.serve_forever, daemon=True)
|
||||
endpoint_thread.start()
|
||||
task_path = f"{args.node.parent}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
|
||||
mcp_env = {"HOME": str(mcp_home), "PATH": task_path,
|
||||
"NODE_OPTIONS": "--max-old-space-size=2048", "UV_THREADPOOL_SIZE": "1",
|
||||
"REA_LOG_LEVEL": "silent", "REA_MCP_INPUT_SCHEMA_PROFILE": args.input_profile,
|
||||
"REA_MCP_OUTPUT_SCHEMA_PROFILE": args.output_profile}
|
||||
config = 'model_provider = "rea_capture"\nmodel = "rea-wire-probe"\n[analytics]\nenabled = false\n[mcp_servers.rea_audit]\n'
|
||||
config += f'command = {json.dumps(str(args.node))}\n'
|
||||
config += f'args = {json.dumps([str(args.runtime / "scripts/rea.mjs"), "mcp"])}\n'
|
||||
config += 'startup_timeout_sec = 60\ntool_timeout_sec = 60\n'
|
||||
config += '[mcp_servers.rea_audit.env]\n'
|
||||
config += ''.join(f'{key} = {json.dumps(value)}\n' for key, value in mcp_env.items())
|
||||
for name in ['inspect_go_binary','inspect_analysis_view','export_evidence_bundle']:
|
||||
config += f'[mcp_servers.rea_audit.tools.{name}]\napproval_mode = "approve"\noutput_token_limit = 30000\n'
|
||||
config += f'\n[model_providers.rea_capture]\nname = "Local scripted capture"\nbase_url = "http://127.0.0.1:{endpoint.server_port}/v1"\nwire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\nrequest_max_retries = 0\nstream_max_retries = 0\n'
|
||||
(codex_state / "config.toml").write_text(config)
|
||||
(args.output / "declared-config.toml").write_text(config)
|
||||
environment = {"HOME": str(audit_home), "CODEX_HOME": str(codex_state), "PATH": task_path,
|
||||
"NODE_OPTIONS": "--max-old-space-size=2048", "UV_THREADPOOL_SIZE": "1"}
|
||||
report = {"question": "Read embedded Go identity/counts or a selected dependency. Export is a separate task variant.",
|
||||
"client": "Codex app-server 0.163.0", "model_turns_started": 1, "backend": "local deterministic SSE fixture; no AI model or paid service",
|
||||
"actual_model_usage": None, "input_profile": args.input_profile,
|
||||
"output_profile": args.output_profile, "calls": [], "observations": [],
|
||||
"unexpected_server_requests": [], "cleanup_failures": []}
|
||||
client_version = subprocess.check_output([str(args.codex), "--version"], env=environment, cwd=workspace, text=True, timeout=10).strip()
|
||||
assert client_version == "codex-cli 0.163.0", client_version
|
||||
transcript = []
|
||||
pending = {}
|
||||
completed_turn = asyncio.Event()
|
||||
next_id = 0
|
||||
stderr = (args.output / "server.log").open("wb")
|
||||
process = await asyncio.create_subprocess_exec(str(args.codex), "app-server", "--stdio",
|
||||
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=stderr,
|
||||
cwd=workspace, env=environment, limit=16 * 1024 * 1024)
|
||||
|
||||
async def send(message):
|
||||
encoded = (json.dumps(message, separators=(",", ":")) + "\n").encode()
|
||||
transcript.append({"direction": "client", "bytes": len(encoded), "message": message})
|
||||
process.stdin.write(encoded)
|
||||
await process.stdin.drain()
|
||||
|
||||
async def read_messages():
|
||||
try:
|
||||
while line := await process.stdout.readline():
|
||||
value = json.loads(line)
|
||||
transcript.append({"direction": "server", "bytes": len(line), "message": value})
|
||||
if value.get("method") == "turn/completed":
|
||||
report["turn"] = value["params"]["turn"]
|
||||
completed_turn.set()
|
||||
if "id" in value and "method" not in value:
|
||||
future = pending.pop(value["id"], None)
|
||||
if future and not future.done():
|
||||
future.set_result(value)
|
||||
elif "id" in value:
|
||||
report["unexpected_server_requests"].append(value["method"])
|
||||
await send({"id": value["id"], "error": {"code": -32601, "message": "Unexpected request in scripted metadata probe"}})
|
||||
raise RuntimeError("app-server stdout closed")
|
||||
except Exception as error:
|
||||
for future in pending.values():
|
||||
if not future.done():
|
||||
future.set_exception(error)
|
||||
|
||||
reader = asyncio.create_task(read_messages())
|
||||
|
||||
async def request(method, params):
|
||||
nonlocal next_id
|
||||
assert method in ["initialize", "thread/start", "mcpServerStatus/list", "mcpServer/tool/call", "turn/start"]
|
||||
next_id += 1
|
||||
message = {"id": next_id, "method": method, "params": params}
|
||||
future = asyncio.get_running_loop().create_future()
|
||||
pending[next_id] = future
|
||||
start = time.monotonic()
|
||||
await send(message)
|
||||
reply = await asyncio.wait_for(future, 90)
|
||||
report["calls"].append({"method": method, "elapsed_ms": (time.monotonic() - start) * 1000,
|
||||
"error": reply.get("error")})
|
||||
if "error" in reply:
|
||||
raise RuntimeError(json.dumps(reply["error"])[:4000])
|
||||
return reply["result"]
|
||||
|
||||
try:
|
||||
await request("initialize", {"clientInfo": {"name": "rea_host_probe", "title": "REA host compatibility probe", "version": "1"},
|
||||
"capabilities": {"experimentalApi": True, "explicitGatewayOauth": True}})
|
||||
await send({"method": "initialized"})
|
||||
created = await request("thread/start", {"cwd": str(workspace), "ephemeral": True,
|
||||
"approvalPolicy": "never", "sandbox": "read-only"})
|
||||
thread_id = created["thread"]["id"]
|
||||
assert not created["thread"].get("turns", [])
|
||||
inventory = await request("mcpServerStatus/list", {"threadId": thread_id,
|
||||
"serverName": "rea_audit", "detail": "toolsAndAuthOnly", "limit": 10})
|
||||
assert inventory.get("nextCursor") is None
|
||||
assert len(inventory["data"]) == 1
|
||||
server = inventory["data"][0]
|
||||
assert server["name"] == "rea_audit" and server.get("toolsError") is None
|
||||
tools = list(server["tools"].values())
|
||||
names = [tool["name"] for tool in tools]
|
||||
assert len(names) == len(set(names)) == args.expected_tools
|
||||
assert "inspect_go_binary" in names
|
||||
output_schemas = sum(tool.get("outputSchema") is not None for tool in tools)
|
||||
assert output_schemas == (args.expected_tools if args.output_profile == "full" else 0)
|
||||
raw = json.dumps(inventory, separators=(",", ":"), ensure_ascii=False).encode()
|
||||
(args.output / "catalog.json").write_bytes(raw)
|
||||
report["catalog"] = {"tools": len(tools), "output_schemas": output_schemas,
|
||||
"bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"server_info": server.get("serverInfo"), "runtime_status": server.get("runtimeStatus")}
|
||||
await request("turn/start", {"threadId": thread_id, "input": [{"type": "text", "text": ("Read the embedded Go compiler, main module and embedded dependency count; state runtime dependency coverage." if args.question=="identity" else "Read the embedded Go compiler, main module and golang.org/x/crypto dependency and state runtime dependency coverage.")+" The local fixture scripts the required tools; no AI inference is used."}]})
|
||||
await asyncio.wait_for(completed_turn.wait(), 90)
|
||||
assert report["turn"]["status"] == "completed", report["turn"]
|
||||
assert len(captured)==steps+1
|
||||
outputs=outputs_of(captured[-1]["body"])
|
||||
assert len(outputs)==steps
|
||||
initial=outputs["call_local_1"]
|
||||
assert initial["normalized_result"]["artifact"]["sha256"]==oracle["artifact_sha256"]
|
||||
if args.question=="identity":
|
||||
info=initial["normalized_result"]["build_info"] if args.mode=="complete" else initial["normalized_result"]["summary"]["build_info"]
|
||||
count=len(info["module"]["dependencies"]) if args.mode=="complete" else info["module"]["available_counts"]["dependencies"]
|
||||
facts={"go_version":info["go_version"],"main":info["module"]["main"],"runtime_dependencies":"unknown","dependency_count":count}
|
||||
parent=initial["evidence_id"] if args.mode=="complete" else initial["normalized_result"]["parent_evidence_id"]
|
||||
elif args.mode=="complete":
|
||||
info=initial["normalized_result"]["build_info"]
|
||||
facts={"go_version":info["go_version"],"main":info["module"]["main"],"runtime_dependencies":"unknown","dependencies":[{"index":i,**d} for i,d in enumerate(info["module"]["dependencies"]) if d["path"]==oracle["dependency_path"]]}
|
||||
parent=initial["evidence_id"]
|
||||
else:
|
||||
info=initial["normalized_result"]["summary"]["build_info"]
|
||||
selected=outputs["call_local_2"]["normalized_result"]
|
||||
assert selected["coverage"]["exhausted"] and selected["source_coverage"]["runtime_dependencies"]=="unknown"
|
||||
facts={"go_version":info["go_version"],"main":info["module"]["main"],"runtime_dependencies":"unknown","dependencies":selected["page"]["rows"]}
|
||||
parent=initial["normalized_result"]["parent_evidence_id"]
|
||||
expected=({key:oracle["answer"][key] for key in ["go_version","main","runtime_dependencies"]}|{"dependency_count":oracle["dependency_count"]}) if args.question=="identity" else oracle["answer"]
|
||||
assert facts==expected
|
||||
report["question_kind"]=args.question
|
||||
if args.export:
|
||||
bundle=json.loads((args.output/"evidence.json").read_text());evidence=next(e for e in bundle["records"] if e["evidence_id"]==parent)
|
||||
assert evidence["normalized_result"]==json.loads(Path(oracle["complete_result_path"]).read_text())
|
||||
report["observations"]={"answer":facts,"parent_evidence_id":parent,"exported":args.export}
|
||||
report["captured_requests"]=len(captured)
|
||||
report["mode"]=args.mode
|
||||
report["request_tool_counts"] = [len(c["body"].get("tools", [])) for c in captured]
|
||||
assert not report["unexpected_server_requests"]
|
||||
assert hashlib.sha256(args.input.read_bytes()).hexdigest()==oracle["artifact_sha256"]
|
||||
report["status"] = "passed"
|
||||
except Exception:
|
||||
report["status"] = "failed"
|
||||
report["failure"] = traceback.format_exc()[-6000:]
|
||||
finally:
|
||||
process.stdin.close()
|
||||
try:
|
||||
await asyncio.wait_for(process.wait(), 15)
|
||||
except asyncio.TimeoutError:
|
||||
report["cleanup_failures"].append("app-server did not exit after stdin close; terminated owned process")
|
||||
process.terminate()
|
||||
try:
|
||||
await asyncio.wait_for(process.wait(), 5)
|
||||
except asyncio.TimeoutError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
await reader
|
||||
# app-server can acknowledge exit before its MCP child finishes EOF
|
||||
# cleanup. Wait on the allocated resource scope; never target a PID.
|
||||
try:
|
||||
groups = [line[3:] for line in Path("/proc/self/cgroup").read_text().splitlines()
|
||||
if line.startswith("0::")]
|
||||
assert len(groups) == 1
|
||||
group = Path("/sys/fs/cgroup") / groups[0].lstrip("/")
|
||||
assert re.fullmatch(r"rea-efficiency-[0-9a-f]{32}\.scope", group.name)
|
||||
observer = os.getppid()
|
||||
observer_args = Path(f"/proc/{observer}/cmdline").read_bytes().split(b"\0")
|
||||
assert any(Path(os.fsdecode(value)).name == "resource_payload.py" for value in observer_args if value)
|
||||
expected = {os.getpid(), observer}
|
||||
until = time.monotonic() + 10
|
||||
while True:
|
||||
actors = {int(value) for value in (group / "cgroup.procs").read_text().splitlines()}
|
||||
assert expected <= actors
|
||||
remaining = sorted(actors - expected)
|
||||
if not remaining or time.monotonic() >= until:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
report["owned_scope_drain"] = {"remaining_processes": remaining}
|
||||
if remaining:
|
||||
report["cleanup_failures"].append("owned MCP child did not settle after app-server exit")
|
||||
except (OSError, ValueError, AssertionError) as error:
|
||||
report["owned_scope_drain"] = {"status": "unavailable", "reason": type(error).__name__}
|
||||
report["cleanup_failures"].append("allocated resource-scope cleanup could not be verified")
|
||||
endpoint.shutdown()
|
||||
endpoint.server_close()
|
||||
endpoint_thread.join(5)
|
||||
stderr.close()
|
||||
report["appserver_exit_code"] = process.returncode
|
||||
if process.returncode != 0:
|
||||
report["cleanup_failures"].append(f"app-server exit code: {process.returncode}")
|
||||
(args.output / "transcript.json").write_text(json.dumps(transcript) + "\n")
|
||||
(args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps({key: report.get(key) for key in ["status", "failure", "catalog", "observations", "cleanup_failures", "appserver_exit_code"]}))
|
||||
return 0 if report["status"] == "passed" and not report["cleanup_failures"] else 1
|
||||
|
||||
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
@@ -40,6 +40,7 @@ export const finalizeRetainedQueryReceipt = async ({
|
||||
serverLog,
|
||||
serverLogFinished,
|
||||
output,
|
||||
transcript,
|
||||
stdout = process.stdout,
|
||||
}) => {
|
||||
report.cleanup_failures = [];
|
||||
@@ -58,6 +59,10 @@ export const finalizeRetainedQueryReceipt = async ({
|
||||
if (report.cleanup_failures.length > 0) report.retained_workspace = account;
|
||||
|
||||
report.receipt_failures = [];
|
||||
if (transcript !== undefined)
|
||||
await attempt(report.receipt_failures, "transcript-file", () =>
|
||||
writeFile(join(output, "transcript.json"), JSON.stringify(transcript)),
|
||||
);
|
||||
let publication = 0;
|
||||
const saveReport = async () => {
|
||||
// Keep failed publications in the owned output directory for inspection.
|
||||
|
||||
@@ -109,6 +109,23 @@ assert.match(report.cleanup_failures[0],/^workspace:/);
|
||||
assert.equal(report.retained_workspace,malformedAccount);
|
||||
assert.deepEqual((await saved()).failure,originalFailure);
|
||||
assert.deepEqual(JSON.parse(chunks.join('')),report);
|
||||
''')
|
||||
|
||||
def test_transcript_failure_cannot_skip_cleanup_or_lose_original_failure(self):
|
||||
self.run_finalization('''
|
||||
await mkdir(join(output,'transcript.json'));
|
||||
const closed=[];
|
||||
assert.equal(await finalizeRetainedQueryReceipt({...input,transcript:[{phase:'page'}],
|
||||
client:{close:async()=>{closed.push('client');}},
|
||||
transport:{close:async()=>{closed.push('transport');}}}),false);
|
||||
assert.deepEqual(closed,['client','transport']);
|
||||
assert.equal(serverLog.writableEnded,true);
|
||||
await assert.rejects(stat(account),error=>error.code==='ENOENT');
|
||||
assert.deepEqual(report.cleanup_failures,[]);
|
||||
assert.match(report.receipt_failures[0],/^transcript-file:/);
|
||||
assert.strictEqual(report.failure,originalFailure);
|
||||
assert.equal(report.calls[0].elapsed_ms,17);
|
||||
assert.deepEqual(await saved(),report);assert.deepEqual(JSON.parse(chunks.join('')),report);
|
||||
''')
|
||||
|
||||
def test_report_file_refusal_preserves_the_stdout_receipt(self):
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface GoBinaryPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
input: Omit<InspectGoBinaryInput, "detail">,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<GoBinary, AnalysisError>>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { GoBinaryService } from "./GoBinaryService.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
@@ -45,6 +46,25 @@ it("rejects invalid paths and extra caller arguments before invoking the reader"
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it("requires a complete Evidence retention path before starting summary inspection", async () => {
|
||||
let calls = 0;
|
||||
const service = new GoBinaryService({
|
||||
identity,
|
||||
inspect: async () => {
|
||||
calls++;
|
||||
return ok(report);
|
||||
},
|
||||
});
|
||||
const result = await service.inspect({
|
||||
path: report.artifact.path,
|
||||
detail: "summary",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves unsupported subject architectures and does not duplicate metadata", async () => {
|
||||
const service = new GoBinaryService({
|
||||
identity,
|
||||
|
||||
@@ -8,27 +8,24 @@ import {
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
goArchitectureForSubject,
|
||||
goBinarySchema,
|
||||
inspectGoBinaryInputSchema,
|
||||
} from "../../domain/go/goBinary.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
|
||||
import {
|
||||
requireAnalysisViewRetention,
|
||||
summarizeRetainedAnalysis,
|
||||
type AnalysisViewRetention,
|
||||
} from "../analysisView/AnalysisViewService.js";
|
||||
|
||||
const OPERATION = "inspect_go_binary";
|
||||
const architectureForSubject = (architecture: string) => {
|
||||
switch (architecture) {
|
||||
case "386":
|
||||
return "x86";
|
||||
case "amd64":
|
||||
return "x86_64";
|
||||
default:
|
||||
return BINARY_ARCHITECTURES.find(
|
||||
(supported) => supported === architecture,
|
||||
);
|
||||
}
|
||||
const NO_RETENTION: AnalysisViewRetention = {
|
||||
recordEvidence: undefined,
|
||||
evidenceById: undefined,
|
||||
};
|
||||
|
||||
/** Shared exact input validation and artifact-bound Evidence for CLI and MCP. */
|
||||
@@ -43,6 +40,7 @@ export class GoBinaryService {
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
retention: AnalysisViewRetention = NO_RETENTION,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(
|
||||
@@ -65,7 +63,12 @@ export class GoBinaryService {
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
const { detail, ...providerInput } = input.data;
|
||||
if (detail === "summary") {
|
||||
const ready = requireAnalysisViewRetention(OPERATION, retention);
|
||||
if (!ready.ok) return ready;
|
||||
}
|
||||
const inspected = await this.provider.inspect(providerInput, options);
|
||||
if (!inspected.ok) return inspected;
|
||||
const report = goBinarySchema.safeParse(inspected.value);
|
||||
if (!report.success || report.data.artifact.path !== input.data.path)
|
||||
@@ -76,8 +79,8 @@ export class GoBinaryService {
|
||||
),
|
||||
);
|
||||
const value = report.data;
|
||||
const architecture = architectureForSubject(value.architecture);
|
||||
return completeProviderEvidence(
|
||||
const architecture = goArchitectureForSubject(value.architecture);
|
||||
const completed = completeProviderEvidence(
|
||||
createEvidence(
|
||||
{
|
||||
path: value.artifact.path,
|
||||
@@ -88,7 +91,7 @@ export class GoBinaryService {
|
||||
this.provider.identity,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: input.data,
|
||||
parameters: providerInput,
|
||||
result: value,
|
||||
confidence: "observed",
|
||||
limitations: value.limitations,
|
||||
@@ -108,5 +111,9 @@ export class GoBinaryService {
|
||||
),
|
||||
options?.signal,
|
||||
);
|
||||
if (!completed.ok) return completed;
|
||||
return detail === "summary"
|
||||
? summarizeRetainedAnalysis(completed.value, retention)
|
||||
: completed;
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ export const registerAnalysisViewCommands = (
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectAnalysisView, {
|
||||
description:
|
||||
"Project a selected view of completed binary-layout, JavaScript application, native function/inventory, artifact-inventory, desktop-directory, WASM, Mach-O, Interface Builder, EVM, managed, Android package, Dart AOT, web network capture or pcap Evidence JSON",
|
||||
"Project a selected view of completed Go build metadata, binary-layout, JavaScript application, native function/inventory, artifact-inventory, desktop-directory, WASM, Mach-O, Interface Builder, EVM, managed, Android package, Dart AOT, web network capture or pcap Evidence JSON",
|
||||
args: z.object({
|
||||
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
|
||||
}),
|
||||
|
||||
+13
-7
@@ -5,7 +5,10 @@ import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
|
||||
import {
|
||||
analysisEvidenceDeliveryOptions,
|
||||
deliverCliAnalysisEvidence,
|
||||
} from "./analysisEvidenceDelivery.js";
|
||||
import { absoluteCallerPath } from "../filesystem/callerPath.js";
|
||||
|
||||
/** Resolve caller paths and inspect static build metadata through the shared workflow. */
|
||||
@@ -16,24 +19,27 @@ export const registerGoCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
args: z.object({
|
||||
path: z.string().describe("Local ELF, PE or thin Mach-O image"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
options: z.object(analysisEvidenceDeliveryOptions),
|
||||
run: ({ args, options }) =>
|
||||
withCommandCancellation(async (signal) => {
|
||||
const service = createGoBinaryService();
|
||||
return await logCliCommand(
|
||||
logger,
|
||||
CLI_COMMANDS.inspectGoBinary,
|
||||
async () =>
|
||||
finishAnalysisCommand(
|
||||
() =>
|
||||
deliverCliAnalysisEvidence({
|
||||
run: () =>
|
||||
service.inspect(
|
||||
{ path: absoluteCallerPath(args.path) },
|
||||
{ signal },
|
||||
),
|
||||
service,
|
||||
"go-build-info",
|
||||
"inspect_go_binary",
|
||||
providerId: "go-build-info",
|
||||
operation: "inspect_go_binary",
|
||||
signal,
|
||||
),
|
||||
detail: options.detail,
|
||||
evidenceOutput: options.evidence_output,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
|
||||
...toolContractMetadata("inspect_analysis_view"),
|
||||
kind: "application",
|
||||
description:
|
||||
'Inspect selected views of completed binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_macho, decode_interface_builder, inspect_evm_interface, inspect_managed_artifact, inspect_managed_members, inspect_android_package, inspect_dart_aot, inspect_il2cpp_metadata or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized non-entity paths written by POST/PUT/PATCH (item-shaped and delete-only paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state, and every other read tool is a recorded view with a reason. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: "<absolute path>"}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/network states without reading WAT text. Select a layout mitigations/linkage facet, one section/symbol/module, or a stable page. Module pages include assets, bundled and source modules; use node_id for ambiguous or unavailable paths. Typed module refeLine truncated
|
||||
'Inspect selected views of completed Go build metadata, binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_macho, decode_interface_builder, inspect_evm_interface, inspect_managed_artifact, inspect_managed_members, inspect_android_package, inspect_dart_aot, inspect_il2cpp_metadata or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Go metadata uses kind go, collection dependencies/settings, exact paths/keys or indices, fields and pagination. Row index refers to the original collection; empty selections return no rows, and dependency coverage remains unknown. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized non-entity paths written by POST/PUT/PATCH (item-shaped and delete-only paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state, and every other read tool is a recorded view with a reason. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: "<absolute path>"}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/nLine truncated
|
||||
inputSchema: inspectAnalysisViewInputSchema,
|
||||
outputSchema: evidenceResultOf(analysisViewResultSchema),
|
||||
examples: [
|
||||
|
||||
@@ -4,7 +4,8 @@ import {
|
||||
} from "../../domain/go/goBinary.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
import { analysisDetailOutputSchemaOf } from "../analysisDetail.js";
|
||||
import { goBinarySummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
|
||||
|
||||
/** Static Go metadata is independent of active native-analysis providers and host toolchains. */
|
||||
export const GO_TOOL_CONTRACTS = [
|
||||
@@ -13,9 +14,12 @@ export const GO_TOOL_CONTRACTS = [
|
||||
...toolContractMetadata("inspect_go_binary"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Inspect embedded Go compiler version, main module, dependency/replacement versions and build settings in an explicit local ELF, PE or thin Mach-O image. Returns original artifact SHA-256, exact build-info source ranges, raw framed module bytes and unparsed module-text lines inline as observed Evidence. Supports inline and historical pointer encodings without installing Go, opening a disassembler, executing the target, writing temporary files or accessing the network. Missing metadata is reported as unknown, not proof that an image is not Go. Does not recover functions, source mappings, types or runtime behavior. Resource guards bound files to 256 MiB, aggregate embedded strings to 1 MiB, structural table decoding to 16 MiB and complete inline metadata to 8 MiB; malformed, unsupported and oversized inputs receive typed failures rather than partial success.",
|
||||
"Inspect embedded Go compiler version, main module, dependency/replacement versions and build settings in an explicit local ELF, PE or thin Mach-O image. Default detail complete returns original artifact SHA-256, exact build-info source ranges, raw framed module bytes and unparsed module-text lines inline as observed Evidence. Explicit detail summary retains the same complete parent and returns compiler/main-module identity, counts, source ranges and parent_evidence_id. Query retained rows through inspect_analysis_view kind go, collection dependencies or settings; select exact dependency paths or setting keys, indices, fields and pagination. Rows always retain their original index scoped to the parent Evidence; empty filters select none. Runtime dependency completeness remains unknown. Supports inline and historical pointer encodings without installing Go, opening a disassembler, executing the target, writing temporary files or accessing the network. Missing metadata is reported as unknown, not proof that an image is not Go. Does not recover functions, source mappings, types or runtime behavior. Resource guards bound files to 256 MiB, aggregate embedded strings to 1 MiB, structural table decoding to 16 MiB and complete inline metadata to 8 MiB; malformed, unsupported and oversized inputs receive typed failures rather than partial success.",
|
||||
inputSchema: inspectGoBinaryInputSchema,
|
||||
outputSchema: evidenceResultOf(goBinarySchema),
|
||||
outputSchema: analysisDetailOutputSchemaOf(
|
||||
goBinarySchema,
|
||||
goBinarySummaryViewResultSchema,
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect embedded build provenance",
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import {
|
||||
goBinarySummarySchema,
|
||||
goBinaryViewContextSchema,
|
||||
goBinaryViewPageSchema,
|
||||
goBinaryViewRequestSchema,
|
||||
projectGoBinaryView,
|
||||
} from "./goBinaryView.js";
|
||||
import {
|
||||
projectNativeFunctionMatchingView,
|
||||
nativeFunctionMatchingViewRequestSchema,
|
||||
@@ -250,6 +257,7 @@ const nativeViewSchema = z.strictObject({
|
||||
export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
|
||||
nativeFunctionMatchingViewRequestSchema,
|
||||
summaryViewSchema,
|
||||
goBinaryViewRequestSchema,
|
||||
desktopViewRequestSchema,
|
||||
facetViewSchema,
|
||||
itemViewSchema,
|
||||
@@ -361,6 +369,7 @@ const viewResultBase = {
|
||||
parent_evidence_id: prefixedDigestSchema("ev"),
|
||||
parent_operation: z.enum([
|
||||
"inspect_binary_layout",
|
||||
"inspect_go_binary",
|
||||
"inspect_desktop_application",
|
||||
"analyze_javascript_application",
|
||||
"analyze_function",
|
||||
@@ -394,6 +403,14 @@ const summaryViewResultBase = {
|
||||
...viewResultBase,
|
||||
} as const;
|
||||
|
||||
/** Opt-in Go delivery retains original bytes and exposes build identity/counts. */
|
||||
export const goBinarySummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
...goBinaryViewContextSchema.shape,
|
||||
parent_operation: z.literal("inspect_go_binary"),
|
||||
summary: goBinarySummarySchema,
|
||||
});
|
||||
|
||||
/** Summary `inspect_binary_layout` detail returns; no other view kind. */
|
||||
export const binaryLayoutSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
@@ -577,6 +594,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
view: environmentStateViewRequestSchema,
|
||||
}),
|
||||
z.discriminatedUnion("parent_operation", [
|
||||
goBinarySummaryViewResultSchema,
|
||||
binaryLayoutSummaryViewResultSchema,
|
||||
desktopApplicationSummaryViewResultSchema,
|
||||
javascriptApplicationSummaryViewResultSchema,
|
||||
@@ -641,6 +659,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
facet: jsonValueSchema,
|
||||
...viewResultBase,
|
||||
}),
|
||||
z.strictObject({
|
||||
...viewResultBase,
|
||||
...goBinaryViewContextSchema.shape,
|
||||
kind: z.literal("go"),
|
||||
parent_operation: z.literal("inspect_go_binary"),
|
||||
view: goBinaryViewRequestSchema,
|
||||
page: goBinaryViewPageSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("item"),
|
||||
view: itemViewSchema,
|
||||
@@ -851,6 +877,7 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
|
||||
|
||||
/** Named source owners for views that need no extra decoder or accumulator. */
|
||||
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
|
||||
["inspect_go_binary", projectGoBinaryView],
|
||||
...NATIVE_INVENTORY_OPERATIONS.map(
|
||||
(operation) => [operation, projectNativeInventoryView] as const,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { createEvidence } from "../evidence.js";
|
||||
import type { GoBinary } from "../go/goBinary.js";
|
||||
import {
|
||||
projectAnalysisView,
|
||||
type AnalysisViewParent,
|
||||
} from "./analysisView.js";
|
||||
|
||||
const report: GoBinary = {
|
||||
artifact: { path: "/artifacts/program", sha256: "a".repeat(64), bytes: 512 },
|
||||
format: "elf",
|
||||
architecture: "amd64",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
build_info: null,
|
||||
limitations: [],
|
||||
};
|
||||
const parent = (): AnalysisViewParent => {
|
||||
const evidence = createEvidence(
|
||||
{
|
||||
path: report.artifact.path,
|
||||
sha256: report.artifact.sha256,
|
||||
format: "elf",
|
||||
architecture: "x86_64",
|
||||
},
|
||||
{
|
||||
id: "go-build-info",
|
||||
name: "REA Go build-information reader",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
operation: "inspect_go_binary",
|
||||
parameters: { path: report.artifact.path },
|
||||
result: report,
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
return {
|
||||
evidenceId: evidence.evidence_id,
|
||||
operation: evidence.operation,
|
||||
subject: evidence.subject,
|
||||
normalizedResult: structuredClone(report),
|
||||
limitations: [],
|
||||
};
|
||||
};
|
||||
|
||||
it("validates mutable inline reports again after an earlier successful view", () => {
|
||||
const mutable = structuredClone(report);
|
||||
const input = { ...parent(), normalizedResult: mutable };
|
||||
expect(projectAnalysisView(input, { kind: "summary" }).ok).toBe(true);
|
||||
mutable.artifact.bytes = -1;
|
||||
expect(
|
||||
projectAnalysisView({ ...input, sealedResult: true }, { kind: "summary" })
|
||||
.ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("bounds inherited messages while keeping their complete parent reference", () => {
|
||||
const note = "Large source note: " + "x".repeat(300_000);
|
||||
const input = {
|
||||
...parent(),
|
||||
limitations: [note],
|
||||
};
|
||||
const result = projectAnalysisView(input, { kind: "summary" });
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.limitations.join(" ")).toContain(input.evidenceId);
|
||||
expect(result.value.limitations.join(" ")).toContain("omitted");
|
||||
expect(result.value.unknowns.join(" ")).toContain("runtime dependencies");
|
||||
expect(input.limitations[0]).toBe(note);
|
||||
});
|
||||
|
||||
it.each(["path", "digest", "format"] as const)(
|
||||
"rejects a Go parent whose authenticated %s conflicts with its report",
|
||||
(field) => {
|
||||
const input = parent();
|
||||
if (input.subject == null) throw new Error("Expected artifact subject");
|
||||
const subject = {
|
||||
...input.subject,
|
||||
...(field === "path" ? { local_path: "/artifacts/other" } : {}),
|
||||
...(field === "digest" ? { digest: { sha256: "b".repeat(64) } } : {}),
|
||||
};
|
||||
const result = projectAnalysisView(
|
||||
{
|
||||
...input,
|
||||
subject,
|
||||
...(field === "format"
|
||||
? { normalizedResult: { ...report, format: "pe" } }
|
||||
: {}),
|
||||
},
|
||||
{ kind: "summary" },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["386", "x86", true],
|
||||
["x86", "x86", true],
|
||||
["amd64", "x86_64", true],
|
||||
["x86_64", "x86_64", true],
|
||||
["arm64", "arm64", true],
|
||||
["future-cpu", null, true],
|
||||
["", null, true],
|
||||
["amd64", "arm64", false],
|
||||
["amd64", null, false],
|
||||
["future-cpu", "arm64", false],
|
||||
] as const)(
|
||||
"checks report architecture %j against subject %j for every Go view",
|
||||
(architecture, subjectArchitecture, accepted) => {
|
||||
const input = parent();
|
||||
if (input.subject == null) throw new Error("Expected artifact subject");
|
||||
const subject = { ...input.subject, architecture: subjectArchitecture };
|
||||
const normalizedResult = { ...report, architecture };
|
||||
for (const view of [
|
||||
{ kind: "summary" },
|
||||
{ kind: "go", collection: "dependencies", offset: 0, limit: 64 },
|
||||
] as const) {
|
||||
const result = projectAnalysisView(
|
||||
{ ...input, subject, normalizedResult },
|
||||
view,
|
||||
);
|
||||
expect(result.ok).toBe(accepted);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,312 @@
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import {
|
||||
goArchitectureForSubject,
|
||||
goBinarySchema,
|
||||
goBuildInfoSchema,
|
||||
goModuleMetadataSchema,
|
||||
goModuleSchema,
|
||||
type GoBinary,
|
||||
} from "../go/goBinary.js";
|
||||
import { isImmutableJsonSnapshot } from "../immutableJson.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import type {
|
||||
AnalysisViewParent,
|
||||
AnalysisViewRequest,
|
||||
UnsignedAnalysisView,
|
||||
} from "./analysisView.js";
|
||||
import {
|
||||
boundedViewMessages,
|
||||
completeWithinViewCoverage,
|
||||
pageViewCoverage,
|
||||
} from "./analysisViewCoverage.js";
|
||||
import { analysisViewInputError } from "./analysisViewErrors.js";
|
||||
import { parseAnalysisViewResult } from "./analysisViewParent.js";
|
||||
|
||||
const indexSchema = z.number().int().nonnegative();
|
||||
const count = z.number().int().nonnegative();
|
||||
const settingSchema = goModuleMetadataSchema.shape.settings.element;
|
||||
const page = {
|
||||
kind: z.literal("go"),
|
||||
indices: z.array(indexSchema).optional(),
|
||||
offset: indexSchema.default(0),
|
||||
limit: z.number().int().positive().default(64),
|
||||
};
|
||||
|
||||
/** Exact filters intersect; empty arrays select none. Offsets count matching rows. */
|
||||
export const goBinaryViewRequestSchema = z.discriminatedUnion("collection", [
|
||||
z.strictObject({
|
||||
...page,
|
||||
collection: z.literal("dependencies"),
|
||||
paths: z.array(z.string()).optional(),
|
||||
fields: z.array(goModuleSchema.keyof()).optional(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...page,
|
||||
collection: z.literal("settings"),
|
||||
keys: z.array(z.string()).optional(),
|
||||
fields: z.array(settingSchema.keyof()).optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const goBinaryViewPageSchema = z.discriminatedUnion("collection", [
|
||||
z.strictObject({
|
||||
collection: z.literal("dependencies"),
|
||||
rows: z.array(goModuleSchema.partial().extend({ index: indexSchema })),
|
||||
}),
|
||||
z.strictObject({
|
||||
collection: z.literal("settings"),
|
||||
rows: z.array(settingSchema.partial().extend({ index: indexSchema })),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const goBinaryViewContextSchema = z.strictObject({
|
||||
source_coverage: z.strictObject({
|
||||
build_info_available: z.boolean(),
|
||||
module_parse_complete: z.boolean().nullable(),
|
||||
runtime_dependencies: z.literal("unknown"),
|
||||
}),
|
||||
});
|
||||
|
||||
export const goBinarySummarySchema = z.strictObject({
|
||||
bytes: count,
|
||||
format: goBinarySchema.shape.format,
|
||||
architecture: goBinarySchema.shape.architecture,
|
||||
bits: goBinarySchema.shape.bits,
|
||||
byte_order: goBinarySchema.shape.byte_order,
|
||||
build_info: goBuildInfoSchema
|
||||
.omit({
|
||||
go_version_bytes_base64: true,
|
||||
module_text: true,
|
||||
module_bytes_base64: true,
|
||||
module: true,
|
||||
})
|
||||
.extend({
|
||||
module: goModuleMetadataSchema
|
||||
.omit({
|
||||
dependencies: true,
|
||||
settings: true,
|
||||
unparsed_lines: true,
|
||||
unparsed_line_bytes_base64: true,
|
||||
})
|
||||
.extend({
|
||||
available_counts: z.strictObject({
|
||||
dependencies: count,
|
||||
settings: count,
|
||||
unparsed_lines: count,
|
||||
unparsed_line_bytes_base64: count,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
.nullable(),
|
||||
});
|
||||
|
||||
// Reuse only authenticated immutable report facts, for their Evidence lifetime.
|
||||
// Inline mutable reports are validated each time; this never caches live files.
|
||||
const checkedReports = new WeakMap<object, GoBinary>();
|
||||
const parseReport = (
|
||||
parent: AnalysisViewParent,
|
||||
): Result<GoBinary, AnalysisError> => {
|
||||
const key = parent.normalizedResult;
|
||||
const reusable =
|
||||
parent.sealedResult === true &&
|
||||
typeof key === "object" &&
|
||||
key !== null &&
|
||||
isImmutableJsonSnapshot(key);
|
||||
const existing = reusable ? checkedReports.get(key) : undefined;
|
||||
if (existing !== undefined) return ok(existing);
|
||||
const parsed = parseAnalysisViewResult(goBinarySchema, parent);
|
||||
if (!parsed.ok) return parsed;
|
||||
// No schema transforms/coercions: keep the validated owner's frozen value.
|
||||
const report = reusable ? (key as GoBinary) : parsed.value;
|
||||
if (reusable) checkedReports.set(key, report);
|
||||
return ok(report);
|
||||
};
|
||||
|
||||
const selectRows = <Source, Row>(
|
||||
rows: readonly Source[],
|
||||
view: { readonly offset: number; readonly limit: number },
|
||||
matches: (row: Source, index: number) => boolean,
|
||||
project: (row: Source, index: number) => Row,
|
||||
): { rows: Row[]; total: number } => {
|
||||
const selected: Row[] = [];
|
||||
let total = 0;
|
||||
for (const [index, row] of rows.entries()) {
|
||||
if (!matches(row, index)) continue;
|
||||
if (total >= view.offset && selected.length < view.limit)
|
||||
selected.push(project(row, index));
|
||||
total++;
|
||||
}
|
||||
return { rows: selected, total };
|
||||
};
|
||||
|
||||
/** Query the existing metadata owner's facts; never reopen or reinterpret a file. */
|
||||
export const projectGoBinaryView = (
|
||||
parent: AnalysisViewParent,
|
||||
view: AnalysisViewRequest,
|
||||
): Result<UnsignedAnalysisView, AnalysisError> => {
|
||||
if (view.kind !== "summary" && view.kind !== "go")
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["view"],
|
||||
reason: "invalid_value",
|
||||
message: "Go build Evidence supports summary and go views.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const parsed = parseReport(parent);
|
||||
if (!parsed.ok) return parsed;
|
||||
const report = parsed.value;
|
||||
if (
|
||||
parent.subject?.local_path !== report.artifact.path ||
|
||||
parent.subject.digest.sha256 !== report.artifact.sha256 ||
|
||||
parent.subject.format !==
|
||||
(report.format === "macho" ? "mach-o" : report.format) ||
|
||||
parent.subject.architecture !==
|
||||
(goArchitectureForSubject(report.architecture) ?? null)
|
||||
)
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["source", "subject"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Go parent subject must identify the report's exact artifact.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const info = report.build_info;
|
||||
const runtimeUnknown =
|
||||
"Embedded build records do not establish complete runtime dependencies or target behavior.";
|
||||
const unknowns = [
|
||||
runtimeUnknown,
|
||||
...(info === null
|
||||
? [
|
||||
"Build information is unavailable; language and dependencies remain unknown.",
|
||||
]
|
||||
: [
|
||||
...(info.module.complete
|
||||
? []
|
||||
: [
|
||||
"Some module records were not parsed; consult the complete parent Evidence for original lines and bytes.",
|
||||
]),
|
||||
...(info.module.main === null
|
||||
? [
|
||||
"No main module was decoded; embedded dependency coverage remains unknown.",
|
||||
]
|
||||
: []),
|
||||
]),
|
||||
];
|
||||
const shared = {
|
||||
parent_evidence_id: parent.evidenceId,
|
||||
parent_operation: "inspect_go_binary" as const,
|
||||
parent_digest: parent.evidenceId.slice(3),
|
||||
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
|
||||
source_coverage: {
|
||||
build_info_available: info !== null,
|
||||
module_parse_complete: info?.module.complete ?? null,
|
||||
runtime_dependencies: "unknown" as const,
|
||||
},
|
||||
limitations: boundedViewMessages(
|
||||
[...parent.limitations, ...report.limitations],
|
||||
parent.evidenceId,
|
||||
"limitations",
|
||||
),
|
||||
unknowns: boundedViewMessages(unknowns, parent.evidenceId, "unknowns", [
|
||||
runtimeUnknown,
|
||||
]),
|
||||
};
|
||||
if (view.kind === "summary")
|
||||
return ok({
|
||||
kind: "summary",
|
||||
view,
|
||||
...shared,
|
||||
summary: {
|
||||
bytes: report.artifact.bytes,
|
||||
format: report.format,
|
||||
architecture: report.architecture,
|
||||
bits: report.bits,
|
||||
byte_order: report.byte_order,
|
||||
build_info:
|
||||
info === null
|
||||
? null
|
||||
: {
|
||||
header_offset: info.header_offset,
|
||||
encoding: info.encoding,
|
||||
go_version: info.go_version,
|
||||
version_location: info.version_location,
|
||||
module_location: info.module_location,
|
||||
module: {
|
||||
path: info.module.path,
|
||||
main: info.module.main,
|
||||
complete: info.module.complete,
|
||||
available_counts: {
|
||||
dependencies: info.module.dependencies.length,
|
||||
settings: info.module.settings.length,
|
||||
unparsed_lines: info.module.unparsed_lines.length,
|
||||
unparsed_line_bytes_base64:
|
||||
info.module.unparsed_line_bytes_base64.length,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
coverage: completeWithinViewCoverage(1, 1),
|
||||
});
|
||||
const indices =
|
||||
view.indices === undefined ? undefined : new Set(view.indices);
|
||||
const fields =
|
||||
view.fields === undefined ? undefined : new Set<string>(view.fields);
|
||||
if (view.collection === "dependencies") {
|
||||
const paths = view.paths === undefined ? undefined : new Set(view.paths);
|
||||
const selected = selectRows(
|
||||
info?.module.dependencies ?? [],
|
||||
view,
|
||||
(row, index) =>
|
||||
(indices?.has(index) ?? true) && (paths?.has(row.path) ?? true),
|
||||
(row, index) => ({
|
||||
index,
|
||||
...((fields?.has("path") ?? true) && { path: row.path }),
|
||||
...((fields?.has("version") ?? true) && { version: row.version }),
|
||||
...((fields?.has("sum") ?? true) && { sum: row.sum }),
|
||||
...((fields?.has("replacement") ?? true) && {
|
||||
replacement: row.replacement,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return ok({
|
||||
kind: "go",
|
||||
view,
|
||||
...shared,
|
||||
page: { collection: "dependencies", rows: selected.rows },
|
||||
coverage: pageViewCoverage(
|
||||
view.offset,
|
||||
selected.rows.length,
|
||||
selected.total,
|
||||
),
|
||||
});
|
||||
}
|
||||
const keys = view.keys === undefined ? undefined : new Set(view.keys);
|
||||
const selected = selectRows(
|
||||
info?.module.settings ?? [],
|
||||
view,
|
||||
(row, index) =>
|
||||
(indices?.has(index) ?? true) && (keys?.has(row.key) ?? true),
|
||||
(row, index) => ({
|
||||
index,
|
||||
...((fields?.has("key") ?? true) && { key: row.key }),
|
||||
...((fields?.has("value") ?? true) && { value: row.value }),
|
||||
}),
|
||||
);
|
||||
return ok({
|
||||
kind: "go",
|
||||
view,
|
||||
...shared,
|
||||
page: { collection: "settings", rows: selected.rows },
|
||||
coverage: pageViewCoverage(
|
||||
view.offset,
|
||||
selected.rows.length,
|
||||
selected.total,
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -1,8 +1,23 @@
|
||||
import { z } from "zod";
|
||||
import { BINARY_ARCHITECTURES } from "../binaryTargetTypes.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
import { canonicalBase64Schema } from "../stringPatterns.js";
|
||||
|
||||
/** Map reader architecture names into Evidence identity; unknown names stay unknown. */
|
||||
export const goArchitectureForSubject = (architecture: string) => {
|
||||
switch (architecture) {
|
||||
case "386":
|
||||
return "x86";
|
||||
case "amd64":
|
||||
return "x86_64";
|
||||
default:
|
||||
return BINARY_ARCHITECTURES.find(
|
||||
(supported) => supported === architecture,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const sourceRangeSchema = z.strictObject({
|
||||
offset: z.number().int().nonnegative(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
@@ -34,6 +49,12 @@ export const inspectGoBinaryInputSchema = z.strictObject({
|
||||
path: localPathStringSchema.describe(
|
||||
"Absolute filesystem path to the selected executable or library",
|
||||
),
|
||||
detail: z
|
||||
.enum(["complete", "summary"])
|
||||
.default("complete")
|
||||
.describe(
|
||||
"complete returns all metadata inline; summary retains complete Evidence and returns build identity and counts for subsequent retained Go views.",
|
||||
),
|
||||
});
|
||||
|
||||
/** Compiler-written build information and its original file-backed source ranges. */
|
||||
|
||||
@@ -211,7 +211,7 @@ export class GoBinaryProvider implements GoBinaryPort {
|
||||
|
||||
/** Read complete compiler/module metadata while preserving original byte identity and source ranges. */
|
||||
async inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
input: Omit<InspectGoBinaryInput, "detail">,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<GoBinary, AnalysisError>> {
|
||||
try {
|
||||
|
||||
@@ -741,6 +741,7 @@ const registerConfiguredAnalysisTools = (
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
evidenceById,
|
||||
);
|
||||
registerIl2cppTools(
|
||||
server,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
|
||||
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
@@ -14,11 +15,13 @@ export const registerGoTools = (
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
evidenceById?: EvidenceLookup,
|
||||
): void => {
|
||||
const contract = toolContract("inspect_go_binary");
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspect(input, options),
|
||||
(input, options) =>
|
||||
service.inspect(input, options, { recordEvidence, evidenceById }),
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { goBinarySchema } from "../../src/domain/go/goBinary.js";
|
||||
import { evidenceResultOf } from "../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { machoImageWithUnknownCommand } from "../../src/artifacts/apple/MachoImage.fixture.js";
|
||||
import {
|
||||
createGoBinaryByteStringFixture,
|
||||
@@ -16,9 +17,69 @@ import {
|
||||
} from "../fixtures/go/image.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { parseMcpToolError } from "../fixtures/mcpToolError.js";
|
||||
|
||||
cliTest(
|
||||
"delivers a Go CLI summary with its unchanged complete source bundle",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-go-cli-summary-");
|
||||
const path = join(root, "application.elf");
|
||||
const output = join(root, "source.json");
|
||||
await writeFile(path, createGoBinaryFixture().bytes);
|
||||
const complete = await cli.run({
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(complete.exitCode, complete.stderr).toBe(0);
|
||||
const full = evidenceResultOf(goBinarySchema).parse(complete.json);
|
||||
const summary = await cli.run({
|
||||
arguments: [
|
||||
"inspect-go-binary",
|
||||
path,
|
||||
"--detail",
|
||||
"summary",
|
||||
"--evidence_output",
|
||||
output,
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(summary.exitCode, summary.stderr).toBe(0);
|
||||
expect(summary.json).toMatchObject({
|
||||
summary: {
|
||||
normalized_result: {
|
||||
kind: "summary",
|
||||
parent_evidence_id: full.evidence_id,
|
||||
source_coverage: { runtime_dependencies: "unknown" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const bundle = JSON.parse(await readFile(output, "utf8")) as {
|
||||
records: unknown[];
|
||||
};
|
||||
expect(
|
||||
bundle.records
|
||||
.map((record) => parseEvidence(record))
|
||||
.find((record) => record.evidence_id === full.evidence_id),
|
||||
).toEqual(full);
|
||||
const refused = await cli.run({
|
||||
arguments: [
|
||||
"inspect-go-binary",
|
||||
join(root, "missing"),
|
||||
"--detail",
|
||||
"summary",
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(refused.exitCode).toBe(1);
|
||||
expect(refused.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ path: ["evidence_output"] }] },
|
||||
});
|
||||
},
|
||||
30000,
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"bounds overlapping ELF scans through CLI and keeps MCP responsive",
|
||||
async ({ cli }) => {
|
||||
@@ -63,9 +124,7 @@ cliTest(
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.normalized_result.build_info).not.toBeNull();
|
||||
infos.push(evidence.normalized_result.build_info);
|
||||
const response = await call("inspect_go_binary", { path });
|
||||
@@ -101,9 +160,7 @@ for (const bits of [32, 64] as const) {
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.subject?.digest.sha256).toBe(
|
||||
createHash("sha256").update(bytes).digest("hex"),
|
||||
);
|
||||
@@ -168,9 +225,7 @@ cliTest(
|
||||
}
|
||||
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
format: "macho",
|
||||
bits: fixture.bits,
|
||||
@@ -228,9 +283,7 @@ cliTest(
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.normalized_result.build_info).toEqual(
|
||||
fixture.expectedBuildInfo,
|
||||
);
|
||||
@@ -290,9 +343,7 @@ for (const format of ["elf", "pe", "macho"] as const) {
|
||||
cwd: root,
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.raw_result).toBeNull();
|
||||
expect(evidence.subject?.local_path).toBe(path);
|
||||
expect(evidence.subject?.digest.sha256).toBe(
|
||||
@@ -362,9 +413,7 @@ cliTest("preserves MIPS identity in Go CLI Evidence", async ({ cli }) => {
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.subject?.architecture).toBe("mips");
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
architecture: "mips",
|
||||
@@ -383,7 +432,7 @@ cliTest(
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
const report = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
const report = evidenceResultOf(goBinarySchema).parse(
|
||||
result.json,
|
||||
).normalized_result;
|
||||
expect(report.build_info).toBeNull();
|
||||
@@ -407,9 +456,7 @@ cliTest(
|
||||
arguments: ["inspect-go-binary", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
result.json,
|
||||
);
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(result.json);
|
||||
expect(evidence.normalized_result.build_info?.module).toMatchObject({
|
||||
path: "example.com/tool/cmd/tool",
|
||||
main: null,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { goBinarySchema } from "../../../src/domain/go/goBinary.js";
|
||||
import type { Client } from "@modelcontextprotocol/client";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
@@ -6,7 +7,10 @@ import { expect } from "vitest";
|
||||
import { readAnalysisSnapshot } from "../../../src/application/binary/AnalysisSnapshotFiles.js";
|
||||
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
evidenceResultOf,
|
||||
expandToolAvailability,
|
||||
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
@@ -97,7 +101,7 @@ mcpTest(
|
||||
expect(inspected.isError, JSON.stringify(inspected.content)).not.toBe(
|
||||
true,
|
||||
);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(
|
||||
inspected.structuredContent,
|
||||
);
|
||||
expect(evidence.subject?.architecture).toBe("mips");
|
||||
@@ -165,7 +169,7 @@ goMcpTest(
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
const evidence = evidenceResultOf(goBinarySchema).parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
expect(evidence.normalized_result.build_info).toEqual(
|
||||
@@ -256,7 +260,7 @@ goMcpTest(
|
||||
ajv.validate(outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
).toBe(true);
|
||||
const parsed = toolContract("inspect_go_binary").outputSchema.parse(
|
||||
const parsed = evidenceResultOf(goBinarySchema).parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
const evidence = parseEvidence(parsed);
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
import { readFile, unlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import type { AnySchema } from "ajv";
|
||||
import type { Client } from "@modelcontextprotocol/client";
|
||||
import {
|
||||
createEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../../../src/domain/evidence.js";
|
||||
import { goBinarySchema } from "../../../src/domain/go/goBinary.js";
|
||||
import {
|
||||
analysisViewResultSchema,
|
||||
goBinarySummaryViewResultSchema,
|
||||
} from "../../../src/domain/analysisView/analysisView.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createGoBinaryFixture,
|
||||
GO_MODULE_TEXT,
|
||||
} from "../../fixtures/go/image.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
type Operation = "inspect_go_binary" | "inspect_analysis_view";
|
||||
const goViewTest = mcpTest.extend<{
|
||||
goViews: {
|
||||
client: Client;
|
||||
root: string;
|
||||
path: string;
|
||||
bytes: Buffer;
|
||||
call: (
|
||||
name: Operation,
|
||||
input: Record<string, unknown>,
|
||||
) => Promise<Evidence>;
|
||||
};
|
||||
}>({
|
||||
goViews: async ({ mcp }, use) => {
|
||||
const root = await createTestTempDirectory("rea-go-views-");
|
||||
const path = join(root, "application");
|
||||
const fixture = createGoBinaryFixture({
|
||||
goVersion: "go1.26.0",
|
||||
moduleText:
|
||||
GO_MODULE_TEXT +
|
||||
"dep\texample.com/dependency\tv2.0.0\th1:second\nfuture\tunknown\n",
|
||||
});
|
||||
await writeFile(path, fixture.bytes);
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("No disassembler for Go views");
|
||||
});
|
||||
try {
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }),
|
||||
);
|
||||
const catalog = await client.listTools();
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
const schemas = new Map(
|
||||
catalog.tools
|
||||
.filter(
|
||||
(tool) =>
|
||||
tool.name === "inspect_go_binary" ||
|
||||
tool.name === "inspect_analysis_view",
|
||||
)
|
||||
.map((tool) => {
|
||||
const output = tool.outputSchema as AnySchema;
|
||||
expect(tool.outputSchema?.$schema).toBe(
|
||||
"https://json-schema.org/draft/2020-12/schema",
|
||||
);
|
||||
expect(ajv.validateSchema(output)).toBe(true);
|
||||
return [
|
||||
tool.name,
|
||||
{
|
||||
input: ajv.compile(tool.inputSchema),
|
||||
output: ajv.compile(output),
|
||||
},
|
||||
] as const;
|
||||
}),
|
||||
);
|
||||
const call = async (name: Operation, input: Record<string, unknown>) => {
|
||||
const schema = schemas.get(name)!;
|
||||
expect(schema.input(input), JSON.stringify(schema.input.errors)).toBe(
|
||||
true,
|
||||
);
|
||||
const reply = await client.callTool({ name, arguments: input });
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
expect(
|
||||
schema.output(reply.structuredContent),
|
||||
JSON.stringify(schema.output.errors),
|
||||
).toBe(true);
|
||||
return parseEvidence(reply.structuredContent);
|
||||
};
|
||||
await use({ client, root, path, bytes: fixture.bytes, call });
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const goPage = (evidence: Evidence) => {
|
||||
const view = analysisViewResultSchema.parse(evidence.normalized_result);
|
||||
if (view.kind !== "go") throw new Error("Expected a Go row page");
|
||||
return view;
|
||||
};
|
||||
|
||||
goViewTest(
|
||||
"rejects authenticated inline and file parents with conflicting architecture",
|
||||
async ({ goViews: { client, root, path, call } }) => {
|
||||
const complete = await call("inspect_go_binary", { path });
|
||||
const report = goBinarySchema.parse(complete.normalized_result);
|
||||
const conflicting = createEvidence(
|
||||
{
|
||||
path,
|
||||
sha256: report.artifact.sha256,
|
||||
format: "elf",
|
||||
architecture: "arm64",
|
||||
},
|
||||
{ id: "go-build-info", name: "Go metadata test fixture", version: "1" },
|
||||
{
|
||||
operation: "inspect_go_binary",
|
||||
parameters: { path },
|
||||
result: report,
|
||||
confidence: "observed",
|
||||
},
|
||||
);
|
||||
const evidencePath = join(root, "conflicting.json");
|
||||
await writeFile(evidencePath, JSON.stringify(conflicting));
|
||||
for (const source of [
|
||||
{ kind: "inline", evidence: conflicting },
|
||||
{ kind: "evidence-file", path: evidencePath },
|
||||
]) {
|
||||
for (const view of [
|
||||
{ kind: "summary" },
|
||||
{ kind: "go", collection: "dependencies" },
|
||||
]) {
|
||||
const reply = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: { source, view },
|
||||
});
|
||||
expect(parseMcpToolError(reply).error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
operation: "inspect_analysis_view",
|
||||
issues: [{ path: ["source", "subject"], reason: "invalid_value" }],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
goViewTest(
|
||||
"retains exact Go rows and complete Evidence after source removal",
|
||||
async ({ goViews: { client, root, path, bytes, call } }) => {
|
||||
const complete = await call("inspect_go_binary", { path });
|
||||
const report = goBinarySchema.parse(complete.normalized_result);
|
||||
const summary = await call("inspect_go_binary", {
|
||||
path,
|
||||
detail: "summary",
|
||||
});
|
||||
expect(summary).toMatchObject({
|
||||
raw_result: null,
|
||||
normalized_result: {
|
||||
kind: "summary",
|
||||
parent_evidence_id: complete.evidence_id,
|
||||
source_coverage: {
|
||||
build_info_available: true,
|
||||
module_parse_complete: false,
|
||||
runtime_dependencies: "unknown",
|
||||
},
|
||||
summary: {
|
||||
build_info: {
|
||||
go_version: "go1.26.0",
|
||||
module: {
|
||||
available_counts: {
|
||||
dependencies: 2,
|
||||
settings: 3,
|
||||
unparsed_lines: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(await readFile(path)).toEqual(bytes);
|
||||
await unlink(path);
|
||||
const source = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: complete.evidence_id,
|
||||
};
|
||||
const view = {
|
||||
kind: "go",
|
||||
collection: "dependencies",
|
||||
paths: ["example.com/dependency"],
|
||||
fields: ["version", "replacement"],
|
||||
offset: 0,
|
||||
limit: 1,
|
||||
};
|
||||
const first = goPage(await call("inspect_analysis_view", { source, view }));
|
||||
expect(first.page.rows).toEqual([
|
||||
{
|
||||
index: 0,
|
||||
version: "v1.2.3",
|
||||
replacement: report.build_info!.module.dependencies[0]!.replacement,
|
||||
},
|
||||
]);
|
||||
expect(first.coverage).toMatchObject({
|
||||
total: 2,
|
||||
next_offset: 1,
|
||||
exhausted: false,
|
||||
});
|
||||
const second = goPage(
|
||||
await call("inspect_analysis_view", {
|
||||
source,
|
||||
view: { ...view, offset: 1 },
|
||||
}),
|
||||
);
|
||||
expect(second.page.rows).toEqual([
|
||||
{ index: 1, version: "v2.0.0", replacement: null },
|
||||
]);
|
||||
expect(second.coverage).toMatchObject({
|
||||
total: 2,
|
||||
next_offset: null,
|
||||
exhausted: true,
|
||||
});
|
||||
const bundlePath = join(root, "evidence.json");
|
||||
const exported = await client.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: { path: bundlePath },
|
||||
});
|
||||
expect(exported.isError, JSON.stringify(exported)).not.toBe(true);
|
||||
const bundle = JSON.parse(await readFile(bundlePath, "utf8")) as {
|
||||
records: unknown[];
|
||||
};
|
||||
expect(
|
||||
bundle.records
|
||||
.map((record) => parseEvidence(record))
|
||||
.find((record) => record.evidence_id === complete.evidence_id),
|
||||
).toEqual(complete);
|
||||
await client.ping();
|
||||
},
|
||||
);
|
||||
|
||||
goViewTest(
|
||||
"intersects exact Go selections and keeps row identity with no selected fields",
|
||||
async ({ goViews: { client, path, call } }) => {
|
||||
const summary = goBinarySummaryViewResultSchema.parse(
|
||||
(await call("inspect_go_binary", { path, detail: "summary" }))
|
||||
.normalized_result,
|
||||
);
|
||||
const source = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: summary.parent_evidence_id,
|
||||
};
|
||||
const identity = goPage(
|
||||
await call("inspect_analysis_view", {
|
||||
source,
|
||||
view: { kind: "go", collection: "dependencies", fields: [] },
|
||||
}),
|
||||
);
|
||||
expect(identity.page.rows).toEqual([{ index: 0 }, { index: 1 }]);
|
||||
for (const selection of [
|
||||
{ paths: [] },
|
||||
{ indices: [] },
|
||||
{ paths: ["other"], indices: [1] },
|
||||
{ offset: 99 },
|
||||
]) {
|
||||
const empty = goPage(
|
||||
await call("inspect_analysis_view", {
|
||||
source,
|
||||
view: { kind: "go", collection: "dependencies", ...selection },
|
||||
}),
|
||||
);
|
||||
expect(empty.page.rows).toEqual([]);
|
||||
expect(empty.coverage).toMatchObject({
|
||||
next_offset: null,
|
||||
exhausted: true,
|
||||
});
|
||||
}
|
||||
const selected = goPage(
|
||||
await call("inspect_analysis_view", {
|
||||
source,
|
||||
view: {
|
||||
kind: "go",
|
||||
collection: "dependencies",
|
||||
paths: ["example.com/dependency"],
|
||||
indices: [1],
|
||||
fields: ["version"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(selected.page.rows).toEqual([{ index: 1, version: "v2.0.0" }]);
|
||||
const setting = goPage(
|
||||
await call("inspect_analysis_view", {
|
||||
source,
|
||||
view: {
|
||||
kind: "go",
|
||||
collection: "settings",
|
||||
keys: ["GOOS"],
|
||||
fields: ["value"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(setting.page.rows).toEqual([{ index: 1, value: "linux" }]);
|
||||
expect(setting.coverage.total).toBe(1);
|
||||
const invalid = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: {
|
||||
source,
|
||||
view: {
|
||||
kind: "go",
|
||||
collection: "dependencies",
|
||||
fields: ["module_bytes_base64"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"keeps unavailable Go metadata unknown in summaries and empty pages",
|
||||
async ({ mcp }) => {
|
||||
const root = await createTestTempDirectory("rea-go-absent-view-");
|
||||
const path = join(root, "application");
|
||||
await writeFile(path, createGoBinaryFixture({ omitBuildInfo: true }).bytes);
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("No deep provider");
|
||||
});
|
||||
try {
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }),
|
||||
);
|
||||
const reply = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path, detail: "summary" },
|
||||
});
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
const summary = goBinarySummaryViewResultSchema.parse(
|
||||
parseEvidence(reply.structuredContent).normalized_result,
|
||||
);
|
||||
expect(summary).toMatchObject({
|
||||
summary: { build_info: null },
|
||||
source_coverage: {
|
||||
build_info_available: false,
|
||||
module_parse_complete: null,
|
||||
runtime_dependencies: "unknown",
|
||||
},
|
||||
});
|
||||
const source = {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: summary.parent_evidence_id,
|
||||
};
|
||||
const empty = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: { source, view: { kind: "go", collection: "dependencies" } },
|
||||
});
|
||||
expect(empty.isError, JSON.stringify(empty)).not.toBe(true);
|
||||
const page = goPage(parseEvidence(empty.structuredContent));
|
||||
expect(page).toMatchObject({
|
||||
page: { rows: [] },
|
||||
coverage: { total: 0 },
|
||||
source_coverage: {
|
||||
build_info_available: false,
|
||||
module_parse_complete: null,
|
||||
runtime_dependencies: "unknown",
|
||||
},
|
||||
});
|
||||
expect(page.unknowns.join(" ")).toContain("remain unknown");
|
||||
const incompatible = await client.callTool({
|
||||
name: "inspect_analysis_view",
|
||||
arguments: { source, view: { kind: "native", facet: "procedure" } },
|
||||
});
|
||||
expect(parseMcpToolError(incompatible).error.code).toBe(
|
||||
"invalid_request",
|
||||
);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user