Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7fdd7e153 | ||
|
|
3c794a5cc0 | ||
|
|
16caa5ca9b | ||
|
|
5100a1a1a5 | ||
|
|
de0d341524 | ||
|
|
d1f04512af | ||
|
|
514df0918c | ||
|
|
8fb79c67ee | ||
|
|
6a41a29963 | ||
|
|
c12a532b9c | ||
|
|
b28c0337fc | ||
|
|
f4e437e544 | ||
|
|
8ba0a887ff | ||
|
|
f9ea9a9268 | ||
|
|
78778d91a4 | ||
|
|
d510f3e928 | ||
|
|
043fd2579d | ||
|
|
a761981897 | ||
|
|
2653b194b6 | ||
|
|
16d9c5adef | ||
|
|
b582b6ecb4 | ||
|
|
ba056e08a4 | ||
|
|
cb13a27bfa | ||
|
|
3d79903fb1 | ||
|
|
dce81ca400 | ||
|
|
bb764d26bd | ||
|
|
acd8d86898 | ||
|
|
e6d0b3993d | ||
|
|
92a901e0db | ||
|
|
cef6d6d3c4 | ||
|
|
bd972bf80b | ||
|
|
ac9709a80a | ||
|
|
d1e6fe2eca | ||
|
|
a147ecd4b4 | ||
|
|
22fdcb8ab7 | ||
|
|
b22d817073 | ||
|
|
3d876c5c1a | ||
|
|
cf346368c4 | ||
|
|
e52c0a72c5 | ||
|
|
999e3e2098 | ||
|
|
2a6bef5589 | ||
|
|
c1217e711b | ||
|
|
0d89978333 | ||
|
|
cace19caad | ||
|
|
11e3fae697 | ||
|
|
87b7bf8db1 | ||
|
|
3b66532e26 | ||
|
|
3ad063b454 | ||
|
|
69485e27f7 | ||
|
|
603d04ee3a | ||
|
|
472f313232 | ||
|
|
1f7e279aa2 | ||
|
|
db8ccaa251 | ||
|
|
5daff4d67e | ||
|
|
a9fd1aecae | ||
|
|
abb8e81d3a |
@@ -2,7 +2,7 @@
|
||||
name: reverse-engineer-anything
|
||||
description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
|
||||
metadata:
|
||||
version: "36"
|
||||
version: "37"
|
||||
---
|
||||
|
||||
# REA
|
||||
@@ -25,57 +25,18 @@ a skill installed from repository main may describe capabilities absent from
|
||||
an older npm release. Keep complete inline Evidence when that server does not
|
||||
advertise retained references.
|
||||
|
||||
When tools are absent or registration is stale:
|
||||
If tools are absent, a call is blocked by the client, or a required provider is
|
||||
unavailable, read [connection and recovery](references/connection-and-recovery.md).
|
||||
Diagnose the observed blocker, continue useful supported work, and resume the
|
||||
original task after repair. Client approval, shell PATH, registration and engine
|
||||
availability have different remedies; avoid repeating setup for all of them.
|
||||
|
||||
1. Diagnose without changing files. For Codex, run
|
||||
`npx -y rea-agents@latest doctor --client codex --json`. Substitute the current
|
||||
supported client: `claude_code`, `claude_desktop`, `codex`, `cursor`,
|
||||
`gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`, `copilot_cli`,
|
||||
`commandcode`, `qwen_code`, `vscode`, `grok_build`, `omp`, `pi`, `hermes`, or `grok_bot`. `grok_bot` has no local
|
||||
file registration: doctor reports the Grok Bot chat step, and setup does not
|
||||
write `mcp.json`. If the client is unknown, use `doctor --json` and
|
||||
inspect its registration results before choosing a setup scope.
|
||||
2. Distinguish the reason. Missing, malformed, or stale registration needs a
|
||||
scoped configuration repair. An aligned registration with no tools in the
|
||||
active session needs a restart/reconnection; doctor cannot prove that the
|
||||
current agent has connected. A missing provider affects only tasks requiring
|
||||
that provider: static JavaScript inspection needs neither Hopper nor Ghidra,
|
||||
and Android inspection has separate bring-your-own JADX/Java prerequisites.
|
||||
3. For a configuration repair, prepare the read-only plan:
|
||||
`npx -y rea-agents@latest setup --client codex --dry-run --json`.
|
||||
Use the current client's ID, show its exact proposed paths, backups, and
|
||||
changes, and obtain approval before setup writes configuration or installs
|
||||
Hopper. Setup normally installs the matching bundled skill too; include that
|
||||
replacement in the reviewed plan. After approval, apply the same scope with
|
||||
`npx -y rea-agents@latest setup --client codex --yes`. Add `--install-hopper`
|
||||
only if that separate installation was needed and explicitly approved.
|
||||
4. Restart/reconnect the affected agent. Verify that REA tools actually appear
|
||||
in the session, then resume the original investigation. If they remain
|
||||
absent, inspect the client's MCP launch error rather than repeating setup.
|
||||
|
||||
REA setup never installs or upgrades Node.js, npm, Homebrew, Java, Ghidra, IDA,
|
||||
JADX, Binwalk, or Unblob. Use existing prerequisites; do not install unrelated
|
||||
software to repair
|
||||
MCP registration. For an unsupported client, use manual stdio registration
|
||||
with a version-pinned `rea-agents` package or continue through the CLI.
|
||||
|
||||
A concrete CLI fallback for an operator-supplied JavaScript tree or ASAR is:
|
||||
|
||||
```bash
|
||||
npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json > app-evidence.json
|
||||
jq -c '{source: {kind: "inline", evidence: .}, view: {kind: "summary"}}' app-evidence.json > app-view.json
|
||||
npx -y rea-agents@latest inspect-analysis-view app-view.json
|
||||
```
|
||||
|
||||
No MCP registration or native engine is required. The CLI returns the complete
|
||||
Evidence record directly, and a real application can produce hundreds of
|
||||
megabytes, so save it to a file rather than reading it into context. Start from
|
||||
the summary view, then request a module page
|
||||
(`{"kind": "page", "collection": "modules", "offset": 0, "limit": 32}`) or one
|
||||
module the same way, or pass the saved Evidence inline to
|
||||
`trace-application-feature`. Read graph, limitations, and unknowns with the
|
||||
same care as an MCP result. This fallback does not establish that MCP is
|
||||
configured. Native CLI tasks still require their selected engine.
|
||||
Prefer an existing `rea` CLI. When none is installed and REA package acquisition
|
||||
is within the authorized scope, use `npx -y rea-agents@latest` in its place.
|
||||
Configuration repair starts with a read-only setup plan; show paths, backups and
|
||||
skill replacement before applying authorized changes. Preserve existing approval
|
||||
and target-execution boundaries. REA setup never installs or upgrades unrelated
|
||||
software, including Node.js, npm, Homebrew, Java, Ghidra, IDA, JADX, Binwalk or Unblob.
|
||||
|
||||
## Route the target first
|
||||
|
||||
@@ -140,9 +101,11 @@ after opening; IDA does not supply `binary_overview`. Consult session availabili
|
||||
when composing broader workflows. Modern direct callers and unsupported dossier
|
||||
facets remain unknown; live IDA results are not replayed from snapshots.
|
||||
|
||||
If the app is missing, ask which app to inspect. Resolve a human-readable app
|
||||
name to one clear installed artifact when possible; ask only when matches are
|
||||
ambiguous. Never choose an example app on the user's behalf.
|
||||
If the user says only "my app" without a name, path, or target already selected
|
||||
for this task, ask which app before searching for artifacts. Paths in unrelated
|
||||
saved reports and nearby test fixtures do not select the user's target. Resolve
|
||||
an actual human-readable app name to one clear installed artifact when possible;
|
||||
ask when matches are ambiguous. Never choose an example app on the user's behalf.
|
||||
|
||||
In a target-free session, use `open_binary` to bind any archive/package or
|
||||
native target whose analysis tool operates on the active target. Do not call an
|
||||
@@ -157,7 +120,11 @@ For a JavaScript application or ELF layout whose size is unknown or large,
|
||||
call `analyze_javascript_application` or `inspect_binary_layout` with
|
||||
`"detail": "summary"`, then inspect the retained `parent_evidence_id` with
|
||||
`inspect_analysis_view`.
|
||||
Do not repeat an identical tool call. Make a focused follow-up only when the
|
||||
Page module identities and select the returned `node_id` before requesting an
|
||||
item; a single file path can represent several graph roles. Do not repeat an
|
||||
identical analysis or rejected call without a changed input or resolved blocker.
|
||||
Recheck session state when a lifecycle change makes that status useful.
|
||||
Make a focused follow-up only when the
|
||||
returned result leaves a specific question unanswered.
|
||||
|
||||
If MCP reports `resource_constraint` with `details.resource: "transport"`, call
|
||||
@@ -168,6 +135,14 @@ session to a selected path. The analysis remains complete in the ledger; avoid
|
||||
repeating it merely to request the same oversized response. Complete CLI JSON
|
||||
output also streams without a single MCP frame.
|
||||
|
||||
A client can also truncate a successful tool result without a REA transport
|
||||
error. Treat that preview as incomplete; use the retained parent ID for smaller
|
||||
views or export when the full record is needed. Do not parse the preview as
|
||||
canonical JSON or repeat the producer. For JavaScript, read the
|
||||
[module-view and trace recipes](references/javascript-applications.md) before
|
||||
drilling into a large graph; a broad bidirectional trace can expand unrelated
|
||||
containment relationships even after summary analysis.
|
||||
|
||||
Every conclusion must distinguish observations, inferences, and unknowns. Cite
|
||||
Evidence IDs, preserve limitations and incomplete coverage, and never imply
|
||||
that static analysis observed execution. Runtime requests execute the declared
|
||||
@@ -175,7 +150,9 @@ target and lifecycle; do not broaden the target or action beyond those fields.
|
||||
|
||||
Within the user's requested investigation, call available analysis tools
|
||||
directly. REA does not require permission grants or per-call approval flags.
|
||||
Follow the declared request scope and the host's actual access requirements.
|
||||
The agent client can independently require approval. Follow the declared request
|
||||
scope and the host's actual access requirements; use the recovery guide for an
|
||||
observed client-policy rejection.
|
||||
|
||||
## Plan broader investigations
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
# Connection and task recovery
|
||||
|
||||
Read this guide only for an observed connection, command, approval or provider
|
||||
blocker. Keep the user's target and question in view. Explain what prevented the
|
||||
operation and the next useful step; after repair, continue the investigation.
|
||||
|
||||
Commands below use an installed `rea`. If none is available, use the package
|
||||
invocation in `SKILL.md` when acquiring REA is authorized. Follow the connected
|
||||
server's schemas and the installed CLI's help rather than assuming repository
|
||||
main and an older release expose the same arguments.
|
||||
|
||||
## Choose the remedy from the observed failure
|
||||
|
||||
| Observation | Meaning and next step |
|
||||
| --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| No REA tools in the active session | Inspect registration with `rea doctor --client codex --json`. A skill installation alone does not register MCP. |
|
||||
| Missing, malformed or stale registration | Prepare a scoped setup plan; apply only authorized changes with backups. |
|
||||
| Aligned registration, but no connected tools | Restart/reconnect the client. Doctor checks registration; it cannot establish the current agent's connection. Inspect the client's launch error if reconnection fails. |
|
||||
| `MCP tool call requires approval, but approval policy is never` | Codex rejected the call before REA executed it. Do not install an engine or repeat setup to solve this client-policy decision. See the approval section below. |
|
||||
| REA returns `provider_unavailable` or an unavailable tool entry | Read that operation's provider diagnostics or `binary_session.result.tool_availability`. Resolve only the prerequisite needed for the task; a complete tool catalog does not imply every operation is available. |
|
||||
| `rea` is missing in a child shell, or Node is incompatible | Inspect the actual shell PATH and launcher/runtime. A prefix installation may be absent from a login shell's PATH; this does not establish a broken MCP registration. |
|
||||
|
||||
If the client cannot launch its shell/sandbox helper or read the installed skill,
|
||||
inspect its launch diagnostic. For example, Codex can refuse helper aliases when
|
||||
CODEX_HOME is under `/tmp`; use an authorized profile outside the OS temporary
|
||||
directory. REA setup cannot repair the client's executor. Preserve the sandbox
|
||||
instead of silently disabling it to make an analysis command work.
|
||||
|
||||
Static JavaScript and ordinary ZIP inventory need neither Hopper nor Ghidra.
|
||||
HAR inspection is offline and does not require a live browser. Native
|
||||
decompilation, Android analysis and firmware extraction have their own
|
||||
bring-your-own prerequisites. Use supported inventory/static evidence when it
|
||||
answers part of the question, and name the unavailable evidence separately.
|
||||
Do not substitute another target. Label observations from ordinary shell tools
|
||||
as such; only actual REA output supplies REA Evidence.
|
||||
|
||||
## Repair registration when needed
|
||||
|
||||
For Codex:
|
||||
|
||||
```bash
|
||||
rea doctor --client codex --json
|
||||
rea setup --client codex --dry-run --json
|
||||
```
|
||||
|
||||
Use the current supported client's ID: `claude_code`, `claude_desktop`, `codex`,
|
||||
`cursor`, `gemini_cli`, `windsurf`, `devin`, `opencode`, `antigravity`,
|
||||
`copilot_cli`, `commandcode`, `qwen_code`, `vscode`, `grok_build`, `omp`, `pi`,
|
||||
`hermes`, or `grok_bot`. If unknown, inspect `doctor --json` before choosing a
|
||||
scope. `grok_bot` uses a chat registration step rather than local `mcp.json`.
|
||||
For unsupported clients, use version-pinned manual stdio registration or CLI.
|
||||
|
||||
Show the plan's exact paths, backups, changes and bundled-skill replacement.
|
||||
Obtain approval for writes when that concrete scope is not already authorized,
|
||||
then apply the same scope with `rea setup --client codex --yes`. Add
|
||||
`--install-hopper` only when separately needed and explicitly approved. Do not
|
||||
install or upgrade unrelated prerequisites. Restart/reconnect, verify tools
|
||||
actually appear, and resume the original task. If they remain absent, inspect
|
||||
the launch failure rather than looping through setup.
|
||||
|
||||
## Codex tool approval is separate from REA readiness
|
||||
|
||||
REA tools have no permission-grant handshake. Codex can still require approval
|
||||
because an operation creates owned resources, launches a helper or has cleanup
|
||||
effects. An advertised tool or successful doctor result does not override that
|
||||
client policy. `workspace-write` alone does not resolve an MCP approval
|
||||
rejection, and `approval_policy = "never"` does not mean every MCP tool is
|
||||
preapproved.
|
||||
|
||||
When interactive approval is available, use the client's approval flow for the
|
||||
requested operation. In an unattended run, continue through an authorized CLI
|
||||
workflow if the execution environment permits it, or report the blocked
|
||||
operation and the approval needed to proceed. Do not retry the same rejected
|
||||
call, silently broaden approvals, or rewrite MCP effects as read-only.
|
||||
|
||||
For an operator who explicitly wants to preapprove named operations in a
|
||||
disposable Codex profile, current Codex supports per-tool configuration. For
|
||||
example, opening and closing an analysis session can be scoped independently:
|
||||
|
||||
```toml
|
||||
[mcp_servers.rea.tools.open_binary]
|
||||
approval_mode = "approve"
|
||||
|
||||
[mcp_servers.rea.tools.close_binary]
|
||||
approval_mode = "approve"
|
||||
```
|
||||
|
||||
Use the actual server ID and only the operations whose effects were approved;
|
||||
this example does not approve inspection, extraction or runtime execution.
|
||||
Show the proposed config edit and preserve unrelated entries and backups before
|
||||
writing. Managed policy can constrain client settings. Consult the
|
||||
[Codex configuration reference](https://learn.chatgpt.com/docs/config-file/config-reference)
|
||||
for the installed client's supported settings. This is an optional recovery
|
||||
choice, not a prerequisite for every REA task.
|
||||
|
||||
## Continue through an installed CLI
|
||||
|
||||
Check the command environment only if the launcher fails:
|
||||
|
||||
```bash
|
||||
command -v rea
|
||||
command -v node
|
||||
node --version
|
||||
rea --version
|
||||
```
|
||||
|
||||
Use the public launcher at its known installation path with a supported existing
|
||||
Node on PATH when the child shell loses a prefix installation. Avoid internal
|
||||
`dist/cli.js` entrypoints or global toolchain changes. MCP may have its own valid
|
||||
launcher even when a shell cannot resolve `rea`.
|
||||
|
||||
For a user-supplied JavaScript tree or ASAR, select output files in the authorized
|
||||
workspace and save complete Evidence before reading a view:
|
||||
|
||||
```bash
|
||||
rea analyze-javascript-application /absolute/path/to/app --json > app-evidence.json
|
||||
jq -c '{source: {kind: "inline", evidence: .}, view: {kind: "summary"}}' app-evidence.json > app-view.json
|
||||
rea inspect-analysis-view app-view.json
|
||||
```
|
||||
|
||||
These commands do not register MCP or install an analysis engine. CLI JavaScript
|
||||
JSON is complete and can be very large; redirect it rather than loading it into
|
||||
context. Use an existing JSON processor if `jq` is absent, without installing
|
||||
one just for this recipe. Inspect a module page or item using the same inline
|
||||
source and the [JavaScript recipes](javascript-applications.md). Preserve graph
|
||||
coverage, limitations and unknowns. Native CLI analysis still requires its
|
||||
selected engine, and all CLI operations retain the host's execution permissions.
|
||||
@@ -1,20 +1,90 @@
|
||||
# JavaScript and Electron application artifacts
|
||||
|
||||
Use `analyze_javascript_application` directly on the operator-supplied ASAR or
|
||||
extracted tree. The complete result, graph, and Evidence context are returned
|
||||
inline when they fit the MCP frame. Source-map contents are part of the static analysis. Start from its
|
||||
findings, coverage, unknowns, and graph context, then make a focused follow-up
|
||||
only when a specific question remains unanswered.
|
||||
extracted tree. When size is unknown or large and the connected schema advertises
|
||||
`detail`, request `detail: "summary"`. This returns an `inspect_analysis_view`
|
||||
Evidence record with a distinct ID and a `normalized_result.parent_evidence_id`
|
||||
for the complete retained application analysis. Source-map contents are part of
|
||||
that static analysis. Read findings, coverage, limitations and unknowns, then
|
||||
follow a specific unanswered question. Older servers without `detail` return
|
||||
the complete application Evidence inline when it fits.
|
||||
|
||||
## Read a module without repeating analysis
|
||||
|
||||
Use the actual returned parent ID, on the same connection, as `source.evidence_id`.
|
||||
The following IDs are placeholders to replace with returned values. When the
|
||||
module's node ID is not already known, page identities before selecting an item.
|
||||
Pages return only node IDs, paths and roles; choose a useful page size and follow
|
||||
`coverage.next_offset` when another page matters:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": {
|
||||
"kind": "retained-evidence",
|
||||
"evidence_id": "ev_ACTUAL_PARENT_ID"
|
||||
},
|
||||
"view": { "kind": "page", "collection": "modules", "offset": 0, "limit": 16 }
|
||||
}
|
||||
```
|
||||
|
||||
Select the relevant page entry by its exact `node_id` and recorded role:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": {
|
||||
"kind": "retained-evidence",
|
||||
"evidence_id": "ev_ACTUAL_PARENT_ID"
|
||||
},
|
||||
"view": {
|
||||
"kind": "item",
|
||||
"collection": "modules",
|
||||
"selector": { "node_id": "jag_node_ACTUAL_NODE_ID" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Module pages include asset, bundled and source module roles, so one path can
|
||||
identify several entries. Use `selector.path` only when uniqueness is established;
|
||||
the returned node ID avoids needing a complete inventory to prove uniqueness. On ambiguity,
|
||||
select the matching node ID from the page or the error's candidates. Follow
|
||||
`next_offset` when another page matters. An item exposes that module node's
|
||||
recorded observations, identity, hashes, exports and source ranges; it does not
|
||||
include every child syntax observation, related edge or original source file.
|
||||
An absent item fact is not evidence of absence from the whole application.
|
||||
|
||||
## Trace only the remaining question
|
||||
|
||||
Use `trace_application_feature` on the parent application Evidence for one
|
||||
literal node ID, route, string, API, IPC channel, module, or native export.
|
||||
Select `incoming` for relationships leading to the seed, `outgoing` for those
|
||||
leaving it, and `both` when the question needs both. Trace traversal includes
|
||||
containment relationships, so even a narrow seed can expand many nodes; a
|
||||
bidirectional trace can reach unrelated sibling modules. A module item or page
|
||||
is preferable when its observations already answer the question. Do not treat
|
||||
all reached nodes as participants in the feature.
|
||||
|
||||
Reuse retained parent Evidence when the server advertises it, or supply complete
|
||||
Evidence inline. Include Hopper or Ghidra Evidence only when its artifact digest
|
||||
matches exactly.
|
||||
|
||||
## Recover an oversized display
|
||||
|
||||
An oversized response reports `resource_constraint` and
|
||||
`details.resource: "transport"`. Reuse
|
||||
`details.reported_limits.evidence_reference` with `inspect_analysis_view` for a
|
||||
summary, one module, or a stable page of module identities. Use
|
||||
`trace_application_feature` once a module, route, or string seed is known.
|
||||
summary, one module, or a stable page of module identities.
|
||||
`export_evidence_bundle` writes the complete canonical session to a
|
||||
caller-selected file. These workflows keep the original Evidence and coverage;
|
||||
a broad follow-up can also exceed framing.
|
||||
|
||||
A client can truncate a successful result inside its text envelope without a
|
||||
REA `resource_constraint`. Treat a truncation notice or incomplete JSON as a
|
||||
display limitation; do not claim the full record was examined. Reuse the known
|
||||
parent ID for smaller views, or export complete Evidence to a selected file
|
||||
while the session remains open. If the parent ID was lost from the preview,
|
||||
use the prior analysis summary or explicit ledger entries to recover it; do
|
||||
not invent an ID or rerun analysis just to reproduce the same display.
|
||||
|
||||
BrowserWindow preferences, preload and contextBridge surfaces, IPC
|
||||
registrations, utility processes, and native binding requests are static syntax
|
||||
observations. Only a unique exact literal IPC channel match supports an inferred
|
||||
@@ -22,13 +92,6 @@ pairing. Dynamic or ambiguous channels remain unresolved. A requested `.node`
|
||||
member is not a verified native export. Never claim runtime reachability,
|
||||
registration, defaults, or policy enforcement from static analysis.
|
||||
|
||||
Use `trace_application_feature` on existing application Evidence for one
|
||||
literal node ID, route, string, API, IPC channel, module, or native export.
|
||||
Choose a direction and reuse the returned application Evidence ID when the
|
||||
connected server advertises retained references, or supply complete Evidence
|
||||
inline. Include
|
||||
Hopper or Ghidra Evidence only when its artifact digest matches exactly.
|
||||
|
||||
For version comparison, analyze each version once, then call
|
||||
`compare_application_versions`. Accept only its digest, source-map, structural
|
||||
fingerprint, or non-module semantic matches. Module ordinals and minified names
|
||||
|
||||
@@ -136,6 +136,12 @@ existing analysis families directly, for example
|
||||
- Pull and capture outputs are additive: the destination must not already
|
||||
exist. Re-running a completed pull refuses the existing directory instead
|
||||
of overwriting evidence.
|
||||
- Cancellation during a package pull preserves caller-selected output. The
|
||||
error includes partial observations identifying completed artifacts and the
|
||||
interrupted local path; remaining APKs were not attempted.
|
||||
- Failed package acquisition rollback retains its directory identity and retries
|
||||
cleanup before later work and during shutdown. Cleanup refuses a replacement
|
||||
directory. Terminal shutdown stops admission and drains active operations.
|
||||
- The provider holds no long-lived processes; every invocation is one
|
||||
bounded adb run. The adb server belongs to the caller.
|
||||
|
||||
|
||||
@@ -142,6 +142,18 @@ listed after the table because its connector is not one of these files:
|
||||
| Pi | `pi` |
|
||||
| Hermes | `hermes` |
|
||||
|
||||
For GitHub Copilot CLI 1.0.95, `gpt-4.1` model metadata can block ordinary
|
||||
chat with REA's full input-schema profile before sending a model request
|
||||
(`compaction_static_context_blocked`; [#1554](https://github.com/morluto/rea/issues/1554)).
|
||||
The existing compact profile passed native chat and analysis with the complete
|
||||
tool inventory on Linux using a loopback model fixture. After setup, add
|
||||
`"REA_MCP_INPUT_SCHEMA_PROFILE": "compact"` to the `env` object of the
|
||||
`mcpServers.rea` entry in Copilot's `mcp-config.json`, preserving its other
|
||||
settings, then restart the client. Compact advertisements can reduce nested
|
||||
schema constraints; REA still validates complete canonical inputs. Full-profile
|
||||
`gpt-5.4` metadata is also verified locally. Live model API acceptance and
|
||||
Windows remain unverified; see [native client verification](testing.md).
|
||||
|
||||
For [Pi](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/mcp.md),
|
||||
setup writes a `type: "stdio"` entry under `mcpServers.rea` in the user-level
|
||||
`~/.pi/agent/mcp.json` and installs the bundled skill under `~/.agents/skills`.
|
||||
|
||||
@@ -114,6 +114,12 @@ from launch, must be ordered, and must fall within `timeout_ms`. Inputs marked
|
||||
Environment overrides are recorded in the scenario commitment; inherited
|
||||
values are not copied into Evidence.
|
||||
|
||||
Terminal dimensions must satisfy `columns × (rows + scrollback) ≤ 1,000,000`.
|
||||
Every scheduled resize uses the same selected scrollback and must fit this
|
||||
working-buffer budget. REA rejects oversized scenarios before launching the
|
||||
command; it never clamps the requested dimensions. This limit is independent
|
||||
of `limits.output_bytes`, which bounds retained terminal observations.
|
||||
|
||||
The capture contains raw PTY output chunks and rendered terminal states,
|
||||
interaction dispatch outcomes, exit reason, sampled process-tree observations,
|
||||
and settlement status. When filesystem paths are selected, REA records
|
||||
|
||||
+64
-4
@@ -160,10 +160,21 @@ chat or `REA_VERIFY_RUNTIME_ROOT` for a production-only installed package.
|
||||
The native offline BYOK adapter uses a loopback OpenAI completions/SSE fixture
|
||||
and `gpt-5.4` model metadata; model inference and token usage are synthetic.
|
||||
Set `REA_VERIFY_COPILOT_MODEL` to examine another model configuration. In the
|
||||
verified client, `gpt-4.1` blocks the complete catalog before HTTP with
|
||||
verified client, `gpt-4.1` blocks the full input-schema profile before HTTP with
|
||||
`compaction_static_context_blocked`, even when requesting a larger BYOK prompt
|
||||
capacity. The effective capacity is unknown; this lane does not establish a
|
||||
fix for that client/model limit. It preserves the complete catalog and schemas.
|
||||
capacity. The effective capacity is unknown. The default verifier preserves
|
||||
the complete catalog and full schemas. To verify the existing compact profile:
|
||||
|
||||
```bash
|
||||
REA_VERIFY_COPILOT_MODEL=gpt-4.1 REA_VERIFY_COPILOT_SCHEMA_PROFILE=compact npm run verify:copilot-client -- chat
|
||||
REA_VERIFY_COPILOT_MODEL=gpt-4.1 REA_VERIFY_COPILOT_SCHEMA_PROFILE=compact npm run verify:copilot-client -- call
|
||||
```
|
||||
|
||||
Both native workflows passed with the complete tool inventory. The verifier selects the
|
||||
profile only in its disposable Copilot registration and records it in the
|
||||
receipt. Compact advertisements can reduce nested validation structure; the
|
||||
server still validates complete canonical inputs. This is a tested alternate
|
||||
workflow, not a fix for the full-profile client/model limit tracked in #1554.
|
||||
Live model APIs, native Windows and default OS-home skill discovery remain
|
||||
unverified.
|
||||
|
||||
@@ -1053,6 +1064,39 @@ real local Codex CLI with:
|
||||
npm run verify:agent
|
||||
```
|
||||
|
||||
The lane runs scenarios sequentially in standalone Codex (`--no-daemon`) with a
|
||||
disposable HOME and CODEX_HOME under `~/.cache/rea-agent-evaluations/`. Set
|
||||
`REA_AGENT_EVAL_ROOT` to choose another parent directory outside the OS temporary
|
||||
directory: current Codex refuses helper aliases under `/tmp`, preventing shell
|
||||
commands and skill reads even if MCP works. Each owned run directory is removed
|
||||
after verification unless fixture retention is requested. The lane
|
||||
installs the packaged skill and MCP registration through public `rea setup`,
|
||||
rather than copying a skill into a project that also inherits the caller's
|
||||
skills and configuration. Only authentication is copied, when present, and it
|
||||
is removed even with `REA_AGENT_EVAL_KEEP_FIXTURES=true`. No user configuration,
|
||||
rules, plugins or history is copied; shell snapshots and additional agents are
|
||||
disabled. Existing API-key environment authentication remains available.
|
||||
The native missing-provider scenario preapproves only `open_binary` and
|
||||
`close_binary` in the disposable client so it reaches REA's actual provider
|
||||
boundary instead of stopping at Codex approval. This does not validate a real
|
||||
native engine or authorize arbitrary runtime execution.
|
||||
|
||||
Select a smaller run with `REA_AGENT_EVAL_SCENARIOS`, a comma-separated list of
|
||||
scenario IDs. `asar-zh` exercises the packaged desktop rubric from a Chinese
|
||||
request. `javascript-module-view` exercises summary analysis, module paging and
|
||||
item inspection in a tree with unrelated modules; its routing and text checks
|
||||
remain heuristic, so review the retained transcript for selector choice and
|
||||
coverage claims. Set `REA_CODEX_CLI` to an installed Codex executable and
|
||||
`REA_AGENT_EVAL_MODEL` to an account-supported model. Use an external resource
|
||||
limit for the whole process tree when testing on a constrained host; a Node
|
||||
heap limit alone does not bound client and child-process memory.
|
||||
|
||||
`missing-target` leaves desktop fixtures visible without selecting one in the
|
||||
request. It requires zero REA calls and a structured request for an app name or
|
||||
artifact path. Its `expectedFirstTool` is `null`, and
|
||||
`targetClarificationPassed` grades that limited routing outcome independently
|
||||
of analysis prose heuristics. Analyzing a nearby example cannot pass this case.
|
||||
|
||||
The packaged desktop and parser-comparison scenarios now assess a closed set of
|
||||
known fixture claims. Each final answer must be a strict JSON manifest containing
|
||||
exactly the requested claim IDs, values, Evidence IDs, and Evidence authority and
|
||||
@@ -1077,9 +1121,21 @@ navigation-context, and address-context scenarios have no factual rubric and
|
||||
remain `not_assessed`; the managed workflow requires both artifact and member
|
||||
inspection to answer its type and entry-point question.
|
||||
|
||||
The closed factual scenarios request complete producer Evidence on the initial
|
||||
analysis so their source selectors can authenticate all configured facts.
|
||||
Summary/page/item workflows are exercised separately by `javascript-module-view`;
|
||||
its heuristic gate does not establish full-producer factual correctness.
|
||||
|
||||
All scenarios retain routing, workflow, validation, repetition, process-exit,
|
||||
and token-use gates. Configured factual scenarios additionally require a factual
|
||||
pass. Their answer-text heuristics are diagnostic and do not affect the gate.
|
||||
Validation counts include complete text-only REA `invalid_request` envelopes
|
||||
and failed SDK calls whose arguments violate the named current REA contract.
|
||||
Client approval rejections and provider unavailability remain distinct failures;
|
||||
truncated JSON previews are not parsed into invented error codes.
|
||||
Repeated `binary_session` observations separated by a successful `open_binary`
|
||||
or `close_binary` are treated as lifecycle verification. An unchanged retry,
|
||||
including one after a failed lifecycle call, still counts as repetition.
|
||||
Scenarios without a rubric retain the legacy text-heuristic gate.
|
||||
`answerTermCoverageMet` checks case-insensitive substrings,
|
||||
`epistemicCuePresent` checks keywords, and `finalCitesEvidence` checks only an ID's
|
||||
@@ -1087,7 +1143,11 @@ presence. These metrics can still accept fabricated prose and must not be read
|
||||
as factual assessments. Set `REA_AGENT_EVAL_TRANSCRIPT_DIR` to retain complete
|
||||
tool results and final answers for review.
|
||||
|
||||
Report schema version 3 changes the top-level `factualCorrectness` from a constant
|
||||
Report schema version 4 adds negative routing scenarios with nullable
|
||||
`expectedFirstTool` and a `targetClarificationPassed` outcome. Consumers must
|
||||
allow an expected absence of REA calls; this does not make an analysis scenario
|
||||
pass without its required tools. Version 3 changed the top-level
|
||||
`factualCorrectness` from a constant
|
||||
string to an assessment summary with status, scope, and assessed/passed/failed/
|
||||
not-assessed scenario counts. Scenario records include the factual assessment and
|
||||
configured claim IDs. The evaluation scope is
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import {
|
||||
chmod,
|
||||
copyFile,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { delimiter, dirname, join, resolve } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { z } from "zod";
|
||||
|
||||
import { evaluateCodexEvents } from "../dist/evaluation/CodexAgentEval.js";
|
||||
import {
|
||||
@@ -15,32 +24,95 @@ import {
|
||||
agentEvaluationPassed,
|
||||
summarizeFactualCorrectness,
|
||||
} from "../dist/evaluation/AgentEvaluationReport.js";
|
||||
import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";
|
||||
import { PRODUCT_IDENTITY } from "../dist/identity.js";
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
|
||||
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const verifierRun = createVerifierRun();
|
||||
const evaluationRoot = await mkdtemp(join(tmpdir(), "rea-agent-eval-"));
|
||||
const fixtureRoot = join(evaluationRoot, "targets");
|
||||
const skillDestination = join(
|
||||
evaluationRoot,
|
||||
".agents/skills/reverse-engineer-anything",
|
||||
);
|
||||
const timeoutMs = Number(process.env.REA_AGENT_EVAL_TIMEOUT_MS ?? 480_000);
|
||||
const codex = process.env.REA_CODEX_CLI ?? "codex";
|
||||
const optionalModel = process.env.REA_AGENT_EVAL_MODEL;
|
||||
|
||||
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10_000)
|
||||
throw new Error("REA_AGENT_EVAL_TIMEOUT_MS must be an integer >= 10000");
|
||||
const codexVersion = await readCommandVersion(codex);
|
||||
// Codex refuses helper aliases when CODEX_HOME is under the OS temp directory.
|
||||
// Keep the disposable account in a private cache, then remove the owned run.
|
||||
const evaluationParent = resolve(
|
||||
process.env.REA_AGENT_EVAL_ROOT ??
|
||||
join(homedir(), ".cache", "rea-agent-evaluations"),
|
||||
);
|
||||
await mkdir(evaluationParent, { recursive: true, mode: 0o700 });
|
||||
const evaluationRoot = await mkdtemp(join(evaluationParent, "run-"));
|
||||
const fixtureRoot = join(evaluationRoot, "targets");
|
||||
const account = join(evaluationRoot, "account");
|
||||
const codexHome = join(evaluationRoot, "codex");
|
||||
const authPath = join(codexHome, "auth.json");
|
||||
const skillDestination = join(
|
||||
account,
|
||||
".agents/skills/reverse-engineer-anything",
|
||||
);
|
||||
const evaluationEnvironment = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(process.env).filter(
|
||||
([name]) => !/^(?:REA_|CODEX_|GHIDRA_|HOPPER_|IDA_)/u.test(name),
|
||||
),
|
||||
),
|
||||
HOME: account,
|
||||
USERPROFILE: account,
|
||||
CODEX_HOME: codexHome,
|
||||
XDG_CONFIG_HOME: join(account, ".config"),
|
||||
XDG_DATA_HOME: join(account, ".local/share"),
|
||||
XDG_CACHE_HOME: join(account, ".cache"),
|
||||
REA_PROCESS_RUN_ID: verifierRun.run_id,
|
||||
PATH: `${dirname(process.execPath)}${delimiter}${process.env.PATH ?? ""}`,
|
||||
};
|
||||
|
||||
try {
|
||||
await mkdir(fixtureRoot, { recursive: true });
|
||||
await cp(
|
||||
join(repositoryRoot, "skills/reverse-engineer-anything"),
|
||||
skillDestination,
|
||||
{ recursive: true },
|
||||
const codexVersion = await readCommandVersion(codex);
|
||||
await Promise.all([
|
||||
mkdir(fixtureRoot, { recursive: true }),
|
||||
mkdir(account),
|
||||
mkdir(codexHome, { mode: 0o700 }),
|
||||
]);
|
||||
// Reuse authentication only. User config, plugins, rules, history and skills
|
||||
// must not make a fresh installed-skill trial pass accidentally.
|
||||
try {
|
||||
await copyFile(
|
||||
join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "auth.json"),
|
||||
authPath,
|
||||
);
|
||||
await chmod(authPath, 0o600);
|
||||
} catch (cause) {
|
||||
if (cause?.code !== "ENOENT") throw cause;
|
||||
// Environment/API-key authentication can work without a local auth file.
|
||||
}
|
||||
await writeFile(
|
||||
join(codexHome, "config.toml"),
|
||||
'approval_policy = "never"\nsandbox_mode = "read-only"\nweb_search = "disabled"\n[features]\nmulti_agent = false\nshell_snapshot = false\n[history]\npersistence = "none"\n',
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
for (const approval of ["--dry-run", "--yes"]) {
|
||||
await runProcess(
|
||||
process.execPath,
|
||||
[
|
||||
join(repositoryRoot, "scripts/rea.mjs"),
|
||||
"setup",
|
||||
"--client",
|
||||
"codex",
|
||||
approval,
|
||||
"--json",
|
||||
],
|
||||
evaluationRoot,
|
||||
120_000,
|
||||
evaluationEnvironment,
|
||||
);
|
||||
}
|
||||
const installedSkill = await readFile(
|
||||
join(skillDestination, "SKILL.md"),
|
||||
"utf8",
|
||||
);
|
||||
if (!installedSkill.includes(` version: "${PRODUCT_IDENTITY.skillVersion}"`))
|
||||
throw new Error("Setup did not install the current packaged REA skill");
|
||||
const requestedScenarioIds = new Set(
|
||||
(process.env.REA_AGENT_EVAL_SCENARIOS ?? "")
|
||||
.split(",")
|
||||
@@ -57,7 +129,11 @@ try {
|
||||
expectedFirstTool: "open_binary",
|
||||
requiresEvidence: false,
|
||||
requiredAnswerTermGroups: [["unavailable", "could not", "provider"]],
|
||||
prompt: `Explain what the shipped native program at ${targets.native} does. Base the answer on artifact analysis, and clearly state any facts that remain unavailable.`,
|
||||
// The verifier authorizes these named session operations, not arbitrary
|
||||
// writes or runtime execution. Missing-engine behavior stays observable.
|
||||
approvedTools: ["open_binary", "close_binary"],
|
||||
requiredToolSubsequence: ["open_binary", "close_binary"],
|
||||
prompt: `Explain what static artifact evidence establishes about the shipped native program at ${targets.native}. Do not execute the target or install tools. Clearly state unavailable provider evidence, and close any analysis session you opened before finishing.`,
|
||||
},
|
||||
{
|
||||
id: "asar",
|
||||
@@ -70,6 +146,38 @@ try {
|
||||
],
|
||||
prompt: `Explain how the desktop application at ${targets.javascript} exposes APIs to its renderer. Base the answer on the shipped application artifact, and state what remains unknown.`,
|
||||
},
|
||||
{
|
||||
id: "asar-zh",
|
||||
fixtureScenarioId: "asar",
|
||||
expectedFirstTool: "analyze_javascript_application",
|
||||
requiresEvidence: true,
|
||||
requiredAnswerTermGroups: [["profileapi"], ["profile:read"]],
|
||||
prompt: `請靜態分析已交付的 Electron 程式 ${targets.javascript},說明 renderer 如何透過 preload 讀取 profile,以及 main handler 的關係。不要執行目標或安裝分析引擎;引用完整的產出 Evidence,保留 runtime 未知事項。`,
|
||||
},
|
||||
{
|
||||
id: "javascript-module-view",
|
||||
expectedFirstTool: "analyze_javascript_application",
|
||||
requiresEvidence: true,
|
||||
requiredToolSubsequence: [
|
||||
"analyze_javascript_application",
|
||||
"inspect_analysis_view",
|
||||
"inspect_analysis_view",
|
||||
],
|
||||
requiredAnswerTermGroups: [
|
||||
["main.js"],
|
||||
["node", "identity"],
|
||||
["observations", "recorded"],
|
||||
],
|
||||
prompt: `Inspect the recorded module identity, exports and observations for main.js in the shipped JavaScript tree ${targets.largeJavascript}. Use REA without directly reading target files or executing the target. Keep results focused on that module, cite Evidence, and state the limits of what its module view establishes.`,
|
||||
},
|
||||
{
|
||||
id: "missing-target",
|
||||
expectedFirstTool: null,
|
||||
requiresEvidence: false,
|
||||
requiredAnswerTermGroups: [],
|
||||
prompt:
|
||||
'Reverse engineer my desktop app and explain how it saves user settings. Use static analysis; do not install software. End with one JSON object containing status ("needs_target" or "analyzed"), requested_input ("app_name_or_artifact_path" or null), and question (a string or null).',
|
||||
},
|
||||
{
|
||||
id: "javascript-export-shape",
|
||||
expectedFirstTool: "analyze_javascript_application",
|
||||
@@ -145,12 +253,14 @@ try {
|
||||
const results = [];
|
||||
for (const scenario of scenarios) {
|
||||
process.stderr.write(`Running Codex agent evaluation: ${scenario.id}\n`);
|
||||
const fixtureClaims = agentFixtureClaims(scenario.id, targets);
|
||||
const answerInstructions = agentFixtureAnswerInstructions(scenario.id);
|
||||
const fixtureId = scenario.fixtureScenarioId ?? scenario.id;
|
||||
const fixtureClaims = agentFixtureClaims(fixtureId, targets);
|
||||
const answerInstructions = agentFixtureAnswerInstructions(fixtureId);
|
||||
const execution = await runCodex(
|
||||
answerInstructions.length === 0
|
||||
? scenario.prompt
|
||||
: `${scenario.prompt}\n\n${answerInstructions}`,
|
||||
: `${scenario.prompt}\n\nThis closed factual rubric needs complete producer Evidence in the transcript. Request complete detail on each initial application analysis when supported; summary or view records alone are not accepted by this rubric.\n\n${answerInstructions}`,
|
||||
scenario.approvedTools ?? [],
|
||||
);
|
||||
const transcriptDirectory = process.env.REA_AGENT_EVAL_TRANSCRIPT_DIR;
|
||||
if (transcriptDirectory !== undefined) {
|
||||
@@ -175,6 +285,12 @@ try {
|
||||
...(fixtureClaims === undefined ? {} : { fixtureClaims }),
|
||||
},
|
||||
);
|
||||
// Fixtures are deliberately visible beside prior investigation artifacts.
|
||||
// Their existence does not identify the unnamed app in this request.
|
||||
const targetClarificationPassed =
|
||||
scenario.expectedFirstTool === null
|
||||
? validTargetClarification(metrics.finalMessage)
|
||||
: undefined;
|
||||
const result = {
|
||||
id: scenario.id,
|
||||
expectedFirstTool: scenario.expectedFirstTool,
|
||||
@@ -185,6 +301,9 @@ try {
|
||||
exitCode: execution.exitCode,
|
||||
stderr: execution.stderr,
|
||||
...metrics,
|
||||
...(targetClarificationPassed === undefined
|
||||
? {}
|
||||
: { targetClarificationPassed }),
|
||||
};
|
||||
results.push(result);
|
||||
process.stderr.write(
|
||||
@@ -194,13 +313,20 @@ try {
|
||||
|
||||
const factualCorrectness = summarizeFactualCorrectness(results);
|
||||
const summary = {
|
||||
schemaVersion: 3,
|
||||
schemaVersion: 4,
|
||||
evaluationScope: "routing_workflow_and_configured_fixture_claims",
|
||||
factualCorrectness,
|
||||
verifier_run: await completeVerifierRun(verifierRun),
|
||||
codex,
|
||||
codexVersion,
|
||||
model: optionalModel ?? null,
|
||||
installation: {
|
||||
method: "rea_setup_codex",
|
||||
isolatedHome: true,
|
||||
isolatedCodexHome: true,
|
||||
skillVersion: PRODUCT_IDENTITY.skillVersion,
|
||||
authentication: "caller_auth_only_removed_after_run",
|
||||
},
|
||||
scenarios: results,
|
||||
totals: {
|
||||
scenarios: results.length,
|
||||
@@ -253,12 +379,32 @@ try {
|
||||
`Agent routing/workflow/answer checks failed: ${failed.map(({ id }) => id).join(", ")}`,
|
||||
);
|
||||
} finally {
|
||||
// Even a deliberately retained fixture directory must never retain auth.
|
||||
await rm(authPath, { force: true });
|
||||
if (process.env.REA_AGENT_EVAL_KEEP_FIXTURES !== "true")
|
||||
await rm(evaluationRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function createTargets(root, includeManaged) {
|
||||
const fixtures = await createAgentEvaluationFixtures(root, repositoryRoot);
|
||||
const largeJavascript = join(root, "large-app");
|
||||
await mkdir(join(largeJavascript, "lib"), { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(largeJavascript, "package.json"),
|
||||
'{"name":"large-app","main":"main.js"}\n',
|
||||
),
|
||||
writeFile(
|
||||
join(largeJavascript, "main.js"),
|
||||
'const { ipcMain } = require("electron");\nipcMain.handle("profile:read", (_event, id) => ({ id }));\n',
|
||||
),
|
||||
...Array.from({ length: 180 }, (_, index) =>
|
||||
writeFile(
|
||||
join(largeJavascript, "lib", `formatter-${String(index)}.js`),
|
||||
`export const format = (value) => String(value).trim();\n`,
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
const managedOutput = join(root, "managed-output");
|
||||
if (includeManaged) {
|
||||
@@ -292,15 +438,29 @@ async function createTargets(root, includeManaged) {
|
||||
return {
|
||||
native: "/bin/true",
|
||||
...fixtures,
|
||||
largeJavascript,
|
||||
managed: join(managedOutput, "AgentEval.dll"),
|
||||
};
|
||||
}
|
||||
|
||||
async function runCodex(prompt) {
|
||||
function validTargetClarification(message) {
|
||||
const schema = z.strictObject({
|
||||
status: z.literal("needs_target"),
|
||||
requested_input: z.literal("app_name_or_artifact_path"),
|
||||
question: z.string().refine((value) => value.trim().length > 0),
|
||||
});
|
||||
try {
|
||||
return schema.safeParse(JSON.parse(message)).success;
|
||||
} catch (cause) {
|
||||
if (cause instanceof SyntaxError) return false;
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
async function runCodex(prompt, approvedTools) {
|
||||
const arguments_ = [
|
||||
"--no-daemon",
|
||||
"exec",
|
||||
"--ignore-user-config",
|
||||
"--ignore-rules",
|
||||
"--ephemeral",
|
||||
"--skip-git-repo-check",
|
||||
"--sandbox",
|
||||
@@ -312,18 +472,16 @@ async function runCodex(prompt) {
|
||||
evaluationRoot,
|
||||
"-c",
|
||||
'approval_policy="never"',
|
||||
"-c",
|
||||
`mcp_servers.rea.command=${JSON.stringify(process.execPath)}`,
|
||||
"-c",
|
||||
`mcp_servers.rea.args=${JSON.stringify([join(repositoryRoot, "scripts/rea.mjs"), "mcp"])}`,
|
||||
"-c",
|
||||
`mcp_servers.rea.startup_timeout_sec=${String(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds)}`,
|
||||
...approvedTools.flatMap((name) => [
|
||||
"-c",
|
||||
`mcp_servers.rea.tools.${name}.approval_mode="approve"`,
|
||||
]),
|
||||
...(optionalModel === undefined ? [] : ["--model", optionalModel]),
|
||||
prompt,
|
||||
];
|
||||
const child = spawn(codex, arguments_, {
|
||||
cwd: evaluationRoot,
|
||||
env: process.env,
|
||||
env: evaluationEnvironment,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const events = [];
|
||||
@@ -362,9 +520,16 @@ async function runCodex(prompt) {
|
||||
return { events, exitCode, stderr: stderr.join("").slice(0, 32_768) };
|
||||
}
|
||||
|
||||
async function runProcess(command, arguments_, cwd, timeout) {
|
||||
async function runProcess(
|
||||
command,
|
||||
arguments_,
|
||||
cwd,
|
||||
timeout,
|
||||
env = process.env,
|
||||
) {
|
||||
const child = spawn(command, arguments_, {
|
||||
cwd,
|
||||
env,
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
let stderr = "";
|
||||
|
||||
@@ -22,6 +22,12 @@ const runtimeRoot = process.env.REA_VERIFY_RUNTIME_ROOT ?? repo;
|
||||
const command = process.env.REA_VERIFY_COPILOT_COMMAND ?? "copilot";
|
||||
const mode = process.argv[2] ?? "call";
|
||||
const model = process.env.REA_VERIFY_COPILOT_MODEL ?? "gpt-5.4";
|
||||
const inputSchemaProfile =
|
||||
process.env.REA_VERIFY_COPILOT_SCHEMA_PROFILE ?? "full";
|
||||
assert(
|
||||
["full", "compact"].includes(inputSchemaProfile),
|
||||
"REA_VERIFY_COPILOT_SCHEMA_PROFILE must be full or compact",
|
||||
);
|
||||
assert(
|
||||
["chat", "call"].includes(mode),
|
||||
"Usage: verify-copilot-client.mjs [chat|call]",
|
||||
@@ -311,6 +317,16 @@ try {
|
||||
assert.deepEqual(JSON.parse(repeated.stdout).appliedActions, []);
|
||||
assert.equal(await readFile(configPath, "utf8"), configured);
|
||||
assert.equal(await readFile(`${configPath}.rea.backup`, "utf8"), original);
|
||||
if (inputSchemaProfile === "compact") {
|
||||
// Select the existing presentation in this disposable native-client profile.
|
||||
const customized = JSON.parse(configured);
|
||||
assert(customized.mcpServers.rea);
|
||||
customized.mcpServers.rea.env = {
|
||||
...customized.mcpServers.rea.env,
|
||||
REA_MCP_INPUT_SCHEMA_PROFILE: inputSchemaProfile,
|
||||
};
|
||||
await writeFile(configPath, JSON.stringify(customized, null, 2));
|
||||
}
|
||||
const installedSkill = await readFile(
|
||||
join(skillDirectory, "SKILL.md"),
|
||||
"utf8",
|
||||
@@ -408,6 +424,7 @@ try {
|
||||
clientVersion,
|
||||
mode,
|
||||
model,
|
||||
inputSchemaProfile,
|
||||
passed: failure === undefined,
|
||||
artifacts: lab,
|
||||
runtimeRoot,
|
||||
@@ -421,7 +438,9 @@ try {
|
||||
skillDiscovery:
|
||||
"native COPILOT_HOME MCP configuration and caller-added isolated skill directory; default OS-home discovery unverified",
|
||||
capacityBoundary:
|
||||
"gpt-4.1 model configuration blocks the full catalog before HTTP even with a ten-million-token requested prompt override; gpt-5.4 is the verified local fixture configuration",
|
||||
inputSchemaProfile === "compact"
|
||||
? "Explicit compact profile: complete inventory and canonical server validation; advertised schemas may be reduced. This does not fix the full-profile gpt-4.1 context boundary."
|
||||
: "gpt-4.1 model configuration blocks the full catalog before HTTP even with a ten-million-token requested prompt override; gpt-5.4 is the verified full-profile local fixture configuration",
|
||||
catalogSize,
|
||||
schemasChecked,
|
||||
spillReadRequested,
|
||||
|
||||
+348
-46
@@ -1,6 +1,6 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream, constants as fsConstants } from "node:fs";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { access, lstat, mkdir, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { basename, join, resolve } from "node:path";
|
||||
|
||||
@@ -24,8 +24,11 @@ import {
|
||||
AnalysisTimeoutError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { hashStableFile } from "../filesystem/StableFileHash.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import {
|
||||
execFileOutput,
|
||||
execFileOutputFailure,
|
||||
@@ -97,11 +100,18 @@ const STDERR_EXCERPT_BYTES = 512;
|
||||
const UNPARSED_LINES_REPORTED = 10;
|
||||
const STOP_GRACE_MS = 5_000;
|
||||
|
||||
/** Stream a local file digest without retaining large files in memory. */
|
||||
const sha256File = async (path: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
const hashAdbFile = async (
|
||||
path: string,
|
||||
operation: string,
|
||||
signal: AbortSignal | undefined,
|
||||
) => {
|
||||
try {
|
||||
return await hashStableFile(path, signal);
|
||||
} catch (cause: unknown) {
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError(operation, { cause });
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** adb joins shell operands into a remote POSIX command; quote at that boundary. */
|
||||
@@ -335,6 +345,48 @@ export interface AdbProviderOptions {
|
||||
readonly environment?: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
interface PendingPackageDirectoryCleanup {
|
||||
readonly path: string;
|
||||
readonly identity: PackageDirectoryIdentity | undefined;
|
||||
readonly primary: AnalysisError;
|
||||
readonly remove: () => Promise<void>;
|
||||
}
|
||||
|
||||
interface PackageDirectoryIdentity {
|
||||
readonly dev: number;
|
||||
readonly ino: number;
|
||||
readonly mode: number;
|
||||
}
|
||||
|
||||
const removeOwnedPackageDirectory = async (
|
||||
path: string,
|
||||
identity: PackageDirectoryIdentity | undefined,
|
||||
): Promise<void> => {
|
||||
if (identity === undefined)
|
||||
throw new Error(
|
||||
`Cannot verify the created package directory identity; refusing to remove ${path}`,
|
||||
);
|
||||
let current: Awaited<ReturnType<typeof lstat>>;
|
||||
try {
|
||||
current = await lstat(path);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && Reflect.get(cause, "code") === "ENOENT")
|
||||
return;
|
||||
throw cause;
|
||||
}
|
||||
if (
|
||||
!current.isDirectory() ||
|
||||
current.isSymbolicLink() ||
|
||||
current.dev !== identity.dev ||
|
||||
current.ino !== identity.ino ||
|
||||
current.mode !== identity.mode
|
||||
)
|
||||
throw new Error(
|
||||
`The created package directory was replaced or changed; refusing to remove ${path}`,
|
||||
);
|
||||
await rm(path, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
/**
|
||||
* ADB device inspection and acquisition over a caller-selected adb binary.
|
||||
*
|
||||
@@ -346,6 +398,12 @@ export interface AdbProviderOptions {
|
||||
*/
|
||||
export class AdbProvider {
|
||||
private readonly environment: Readonly<Record<string, string | undefined>>;
|
||||
readonly #pendingPackageDirectoryCleanup =
|
||||
new Set<PendingPackageDirectoryCleanup>();
|
||||
readonly #activeOperations = new Set<Promise<void>>();
|
||||
#closing = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#packageCleanupPromise: Promise<void> | undefined;
|
||||
|
||||
constructor(options: AdbProviderOptions = {}) {
|
||||
this.environment = options.environment ?? process.env;
|
||||
@@ -378,12 +436,121 @@ export class AdbProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The provider holds no long-lived resources; the adb server is caller-owned. */
|
||||
async close(): Promise<void> {}
|
||||
/** Retry removal of package directories retained after failed rollback. */
|
||||
close(): Promise<void> {
|
||||
this.#closing = true;
|
||||
if (this.#closePromise !== undefined) return this.#closePromise;
|
||||
const closing = (async () => {
|
||||
await Promise.all(this.#activeOperations);
|
||||
await this.#retryPackageDirectoryCleanup();
|
||||
})().finally(() => {
|
||||
if (this.#closePromise === closing) this.#closePromise = undefined;
|
||||
});
|
||||
this.#closePromise = closing;
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
#retryPackageDirectoryCleanup(): Promise<void> {
|
||||
if (this.#packageCleanupPromise !== undefined)
|
||||
return this.#packageCleanupPromise;
|
||||
const cleanup = this.#performPackageDirectoryCleanup().finally(() => {
|
||||
if (this.#packageCleanupPromise === cleanup)
|
||||
this.#packageCleanupPromise = undefined;
|
||||
});
|
||||
this.#packageCleanupPromise = cleanup;
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
async #performPackageDirectoryCleanup(): Promise<void> {
|
||||
const failures: AnalysisError[] = [];
|
||||
for (const owner of this.#pendingPackageDirectoryCleanup) {
|
||||
try {
|
||||
await owner.remove();
|
||||
this.#pendingPackageDirectoryCleanup.delete(owner);
|
||||
} catch (cause: unknown) {
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[owner.path],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: "pull_adb_package", cause },
|
||||
);
|
||||
failures.push(
|
||||
analysisErrorWithCleanupFailure(
|
||||
owner.primary,
|
||||
cleanup,
|
||||
"pull_adb_package",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (failures.length === 1) throw failures[0];
|
||||
if (failures.length > 1)
|
||||
throw new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[...this.#pendingPackageDirectoryCleanup].map(({ path }) => path),
|
||||
{
|
||||
reason:
|
||||
"Failed package output directories remain after cleanup retry",
|
||||
failures: failures.map(({ message, cleanupResources }) => ({
|
||||
message,
|
||||
resources: [...cleanupResources],
|
||||
})),
|
||||
},
|
||||
{
|
||||
operation: "pull_adb_package",
|
||||
cause: new AggregateError(
|
||||
failures,
|
||||
"Multiple ADB package rollback cleanups failed",
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async execute(
|
||||
request: AdbRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
if (this.#closing)
|
||||
return err(new AnalysisCancelledError(request.operation));
|
||||
let release!: () => void;
|
||||
const active = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
this.#activeOperations.add(active);
|
||||
try {
|
||||
if (this.#pendingPackageDirectoryCleanup.size > 0) {
|
||||
try {
|
||||
await this.#retryPackageDirectoryCleanup();
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[...this.#pendingPackageDirectoryCleanup].map(
|
||||
({ path }) => path,
|
||||
),
|
||||
{
|
||||
reason:
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: request.operation, cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return await this.#executeOperation(request, options);
|
||||
} finally {
|
||||
this.#activeOperations.delete(active);
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
async #executeOperation(
|
||||
request: AdbRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const signal = options?.signal;
|
||||
if (signal?.aborted === true)
|
||||
@@ -1010,9 +1177,11 @@ export class AdbProvider {
|
||||
);
|
||||
if (!directory.ok) return directory;
|
||||
const packageDirectory = join(directory.value, packageName);
|
||||
let packageDirectoryCreated = false;
|
||||
let packageDirectoryIdentity: PackageDirectoryIdentity | undefined;
|
||||
try {
|
||||
if (
|
||||
await stat(packageDirectory).then(
|
||||
await lstat(packageDirectory).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
@@ -1021,14 +1190,44 @@ export class AdbProvider {
|
||||
`The package output directory already exists: ${packageDirectory}`,
|
||||
);
|
||||
await mkdir(packageDirectory);
|
||||
packageDirectoryCreated = true;
|
||||
const created = await lstat(packageDirectory);
|
||||
if (!created.isDirectory() || created.isSymbolicLink())
|
||||
throw new Error(
|
||||
`The created package output is not a regular directory: ${packageDirectory}`,
|
||||
);
|
||||
packageDirectoryIdentity = {
|
||||
dev: created.dev,
|
||||
ino: created.ino,
|
||||
mode: created.mode,
|
||||
};
|
||||
} catch (cause) {
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
{ cause },
|
||||
),
|
||||
const primary = new AnalysisOutputError(
|
||||
operation,
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
{ cause },
|
||||
);
|
||||
if (!packageDirectoryCreated) return err(primary);
|
||||
const owner: PendingPackageDirectoryCleanup = {
|
||||
path: packageDirectory,
|
||||
identity: packageDirectoryIdentity,
|
||||
primary,
|
||||
remove: () =>
|
||||
removeOwnedPackageDirectory(
|
||||
packageDirectory,
|
||||
packageDirectoryIdentity,
|
||||
),
|
||||
};
|
||||
this.#pendingPackageDirectoryCleanup.add(owner);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[packageDirectory],
|
||||
{
|
||||
reason: "Could not establish an owned package directory identity",
|
||||
},
|
||||
{ operation, cause },
|
||||
);
|
||||
return err(analysisErrorWithCleanupFailure(primary, cleanup, operation));
|
||||
}
|
||||
const artifacts: {
|
||||
device_path: string;
|
||||
@@ -1044,6 +1243,37 @@ export class AdbProvider {
|
||||
stage: "resolve_paths" | "pull" | "digest";
|
||||
message: string;
|
||||
}[] = [];
|
||||
const cancelledPackagePull = (
|
||||
error: AnalysisCancelledError,
|
||||
localPath: string,
|
||||
devicePath: string,
|
||||
stage: "pull" | "digest",
|
||||
) => {
|
||||
error.retainPartialObservation({
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: {
|
||||
client,
|
||||
serial,
|
||||
package_name: packageName,
|
||||
output_directory: directory.value,
|
||||
artifacts,
|
||||
failures: [
|
||||
...failures,
|
||||
{
|
||||
device_path: devicePath,
|
||||
stage,
|
||||
message:
|
||||
stage === "pull"
|
||||
? `Pull cancelled; any incomplete file is retained at ${localPath}. Remaining APKs were not attempted.`
|
||||
: `Digesting the pulled file was cancelled; the file is retained at ${localPath}. Remaining APKs were not attempted.`,
|
||||
},
|
||||
],
|
||||
coverage: "partial",
|
||||
},
|
||||
});
|
||||
return err(error);
|
||||
};
|
||||
const seenFileNames = new Set<string>();
|
||||
for (const entry of parsed.paths) {
|
||||
if (seenFileNames.has(entry.file_name)) {
|
||||
@@ -1065,7 +1295,13 @@ export class AdbProvider {
|
||||
signal,
|
||||
);
|
||||
if (!pulled.ok) {
|
||||
if (pulled.error instanceof AnalysisCancelledError) return pulled;
|
||||
if (pulled.error instanceof AnalysisCancelledError)
|
||||
return cancelledPackagePull(
|
||||
pulled.error,
|
||||
localPath,
|
||||
entry.device_path,
|
||||
"pull",
|
||||
);
|
||||
failures.push({
|
||||
device_path: entry.device_path,
|
||||
stage: "pull",
|
||||
@@ -1074,18 +1310,24 @@ export class AdbProvider {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const info = await stat(localPath);
|
||||
const sha256 = await sha256File(localPath);
|
||||
const digest = await hashAdbFile(localPath, operation, signal);
|
||||
artifacts.push({
|
||||
device_path: entry.device_path,
|
||||
file_name: entry.file_name,
|
||||
local_path: localPath,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
role: entry.role,
|
||||
role_basis: "file_name",
|
||||
});
|
||||
} catch {
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisCancelledError)
|
||||
return cancelledPackagePull(
|
||||
cause,
|
||||
localPath,
|
||||
entry.device_path,
|
||||
"digest",
|
||||
);
|
||||
failures.push({
|
||||
device_path: entry.device_path,
|
||||
stage: "digest",
|
||||
@@ -1094,14 +1336,36 @@ export class AdbProvider {
|
||||
}
|
||||
}
|
||||
if (artifacts.length === 0 && failures.length > 0) {
|
||||
await rm(packageDirectory, { recursive: true, force: true }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
`Every APK pull failed for ${packageName} on ${serial}: ${failures[0]!.message}`,
|
||||
),
|
||||
const primary = new AnalysisProtocolError(
|
||||
`Every APK pull failed for ${packageName} on ${serial}: ${failures[0]!.message}`,
|
||||
);
|
||||
const owner: PendingPackageDirectoryCleanup = {
|
||||
path: packageDirectory,
|
||||
identity: packageDirectoryIdentity,
|
||||
primary,
|
||||
remove: () =>
|
||||
removeOwnedPackageDirectory(
|
||||
packageDirectory,
|
||||
packageDirectoryIdentity,
|
||||
),
|
||||
};
|
||||
try {
|
||||
await owner.remove();
|
||||
} catch (cause: unknown) {
|
||||
this.#pendingPackageDirectoryCleanup.add(owner);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
ADB_PROVIDER_IDENTITY.id,
|
||||
[packageDirectory],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ operation: operation, cause },
|
||||
);
|
||||
return err(
|
||||
analysisErrorWithCleanupFailure(primary, cleanup, operation),
|
||||
);
|
||||
}
|
||||
return err(primary);
|
||||
}
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
@@ -1156,8 +1420,7 @@ export class AdbProvider {
|
||||
);
|
||||
if (!pulled.ok) return pulled;
|
||||
try {
|
||||
const info = await stat(localPath);
|
||||
const sha256 = await sha256File(localPath);
|
||||
const digest = await hashAdbFile(localPath, operation, signal);
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
@@ -1165,8 +1428,8 @@ export class AdbProvider {
|
||||
serial: input.serial,
|
||||
device_path: input.device_path,
|
||||
local_path: localPath,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
},
|
||||
provider,
|
||||
{
|
||||
@@ -1177,6 +1440,20 @@ export class AdbProvider {
|
||||
),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisCancelledError) {
|
||||
cause.retainPartialObservation({
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: {
|
||||
client,
|
||||
serial: input.serial,
|
||||
local_path: localPath,
|
||||
device_path: input.device_path,
|
||||
digest_status: "unknown",
|
||||
},
|
||||
});
|
||||
return err(cause);
|
||||
}
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
@@ -1211,7 +1488,13 @@ export class AdbProvider {
|
||||
cause: new Error(`The local file does not exist: ${localPath}`),
|
||||
}),
|
||||
);
|
||||
const sha256 = await sha256File(localPath);
|
||||
let digest: Awaited<ReturnType<typeof hashAdbFile>>;
|
||||
try {
|
||||
digest = await hashAdbFile(localPath, operation, signal);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisCancelledError) return err(cause);
|
||||
throw cause;
|
||||
}
|
||||
const existsProbe = await runAdb(
|
||||
operation,
|
||||
input.device_path,
|
||||
@@ -1257,7 +1540,7 @@ export class AdbProvider {
|
||||
);
|
||||
if (deviceDigest.ok) {
|
||||
const digestMatch = /^([a-f0-9]{64})\s/u.exec(deviceDigest.value.stdout);
|
||||
if (digestMatch !== null && digestMatch[1] !== sha256)
|
||||
if (digestMatch !== null && digestMatch[1] !== digest.sha256)
|
||||
return err(
|
||||
new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
@@ -1272,8 +1555,8 @@ export class AdbProvider {
|
||||
serial: input.serial,
|
||||
local_path: localPath,
|
||||
device_path: input.device_path,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
device_sha256: digestMatch?.[1] ?? null,
|
||||
overwritten: deviceExists,
|
||||
device_digest_source: "device_sha256sum",
|
||||
@@ -1294,8 +1577,8 @@ export class AdbProvider {
|
||||
serial: input.serial,
|
||||
local_path: localPath,
|
||||
device_path: input.device_path,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
device_sha256: null,
|
||||
overwritten: deviceExists,
|
||||
device_digest_source: "unavailable",
|
||||
@@ -1334,7 +1617,13 @@ export class AdbProvider {
|
||||
cause: new Error(`The local APK does not exist: ${apkPath}`),
|
||||
}),
|
||||
);
|
||||
const sha256 = await sha256File(apkPath);
|
||||
let digest: Awaited<ReturnType<typeof hashAdbFile>>;
|
||||
try {
|
||||
digest = await hashAdbFile(apkPath, operation, signal);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisCancelledError) return err(cause);
|
||||
throw cause;
|
||||
}
|
||||
const installed = await runAdb(
|
||||
operation,
|
||||
input.serial,
|
||||
@@ -1363,8 +1652,8 @@ export class AdbProvider {
|
||||
client,
|
||||
serial: input.serial,
|
||||
apk_path: apkPath,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
replaced: input.replace,
|
||||
},
|
||||
provider,
|
||||
@@ -1734,16 +2023,15 @@ export class AdbProvider {
|
||||
),
|
||||
);
|
||||
try {
|
||||
const info = await stat(reportedPath);
|
||||
const sha256 = await sha256File(reportedPath);
|
||||
const digest = await hashAdbFile(reportedPath, operation, signal);
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
client,
|
||||
serial: input.serial,
|
||||
local_path: reportedPath,
|
||||
bytes: info.size,
|
||||
sha256,
|
||||
bytes: digest.bytes,
|
||||
sha256: digest.sha256,
|
||||
adb_reported_path: reportedPath,
|
||||
},
|
||||
provider,
|
||||
@@ -1755,6 +2043,20 @@ export class AdbProvider {
|
||||
),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisCancelledError) {
|
||||
cause.retainPartialObservation({
|
||||
provider_id: "adb",
|
||||
operation,
|
||||
result: {
|
||||
client,
|
||||
serial: input.serial,
|
||||
local_path: reportedPath,
|
||||
adb_reported_path: reportedPath,
|
||||
digest_status: "unknown",
|
||||
},
|
||||
});
|
||||
return err(cause);
|
||||
}
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
|
||||
@@ -1,40 +1,43 @@
|
||||
import { constants, createReadStream } from "node:fs";
|
||||
import { chmod, copyFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { ReadStream, Stats, WriteStream } from "node:fs";
|
||||
import { chmod, open, rm, stat, type FileHandle } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Transform, type TransformCallback } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
openRegularFile,
|
||||
sameRegularFileState,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import type { AndroidOperation } from "../domain/android/androidAnalysis.js";
|
||||
|
||||
/** Stream a local file digest without retaining the APK or JAR in memory. */
|
||||
export const hashAndroidFile = async (path: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
/** Bind decompiler input to the admitted artifact, even if the original changes. */
|
||||
export const snapshotAndroidTarget = async (
|
||||
path: string,
|
||||
sha256: string,
|
||||
root: string,
|
||||
operation: AndroidOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
const snapshot = join(root, "target.apk");
|
||||
await copyFile(path, snapshot, constants.COPYFILE_EXCL);
|
||||
await chmod(snapshot, 0o400);
|
||||
if ((await hashAndroidFile(snapshot)) !== sha256)
|
||||
throw new AnalysisInputError(operation, undefined, [
|
||||
try {
|
||||
await copyAndroidSnapshot(path, snapshot, sha256, signal);
|
||||
signal?.throwIfAborted();
|
||||
await chmod(snapshot, 0o400);
|
||||
return snapshot;
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof AndroidSnapshotChangedError)) throw cause;
|
||||
throw new AnalysisInputError(operation, { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"APK bytes changed after admission; retry against a stable file.",
|
||||
message: `APK bytes changed after admission at ${path}; retry against a stable file.`,
|
||||
},
|
||||
]);
|
||||
return snapshot;
|
||||
}
|
||||
};
|
||||
|
||||
/** Fingerprint the actual immutable engine bytes executed for this observation. */
|
||||
@@ -43,15 +46,120 @@ export const snapshotAndroidEngine = async (
|
||||
sha256: string,
|
||||
root: string,
|
||||
operation: AndroidOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ path: string; sha256: string }> => {
|
||||
const path = join(root, "engine.jar");
|
||||
await copyFile(source, path, constants.COPYFILE_EXCL);
|
||||
await chmod(path, 0o400);
|
||||
if ((await hashAndroidFile(path)) !== sha256)
|
||||
try {
|
||||
const observed = await copyAndroidSnapshot(source, path, sha256, signal);
|
||||
signal?.throwIfAborted();
|
||||
await chmod(path, 0o400);
|
||||
return { path, sha256: observed };
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof AndroidSnapshotChangedError)) throw cause;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
"REA_JADX_MCP_JAR bytes changed during admission; retry with a stable engine file.",
|
||||
`REA_JADX_MCP_JAR bytes changed during admission at ${source}; retry with a stable engine file.`,
|
||||
{ cause },
|
||||
);
|
||||
return { path, sha256 };
|
||||
}
|
||||
};
|
||||
|
||||
const copyAndroidSnapshot = async (
|
||||
sourcePath: string,
|
||||
snapshotPath: string,
|
||||
expectedSha256: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
signal?.throwIfAborted();
|
||||
const source = await openRegularFile(sourcePath, {
|
||||
symlinks: "follow",
|
||||
signal,
|
||||
});
|
||||
let destination: FileHandle | undefined;
|
||||
let inputStream: ReadStream | undefined;
|
||||
let outputStream: WriteStream | undefined;
|
||||
let removeSnapshot = false;
|
||||
let copiedBytes = 0;
|
||||
const hash = createHash("sha256");
|
||||
try {
|
||||
const initial = await source.stat();
|
||||
signal?.throwIfAborted();
|
||||
const digest = new Transform({
|
||||
transform(
|
||||
chunk: Buffer,
|
||||
_encoding: BufferEncoding,
|
||||
callback: TransformCallback,
|
||||
) {
|
||||
copiedBytes += chunk.length;
|
||||
if (copiedBytes > initial.size) {
|
||||
callback(
|
||||
new AndroidSnapshotChangedError(
|
||||
`Android input grew while being copied: ${sourcePath}`,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
try {
|
||||
destination = await open(snapshotPath, "wx", 0o600);
|
||||
signal?.throwIfAborted();
|
||||
inputStream = source.createReadStream({
|
||||
start: 0,
|
||||
end: initial.size,
|
||||
autoClose: false,
|
||||
});
|
||||
outputStream = destination.createWriteStream({ autoClose: false });
|
||||
await pipeline(inputStream, digest, outputStream, { signal });
|
||||
signal?.throwIfAborted();
|
||||
await verifySourceState(source, sourcePath, initial, copiedBytes);
|
||||
const observedSha256 = hash.digest("hex");
|
||||
if (observedSha256 !== expectedSha256)
|
||||
throw new AndroidSnapshotChangedError(
|
||||
`Android snapshot digest mismatch for ${sourcePath}`,
|
||||
);
|
||||
return observedSha256;
|
||||
} catch (cause: unknown) {
|
||||
removeSnapshot = destination !== undefined;
|
||||
throw cause;
|
||||
}
|
||||
} finally {
|
||||
// Non-auto-closing streams retain a reference to their FileHandle even
|
||||
// after pipeline completion. Release those references before awaiting
|
||||
// descriptor closure, after the admitted source state has been verified.
|
||||
inputStream?.destroy();
|
||||
outputStream?.destroy();
|
||||
try {
|
||||
await Promise.all([source.close(), destination?.close()]);
|
||||
} finally {
|
||||
if (removeSnapshot)
|
||||
await rm(snapshotPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const verifySourceState = async (
|
||||
handle: Awaited<ReturnType<typeof openRegularFile>>,
|
||||
path: string,
|
||||
initial: Stats,
|
||||
observedBytes: number,
|
||||
): Promise<void> => {
|
||||
const [opened, currentPath] = await Promise.all([handle.stat(), stat(path)]);
|
||||
if (
|
||||
observedBytes !== initial.size ||
|
||||
!sameRegularFileState(initial, opened) ||
|
||||
!sameRegularFileState(initial, currentPath)
|
||||
)
|
||||
throw new AndroidSnapshotChangedError(
|
||||
`Android input changed while being read: ${path}`,
|
||||
);
|
||||
};
|
||||
|
||||
class AndroidSnapshotChangedError extends Error {
|
||||
constructor(message: string, options?: ErrorOptions) {
|
||||
super(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,11 @@ export const inspectJadxAvailability = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProviderAvailability> => {
|
||||
try {
|
||||
const configuration = await readJadxConfiguration(environment, signal);
|
||||
const configuration = await readJadxConfigurationInputs(
|
||||
environment,
|
||||
signal,
|
||||
);
|
||||
await validateJadxConfigurationContents(configuration, environment, signal);
|
||||
return {
|
||||
status: "available",
|
||||
code: null,
|
||||
@@ -77,52 +81,83 @@ export const inspectJadxAvailability = async (
|
||||
}
|
||||
};
|
||||
|
||||
/** Resolve caller-selected tools and preserve the same prerequisite diagnostics. */
|
||||
export const resolveJadxConfiguration = async (
|
||||
/** Resolve caller-selected paths and JVM options without probing their contents. */
|
||||
export const resolveJadxConfigurationInputs = async (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
operation: AndroidOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JadxConfiguration> => {
|
||||
try {
|
||||
return await readJadxConfiguration(environment, signal);
|
||||
return await readJadxConfigurationInputs(environment, signal);
|
||||
} catch (cause) {
|
||||
if (signal?.aborted === true) throw cause;
|
||||
if (!(cause instanceof JadxConfigurationFailure)) throw cause;
|
||||
const output = cause.diagnostics;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
cause.message,
|
||||
{
|
||||
cause,
|
||||
userMessage: cause.message,
|
||||
...(typeof output.stdout === "string" &&
|
||||
typeof output.stderr === "string"
|
||||
? {
|
||||
capturedOutput: {
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
truncated: output.output_truncated === true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
throw projectConfigurationFailure(operation, cause);
|
||||
}
|
||||
};
|
||||
|
||||
const readJadxConfiguration = async (
|
||||
/** Probe Java and archive prerequisites before starting a new engine session. */
|
||||
export const validateJadxConfiguration = async (
|
||||
configuration: JadxConfiguration,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
operation: AndroidOperation,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
try {
|
||||
await validateJadxConfigurationContents(configuration, environment, signal);
|
||||
} catch (cause) {
|
||||
if (signal?.aborted === true) throw cause;
|
||||
if (!(cause instanceof JadxConfigurationFailure)) throw cause;
|
||||
throw projectConfigurationFailure(operation, cause);
|
||||
}
|
||||
};
|
||||
|
||||
const readJadxConfigurationInputs = async (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<JadxConfiguration> => {
|
||||
signal?.throwIfAborted();
|
||||
requireSupportedHost();
|
||||
const jar = await resolveJar(environment);
|
||||
const java = await resolveJava(environment, signal);
|
||||
await requireJavaHomeExecutable(environment.JAVA_HOME, java);
|
||||
const jvmArguments = resolveJvmArguments(environment);
|
||||
await inspectJavaRuntime(java, environment, signal);
|
||||
await requireEngineArchive(jar, signal);
|
||||
return { jar, java, jvmArguments };
|
||||
signal?.throwIfAborted();
|
||||
return { jar, java, jvmArguments: resolveJvmArguments(environment) };
|
||||
};
|
||||
|
||||
const validateJadxConfigurationContents = async (
|
||||
configuration: JadxConfiguration,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> => {
|
||||
signal?.throwIfAborted();
|
||||
await inspectJavaRuntime(configuration.java, environment, signal);
|
||||
await requireEngineArchive(configuration.jar, signal);
|
||||
};
|
||||
|
||||
const projectConfigurationFailure = (
|
||||
operation: AndroidOperation,
|
||||
cause: JadxConfigurationFailure,
|
||||
): AnalysisCapabilityUnavailableError => {
|
||||
const output = cause.diagnostics;
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
cause.message,
|
||||
{
|
||||
cause,
|
||||
userMessage: cause.message,
|
||||
...(typeof output.stdout === "string" && typeof output.stderr === "string"
|
||||
? {
|
||||
capturedOutput: {
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
truncated: output.output_truncated === true,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const requireEngineArchive = async (
|
||||
|
||||
+98
-28
@@ -21,12 +21,14 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import {
|
||||
snapshotAndroidEngine,
|
||||
hashAndroidFile,
|
||||
snapshotAndroidTarget,
|
||||
} from "./AndroidTargetSnapshot.js";
|
||||
import { hashStableFile } from "../filesystem/StableFileHash.js";
|
||||
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
|
||||
import {
|
||||
inspectJadxAvailability,
|
||||
resolveJadxConfiguration,
|
||||
resolveJadxConfigurationInputs,
|
||||
validateJadxConfiguration,
|
||||
} from "./JadxConfiguration.js";
|
||||
import type { JadxLauncher } from "./JadxMcpTransport.js";
|
||||
|
||||
@@ -104,6 +106,50 @@ const executionError = (context: {
|
||||
});
|
||||
};
|
||||
|
||||
const androidTargetChanged = (
|
||||
operation: string,
|
||||
path: string,
|
||||
cause?: unknown,
|
||||
): AnalysisInputError =>
|
||||
new AnalysisInputError(
|
||||
operation,
|
||||
cause === undefined ? undefined : { cause },
|
||||
[
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `APK bytes changed after admission at ${path}; retry against a stable file.`,
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
const androidSourceChanged = (
|
||||
operation: string,
|
||||
source: string,
|
||||
cause?: unknown,
|
||||
): AnalysisCapabilityUnavailableError =>
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
operation,
|
||||
`Selected JADX input bytes changed during admission at ${source}; retry with a stable installation.`,
|
||||
cause === undefined ? undefined : { cause },
|
||||
);
|
||||
|
||||
const hashAndroidSource = async (
|
||||
path: string,
|
||||
operation: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
return (await hashStableFile(path, signal)).sha256;
|
||||
} catch (cause: unknown) {
|
||||
if (signal.aborted) throw cause;
|
||||
if (cause instanceof RegularFileChangedError)
|
||||
throw androidSourceChanged(operation, path, cause);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
interface PendingCleanup {
|
||||
session: JadxSession | undefined;
|
||||
root: PrivateRuntimeRoot | undefined;
|
||||
@@ -147,17 +193,18 @@ const cleanup = async (
|
||||
await root?.close();
|
||||
resources.root = undefined;
|
||||
} catch (cause) {
|
||||
return err(
|
||||
new ProviderCleanupError(
|
||||
"jadx",
|
||||
[root?.path ?? "unknown"],
|
||||
{
|
||||
...diagnostics,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ cause: previousError ?? cause },
|
||||
),
|
||||
const error = new ProviderCleanupError(
|
||||
"jadx",
|
||||
[root?.path ?? "unknown"],
|
||||
{
|
||||
...diagnostics,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ cause: previousError ?? cause },
|
||||
);
|
||||
if (previousError?.partialObservation !== undefined)
|
||||
error.retainPartialObservation(previousError.partialObservation);
|
||||
return err(error);
|
||||
}
|
||||
return ok(undefined);
|
||||
};
|
||||
@@ -287,23 +334,33 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
request.operation,
|
||||
`Target ${target.path} is ${target.format}; provide one standalone APK.`,
|
||||
);
|
||||
const configuration = await resolveJadxConfiguration(
|
||||
const configuration = await resolveJadxConfigurationInputs(
|
||||
this.environment,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
const jarHash = await hashAndroidFile(configuration.jar);
|
||||
const bridgeHash = await hashAndroidFile(BRIDGE_SOURCE);
|
||||
if ((await hashAndroidFile(target.path)) !== target.sha256)
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"APK bytes changed after admission; retry against a stable file.",
|
||||
},
|
||||
]);
|
||||
const jarHash = await hashAndroidSource(
|
||||
configuration.jar,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
const bridgeHash = await hashAndroidSource(
|
||||
BRIDGE_SOURCE,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
let targetHash: string;
|
||||
try {
|
||||
targetHash = (await hashStableFile(target.path, signal)).sha256;
|
||||
} catch (cause: unknown) {
|
||||
if (signal.aborted) throw cause;
|
||||
if (cause instanceof RegularFileChangedError)
|
||||
throw androidTargetChanged(request.operation, target.path, cause);
|
||||
throw cause;
|
||||
}
|
||||
if (targetHash !== target.sha256)
|
||||
throw androidTargetChanged(request.operation, target.path);
|
||||
const key = JSON.stringify({
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
@@ -326,27 +383,40 @@ export class JadxProvider implements AndroidAnalysisPort {
|
||||
}
|
||||
let retained = this.#retained;
|
||||
if (retained === undefined) {
|
||||
await validateJadxConfiguration(
|
||||
configuration,
|
||||
this.environment,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-android-" });
|
||||
const engine = await snapshotAndroidEngine(
|
||||
configuration.jar,
|
||||
jarHash,
|
||||
root.path,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
const snapshot = await snapshotAndroidTarget(
|
||||
target.path,
|
||||
target.sha256,
|
||||
root.path,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
const bridge = join(root.path, "ReaJadxBridge.java");
|
||||
await copyFile(BRIDGE_SOURCE, bridge);
|
||||
await chmod(bridge, 0o400);
|
||||
if ((await hashAndroidFile(bridge)) !== bridgeHash)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"jadx",
|
||||
const copiedBridgeHash = await hashAndroidSource(
|
||||
bridge,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
if (copiedBridgeHash !== bridgeHash)
|
||||
throw androidSourceChanged(
|
||||
request.operation,
|
||||
"REA Android bridge bytes changed during admission; retry with a stable installation.",
|
||||
BRIDGE_SOURCE,
|
||||
undefined,
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
session = new JadxSession(
|
||||
|
||||
@@ -157,7 +157,7 @@ const runApktool = async (
|
||||
timeoutMs: limits.timeoutMs,
|
||||
diagnosticBytes: limits.maxOutputBytes,
|
||||
},
|
||||
(signal === undefined ? {} : { signal }),
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return ok({ stdout: output.stdout.text, stderr: output.stderr.text });
|
||||
} catch (cause) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import {
|
||||
effectiveClientServer,
|
||||
parseClientConfiguration,
|
||||
@@ -19,7 +19,7 @@ export const readConfigurationText = async (
|
||||
path: string,
|
||||
): Promise<Result<string | undefined, ClientConfigurationFileError>> => {
|
||||
try {
|
||||
return ok(await readFile(path, "utf8"));
|
||||
return ok(await readRegularFileText(path));
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return ok(undefined);
|
||||
|
||||
@@ -5,27 +5,22 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { compareBundles } from "../domain/bundleComparison.js";
|
||||
import { EvidenceLedger } from "./investigation/EvidenceLedger.js";
|
||||
import {
|
||||
readEvidenceBundle,
|
||||
writeEvidenceBundle,
|
||||
} from "./EvidenceBundleFiles.js";
|
||||
|
||||
/** Validate and merge one bundle using the session Evidence ledger. */
|
||||
/** Validate a standalone bundle and report its complete record/revision counts. */
|
||||
export const importEvidenceBundleCommand = async (
|
||||
path: string,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const loaded = await readEvidenceBundle(path);
|
||||
if (!loaded.ok) return loaded;
|
||||
const ledger = createLedger();
|
||||
const imported = ledger.import(loaded.value);
|
||||
return imported.ok
|
||||
? ok({
|
||||
imported: imported.value.recordsAdded,
|
||||
unknowns_added: imported.value.unknownsAdded,
|
||||
total: ledger.export().records.length,
|
||||
})
|
||||
: imported;
|
||||
return ok({
|
||||
imported: loaded.value.records.length,
|
||||
unknowns_added: loaded.value.unknowns.length,
|
||||
total: loaded.value.records.length,
|
||||
});
|
||||
};
|
||||
|
||||
/** Validate a source bundle and atomically export canonical bytes. */
|
||||
@@ -64,8 +59,6 @@ export const compareEvidenceBundlesCommand = async (input: {
|
||||
}
|
||||
};
|
||||
|
||||
const createLedger = (): EvidenceLedger => new EvidenceLedger();
|
||||
|
||||
const projectWrite = (
|
||||
bundle: EvidenceBundle,
|
||||
written: Awaited<ReturnType<typeof writeEvidenceBundle>>,
|
||||
|
||||
@@ -16,8 +16,7 @@ import {
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { parseUtf8Json } from "./Utf8JsonInput.js";
|
||||
import { readRegularFile } from "./RegularFileRead.js";
|
||||
import { readJsonInputFile } from "./JsonInputFile.js";
|
||||
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
|
||||
|
||||
/** Request control and its owning operation for an interruptible atomic write. */
|
||||
@@ -37,12 +36,20 @@ export const readJsonFile = async (
|
||||
> => {
|
||||
const requestedPath = resolve(path);
|
||||
try {
|
||||
const encoded = await readRegularFile(requestedPath);
|
||||
const decoded = parseUtf8Json(encoded, "read_evidence_file", requestedPath);
|
||||
const decoded = await readJsonInputFile(
|
||||
requestedPath,
|
||||
"read_evidence_file",
|
||||
);
|
||||
if (!decoded.ok) {
|
||||
if (decoded.error instanceof AnalysisResourceConstraintError)
|
||||
return err(decoded.error);
|
||||
return err(
|
||||
new EvidenceFileError("read", "invalid-json", {
|
||||
cause: decoded.cause ?? new SyntaxError(decoded.error),
|
||||
cause:
|
||||
decoded.error.cause ??
|
||||
new SyntaxError(
|
||||
decoded.error.issues[0]?.message ?? decoded.error.message,
|
||||
),
|
||||
path: requestedPath,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,61 +6,76 @@ import { getHeapStatistics } from "node:v8";
|
||||
import parser from "stream-json/parser.js";
|
||||
import streamValues from "stream-json/streamers/stream-values.js";
|
||||
|
||||
import { withRegularFile } from "./application/RegularFileRead.js";
|
||||
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
|
||||
import { withRegularFile } from "./RegularFileRead.js";
|
||||
import {
|
||||
JSON_BYTE_ORDER_MARK_MESSAGE,
|
||||
JSON_INPUT_RESOURCE_REMEDIATION,
|
||||
parseUtf8Json,
|
||||
} from "./application/Utf8JsonInput.js";
|
||||
} from "./Utf8JsonInput.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "./domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "./domain/result.js";
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type JsonFileFailure = AnalysisInputError | AnalysisResourceConstraintError;
|
||||
type JsonInputFileFailure =
|
||||
| AnalysisInputError
|
||||
| AnalysisResourceConstraintError;
|
||||
const READ_CHUNK_BYTES = 64 * 1024;
|
||||
const PACKED_STRING_PART_CODE_UNITS = 64 * 1024;
|
||||
const PACKED_TOKEN_PART_CODE_UNITS = 64 * 1024;
|
||||
// Retain native-parser speed for modest inputs while bounding its extra copies.
|
||||
// This selects an implementation; larger files remain accepted through streaming.
|
||||
const NATIVE_PARSE_READ_BUDGET = 8 * 1024 * 1024;
|
||||
|
||||
/** Keep native parsing only when input copies and value expansion fit live headroom. */
|
||||
const nativeParseFits = (inputBytes: number): boolean =>
|
||||
inputBytes <= NATIVE_PARSE_READ_BUDGET &&
|
||||
// The assembler estimate reserves up to 128 bytes per two-byte container.
|
||||
// Allow that 64x expansion plus byte/text copies before native JSON.parse,
|
||||
// whose individual container allocations cannot be intercepted.
|
||||
inputBytes * 72 + READ_CHUNK_BYTES <=
|
||||
getHeapStatistics().total_available_size;
|
||||
|
||||
/** Parse strict UTF-8 JSON without requiring a whole-document string. */
|
||||
export const readCliJsonFile = (
|
||||
export const readJsonInputFile = (
|
||||
path: string,
|
||||
operation: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<unknown, JsonFileFailure>> =>
|
||||
): Promise<Result<unknown, JsonInputFileFailure>> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
async (handle, stats) => {
|
||||
let found = false;
|
||||
let value: unknown;
|
||||
try {
|
||||
const prefix =
|
||||
stats.size <= NATIVE_PARSE_READ_BUDGET
|
||||
? await readPrefix(handle, stats.size + 1, signal)
|
||||
: undefined;
|
||||
if (prefix?.complete === true) {
|
||||
const prefix = nativeParseFits(stats.size)
|
||||
? await readPrefix(handle, stats.size + 1, signal)
|
||||
: undefined;
|
||||
if (prefix !== undefined) {
|
||||
if (!prefix.complete || prefix.bytes.length !== stats.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
const parsed = parseUtf8Json(
|
||||
prefix.bytes,
|
||||
operation,
|
||||
path,
|
||||
"cli-json-input",
|
||||
"json-file-input",
|
||||
);
|
||||
return parsed.ok
|
||||
? ok(parsed.value)
|
||||
: err(invalidJson(operation, parsed.error, parsed.cause));
|
||||
}
|
||||
await pipeline(
|
||||
decodedChunks(handle, signal, prefix?.bytes),
|
||||
decodedChunks(handle, stats.size, path, signal),
|
||||
parser.asStream({
|
||||
jsonStreaming: false,
|
||||
streamValues: false,
|
||||
packKeys: false,
|
||||
packStrings: false,
|
||||
packNumbers: false,
|
||||
}),
|
||||
packJsonStrings(operation, stats.size),
|
||||
packJsonScalars(operation, stats.size, path),
|
||||
admitJsonAssembly(operation, stats.size, path),
|
||||
streamValues.asStream(),
|
||||
async (rows: AsyncIterable<unknown>) => {
|
||||
for await (const row of rows) {
|
||||
@@ -107,8 +122,9 @@ export const readCliJsonFile = (
|
||||
new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"An individual JSON string exceeds the runtime string limit",
|
||||
"An individual JSON string or number token exceeds the runtime string limit",
|
||||
{
|
||||
input_path: path,
|
||||
input_file_bytes: stats.size,
|
||||
max_string_code_units: constants.MAX_STRING_LENGTH,
|
||||
},
|
||||
@@ -121,12 +137,16 @@ export const readCliJsonFile = (
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
signal,
|
||||
{ signal },
|
||||
);
|
||||
|
||||
const packJsonStrings = (operation: string, inputFileBytes: number) =>
|
||||
const packJsonScalars = (
|
||||
operation: string,
|
||||
inputFileBytes: number,
|
||||
path: string,
|
||||
) =>
|
||||
async function* (tokens: AsyncIterable<unknown>): AsyncGenerator<unknown> {
|
||||
let kind: "keyValue" | "stringValue" | undefined;
|
||||
let kind: "keyValue" | "stringValue" | "numberValue" | undefined;
|
||||
let length = 0;
|
||||
let value = "";
|
||||
let parts: string[] = [];
|
||||
@@ -139,23 +159,32 @@ const packJsonStrings = (operation: string, inputFileBytes: number) =>
|
||||
case "startString":
|
||||
kind = token.name === "startKey" ? "keyValue" : "stringValue";
|
||||
break;
|
||||
case "startNumber":
|
||||
kind = "numberValue";
|
||||
break;
|
||||
case "numberChunk":
|
||||
case "stringChunk":
|
||||
if (
|
||||
kind === undefined ||
|
||||
!("value" in token) ||
|
||||
typeof token.value !== "string"
|
||||
)
|
||||
throw new Error("Unexpected JSON string fragment");
|
||||
throw new Error("Unexpected JSON scalar fragment");
|
||||
length += token.value.length;
|
||||
if (length > constants.MAX_STRING_LENGTH)
|
||||
throw new RangeError("Invalid string length");
|
||||
parts.push(token.value);
|
||||
partLength += token.value.length;
|
||||
if (partLength >= PACKED_STRING_PART_CODE_UNITS) {
|
||||
if (partLength >= PACKED_TOKEN_PART_CODE_UNITS) {
|
||||
// The tokenizer emits short fragments. Coalesce them before retaining
|
||||
// a string so millions of substring/rope nodes cannot exhaust the heap
|
||||
// a scalar so millions of substring/rope nodes cannot exhaust the heap
|
||||
// before the native string-length constraint can be reported.
|
||||
requireStringAssemblyHeadroom(operation, inputFileBytes, length);
|
||||
requireStringAssemblyHeadroom(
|
||||
operation,
|
||||
inputFileBytes,
|
||||
path,
|
||||
length,
|
||||
);
|
||||
value += parts.join("");
|
||||
parts = [];
|
||||
partLength = 0;
|
||||
@@ -163,8 +192,14 @@ const packJsonStrings = (operation: string, inputFileBytes: number) =>
|
||||
break;
|
||||
case "endKey":
|
||||
case "endString":
|
||||
if (kind === undefined) throw new Error("Unexpected JSON string end");
|
||||
requireStringAssemblyHeadroom(operation, inputFileBytes, length);
|
||||
case "endNumber":
|
||||
if (kind === undefined) throw new Error("Unexpected JSON scalar end");
|
||||
requireStringAssemblyHeadroom(
|
||||
operation,
|
||||
inputFileBytes,
|
||||
path,
|
||||
length,
|
||||
);
|
||||
yield { name: kind, value: value + parts.join("") };
|
||||
kind = undefined;
|
||||
length = 0;
|
||||
@@ -178,22 +213,78 @@ const packJsonStrings = (operation: string, inputFileBytes: number) =>
|
||||
}
|
||||
};
|
||||
|
||||
/** Admit the retained value graph before the upstream assembler grows it. */
|
||||
const admitJsonAssembly = (
|
||||
operation: string,
|
||||
inputFileBytes: number,
|
||||
path: string,
|
||||
) =>
|
||||
async function* (tokens: AsyncIterable<unknown>): AsyncGenerator<unknown> {
|
||||
let projectedBytes = 0;
|
||||
let nextCheck = 0;
|
||||
for await (const token of tokens) {
|
||||
if (typeof token !== "object" || token === null || !("name" in token))
|
||||
throw new Error("Unexpected JSON assembly token");
|
||||
if (token.name === "startObject" || token.name === "startArray") {
|
||||
projectedBytes += 128;
|
||||
} else if (token.name === "keyValue" || token.name === "stringValue") {
|
||||
if (!("value" in token) || typeof token.value !== "string")
|
||||
throw new Error("Unexpected packed JSON string");
|
||||
projectedBytes += 64 + token.value.length * 2;
|
||||
} else if (
|
||||
token.name === "numberValue" ||
|
||||
token.name === "nullValue" ||
|
||||
token.name === "trueValue" ||
|
||||
token.name === "falseValue"
|
||||
) {
|
||||
projectedBytes += 64;
|
||||
}
|
||||
if (projectedBytes >= nextCheck) {
|
||||
const heap = getHeapStatistics();
|
||||
// Conservative capacity for containers, property/array slots and UTF-16
|
||||
// values. Keep another whole projection available for container growth,
|
||||
// plus the next chunk of estimates between samples. This is admission
|
||||
// against live runtime headroom, not a fixed document-size policy.
|
||||
const requiredBytes = projectedBytes + READ_CHUNK_BYTES;
|
||||
if (requiredBytes > heap.total_available_size)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient heap headroom to materialize the complete JSON value",
|
||||
{
|
||||
input_path: path,
|
||||
input_file_bytes: inputFileBytes,
|
||||
projected_value_bytes: projectedBytes,
|
||||
assembly_headroom_bytes: requiredBytes,
|
||||
available_heap_bytes: heap.total_available_size,
|
||||
heap_size_limit_bytes: heap.heap_size_limit,
|
||||
},
|
||||
{ remediationAction: JSON_INPUT_RESOURCE_REMEDIATION },
|
||||
);
|
||||
nextCheck = projectedBytes + READ_CHUNK_BYTES;
|
||||
}
|
||||
yield token;
|
||||
}
|
||||
};
|
||||
|
||||
const requireStringAssemblyHeadroom = (
|
||||
operation: string,
|
||||
inputFileBytes: number,
|
||||
path: string,
|
||||
stringCodeUnits: number,
|
||||
): void => {
|
||||
if (stringCodeUnits < PACKED_STRING_PART_CODE_UNITS) return;
|
||||
if (stringCodeUnits < PACKED_TOKEN_PART_CODE_UNITS) return;
|
||||
const heap = getHeapStatistics();
|
||||
// Concatenation or key interning may flatten the retained rope. Reserve its
|
||||
// UTF-16 representation and the next coalesced part before that allocation.
|
||||
const requiredBytes = 2 * (stringCodeUnits + PACKED_STRING_PART_CODE_UNITS);
|
||||
const requiredBytes = 2 * (stringCodeUnits + PACKED_TOKEN_PART_CODE_UNITS);
|
||||
if (requiredBytes > heap.total_available_size)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"Insufficient heap headroom to assemble a complete JSON string",
|
||||
{
|
||||
input_path: path,
|
||||
input_file_bytes: inputFileBytes,
|
||||
string_code_units: stringCodeUnits,
|
||||
string_assembly_headroom_bytes: requiredBytes,
|
||||
@@ -208,8 +299,9 @@ const requireStringAssemblyHeadroom = (
|
||||
|
||||
async function* decodedChunks(
|
||||
handle: FileHandle,
|
||||
admittedBytes: number,
|
||||
path: string,
|
||||
signal: AbortSignal | undefined,
|
||||
prefix?: Uint8Array,
|
||||
): AsyncGenerator<string> {
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||
let leading = true;
|
||||
@@ -220,25 +312,25 @@ async function* decodedChunks(
|
||||
}
|
||||
return text;
|
||||
};
|
||||
if (prefix !== undefined)
|
||||
for (let offset = 0; offset < prefix.length; offset += READ_CHUNK_BYTES) {
|
||||
signal?.throwIfAborted();
|
||||
yield checked(
|
||||
decoder.decode(prefix.subarray(offset, offset + READ_CHUNK_BYTES), {
|
||||
stream: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
const bytes = Buffer.allocUnsafe(READ_CHUNK_BYTES);
|
||||
let observedBytes = 0;
|
||||
while (true) {
|
||||
signal?.throwIfAborted();
|
||||
const read = await handle.read(bytes, 0, bytes.length, null);
|
||||
const read = await handle.read(
|
||||
bytes,
|
||||
0,
|
||||
Math.min(bytes.length, admittedBytes - observedBytes + 1),
|
||||
null,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (read.bytesRead === 0) break;
|
||||
observedBytes += read.bytesRead;
|
||||
if (observedBytes > admittedBytes) throw new RegularFileChangedError(path);
|
||||
yield checked(
|
||||
decoder.decode(bytes.subarray(0, read.bytesRead), { stream: true }),
|
||||
);
|
||||
}
|
||||
if (observedBytes !== admittedBytes) throw new RegularFileChangedError(path);
|
||||
yield checked(decoder.decode());
|
||||
}
|
||||
|
||||
@@ -264,8 +356,7 @@ const readPrefix = async (
|
||||
return { bytes: bytes.subarray(0, offset), complete: true };
|
||||
offset += read.bytesRead;
|
||||
}
|
||||
// The file grew after admission. Continue from this same handle, preserving
|
||||
// the prefix already read rather than reopening or dropping its bytes.
|
||||
// One byte beyond the admitted extent proves the selected file changed.
|
||||
return { bytes, complete: false };
|
||||
};
|
||||
|
||||
@@ -1,3 +1,11 @@
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../domain/javascript/javascriptApplicationAnalysis.js";
|
||||
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../contracts/javascript/javascriptRuntimeReconciliationExample.js";
|
||||
import {
|
||||
createJavaScriptSemanticGraph,
|
||||
createJavaScriptSemanticGraphNode,
|
||||
JavaScriptSemanticEvidenceContextRegistry,
|
||||
} from "../domain/javascript/javascriptSemanticGraph.js";
|
||||
import { proofEvidence } from "./ReconstructionObligationLedger.fixture.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
@@ -171,3 +179,115 @@ describe("reconstruction obligation candidates", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps each semantic candidate bound to its own file and authority context", () => {
|
||||
const contexts = new JavaScriptSemanticEvidenceContextRegistry();
|
||||
const base = javascriptApplicationAnalysisResultSchema.parse(
|
||||
JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE.normalized_result,
|
||||
);
|
||||
const sourceRecords = [
|
||||
proofEvidence("first-file"),
|
||||
proofEvidence("second-file"),
|
||||
];
|
||||
const module = createJavaScriptSemanticGraphNode(
|
||||
{
|
||||
kind: "module",
|
||||
identity: {
|
||||
artifact_sha256: base.root_artifact_sha256,
|
||||
module_path: "app.js",
|
||||
source_range: null,
|
||||
role_key: "module",
|
||||
},
|
||||
function_node_id: null,
|
||||
application_node_ids: [],
|
||||
label: "app.js",
|
||||
properties: {},
|
||||
evidence: artifactEvidence(base.root_artifact_sha256, "app.js"),
|
||||
},
|
||||
contexts,
|
||||
);
|
||||
const requests = sourceRecords.flatMap((source, fileIndex) =>
|
||||
[1, 2].map((line) => {
|
||||
const sha256 = String(fileIndex + 4).repeat(64);
|
||||
const path = `file-${String(fileIndex)}.js`;
|
||||
return createJavaScriptSemanticGraphNode(
|
||||
{
|
||||
kind: "request",
|
||||
identity: {
|
||||
artifact_sha256: sha256,
|
||||
module_path: path,
|
||||
source_range: {
|
||||
start: { line, column: 0 },
|
||||
end: { line, column: 8 },
|
||||
},
|
||||
role_key: `request-${String(line)}`,
|
||||
},
|
||||
function_node_id: null,
|
||||
application_node_ids: [],
|
||||
label: `${path}:${String(line)}`,
|
||||
properties: {},
|
||||
evidence: {
|
||||
...artifactEvidence(sha256, path, "ast-static-analysis"),
|
||||
evidence_ids: [source.evidence_id],
|
||||
},
|
||||
},
|
||||
contexts,
|
||||
);
|
||||
}),
|
||||
);
|
||||
const { graph_id: _graphId, ...semantic } = base.semantic_graph;
|
||||
const semanticGraph = createJavaScriptSemanticGraph({
|
||||
...semantic,
|
||||
root_node_ids: [module.node_id],
|
||||
nodes: [module, ...requests],
|
||||
evidence_contexts: contexts.contexts,
|
||||
});
|
||||
const example = JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE;
|
||||
const application = createEvidence(
|
||||
{
|
||||
path: base.input_path,
|
||||
sha256: base.root_artifact_sha256,
|
||||
format: base.format,
|
||||
},
|
||||
example.provider,
|
||||
{
|
||||
predicateType: example.predicate_type,
|
||||
operation: example.operation,
|
||||
parameters: example.parameters,
|
||||
result: jsonValueSchema.parse({ ...base, semantic_graph: semanticGraph }),
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
evidenceLinks: sourceRecords.map(({ evidence_id }) => evidence_id),
|
||||
},
|
||||
);
|
||||
const generated = deriveReconstructionObligationCandidates(
|
||||
createEvidenceBundle([...sourceRecords, application]),
|
||||
[],
|
||||
);
|
||||
expect(generated.limitations).toEqual([]);
|
||||
expect(generated.candidates).toHaveLength(requests.length);
|
||||
for (const [index, node] of requests.entries()) {
|
||||
const source = sourceRecords[Math.floor(index / 2)];
|
||||
expect(
|
||||
generated.candidates.find(
|
||||
({ target }) => target.semantic_node_id === node.node_id,
|
||||
),
|
||||
).toMatchObject({
|
||||
title: node.label,
|
||||
family: "request",
|
||||
source_state: "candidate",
|
||||
target: {
|
||||
artifact_sha256: node.identity.artifact_sha256,
|
||||
semantic_node_id: node.node_id,
|
||||
},
|
||||
authority_references: [
|
||||
{
|
||||
evidence_id: source?.evidence_id,
|
||||
authority: "controlled-replay",
|
||||
state: "candidate",
|
||||
location: `${semanticGraph.graph_id}/node/${node.node_id}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -12,7 +12,6 @@ import type {
|
||||
ReconstructionObligation,
|
||||
ReviewedReconstructionObligation,
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
import { resolveJavaScriptSemanticEvidence } from "../domain/javascript/javascriptSemanticGraph.js";
|
||||
import { parseApplicationGraphEvidence } from "./javascript/JavaScriptApplicationEvidenceGraph.js";
|
||||
import {
|
||||
applicationObligationPolicy,
|
||||
@@ -115,14 +114,21 @@ const deriveApplicationCandidates = (
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (source.semanticGraph !== null)
|
||||
if (source.semanticGraph !== null) {
|
||||
const evidenceContexts = new Map(
|
||||
source.semanticGraph.evidence_contexts.map((context) => [
|
||||
context.context_id,
|
||||
context,
|
||||
]),
|
||||
);
|
||||
for (const node of source.semanticGraph.nodes) {
|
||||
const candidatePolicy = semanticObligationPolicy(node.kind);
|
||||
if (candidatePolicy === undefined) continue;
|
||||
const evidenceContext = resolveJavaScriptSemanticEvidence(
|
||||
source.semanticGraph,
|
||||
node.evidence,
|
||||
);
|
||||
const evidenceContext = evidenceContexts.get(node.evidence.context_id);
|
||||
if (evidenceContext === undefined)
|
||||
throw new TypeError(
|
||||
"Semantic evidence reference names an absent context",
|
||||
);
|
||||
addCandidate(
|
||||
candidates,
|
||||
generatedCandidate({
|
||||
@@ -144,6 +150,7 @@ const deriveApplicationCandidates = (
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (source.graph.coverage.status !== "complete")
|
||||
limitations.add(
|
||||
`Application graph ${source.graph.graph_id} coverage is ${source.graph.coverage.status}; omitted candidates remain unknown.`,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { readFile, realpath, stat } from "node:fs/promises";
|
||||
import { lstat, realpath, stat } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import ignore from "ignore";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -47,14 +48,27 @@ const resolveRoot = async (
|
||||
const buildIgnored = async (
|
||||
root: string,
|
||||
excludePaths: readonly string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReturnType<typeof ignore>> => {
|
||||
const ignored = ignore();
|
||||
const policyPath = join(root, ".gitignore");
|
||||
let present = true;
|
||||
try {
|
||||
ignored.add(await readFile(join(root, ".gitignore"), "utf8"));
|
||||
await lstat(policyPath);
|
||||
} catch (cause: unknown) {
|
||||
// Missing or unreadable ignore file does not authorize broader access.
|
||||
void cause;
|
||||
if (
|
||||
!(
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT"
|
||||
)
|
||||
)
|
||||
throw cause;
|
||||
present = false;
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
if (present) ignored.add(await readRegularFileText(policyPath, { signal }));
|
||||
ignored.add([...DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS]);
|
||||
for (const path of excludePaths) {
|
||||
ignored.add(path);
|
||||
@@ -71,9 +85,22 @@ export const prepareReferenceSourceImport = async (
|
||||
> => {
|
||||
const root = await resolveRoot(options.root);
|
||||
if (!root.ok) return root;
|
||||
return ok({
|
||||
root: root.value,
|
||||
ignored: await buildIgnored(root.value, options.excludePaths ?? []),
|
||||
secrets: ignore().add([...options.policy.secretPatterns]),
|
||||
});
|
||||
try {
|
||||
return ok({
|
||||
root: root.value,
|
||||
ignored: await buildIgnored(
|
||||
root.value,
|
||||
options.excludePaths ?? [],
|
||||
options.signal,
|
||||
),
|
||||
secrets: ignore().add([...options.policy.secretPatterns]),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
failure(
|
||||
options.signal?.aborted === true ? "cancelled" : "io",
|
||||
`Reference source ignore policy could not be read at ${join(root.value, ".gitignore")}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import fs from "node:fs";
|
||||
import { lstat, readFile } from "node:fs/promises";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { readRegularFile, readRegularFileText } from "./RegularFileRead.js";
|
||||
|
||||
export type ReferenceSourceVcsInfo =
|
||||
| {
|
||||
@@ -29,7 +30,7 @@ export const readReferenceSourceVcs = async (
|
||||
: { kind: "unknown", head: null, dirty: null };
|
||||
}
|
||||
try {
|
||||
const head = await resolveSourceHead(root);
|
||||
const head = await resolveSourceHead(root, signal);
|
||||
if (isAborted(signal)) return { kind: "unknown", head: null, dirty: null };
|
||||
return { kind: "git", head, dirty: null };
|
||||
} catch (cause: unknown) {
|
||||
@@ -39,13 +40,60 @@ export const readReferenceSourceVcs = async (
|
||||
}
|
||||
};
|
||||
|
||||
const resolveSourceHead = async (root: string): Promise<string> => {
|
||||
const resolveSourceHead = async (
|
||||
root: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
// isomorphic-git is loaded on first use so CLI and MCP startup skip it.
|
||||
const { resolveRef } = await import("isomorphic-git");
|
||||
let failedRead: { readonly cause: unknown } | undefined;
|
||||
const referenceFs = {
|
||||
...fs,
|
||||
promises: {
|
||||
...fs.promises,
|
||||
// isomorphic-git treats every read failure as absence. Preserve real
|
||||
// failures so a readable packed ref cannot hide an unreadable loose ref.
|
||||
readFile: async (path?: string, options?: unknown) => {
|
||||
// isomorphic-git probes promise support with readFile() before reading
|
||||
// metadata. Its rejected probe must not count as a failed file read.
|
||||
if (path === undefined)
|
||||
throw new TypeError("Git metadata path is required");
|
||||
try {
|
||||
const bytes = await readRegularFile(path, { signal });
|
||||
const encoding =
|
||||
typeof options === "string"
|
||||
? options
|
||||
: typeof options === "object" &&
|
||||
options !== null &&
|
||||
"encoding" in options
|
||||
? options.encoding
|
||||
: undefined;
|
||||
if (encoding === undefined || encoding === null) return bytes;
|
||||
if (typeof encoding !== "string" || !Buffer.isEncoding(encoding))
|
||||
throw new TypeError("Unsupported Git metadata text encoding");
|
||||
return bytes.toString(encoding);
|
||||
} catch (cause: unknown) {
|
||||
if (errorCode(cause) !== "ENOENT") failedRead ??= { cause };
|
||||
throw cause;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
const readRef = async (options: {
|
||||
readonly gitdir?: string;
|
||||
readonly ref: string;
|
||||
}) => {
|
||||
const head = await resolveRef({ fs: referenceFs, dir: root, ...options });
|
||||
signal?.throwIfAborted();
|
||||
if (failedRead !== undefined) throw failedRead.cause;
|
||||
return head;
|
||||
};
|
||||
const dotgit = join(root, ".git");
|
||||
if (!(await lstat(dotgit)).isFile())
|
||||
return resolveRef({ fs, dir: root, ref: "HEAD" });
|
||||
const pointer = (await readFile(dotgit, "utf8")).replace(/\r?\n$/u, "");
|
||||
if (!(await lstat(dotgit)).isFile()) return readRef({ ref: "HEAD" });
|
||||
const pointer = (await readRegularFileText(dotgit, { signal })).replace(
|
||||
/\r?\n$/u,
|
||||
"",
|
||||
);
|
||||
if (!pointer.startsWith("gitdir: ") || pointer.length === 8)
|
||||
throw new Error("Invalid Git directory pointer");
|
||||
const gitdir = resolve(root, pointer.slice(8));
|
||||
@@ -53,25 +101,23 @@ const resolveSourceHead = async (root: string): Promise<string> => {
|
||||
try {
|
||||
commonDirectory = resolve(
|
||||
gitdir,
|
||||
(await readFile(join(gitdir, "commondir"), "utf8")).replace(
|
||||
/\r?\n$/u,
|
||||
"",
|
||||
),
|
||||
(
|
||||
await readRegularFileText(join(gitdir, "commondir"), { signal })
|
||||
).replace(/\r?\n$/u, ""),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (errorCode(cause) !== "ENOENT") throw cause;
|
||||
return resolveRef({ fs, dir: root, gitdir, ref: "HEAD" });
|
||||
return readRef({ gitdir, ref: "HEAD" });
|
||||
}
|
||||
const head = (await readFile(join(gitdir, "HEAD"), "utf8")).trim();
|
||||
if (!head.startsWith("ref: "))
|
||||
return resolveRef({ fs, dir: root, gitdir, ref: "HEAD" });
|
||||
const head = (
|
||||
await readRegularFileText(join(gitdir, "HEAD"), { signal })
|
||||
).trim();
|
||||
if (!head.startsWith("ref: ")) return readRef({ gitdir, ref: "HEAD" });
|
||||
const ref = head.slice(5);
|
||||
const privateRef = ["refs/bisect/", "refs/rewritten/", "refs/worktree/"].some(
|
||||
(prefix) => ref.startsWith(prefix),
|
||||
);
|
||||
return resolveRef({
|
||||
fs,
|
||||
dir: root,
|
||||
return readRef({
|
||||
gitdir: privateRef ? gitdir : commonDirectory,
|
||||
ref,
|
||||
});
|
||||
|
||||
@@ -1,20 +1,44 @@
|
||||
import type { Stats } from "node:fs";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { lstat, stat, type FileHandle } from "node:fs/promises";
|
||||
|
||||
import { openRegularFile } from "../filesystem/RegularFile.js";
|
||||
import {
|
||||
openRegularFile,
|
||||
sameRegularFileState,
|
||||
RegularFileChangedError,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
|
||||
/** Filesystem admission policy for one selected regular input. */
|
||||
export interface RegularFileReadOptions {
|
||||
readonly signal?: AbortSignal | undefined;
|
||||
readonly symlinks?: "follow" | "reject";
|
||||
}
|
||||
|
||||
/** Admit one regular-file handle, retain it through the consumer, and always close it. */
|
||||
export const withRegularFile = async <Value>(
|
||||
path: string,
|
||||
read: (handle: FileHandle, stats: Stats) => Promise<Value>,
|
||||
signal?: AbortSignal,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<Value> => {
|
||||
const handle = await openRegularFile(path, { symlinks: "follow", signal });
|
||||
const { signal } = options;
|
||||
const handle = await openRegularFile(path, {
|
||||
symlinks: options.symlinks ?? "follow",
|
||||
signal,
|
||||
});
|
||||
try {
|
||||
const stats = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
const value = await read(handle, stats);
|
||||
signal?.throwIfAborted();
|
||||
const [opened, currentPath] = await Promise.all([
|
||||
handle.stat(),
|
||||
options.symlinks === "reject" ? lstat(path) : stat(path),
|
||||
]);
|
||||
if (
|
||||
!sameRegularFileState(stats, opened) ||
|
||||
!sameRegularFileState(stats, currentPath)
|
||||
)
|
||||
throw new RegularFileChangedError(path);
|
||||
return value;
|
||||
} finally {
|
||||
await handle.close();
|
||||
@@ -24,6 +48,25 @@ export const withRegularFile = async <Value>(
|
||||
/** Admit a regular file without waiting for a pipe, then read its verified handle. */
|
||||
export const readRegularFile = (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<Buffer> =>
|
||||
withRegularFile(path, (handle) => handle.readFile({ signal }), signal);
|
||||
withRegularFile(
|
||||
path,
|
||||
async (handle, stats) => {
|
||||
const bytes = await readBoundedFileBytes(
|
||||
handle,
|
||||
stats.size,
|
||||
options.signal,
|
||||
);
|
||||
if (bytes === undefined || bytes.length !== stats.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
return bytes;
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
/** Read one admitted regular file as UTF-8 without waiting on a pipe. */
|
||||
export const readRegularFileText = async (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<string> => (await readRegularFile(path, options)).toString("utf8");
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type ClientRegistrationDialect,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
@@ -22,6 +22,7 @@ import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import type {
|
||||
ClientConfigurationInspection,
|
||||
ClientConfigurationResult,
|
||||
@@ -64,7 +65,7 @@ const configureClientDocument = async (
|
||||
return { status: "failed", reason: "path" };
|
||||
let original: string | undefined;
|
||||
try {
|
||||
original = await readFile(transactionPath, "utf8");
|
||||
original = await readRegularFileText(transactionPath);
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissing(cause)) return { status: "failed", reason: "readback" };
|
||||
}
|
||||
@@ -149,7 +150,7 @@ const configureClientDocument = async (
|
||||
}
|
||||
try {
|
||||
const readback = parseClientConfiguration(
|
||||
await readFile(transactionPath, "utf8"),
|
||||
await readRegularFileText(transactionPath),
|
||||
format,
|
||||
);
|
||||
if (!registrationCurrent(readback, desired)) {
|
||||
@@ -178,7 +179,7 @@ export const clientConfigurationAligned = async (
|
||||
try {
|
||||
const files = await readClientConfigurationFiles(client);
|
||||
if (!files.ok) return false;
|
||||
const original = await readFile(client.configPath, "utf8");
|
||||
const original = await readRegularFileText(client.configPath);
|
||||
const parsed = parseClientConfiguration(original, client.format);
|
||||
const policy = await readClientPolicyBlock(
|
||||
client,
|
||||
@@ -246,7 +247,7 @@ export const inspectClientConfiguration = async (
|
||||
};
|
||||
let original: string;
|
||||
try {
|
||||
original = await readFile(transactionPath, "utf8");
|
||||
original = await readRegularFileText(transactionPath);
|
||||
} catch (cause: unknown) {
|
||||
if (isMissing(cause)) return { status: "create" };
|
||||
return {
|
||||
|
||||
@@ -4,14 +4,13 @@ import { dirname, join } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
openRegularFile,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import { clientSkillDirectories } from "./SupportedClients.js";
|
||||
|
||||
export const MANAGED_SKILL_FILES = [
|
||||
"SKILL.md",
|
||||
"references/connection-and-recovery.md",
|
||||
"references/native-and-artifacts.md",
|
||||
"references/javascript-applications.md",
|
||||
"references/android-applications.md",
|
||||
@@ -23,14 +22,8 @@ export const isManagedSkillManifest = (content: string): boolean =>
|
||||
content.startsWith(`---\nname: ${PRODUCT_IDENTITY.skillName}\n`) ||
|
||||
content.startsWith(`---\r\nname: ${PRODUCT_IDENTITY.skillName}\r\n`);
|
||||
|
||||
export const readSkillFile = async (path: string): Promise<string> => {
|
||||
const handle = await openRegularFile(path, { symlinks: "reject" });
|
||||
try {
|
||||
return await handle.readFile("utf8");
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
export const readSkillFile = (path: string): Promise<string> =>
|
||||
readRegularFileText(path, { symlinks: "reject" });
|
||||
|
||||
interface CanonicalSkillFile {
|
||||
readonly content: string;
|
||||
@@ -199,7 +192,7 @@ export const installCanonicalSkill = async (
|
||||
for (const { destination, content } of changed)
|
||||
await writeText(destination, content);
|
||||
for (const { destination, content } of changed)
|
||||
if ((await readFile(destination, "utf8")) !== content)
|
||||
if ((await readSkillFile(destination)) !== content)
|
||||
throw new Error(`skill readback mismatch: ${destination}`);
|
||||
return "installed";
|
||||
} catch (cause: unknown) {
|
||||
@@ -231,7 +224,7 @@ export const readInstalledSkillIdentity = async (
|
||||
let content: string | undefined;
|
||||
for (const destination of destinations) {
|
||||
try {
|
||||
content = await readFile(join(destination.path, "SKILL.md"), "utf8");
|
||||
content = await readSkillFile(join(destination.path, "SKILL.md"));
|
||||
break;
|
||||
} catch {
|
||||
// Another selected copy may provide metadata; canonical validation below
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
withClientServers,
|
||||
type ClientConfigurationDocument,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { copyFile, lstat, readFile, realpath, rm } from "node:fs/promises";
|
||||
import { copyFile, lstat, realpath, rm } from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
|
||||
import { join } from "node:path";
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "./SetupSkill.js";
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import {
|
||||
manualRegistrationRemediation,
|
||||
supportedClients,
|
||||
@@ -49,7 +50,7 @@ export interface UninstallFileSystem {
|
||||
}
|
||||
|
||||
const systemFileSystem: UninstallFileSystem = {
|
||||
readText: (path) => readFile(path, "utf8"),
|
||||
readText: (path) => readRegularFileText(path),
|
||||
readRegularText: readSkillFile,
|
||||
copy: (source, destination) =>
|
||||
copyFile(source, destination, fsConstants.COPYFILE_EXCL),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { z } from "zod";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
@@ -14,6 +13,7 @@ import { supportedClients } from "./SupportedClients.js";
|
||||
import { existingSkillDestinations } from "./SetupSkill.js";
|
||||
import type { SetupAction } from "./SetupTypes.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
|
||||
/** Existing REA integrations selected for maintenance, without discovering new targets. */
|
||||
export interface MaintenanceScope {
|
||||
@@ -73,7 +73,7 @@ export const existingMaintenanceScope = async (
|
||||
const client = supported.find(({ name }) => name === registration.client);
|
||||
if (client === undefined) continue;
|
||||
const parsed = parseClientConfiguration(
|
||||
await readFile(client.configPath, "utf8"),
|
||||
await readRegularFileText(client.configPath),
|
||||
client.format,
|
||||
);
|
||||
const enabled = z
|
||||
@@ -130,7 +130,9 @@ export const planIntegrationMaintenance = async (
|
||||
};
|
||||
if (plan.data.plannedActions.length === 0)
|
||||
return { status: "current", plannedActions: [] };
|
||||
const allowedIds = new Set(scope.clients.map((client) => `configure_client:${client}`));
|
||||
const allowedIds = new Set(
|
||||
scope.clients.map((client) => `configure_client:${client}`),
|
||||
);
|
||||
const skillTargets = new Set(skillDestinations.map(({ path }) => path));
|
||||
if (
|
||||
plan.data.plannedActions.some((action) =>
|
||||
|
||||
@@ -27,7 +27,10 @@ import { WebScriptExportError } from "../domain/webScriptExportError.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import { WEB_SCRIPT_EXPORT_PROVIDER as PROVIDER } from "./InvestigationProviders.js";
|
||||
import { readRegularFile } from "./RegularFileRead.js";
|
||||
import { NonRegularFileReadError } from "../filesystem/RegularFile.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
RegularFileChangedError,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
|
||||
const OPERATION = "export_web_scripts";
|
||||
|
||||
@@ -153,7 +156,7 @@ const readCapture = async (
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<Buffer, AnalysisError>> => {
|
||||
try {
|
||||
return ok(await readRegularFile(path, signal));
|
||||
return ok(await readRegularFile(path, { signal }));
|
||||
} catch (cause: unknown) {
|
||||
const code =
|
||||
cause instanceof Error && "code" in cause ? String(cause.code) : "";
|
||||
@@ -163,6 +166,7 @@ const readCapture = async (
|
||||
);
|
||||
if (
|
||||
cause instanceof NonRegularFileReadError ||
|
||||
cause instanceof RegularFileChangedError ||
|
||||
code === "ENOENT" ||
|
||||
code === "ENOTDIR" ||
|
||||
code === "EISDIR" ||
|
||||
|
||||
@@ -14,7 +14,7 @@ import type { Result } from "../../domain/result.js";
|
||||
export interface AdbDeviceAnalysisPort {
|
||||
/** Probe the selected adb binary without contacting devices. */
|
||||
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
|
||||
/** The provider holds no long-lived resources; safe to call always. */
|
||||
/** Terminally stop admission, drain work, and retry retained package rollback. */
|
||||
close(): Promise<void>;
|
||||
execute(
|
||||
request: AdbRequest,
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "../../../tests/fixtures/analysisView.js";
|
||||
import {
|
||||
inspectAnalysisView,
|
||||
inspectAnalysisViewValidated,
|
||||
summarizeRetainedAnalysis,
|
||||
} from "./AnalysisViewService.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
@@ -58,6 +59,35 @@ it.each(["/fixtures/unknown.exe", ""])(
|
||||
},
|
||||
);
|
||||
|
||||
it("reports inline Evidence identity failures at the complete source path", () => {
|
||||
const parent = analysisViewLayoutEvidence();
|
||||
const input = {
|
||||
source: {
|
||||
kind: "inline",
|
||||
evidence: { ...parent, evidence_id: `ev_${"0".repeat(64)}` },
|
||||
},
|
||||
view: { kind: "summary" },
|
||||
} as const;
|
||||
|
||||
for (const result of [
|
||||
inspectAnalysisView(input),
|
||||
inspectAnalysisViewValidated(input),
|
||||
])
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [
|
||||
{
|
||||
path: ["source", "evidence", "evidence_id"],
|
||||
reason: "invalid_value",
|
||||
message: "Evidence semantic identifier does not match its record",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("projects a small native view from an authenticated >10 MiB retained dossier", () => {
|
||||
const original = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
const parent = createEvidence(
|
||||
|
||||
@@ -132,8 +132,11 @@ const resolveAnalysisViewSource = (
|
||||
return err(
|
||||
analysisInputErrorFromIssues(
|
||||
INSPECT_ANALYSIS_VIEW_OPERATION,
|
||||
cause.issues,
|
||||
source.evidence,
|
||||
cause.issues.map((issue) => ({
|
||||
...issue,
|
||||
path: ["source", "evidence", ...issue.path],
|
||||
})),
|
||||
{ source },
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
|
||||
@@ -2,9 +2,10 @@ import type { ApplicationNode } from "../../domain/javascript/javascriptApplicat
|
||||
import { sha256Text } from "../../domain/javascript/javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptSourceRange } from "../../domain/javascript/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../domain/javascript/javascriptArtifactFiles.js";
|
||||
import type {
|
||||
JavaScriptArtifactGraphContext,
|
||||
JavaScriptArtifactGraphCoverage,
|
||||
import {
|
||||
sourceNodeFor,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
type JavaScriptArtifactGraphCoverage,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
astObservationEvidence,
|
||||
@@ -38,10 +39,11 @@ export const electronFindingSourceNode = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
file: JavaScriptArtifactFile,
|
||||
moduleKey: string | null,
|
||||
runtime?: string,
|
||||
): ApplicationNode | undefined =>
|
||||
moduleKey === null
|
||||
? (context.assetNodes.get(file.path) ?? context.fileNodes.get(file.path))
|
||||
: context.moduleNodes.get(`${file.path}\0${moduleKey}`);
|
||||
: sourceNodeFor(context, file.path, moduleKey, runtime);
|
||||
|
||||
/** Observation-scoped identity shared safely across different artifact files. */
|
||||
export const electronObservationIdentity = (
|
||||
|
||||
@@ -73,6 +73,7 @@ const addIpcRecord = (
|
||||
context,
|
||||
record.file,
|
||||
record.finding.module_key,
|
||||
record.finding.module_runtime,
|
||||
);
|
||||
if (source === undefined) return;
|
||||
state.sources.set(record.key, source);
|
||||
@@ -255,6 +256,7 @@ const addValidationObservations = (state: IpcGraphState): void => {
|
||||
state.context,
|
||||
file,
|
||||
validation.module_key,
|
||||
validation.module_runtime,
|
||||
)
|
||||
: state.handlers.get(handlerRecord.key);
|
||||
if (target !== undefined)
|
||||
|
||||
@@ -38,7 +38,12 @@ export const addElectronNativeBoundaries = (
|
||||
|
||||
const addNativeBinding = (input: NativeBindingInput): void => {
|
||||
const { context, file, value, coverage } = input;
|
||||
const source = electronFindingSourceNode(context, file, value.module_key);
|
||||
const source = electronFindingSourceNode(
|
||||
context,
|
||||
file,
|
||||
value.module_key,
|
||||
value.module_runtime,
|
||||
);
|
||||
if (source === undefined) return;
|
||||
const resolved = resolveArtifactPath(
|
||||
value.specifier,
|
||||
|
||||
@@ -39,17 +39,32 @@ export const addElectronWindowBoundaries = (
|
||||
if (javascript === null) continue;
|
||||
const coverage = javascriptAnalysisCoverage(javascript);
|
||||
for (const value of javascript.electron.browser_windows) {
|
||||
const source = electronFindingSourceNode(context, file, value.module_key);
|
||||
const source = electronFindingSourceNode(
|
||||
context,
|
||||
file,
|
||||
value.module_key,
|
||||
value.module_runtime,
|
||||
);
|
||||
if (source !== undefined)
|
||||
addBrowserWindow({ context, file, source, value, coverage });
|
||||
}
|
||||
for (const value of javascript.electron.context_bridge_apis) {
|
||||
const source = electronFindingSourceNode(context, file, value.module_key);
|
||||
const source = electronFindingSourceNode(
|
||||
context,
|
||||
file,
|
||||
value.module_key,
|
||||
value.module_runtime,
|
||||
);
|
||||
if (source !== undefined)
|
||||
addContextBridge({ context, file, source, value, coverage });
|
||||
}
|
||||
for (const value of javascript.electron.utility_processes) {
|
||||
const source = electronFindingSourceNode(context, file, value.module_key);
|
||||
const source = electronFindingSourceNode(
|
||||
context,
|
||||
file,
|
||||
value.module_key,
|
||||
value.module_runtime,
|
||||
);
|
||||
if (source !== undefined)
|
||||
addUtilityProcess({ context, file, source, value, coverage });
|
||||
}
|
||||
|
||||
@@ -31,7 +31,16 @@ const graphIdentities = async (source: string) => {
|
||||
...(identity.strategy === "artifact-local-key"
|
||||
? {
|
||||
namespace: identity.namespace,
|
||||
key: identity.key.replace(/^[0-9a-f]{64}:/u, ""),
|
||||
// Module-export identity is a JSON tuple whose first entry
|
||||
// binds the whole container; only that digest changes here.
|
||||
key:
|
||||
identity.namespace === "module-export"
|
||||
? JSON.stringify(
|
||||
(JSON.parse(identity.key) as unknown[]).slice(1),
|
||||
)
|
||||
: identity.namespace === "source-module"
|
||||
? identity.key.replace(/^[0-9a-f]{64}:/u, "")
|
||||
: identity.key,
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
|
||||
@@ -161,7 +161,7 @@ const addBundlerModuleNodes = (
|
||||
],
|
||||
});
|
||||
context.moduleNodes.set(
|
||||
moduleLookupKey(file.path, moduleValue.module_key),
|
||||
moduleLookupKey(file.path, registration.runtime, moduleValue.module_key),
|
||||
module,
|
||||
);
|
||||
addAstContainsEdge(context, {
|
||||
@@ -195,7 +195,7 @@ const addBundlerRuntimeEdges = (
|
||||
const { file, registration, chunk, coverage } = record;
|
||||
for (const moduleKey of registration.entry_module_keys) {
|
||||
const resolved = context.moduleNodes.get(
|
||||
moduleLookupKey(file.path, moduleKey),
|
||||
moduleLookupKey(file.path, registration.runtime, moduleKey),
|
||||
);
|
||||
const target =
|
||||
resolved ?? unresolvedBundlerModuleNode(context, record, moduleKey);
|
||||
|
||||
@@ -323,8 +323,11 @@ export const selfReferenceOmissions = (
|
||||
];
|
||||
|
||||
/** Deterministic key for one recovered module inside a bundle asset. */
|
||||
export const moduleLookupKey = (path: string, moduleKey: string): string =>
|
||||
`${path}\0${moduleKey}`;
|
||||
export const moduleLookupKey = (
|
||||
path: string,
|
||||
runtime: string,
|
||||
moduleKey: string,
|
||||
): string => compositeKey([path, runtime, moduleKey]);
|
||||
|
||||
/** Deterministic key for one recovered bundler chunk inside a bundle asset. */
|
||||
export const chunkLookupKey = (
|
||||
@@ -353,7 +356,10 @@ export const sourceNodeFor = (
|
||||
context: JavaScriptArtifactGraphContext,
|
||||
path: string,
|
||||
moduleKey: string | null,
|
||||
runtime?: string,
|
||||
): ApplicationNode | undefined =>
|
||||
moduleKey === null
|
||||
? context.sourceModuleNodes.get(path)
|
||||
: context.moduleNodes.get(moduleLookupKey(path, moduleKey));
|
||||
: runtime === undefined
|
||||
? undefined
|
||||
: context.moduleNodes.get(moduleLookupKey(path, runtime, moduleKey));
|
||||
|
||||
@@ -78,8 +78,12 @@ const addReference = (
|
||||
omissions: { selfReferences: number },
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
sourceNodeFor(
|
||||
context,
|
||||
input.file.path,
|
||||
input.value.module_key,
|
||||
input.value.module_runtime,
|
||||
) ?? input.asset;
|
||||
const resolved =
|
||||
input.value.specifier === null
|
||||
? null
|
||||
@@ -162,8 +166,12 @@ const addEndpoint = (
|
||||
input: FindingInput<StaticEndpoint>,
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
sourceNodeFor(
|
||||
context,
|
||||
input.file.path,
|
||||
input.value.module_key,
|
||||
input.value.module_runtime,
|
||||
) ?? input.asset;
|
||||
const key = compactStringIdentityKey(input.value.value);
|
||||
const label = `${input.value.kind} endpoint`;
|
||||
const node = context.accumulator.addNode({
|
||||
@@ -204,8 +212,12 @@ const addStorage = (
|
||||
input: FindingInput<StaticStorage>,
|
||||
): void => {
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
sourceNodeFor(
|
||||
context,
|
||||
input.file.path,
|
||||
input.value.module_key,
|
||||
input.value.module_runtime,
|
||||
) ?? input.asset;
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "storage",
|
||||
identity: artifactLocalIdentity(
|
||||
@@ -262,8 +274,12 @@ const addDiscoveredRole = (
|
||||
coverage: input.coverage,
|
||||
});
|
||||
const source =
|
||||
sourceNodeFor(context, input.file.path, input.value.module_key) ??
|
||||
input.asset;
|
||||
sourceNodeFor(
|
||||
context,
|
||||
input.file.path,
|
||||
input.value.module_key,
|
||||
input.value.module_runtime,
|
||||
) ?? input.asset;
|
||||
addStaticInferenceEdge(context, {
|
||||
source,
|
||||
target: role,
|
||||
@@ -359,9 +375,12 @@ const resolveReference = (
|
||||
if (specifier === null) return null;
|
||||
const chunk = resolveBundlerChunkReference(context, sourcePath, reference);
|
||||
if (chunk !== null) return chunk;
|
||||
const module = context.moduleNodes.get(
|
||||
moduleLookupKey(sourcePath, specifier),
|
||||
);
|
||||
const module =
|
||||
reference.module_runtime === undefined
|
||||
? undefined
|
||||
: context.moduleNodes.get(
|
||||
moduleLookupKey(sourcePath, reference.module_runtime, specifier),
|
||||
);
|
||||
if (module !== undefined) {
|
||||
const file = context.filesByPath.get(sourcePath);
|
||||
return file === undefined
|
||||
@@ -407,10 +426,11 @@ const resolveBundlerChunkReference = (
|
||||
if (file === undefined) return null;
|
||||
const registrations = context.analysis.files
|
||||
.find(({ file: analyzedFile }) => analyzedFile.path === sourcePath)
|
||||
?.javascript?.bundler_registrations.filter(({ modules }) =>
|
||||
reference.module_key === null
|
||||
? true
|
||||
: modules.some(
|
||||
?.javascript?.bundler_registrations.filter(({ runtime, modules }) =>
|
||||
reference.module_runtime === undefined
|
||||
? reference.module_key === null
|
||||
: runtime === reference.module_runtime &&
|
||||
modules.some(
|
||||
({ module_key: moduleKey }) => moduleKey === reference.module_key,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -355,7 +355,7 @@ const semanticNodeFor = (roleKey: string) => {
|
||||
unpacked: false,
|
||||
text: { included: true, value: "" },
|
||||
};
|
||||
const state = createSemanticGraphProjectionState({ nodes: [] });
|
||||
const state = createSemanticGraphProjectionState();
|
||||
return constructSemanticGraphNode(
|
||||
file,
|
||||
{
|
||||
@@ -565,7 +565,7 @@ it("does not mark a file truncated when it exactly fills its budget", () => {
|
||||
it("only records node loss when the budget rejects a new identity", () => {
|
||||
// The truncation signal must record blocked node creation, not a zero
|
||||
// remaining budget: a file using exactly its share drops nothing.
|
||||
const state = createSemanticGraphProjectionState({ nodes: [] });
|
||||
const state = createSemanticGraphProjectionState();
|
||||
state.fileNodeBudget = 2;
|
||||
state.fileNodesDropped = false;
|
||||
const first = addSemanticGraphNode(state, semanticNodeFor("first"));
|
||||
|
||||
@@ -148,7 +148,7 @@ export interface JavaScriptSemanticGraphProjection {
|
||||
/** Accumulate semantic nodes while each source IR is still file-local. */
|
||||
export const createJavaScriptSemanticGraphProjection =
|
||||
(): JavaScriptSemanticGraphProjection => {
|
||||
const state = emptyState({ nodes: [] });
|
||||
const state = emptyState();
|
||||
const fingerprints: JavaScriptSemanticFingerprint[] = [];
|
||||
let truncatedFiles = 0;
|
||||
const projectSourceSteps = function* (
|
||||
|
||||
@@ -28,7 +28,6 @@ export interface SemanticGraphProjectionState {
|
||||
readonly unknowns: Map<string, JavaScriptSemanticGraphUnknown>;
|
||||
readonly evidenceContexts: JavaScriptSemanticEvidenceContextRegistry;
|
||||
readonly roots: Set<string>;
|
||||
readonly applicationNodeIdsByLocation: ReadonlyMap<string, readonly string[]>;
|
||||
/**
|
||||
* Remaining node budget for the file currently being projected.
|
||||
*
|
||||
@@ -69,32 +68,29 @@ export interface SemanticRelationConstructionInput {
|
||||
readonly properties?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Create empty projection state with structural application-node mappings. */
|
||||
export const createSemanticGraphProjectionState = (
|
||||
applicationGraph: Pick<JavaScriptApplicationGraph, "nodes">,
|
||||
): SemanticGraphProjectionState => {
|
||||
const index = indexApplicationNodes(applicationGraph.nodes);
|
||||
return {
|
||||
/** Create empty projection state; application-node links are bound at finish. */
|
||||
export const createSemanticGraphProjectionState =
|
||||
(): SemanticGraphProjectionState => ({
|
||||
nodes: new Map(),
|
||||
relations: new Map(),
|
||||
unknowns: new Map(),
|
||||
evidenceContexts: new JavaScriptSemanticEvidenceContextRegistry(),
|
||||
roots: new Set(),
|
||||
applicationNodeIdsByLocation: index.identifiers,
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
/** Bind retained semantic identities after all application observations exist. */
|
||||
export const bindSemanticGraphApplicationNodes = (
|
||||
state: SemanticGraphProjectionState,
|
||||
applicationGraph: Pick<JavaScriptApplicationGraph, "nodes">,
|
||||
): void => {
|
||||
const index = indexApplicationNodes(applicationGraph.nodes).identifiers;
|
||||
const applicationNodeIdsByLocation = indexApplicationNodes(
|
||||
applicationGraph.nodes,
|
||||
);
|
||||
for (const [identifier, node] of state.nodes) {
|
||||
state.nodes.set(identifier, {
|
||||
...node,
|
||||
application_node_ids: [
|
||||
...(index.get(
|
||||
...(applicationNodeIdsByLocation.get(
|
||||
applicationLocationKey(
|
||||
node.identity.artifact_sha256,
|
||||
node.identity.module_path,
|
||||
@@ -122,7 +118,7 @@ export const constructSemanticGraphNode = (
|
||||
role_key: input.roleKey,
|
||||
},
|
||||
function_node_id: input.functionNodeId,
|
||||
application_node_ids: matchingApplicationNodeIds(file, input, state),
|
||||
application_node_ids: [],
|
||||
label: input.label === null ? null : javascriptDisplayText(input.label),
|
||||
properties: input.properties ?? {},
|
||||
evidence: observedSemanticEvidence(file, input.location),
|
||||
@@ -247,9 +243,7 @@ export const addSemanticFallbackRoot = (
|
||||
|
||||
const indexApplicationNodes = (
|
||||
nodes: JavaScriptApplicationGraph["nodes"],
|
||||
): {
|
||||
readonly identifiers: ReadonlyMap<string, readonly string[]>;
|
||||
} => {
|
||||
): ReadonlyMap<string, readonly string[]> => {
|
||||
const identifiers = new Map<string, Set<string>>();
|
||||
for (const node of nodes) {
|
||||
for (const observation of node.observations) {
|
||||
@@ -280,19 +274,9 @@ const indexApplicationNodes = (
|
||||
return [key, sorted];
|
||||
}),
|
||||
);
|
||||
return { identifiers: indexed };
|
||||
return indexed;
|
||||
};
|
||||
|
||||
const matchingApplicationNodeIds = (
|
||||
file: JavaScriptArtifactFile,
|
||||
input: SemanticNodeConstructionInput,
|
||||
state: SemanticGraphProjectionState,
|
||||
): string[] => [
|
||||
...(state.applicationNodeIdsByLocation.get(
|
||||
applicationLocationKey(file.sha256, file.path, input.location),
|
||||
) ?? []),
|
||||
];
|
||||
|
||||
const addApplicationNodeIdentifier = (
|
||||
identifiers: Map<string, Set<string>>,
|
||||
key: string,
|
||||
|
||||
@@ -325,8 +325,7 @@ const resolveUiAction = (
|
||||
(node) =>
|
||||
["control", "view", "view_controller", "scene"].includes(node.kind) &&
|
||||
(node.id === query ||
|
||||
node.attributes.interface_builder_object_id === query ||
|
||||
node.id.endsWith(`:object:${query}`)),
|
||||
node.attributes.interface_builder_object_id === query),
|
||||
);
|
||||
const actionIds = new Set(
|
||||
graph.edges.flatMap((edge) =>
|
||||
|
||||
@@ -60,6 +60,30 @@ describe("English Unicode case collisions", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("retains every spelling in a high-cardinality folded sibling group", () => {
|
||||
const count = 8_192;
|
||||
const variants = caseVariants("abcdefghijklm", count);
|
||||
const { limitation, byPath } = annotate(variants);
|
||||
const ordered = [...variants].sort();
|
||||
const first = ordered[0];
|
||||
const second = ordered[1];
|
||||
const original = variants[0];
|
||||
if (first === undefined || second === undefined || original === undefined) {
|
||||
throw new Error("Expected at least two case variants");
|
||||
}
|
||||
expect(limitation).toBe(ENGLISH_UNICODE_CASE_INVENTORY_LIMITATION);
|
||||
expect(byPath.size).toBe(count);
|
||||
expect(byPath.get(first)).toEqual([
|
||||
`Logical path ${first} collides under English (en-US) Unicode case folding with ${second} and ${String(count - 2)} other spellings; ${NOTE}`,
|
||||
]);
|
||||
expect(byPath.get(original)?.[0]).toContain(
|
||||
`with ${first} and ${String(count - 2)} other spellings;`,
|
||||
);
|
||||
expect(
|
||||
[...byPath.values()].every((limitations) => limitations.length === 1),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stays linear for large case-variant subtrees", () => {
|
||||
const count = 5_000;
|
||||
const paths = Array.from({ length: count }, (_, index) => [
|
||||
@@ -81,3 +105,12 @@ describe("English Unicode case collisions", () => {
|
||||
expect(byPath.get(deep)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
const caseVariants = (lowercase: string, count: number): string[] =>
|
||||
Array.from({ length: count }, (_, mask) =>
|
||||
[...lowercase]
|
||||
.map((character, index) =>
|
||||
(mask & (1 << index)) === 0 ? character : character.toUpperCase(),
|
||||
)
|
||||
.join(""),
|
||||
);
|
||||
|
||||
@@ -177,12 +177,12 @@ const englishUnicodeCaseCollisions = (
|
||||
if (path.length === 0 || path === ".") continue;
|
||||
let node = root;
|
||||
for (const part of path.split("/")) {
|
||||
const folded = englishCaseFold(part);
|
||||
const spellings = node.spellingsByFold.get(folded);
|
||||
if (spellings === undefined) node.spellingsByFold.set(folded, [part]);
|
||||
else if (!spellings.includes(part)) spellings.push(part);
|
||||
let child = node.bySpelling.get(part);
|
||||
if (child === undefined) {
|
||||
const folded = englishCaseFold(part);
|
||||
const spellings = node.spellingsByFold.get(folded);
|
||||
if (spellings === undefined) node.spellingsByFold.set(folded, [part]);
|
||||
else spellings.push(part);
|
||||
child = emptyCaseNode();
|
||||
node.bySpelling.set(part, child);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { Readable, Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
|
||||
import { getRawHeader, listPackage, statFile, uncache } from "@electron/asar";
|
||||
import { listPackage, statFile, uncache } from "@electron/asar";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
@@ -41,6 +41,11 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
#archiveSize: number | undefined;
|
||||
#headerSize: number | undefined;
|
||||
readonly #entries = new Map<string, AsarEntryState>();
|
||||
readonly #unpackedHandles = new Map<UnpackedFileHandle, string>();
|
||||
readonly #unpackedHandleClosePromises = new Map<
|
||||
UnpackedFileHandle,
|
||||
Promise<void>
|
||||
>();
|
||||
#snapshot: { readonly path: string; readonly sha256: string } | undefined;
|
||||
#snapshotRoot: string | undefined;
|
||||
|
||||
@@ -65,6 +70,7 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
try {
|
||||
const admitted = await admitAsarHeader(headerHandle);
|
||||
this.#archiveSize = admitted.archiveBytes;
|
||||
this.#headerSize = admitted.headerBytes;
|
||||
} finally {
|
||||
await headerHandle.close();
|
||||
}
|
||||
@@ -72,7 +78,6 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
paths = listPackage(snapshotPath, { isPack: false }).sort((left, right) =>
|
||||
left.localeCompare(right, "en"),
|
||||
);
|
||||
this.#headerSize = getRawHeader(snapshotPath).headerSize;
|
||||
const archiveMetadata = await lstat(snapshotPath);
|
||||
if (!archiveMetadata.isFile() || archiveMetadata.isSymbolicLink())
|
||||
throw new ArtifactReaderFailure(
|
||||
@@ -156,32 +161,8 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
);
|
||||
const { metadata } = state;
|
||||
const producedEntry = state.entry;
|
||||
if (producedEntry.unpacked) {
|
||||
const handle = await this.#openUnpackedEntry(producedEntry);
|
||||
try {
|
||||
const observed = await handle.stat();
|
||||
abortIfNeeded(signal);
|
||||
if (!observed.isFile())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${producedEntry.path}`,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw asarFailure(this.path, `read ${producedEntry.path}`, cause);
|
||||
}
|
||||
const source = handle.createReadStream({
|
||||
start: 0,
|
||||
autoClose: true,
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
undefined,
|
||||
producedEntry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
if (producedEntry.unpacked)
|
||||
return this.#openUnpackedStream(producedEntry, signal);
|
||||
const archiveSize = this.#archiveSize;
|
||||
const headerSize = this.#headerSize;
|
||||
const offset =
|
||||
@@ -315,22 +296,39 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
let cleanupFailure: ArtifactReaderFailure | undefined;
|
||||
for (const [handle, path] of this.#unpackedHandles) {
|
||||
try {
|
||||
await this.#closeUnpackedHandle(handle);
|
||||
} catch (cause: unknown) {
|
||||
cleanupFailure = ArtifactReaderFailure.withCleanup(
|
||||
cleanupFailure ?? cause,
|
||||
ArtifactReaderFailure.cleanupObservation(cause, path),
|
||||
);
|
||||
}
|
||||
}
|
||||
const root = this.#snapshotRoot;
|
||||
if (root !== undefined) {
|
||||
try {
|
||||
await this.removeSnapshot(root);
|
||||
if (this.#snapshotRoot === root) this.#snapshotRoot = undefined;
|
||||
} catch (cause: unknown) {
|
||||
throw ArtifactReaderFailure.withCleanup(cause, {
|
||||
reason: `Could not remove ASAR snapshot: ${root}`,
|
||||
resources: [root],
|
||||
});
|
||||
cleanupFailure = ArtifactReaderFailure.withCleanup(
|
||||
cleanupFailure ?? cause,
|
||||
{
|
||||
reason: `Could not remove ASAR snapshot: ${root}`,
|
||||
resources: [root],
|
||||
},
|
||||
);
|
||||
}
|
||||
this.#snapshotRoot = undefined;
|
||||
}
|
||||
if (this.#snapshot !== undefined) uncache(this.#snapshot.path);
|
||||
this.#snapshot = undefined;
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
if (root === undefined || this.#snapshotRoot === undefined) {
|
||||
if (this.#snapshot !== undefined) uncache(this.#snapshot.path);
|
||||
this.#snapshot = undefined;
|
||||
this.#resetArchiveState();
|
||||
this.#entries.clear();
|
||||
}
|
||||
if (cleanupFailure !== undefined) throw cleanupFailure;
|
||||
}
|
||||
|
||||
#snapshotPath(): string {
|
||||
@@ -346,8 +344,12 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
return [];
|
||||
}
|
||||
|
||||
async #openUnpackedEntry(entry: ArtifactEntry): Promise<UnpackedFileHandle> {
|
||||
async #openUnpackedStream(
|
||||
entry: ArtifactEntry,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Readable> {
|
||||
const unpackedRoot = `${this.path}.unpacked`;
|
||||
let handle: UnpackedFileHandle | undefined;
|
||||
try {
|
||||
const rootMetadata = await lstat(unpackedRoot);
|
||||
if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink())
|
||||
@@ -374,22 +376,18 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
"path",
|
||||
`ASAR unpacked entry is not a regular file: ${entry.path}`,
|
||||
);
|
||||
const handle = await this.openUnpackedFile(
|
||||
handle = await this.openUnpackedFile(
|
||||
canonical,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
const openedMetadata = await handle
|
||||
.stat()
|
||||
.catch(async (cause: unknown) => {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
});
|
||||
const openedHandle = handle;
|
||||
this.#unpackedHandles.set(openedHandle, canonical);
|
||||
const openedMetadata = await openedHandle.stat();
|
||||
if (
|
||||
!openedMetadata.isFile() ||
|
||||
openedMetadata.dev !== pathMetadata.dev ||
|
||||
openedMetadata.ino !== pathMetadata.ino
|
||||
) {
|
||||
await handle.close();
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`ASAR unpacked entry changed before read: ${entry.path}`,
|
||||
@@ -402,25 +400,54 @@ export class AsarArtifactReader implements ArtifactReader {
|
||||
},
|
||||
);
|
||||
}
|
||||
return handle;
|
||||
abortIfNeeded(signal);
|
||||
const source = openedHandle.createReadStream({
|
||||
start: 0,
|
||||
autoClose: false,
|
||||
});
|
||||
source.once("close", () => {
|
||||
void this.#closeUnpackedHandle(openedHandle).catch(() => undefined);
|
||||
});
|
||||
return readValidatedAsarEntry(
|
||||
source,
|
||||
undefined,
|
||||
entry.path,
|
||||
this.path,
|
||||
signal,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
throw asarFailure(this.path, `read ${entry.path}`, cause);
|
||||
let failure = asarUnpackedEntryFailure(this.path, entry, cause);
|
||||
if (handle !== undefined && this.#unpackedHandles.has(handle)) {
|
||||
try {
|
||||
await this.#closeUnpackedHandle(handle);
|
||||
} catch (cleanupCause: unknown) {
|
||||
failure = ArtifactReaderFailure.withCleanup(
|
||||
failure,
|
||||
ArtifactReaderFailure.cleanupObservation(
|
||||
cleanupCause,
|
||||
this.#unpackedHandles.get(handle) ?? entry.path,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
async #closeUnpackedHandle(handle: UnpackedFileHandle): Promise<void> {
|
||||
if (!this.#unpackedHandles.has(handle)) return;
|
||||
const pending = this.#unpackedHandleClosePromises.get(handle);
|
||||
if (pending !== undefined) return pending;
|
||||
const closing = Promise.resolve()
|
||||
.then(() => handle.close())
|
||||
.then(() => {
|
||||
this.#unpackedHandles.delete(handle);
|
||||
})
|
||||
.finally(() => this.#unpackedHandleClosePromises.delete(handle));
|
||||
this.#unpackedHandleClosePromises.set(handle, closing);
|
||||
return closing;
|
||||
}
|
||||
|
||||
#resetArchiveState(): void {
|
||||
this.#archiveSize = undefined;
|
||||
this.#headerSize = undefined;
|
||||
@@ -442,6 +469,27 @@ type OpenAsarUnpackedFile = (
|
||||
flags: number,
|
||||
) => Promise<UnpackedFileHandle>;
|
||||
|
||||
const asarUnpackedEntryFailure = (
|
||||
archivePath: string,
|
||||
entry: ArtifactEntry,
|
||||
cause: unknown,
|
||||
): ArtifactReaderFailure => {
|
||||
if (cause instanceof ArtifactReaderFailure) return cause;
|
||||
if (entry.unpacked && isMissingFile(cause))
|
||||
return new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
`ASAR unpacked entry bytes are unavailable: ${entry.path}`,
|
||||
{ cause },
|
||||
{
|
||||
logicalPath: entry.path,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: null,
|
||||
unpacked: true,
|
||||
},
|
||||
);
|
||||
return asarFailure(archivePath, `read ${entry.path}`, cause);
|
||||
};
|
||||
|
||||
const copyArtifactEntry = (entry: ArtifactEntry): ArtifactEntry => ({
|
||||
...entry,
|
||||
limitations: [...entry.limitations],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { open as openFile, stat } from "node:fs/promises";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import type { ArtifactCommand } from "../domain/artifactGraph.js";
|
||||
@@ -19,11 +19,21 @@ import {
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { streamChunkToBuffer } from "./StreamBytes.js";
|
||||
import {
|
||||
openRegularFile,
|
||||
sameRegularFileState,
|
||||
type StableRegularFileDescriptor,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
|
||||
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
|
||||
export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
readonly format = "file" as const;
|
||||
#command: ArtifactCommand | undefined;
|
||||
#source: StableRegularFileDescriptor | undefined;
|
||||
#pendingSource: Promise<StableRegularFileDescriptor> | undefined;
|
||||
readonly #ownsSource: boolean;
|
||||
#closed = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
|
||||
constructor(
|
||||
private readonly path: string,
|
||||
@@ -31,9 +41,15 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
|
||||
environment,
|
||||
),
|
||||
) {}
|
||||
source?: StableRegularFileDescriptor,
|
||||
) {
|
||||
this.#source = source;
|
||||
this.#ownsSource = source === undefined;
|
||||
}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
const source = await this.#ensureSource();
|
||||
await this.#verifySource(source);
|
||||
const captured = await this.runner.run(
|
||||
"lipo",
|
||||
["-detailed_info", this.path],
|
||||
@@ -53,9 +69,11 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
exit_code: captured.value.exitCode,
|
||||
effects: ["read"],
|
||||
};
|
||||
const fileSize = (await stat(this.path)).size;
|
||||
await this.#verifySource(source);
|
||||
const fileSize = source.initial.size;
|
||||
const architectures = parseLipoArchitectures(captured.value.stdout);
|
||||
const structural = await readStructuralSlices(this.path, fileSize);
|
||||
const structural = await readStructuralSlices(source.handle, fileSize);
|
||||
await this.#verifySource(source);
|
||||
if (structural.status === "malformed")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
@@ -168,22 +186,28 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
"integrity",
|
||||
"Invalid Mach-O slice byte range",
|
||||
);
|
||||
const fileSize = (await stat(this.path)).size;
|
||||
if (!Number.isSafeInteger(offset + size) || offset + size > fileSize)
|
||||
const source = await this.#ensureSource();
|
||||
await this.#verifySource(source);
|
||||
if (
|
||||
!Number.isSafeInteger(offset + size) ||
|
||||
offset + size > source.initial.size
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Mach-O slice range is outside the artifact: ${entry.path}`,
|
||||
);
|
||||
const source = createReadStream(this.path, {
|
||||
const sourceStream = source.handle.createReadStream({
|
||||
start: offset,
|
||||
end: offset + size - 1,
|
||||
autoClose: false,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
const verifySource = () => this.#verifySource(source);
|
||||
return Readable.from(
|
||||
(async function* () {
|
||||
let observedBytes = 0;
|
||||
try {
|
||||
for await (const raw of source) {
|
||||
for await (const raw of sourceStream) {
|
||||
const chunk = streamChunkToBuffer(raw);
|
||||
observedBytes += chunk.byteLength;
|
||||
if (observedBytes > size)
|
||||
@@ -212,6 +236,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
"integrity",
|
||||
`Mach-O slice size disagrees with lipo metadata: ${entry.path}`,
|
||||
);
|
||||
await verifySource();
|
||||
})(),
|
||||
);
|
||||
}
|
||||
@@ -220,28 +245,80 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
return this.#command === undefined ? [] : [structuredClone(this.#command)];
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
async close(): Promise<void> {
|
||||
this.#closed = true;
|
||||
this.#closePromise ??= this.#closeSource().catch((cause: unknown) => {
|
||||
this.#closePromise = undefined;
|
||||
throw cause;
|
||||
});
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
async #ensureSource(): Promise<StableRegularFileDescriptor> {
|
||||
if (this.#closed)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Universal Mach-O reader is closed",
|
||||
);
|
||||
if (this.#source !== undefined) return this.#source;
|
||||
this.#pendingSource ??= this.#acquireSource();
|
||||
const source = await this.#pendingSource;
|
||||
if (this.#closed)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Universal Mach-O reader closed during source acquisition",
|
||||
);
|
||||
return source;
|
||||
}
|
||||
|
||||
async #acquireSource(): Promise<StableRegularFileDescriptor> {
|
||||
const handle = await openRegularFile(this.path, { symlinks: "reject" });
|
||||
try {
|
||||
const initial = await handle.stat();
|
||||
const source = { handle, initial };
|
||||
this.#source = source;
|
||||
return source;
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
async #closeSource(): Promise<void> {
|
||||
await this.#pendingSource?.catch(() => undefined);
|
||||
if (!this.#ownsSource || this.#source === undefined) return;
|
||||
const source = this.#source;
|
||||
await source.handle.close();
|
||||
this.#source = undefined;
|
||||
}
|
||||
|
||||
async #verifySource(source: StableRegularFileDescriptor): Promise<void> {
|
||||
const [opened, currentPath] = await Promise.all([
|
||||
source.handle.stat(),
|
||||
lstat(this.path),
|
||||
]);
|
||||
if (
|
||||
!sameRegularFileState(source.initial, opened) ||
|
||||
!sameRegularFileState(source.initial, currentPath)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Universal Mach-O source changed during inventory: ${this.path}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Compare lipo's independent ranges with structurally parsed slice identity. */
|
||||
const readStructuralSlices = async (
|
||||
path: string,
|
||||
file: FileHandle,
|
||||
size: number,
|
||||
): Promise<Awaited<ReturnType<typeof readMachoImage>>> => {
|
||||
const file = await openFile(path, "r");
|
||||
try {
|
||||
const readAt: ReadAt = async (offset, length) => {
|
||||
const bytes = Buffer.alloc(length);
|
||||
const { bytesRead } = await file.read(bytes, 0, length, offset);
|
||||
return bytes.subarray(0, bytesRead);
|
||||
};
|
||||
const facts = await readMachoImage(readAt, size);
|
||||
return facts;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
const readAt: ReadAt = async (offset, length) => {
|
||||
const bytes = Buffer.alloc(length);
|
||||
const { bytesRead } = await file.read(bytes, 0, length, offset);
|
||||
return bytes.subarray(0, bytesRead);
|
||||
};
|
||||
return readMachoImage(readAt, size);
|
||||
};
|
||||
|
||||
const lipoMatchesSlice = (
|
||||
|
||||
+129
-42
@@ -1,12 +1,11 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
readdir,
|
||||
realpath,
|
||||
rm,
|
||||
rmdir,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
||||
@@ -19,6 +18,19 @@ import {
|
||||
normalizeArtifactPath,
|
||||
} from "./ArtifactPaths.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import { removeOwnedTree } from "./SafeOutputTreeCleanup.js";
|
||||
import {
|
||||
assertHandleIdentity,
|
||||
assertFilePathIdentity,
|
||||
assertPathIdentity,
|
||||
isAbsent,
|
||||
pathHasIdentity,
|
||||
readDirectoryIdentity,
|
||||
readFileIdentity,
|
||||
replacedDirectory,
|
||||
type DirectoryIdentity,
|
||||
type FileIdentity,
|
||||
} from "./SafeOutputTreeIdentity.js";
|
||||
|
||||
/** One file durably written to an operation-owned output tree. */
|
||||
export interface SafeOutputFile {
|
||||
@@ -36,10 +48,18 @@ export type SafeOutputCleanup =
|
||||
readonly residualPaths: readonly [string, ...string[]];
|
||||
};
|
||||
|
||||
/** Symlink-resistant materialization in an exclusively owned, initially absent tree. */
|
||||
/**
|
||||
* Materialize files in a tree created by this operation.
|
||||
*
|
||||
* Path identities are revalidated around operations, but Node has no portable
|
||||
* descriptor-relative traversal; a syscall-boundary pathname race remains.
|
||||
*/
|
||||
export class SafeOutputTree {
|
||||
readonly #registry = new ArtifactPathRegistry();
|
||||
readonly #outputRoot: string;
|
||||
readonly #rootIdentity: DirectoryIdentity;
|
||||
readonly #nestedDirectories = new Map<string, DirectoryIdentity>();
|
||||
readonly #ownedFiles = new Map<string, FileIdentity>();
|
||||
#published = false;
|
||||
#cleanup: SafeOutputCleanup = {
|
||||
status: "not-required",
|
||||
@@ -47,9 +67,11 @@ export class SafeOutputTree {
|
||||
|
||||
private constructor(
|
||||
outputRoot: string,
|
||||
rootIdentity: DirectoryIdentity,
|
||||
private readonly platform: NodeJS.Platform,
|
||||
) {
|
||||
this.#outputRoot = outputRoot;
|
||||
this.#rootIdentity = rootIdentity;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,29 +113,45 @@ export class SafeOutputTree {
|
||||
);
|
||||
throw cause;
|
||||
});
|
||||
let rootIdentity: DirectoryIdentity | undefined;
|
||||
try {
|
||||
rootIdentity = await readDirectoryIdentity(canonicalOutput);
|
||||
if (platform !== "win32") {
|
||||
const stagingHandle = await open(
|
||||
canonicalOutput,
|
||||
constants.O_RDONLY | constants.O_DIRECTORY,
|
||||
);
|
||||
try {
|
||||
await assertHandleIdentity(
|
||||
stagingHandle,
|
||||
rootIdentity,
|
||||
canonicalOutput,
|
||||
);
|
||||
await stagingHandle.chmod(0o700);
|
||||
} finally {
|
||||
await stagingHandle.close();
|
||||
}
|
||||
}
|
||||
return new SafeOutputTree(canonicalOutput, platform);
|
||||
await assertPathIdentity(canonicalOutput, rootIdentity);
|
||||
return new SafeOutputTree(canonicalOutput, rootIdentity, platform);
|
||||
} catch (cause: unknown) {
|
||||
let removalFailure: unknown;
|
||||
let ownedRootAtPath = false;
|
||||
try {
|
||||
await rm(canonicalOutput, { recursive: true, force: true });
|
||||
ownedRootAtPath =
|
||||
rootIdentity !== undefined &&
|
||||
(await pathHasIdentity(canonicalOutput, rootIdentity));
|
||||
if (ownedRootAtPath) await rmdir(canonicalOutput);
|
||||
else
|
||||
removalFailure = new Error(
|
||||
"Extraction output root identity changed during setup",
|
||||
);
|
||||
} catch (cleanupCause: unknown) {
|
||||
removalFailure = cleanupCause;
|
||||
}
|
||||
let absent = false;
|
||||
try {
|
||||
absent = await isAbsent(canonicalOutput);
|
||||
absent = ownedRootAtPath && (await isAbsent(canonicalOutput));
|
||||
} catch (cleanupCause: unknown) {
|
||||
removalFailure ??= cleanupCause;
|
||||
}
|
||||
@@ -122,7 +160,7 @@ export class SafeOutputTree {
|
||||
reason:
|
||||
removalFailure instanceof Error
|
||||
? removalFailure.message
|
||||
: "Extraction output root remains after setup failure",
|
||||
: "Extraction output root ownership could not be verified after setup failure",
|
||||
resources: [canonicalOutput],
|
||||
});
|
||||
throw cause;
|
||||
@@ -153,7 +191,11 @@ export class SafeOutputTree {
|
||||
);
|
||||
const path = normalizeArtifactPath(relativePath);
|
||||
this.#registry.add(path, "file");
|
||||
const destination = await this.#prepareParent(path);
|
||||
const lineage = await this.#prepareParent(path);
|
||||
const parent = lineage.at(-1);
|
||||
if (parent === undefined) throw replacedDirectory(this.#outputRoot);
|
||||
const fileName = path.slice(path.lastIndexOf("/") + 1);
|
||||
const destination = join(parent.path, fileName);
|
||||
const handle = await open(
|
||||
destination,
|
||||
constants.O_CREAT |
|
||||
@@ -162,20 +204,24 @@ export class SafeOutputTree {
|
||||
constants.O_NOFOLLOW,
|
||||
0o600,
|
||||
).catch(async (cause: unknown) => {
|
||||
await throwIfDestinationCaseCollision(
|
||||
dirname(destination),
|
||||
path,
|
||||
cause,
|
||||
);
|
||||
await throwIfDestinationCaseCollision(parent.path, path, cause);
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Could not exclusively create extraction path: ${path}`,
|
||||
{ cause },
|
||||
);
|
||||
});
|
||||
const fileIdentity = await readFileIdentity(handle, destination).catch(
|
||||
async (cause: unknown) => {
|
||||
await handle.close().catch(() => undefined);
|
||||
throw cause;
|
||||
},
|
||||
);
|
||||
this.#ownedFiles.set(destination, fileIdentity);
|
||||
const hash = createHash("sha256");
|
||||
let bytes = 0;
|
||||
try {
|
||||
await this.#assertLineage(lineage);
|
||||
for await (const raw of source) {
|
||||
abortIfNeeded(signal);
|
||||
const chunk = streamChunkToBuffer(raw);
|
||||
@@ -199,9 +245,13 @@ export class SafeOutputTree {
|
||||
"integrity",
|
||||
`Extracted content disagrees with inventory: ${path}`,
|
||||
);
|
||||
await this.#assertLineage(lineage);
|
||||
await assertFilePathIdentity(destination, fileIdentity);
|
||||
await handle.sync();
|
||||
await handle.close();
|
||||
const readback = await hashFile(destination, bytes, signal);
|
||||
await this.#assertLineage(lineage);
|
||||
await assertFilePathIdentity(destination, fileIdentity);
|
||||
if (readback.sha256 !== sha256 || readback.bytes !== bytes)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
@@ -226,6 +276,7 @@ export class SafeOutputTree {
|
||||
/** Sync the owned output tree and prevent further writes through this instance. */
|
||||
async commit(): Promise<void> {
|
||||
this.#assertWritable();
|
||||
await this.#assertOwnedDirectories();
|
||||
// Windows has no directory fsync; file contents are already synced in write().
|
||||
if (this.platform === "win32") {
|
||||
this.#published = true;
|
||||
@@ -241,6 +292,7 @@ export class SafeOutputTree {
|
||||
this.#outputRoot,
|
||||
constants.O_RDONLY | constants.O_DIRECTORY,
|
||||
);
|
||||
await assertHandleIdentity(output, this.#rootIdentity, this.#outputRoot);
|
||||
await output.sync();
|
||||
await parent.sync();
|
||||
this.#published = true;
|
||||
@@ -257,14 +309,26 @@ export class SafeOutputTree {
|
||||
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
async rollback(): Promise<SafeOutputCleanup> {
|
||||
if (this.#published) return structuredClone(this.#cleanup);
|
||||
if (this.#published || this.#cleanup.status === "complete")
|
||||
return structuredClone(this.#cleanup);
|
||||
this.#cleanup = {
|
||||
status: "incomplete",
|
||||
residualPaths: [basename(this.#outputRoot)],
|
||||
};
|
||||
let removalFailure: unknown;
|
||||
try {
|
||||
await rm(this.#outputRoot, { recursive: true, force: true });
|
||||
await this.#assertOwnedDirectories();
|
||||
await removeOwnedTree({
|
||||
outputRoot: this.#outputRoot,
|
||||
rootIdentity: this.#rootIdentity,
|
||||
directories: this.#nestedDirectories,
|
||||
files: this.#ownedFiles,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
removalFailure = cause;
|
||||
}
|
||||
const absent = await isAbsent(this.#outputRoot);
|
||||
const absent =
|
||||
removalFailure === undefined && (await isAbsent(this.#outputRoot));
|
||||
this.#cleanup = absent
|
||||
? { status: "complete", residualPaths: [] }
|
||||
: {
|
||||
@@ -289,36 +353,61 @@ export class SafeOutputTree {
|
||||
return structuredClone(this.#cleanup);
|
||||
}
|
||||
|
||||
async #prepareParent(relativePath: string): Promise<string> {
|
||||
async #prepareParent(
|
||||
relativePath: string,
|
||||
): Promise<readonly DirectoryLineageEntry[]> {
|
||||
const parts = relativePath.split("/");
|
||||
const fileName = parts.pop();
|
||||
if (fileName === undefined)
|
||||
if (parts.pop() === undefined)
|
||||
throw new ArtifactReaderFailure("path", "Invalid extraction path");
|
||||
let current = this.#outputRoot;
|
||||
let logicalParent = "";
|
||||
const lineage: DirectoryLineageEntry[] = [
|
||||
{ path: this.#outputRoot, identity: this.#rootIdentity },
|
||||
];
|
||||
if (parts.length === 0)
|
||||
await assertPathIdentity(this.#outputRoot, this.#rootIdentity);
|
||||
for (const part of parts) {
|
||||
const parentDirectory = current;
|
||||
const parent = lineage.at(-1);
|
||||
if (parent === undefined) throw replacedDirectory(this.#outputRoot);
|
||||
const logicalPath =
|
||||
logicalParent.length === 0 ? part : `${logicalParent}/${part}`;
|
||||
current = join(current, part);
|
||||
await assertPathIdentity(parent.path, parent.identity);
|
||||
let created = true;
|
||||
await mkdir(current, { mode: 0o700 }).catch((cause: unknown) => {
|
||||
if (!isAlreadyExists(cause)) throw cause;
|
||||
created = false;
|
||||
});
|
||||
if (!created)
|
||||
await throwIfDestinationCaseCollision(parentDirectory, logicalPath);
|
||||
const metadata = await lstat(current);
|
||||
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
||||
await throwIfDestinationCaseCollision(parentDirectory, logicalPath);
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Unsafe extraction parent: ${relativePath}`,
|
||||
);
|
||||
if (!created) {
|
||||
await throwIfDestinationCaseCollision(parent.path, logicalPath);
|
||||
const identity = this.#nestedDirectories.get(current);
|
||||
if (identity === undefined) throw replacedDirectory(current);
|
||||
await assertPathIdentity(current, identity);
|
||||
} else {
|
||||
const identity = await readDirectoryIdentity(current);
|
||||
this.#nestedDirectories.set(current, identity);
|
||||
}
|
||||
await assertPathIdentity(parent.path, parent.identity);
|
||||
const identity = this.#nestedDirectories.get(current);
|
||||
if (identity === undefined) throw replacedDirectory(current);
|
||||
await assertPathIdentity(current, identity);
|
||||
lineage.push({ path: current, identity });
|
||||
logicalParent = logicalPath;
|
||||
}
|
||||
return join(current, fileName);
|
||||
return lineage;
|
||||
}
|
||||
|
||||
async #assertLineage(
|
||||
lineage: readonly DirectoryLineageEntry[],
|
||||
): Promise<void> {
|
||||
for (const { path, identity } of lineage)
|
||||
await assertPathIdentity(path, identity);
|
||||
}
|
||||
|
||||
async #assertOwnedDirectories(): Promise<void> {
|
||||
await assertPathIdentity(this.#outputRoot, this.#rootIdentity);
|
||||
for (const [path, identity] of this.#nestedDirectories)
|
||||
await assertPathIdentity(path, identity);
|
||||
}
|
||||
|
||||
#assertWritable(): void {
|
||||
@@ -327,9 +416,19 @@ export class SafeOutputTree {
|
||||
"integrity",
|
||||
"Extraction tree is already committed",
|
||||
);
|
||||
if (this.#cleanup.status !== "not-required")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Extraction tree cleanup has already started",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
type DirectoryLineageEntry = {
|
||||
readonly path: string;
|
||||
readonly identity: DirectoryIdentity;
|
||||
};
|
||||
|
||||
const hashFile = async (
|
||||
path: string,
|
||||
maximum: number,
|
||||
@@ -376,18 +475,6 @@ const writeAll = async (
|
||||
}
|
||||
};
|
||||
|
||||
const isAbsent = async (path: string): Promise<boolean> =>
|
||||
lstat(path).then(
|
||||
() => false,
|
||||
(cause: unknown) => {
|
||||
if (isNotFound(cause)) return true;
|
||||
throw cause;
|
||||
},
|
||||
);
|
||||
|
||||
const isNotFound = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { readdir, rmdir, unlink } from "node:fs/promises";
|
||||
import { dirname, sep } from "node:path";
|
||||
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import {
|
||||
assertFilePathIdentity,
|
||||
assertPathIdentity,
|
||||
replacedDirectory,
|
||||
type DirectoryIdentity,
|
||||
type FileIdentity,
|
||||
} from "./SafeOutputTreeIdentity.js";
|
||||
|
||||
/** Remove only tracked files and empty directories, preserving successful progress. */
|
||||
export const removeOwnedTree = async (input: {
|
||||
readonly outputRoot: string;
|
||||
readonly rootIdentity: DirectoryIdentity;
|
||||
readonly directories: Map<string, DirectoryIdentity>;
|
||||
readonly files: Map<string, FileIdentity>;
|
||||
}): Promise<void> => {
|
||||
const { outputRoot, rootIdentity, directories, files } = input;
|
||||
const filesByDirectory = new Map<string, [string, FileIdentity][]>();
|
||||
for (const entry of files) {
|
||||
const directory = dirname(entry[0]);
|
||||
const group = filesByDirectory.get(directory) ?? [];
|
||||
group.push(entry);
|
||||
filesByDirectory.set(directory, group);
|
||||
}
|
||||
const postorder = [...directories].sort(
|
||||
([left], [right]) =>
|
||||
right.slice(outputRoot.length).split(sep).length -
|
||||
left.slice(outputRoot.length).split(sep).length,
|
||||
);
|
||||
for (const [path, identity] of postorder) {
|
||||
await removeFiles(path, identity, filesByDirectory.get(path) ?? [], files);
|
||||
const parentPath = dirname(path);
|
||||
const parentIdentity =
|
||||
parentPath === outputRoot ? rootIdentity : directories.get(parentPath);
|
||||
if (parentIdentity === undefined) throw replacedDirectory(parentPath);
|
||||
await assertPathIdentity(parentPath, parentIdentity);
|
||||
await assertPathIdentity(path, identity);
|
||||
await requireEmpty(path);
|
||||
await rmdir(path);
|
||||
directories.delete(path);
|
||||
}
|
||||
await removeFiles(
|
||||
outputRoot,
|
||||
rootIdentity,
|
||||
filesByDirectory.get(outputRoot) ?? [],
|
||||
files,
|
||||
);
|
||||
await assertPathIdentity(outputRoot, rootIdentity);
|
||||
await requireEmpty(outputRoot);
|
||||
await rmdir(outputRoot);
|
||||
};
|
||||
|
||||
const removeFiles = async (
|
||||
directory: string,
|
||||
identity: DirectoryIdentity,
|
||||
filesInDirectory: readonly (readonly [string, FileIdentity])[],
|
||||
retainedFiles: Map<string, FileIdentity>,
|
||||
): Promise<void> => {
|
||||
for (const [path, fileIdentity] of filesInDirectory) {
|
||||
await assertPathIdentity(directory, identity);
|
||||
await assertFilePathIdentity(path, fileIdentity);
|
||||
await unlink(path);
|
||||
retainedFiles.delete(path);
|
||||
}
|
||||
};
|
||||
|
||||
const requireEmpty = async (directory: string): Promise<void> => {
|
||||
if ((await readdir(directory)).length > 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Unowned entries remain in extraction directory: ${directory}`,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { BigIntStats } from "node:fs";
|
||||
import { lstat } from "node:fs/promises";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
|
||||
export type DirectoryIdentity = Pick<BigIntStats, "dev" | "ino">;
|
||||
export type FileIdentity = DirectoryIdentity;
|
||||
|
||||
export const readDirectoryIdentity = async (
|
||||
path: string,
|
||||
): Promise<DirectoryIdentity> => {
|
||||
const metadata = await lstat(path, { bigint: true });
|
||||
if (!metadata.isDirectory()) throw replacedDirectory(path);
|
||||
return { dev: metadata.dev, ino: metadata.ino };
|
||||
};
|
||||
|
||||
export const assertPathIdentity = async (
|
||||
path: string,
|
||||
expected: DirectoryIdentity,
|
||||
): Promise<void> => {
|
||||
const metadata = await lstat(path, { bigint: true });
|
||||
if (
|
||||
!metadata.isDirectory() ||
|
||||
metadata.dev !== expected.dev ||
|
||||
metadata.ino !== expected.ino
|
||||
)
|
||||
throw replacedDirectory(path);
|
||||
};
|
||||
|
||||
export const assertHandleIdentity = async (
|
||||
handle: FileHandle,
|
||||
expected: DirectoryIdentity,
|
||||
path: string,
|
||||
): Promise<void> => {
|
||||
const metadata = await handle.stat({ bigint: true });
|
||||
if (
|
||||
!metadata.isDirectory() ||
|
||||
metadata.dev !== expected.dev ||
|
||||
metadata.ino !== expected.ino
|
||||
)
|
||||
throw replacedDirectory(path);
|
||||
};
|
||||
|
||||
export const readFileIdentity = async (
|
||||
handle: FileHandle,
|
||||
path: string,
|
||||
): Promise<FileIdentity> => {
|
||||
const metadata = await handle.stat({ bigint: true });
|
||||
if (!metadata.isFile())
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Extraction file identity changed: ${path}`,
|
||||
);
|
||||
return { dev: metadata.dev, ino: metadata.ino };
|
||||
};
|
||||
|
||||
export const assertFilePathIdentity = async (
|
||||
path: string,
|
||||
expected: FileIdentity,
|
||||
): Promise<void> => {
|
||||
const metadata = await lstat(path, { bigint: true });
|
||||
if (
|
||||
!metadata.isFile() ||
|
||||
metadata.dev !== expected.dev ||
|
||||
metadata.ino !== expected.ino
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Extraction file identity changed: ${path}`,
|
||||
);
|
||||
};
|
||||
|
||||
export const pathHasIdentity = async (
|
||||
path: string,
|
||||
expected: DirectoryIdentity,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
await assertPathIdentity(path, expected);
|
||||
return true;
|
||||
} catch (cause: unknown) {
|
||||
if (isNotFound(cause) || cause instanceof ArtifactReaderFailure)
|
||||
return false;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
export const isAbsent = async (path: string): Promise<boolean> =>
|
||||
lstat(path).then(
|
||||
() => false,
|
||||
(cause: unknown) => {
|
||||
if (isNotFound(cause)) return true;
|
||||
throw cause;
|
||||
},
|
||||
);
|
||||
|
||||
export const replacedDirectory = (path: string): ArtifactReaderFailure =>
|
||||
new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Extraction directory identity changed: ${path}`,
|
||||
);
|
||||
|
||||
const isNotFound = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
@@ -90,20 +90,14 @@ export const materializeArtifactInventory = async (
|
||||
const selectedIds = new Set(
|
||||
activeOccurrences.map(({ occurrence_id: id }) => id),
|
||||
);
|
||||
const occurrences = new Map<string, ArtifactOccurrence>();
|
||||
const neededNodes = new Set<string>();
|
||||
collectOccurrences(
|
||||
snapshot.occurrences,
|
||||
selectedIds,
|
||||
occurrences,
|
||||
neededNodes,
|
||||
const neededNodes = new Set(
|
||||
activeOccurrences.map(({ artifact_id: id }) => id),
|
||||
);
|
||||
const nodes = new Map<string, ArtifactNode>();
|
||||
collectNodes(snapshot.nodes, neededNodes, nodes);
|
||||
const inventory: LoadedInventory = {
|
||||
for (const node of snapshot.nodes)
|
||||
if (neededNodes.has(node.artifact_id)) nodes.set(node.artifact_id, node);
|
||||
const inventory: ExtractionInventory = {
|
||||
manifest: snapshot.manifest,
|
||||
occurrences,
|
||||
nodes,
|
||||
integrityContradictions: snapshot.integrity_contradictions.filter(
|
||||
({ occurrence_id: id }) => selectedIds.has(id),
|
||||
),
|
||||
@@ -144,7 +138,7 @@ export const materializeArtifactInventory = async (
|
||||
"format",
|
||||
`Selected occurrence is not an extractable regular child file: ${occurrence.logical_path} (${occurrence.occurrence_id})`,
|
||||
);
|
||||
const node = inventory.nodes.get(occurrence.artifact_id);
|
||||
const node = nodes.get(occurrence.artifact_id);
|
||||
if (node === undefined)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
@@ -183,7 +177,7 @@ const materializeSelection = async ({
|
||||
}: {
|
||||
readonly input: ArtifactExtractionInput;
|
||||
readonly sourcePath: string;
|
||||
readonly inventory: LoadedInventory;
|
||||
readonly inventory: ExtractionInventory;
|
||||
readonly selected: readonly SelectedOccurrence[];
|
||||
readonly signal: AbortSignal | undefined;
|
||||
}): Promise<ArtifactExtractionResult> => {
|
||||
@@ -298,7 +292,7 @@ const materializeSelection = async ({
|
||||
|
||||
const createExtractionResult = (
|
||||
input: ArtifactExtractionInput,
|
||||
inventory: LoadedInventory,
|
||||
inventory: ExtractionInventory,
|
||||
selected: readonly SelectedOccurrence[],
|
||||
extracted: readonly ExtractedOccurrence[],
|
||||
): ArtifactExtractionResult => {
|
||||
@@ -333,35 +327,11 @@ const createExtractionResult = (
|
||||
});
|
||||
};
|
||||
|
||||
interface LoadedInventory {
|
||||
interface ExtractionInventory {
|
||||
readonly manifest: ArtifactGraphManifest;
|
||||
readonly occurrences: ReadonlyMap<string, ArtifactOccurrence>;
|
||||
readonly nodes: ReadonlyMap<string, ArtifactNode>;
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
}
|
||||
|
||||
const collectOccurrences = (
|
||||
items: readonly ArtifactOccurrence[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactOccurrence>,
|
||||
neededNodes: Set<string>,
|
||||
): void => {
|
||||
for (const item of items) {
|
||||
if (!selected.has(item.occurrence_id)) continue;
|
||||
output.set(item.occurrence_id, item);
|
||||
if (item.artifact_id !== null) neededNodes.add(item.artifact_id);
|
||||
}
|
||||
};
|
||||
|
||||
const collectNodes = (
|
||||
items: readonly ArtifactNode[],
|
||||
selected: ReadonlySet<string>,
|
||||
output: Map<string, ArtifactNode>,
|
||||
): void => {
|
||||
for (const item of items)
|
||||
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
|
||||
};
|
||||
|
||||
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
|
||||
|
||||
const isZipFormat = (
|
||||
|
||||
@@ -295,23 +295,53 @@ export const createArtifactEdges = (
|
||||
return edges;
|
||||
};
|
||||
|
||||
export const nearestParent = (
|
||||
path: string,
|
||||
occurrences: ReadonlyMap<string, MutableOccurrence>,
|
||||
interface ArtifactParentIndex {
|
||||
readonly children: Map<string, ArtifactParentIndex>;
|
||||
occurrence?: MutableOccurrence;
|
||||
}
|
||||
|
||||
/** Resolve strict observed ancestors without rebuilding every path prefix. */
|
||||
export const resolveOccurrenceParents = (
|
||||
occurrences: readonly MutableOccurrence[],
|
||||
byPath: ReadonlyMap<string, MutableOccurrence>,
|
||||
expandedContainerIds: ReadonlySet<string>,
|
||||
): MutableOccurrence | undefined => {
|
||||
const parts = path.split("/");
|
||||
while (parts.length > 1) {
|
||||
parts.pop();
|
||||
const candidate = occurrences.get(parts.join("/"));
|
||||
): void => {
|
||||
const root: ArtifactParentIndex = { children: new Map() };
|
||||
for (const occurrence of byPath.values()) {
|
||||
if (
|
||||
candidate !== undefined &&
|
||||
(candidate.entry_kind === "directory" ||
|
||||
expandedContainerIds.has(candidate.occurrence_id))
|
||||
occurrence.entry_kind !== "directory" &&
|
||||
!expandedContainerIds.has(occurrence.occurrence_id)
|
||||
)
|
||||
return candidate;
|
||||
continue;
|
||||
let branch = root;
|
||||
for (const segment of occurrence.logical_path.split("/")) {
|
||||
let child = branch.children.get(segment);
|
||||
if (child === undefined) {
|
||||
child = { children: new Map() };
|
||||
branch.children.set(segment, child);
|
||||
}
|
||||
branch = child;
|
||||
}
|
||||
branch.occurrence = occurrence;
|
||||
}
|
||||
for (const occurrence of occurrences) {
|
||||
const path = occurrence.logical_path;
|
||||
let branch = root;
|
||||
let parent: MutableOccurrence | undefined;
|
||||
// Walk parent segments only. Stop scanning the path once no observed
|
||||
// directory or expanded container can be an ancestor.
|
||||
for (let start = 0; ;) {
|
||||
const slash = path.indexOf("/", start);
|
||||
if (slash < 0) break;
|
||||
const segment = path.slice(start, slash);
|
||||
const child = branch.children.get(segment);
|
||||
if (child === undefined) break;
|
||||
branch = child;
|
||||
parent = branch.occurrence ?? parent;
|
||||
start = slash + 1;
|
||||
}
|
||||
occurrence.parent_occurrence_id = parent?.occurrence_id ?? null;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -24,7 +24,7 @@ interface RootClassification {
|
||||
}
|
||||
|
||||
type RootInventoryClassification = RootClassification & {
|
||||
readonly zipSource: StableRegularFileDescriptor | undefined;
|
||||
readonly rootSource: StableRegularFileDescriptor | undefined;
|
||||
};
|
||||
|
||||
/** Classify and hash one file root through the same stable open descriptor. */
|
||||
@@ -43,7 +43,7 @@ export const classifyAndHashRoot = async (
|
||||
try {
|
||||
return { format: result.format, digest: result.digest };
|
||||
} finally {
|
||||
await result.zipSource?.handle.close();
|
||||
await result.rootSource?.handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -55,7 +55,7 @@ export const classifyAndHashRootForInventory = async (
|
||||
signal?: AbortSignal,
|
||||
): Promise<RootInventoryClassification> => {
|
||||
if (directory)
|
||||
return { format: "directory", digest: null, zipSource: undefined };
|
||||
return { format: "directory", digest: null, rootSource: undefined };
|
||||
const handle = await openRootFile(path, signal);
|
||||
let transferHandle = false;
|
||||
try {
|
||||
@@ -72,12 +72,12 @@ export const classifyAndHashRootForInventory = async (
|
||||
initial,
|
||||
signal,
|
||||
);
|
||||
const zipSource = isZipFormat(format);
|
||||
if (zipSource) transferHandle = true;
|
||||
const retainSource = isZipFormat(format) || format === "mach-o-universal";
|
||||
if (retainSource) transferHandle = true;
|
||||
return {
|
||||
format,
|
||||
digest,
|
||||
zipSource: zipSource ? { handle, initial } : undefined,
|
||||
rootSource: retainSource ? { handle, initial } : undefined,
|
||||
};
|
||||
} finally {
|
||||
if (!transferHandle) await handle.close();
|
||||
|
||||
@@ -13,7 +13,7 @@ export const createReader = async (
|
||||
format: ArtifactOccurrence["artifact_format"],
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
signal?: AbortSignal,
|
||||
zipSource?: StableRegularFileDescriptor,
|
||||
rootSource?: StableRegularFileDescriptor,
|
||||
): Promise<ArtifactReader | undefined> => {
|
||||
switch (format) {
|
||||
case "directory":
|
||||
@@ -23,12 +23,12 @@ export const createReader = async (
|
||||
case "apk":
|
||||
case "msix":
|
||||
case "appx":
|
||||
return new ZipArtifactReader(path, format, undefined, zipSource);
|
||||
return new ZipArtifactReader(path, format, undefined, rootSource);
|
||||
case "asar":
|
||||
return new AsarArtifactReader(path);
|
||||
case "mach-o-universal":
|
||||
return process.platform === "darwin"
|
||||
? new MachOSliceArtifactReader(path, environment)
|
||||
? new MachOSliceArtifactReader(path, environment, undefined, rootSource)
|
||||
: undefined;
|
||||
case "dmg":
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
|
||||
@@ -58,7 +58,7 @@ export const scanCanonicalArtifactInventory = async (
|
||||
const {
|
||||
format: rootFormat,
|
||||
digest: rootDigest,
|
||||
zipSource,
|
||||
rootSource,
|
||||
} = await classifyAndHashRootForInventory(
|
||||
path,
|
||||
metadata.isDirectory(),
|
||||
@@ -73,7 +73,7 @@ export const scanCanonicalArtifactInventory = async (
|
||||
rootFormat,
|
||||
options.environment ?? {},
|
||||
options.signal,
|
||||
zipSource,
|
||||
rootSource,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
readerCreationFailure = { cause };
|
||||
@@ -102,7 +102,7 @@ export const scanCanonicalArtifactInventory = async (
|
||||
metadata,
|
||||
rootFormat,
|
||||
rootDigest,
|
||||
zipSource,
|
||||
rootSource,
|
||||
reader,
|
||||
signal: options.signal,
|
||||
nodes,
|
||||
@@ -133,13 +133,13 @@ export const scanCanonicalArtifactInventory = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
if (zipSource !== undefined) {
|
||||
if (rootSource !== undefined) {
|
||||
try {
|
||||
await zipSource.handle.close();
|
||||
await rootSource.handle.close();
|
||||
} catch (cleanupCause: unknown) {
|
||||
const cleanup = ArtifactReaderFailure.cleanupObservation(
|
||||
cleanupCause,
|
||||
`root ZIP descriptor for ${path}`,
|
||||
`root artifact descriptor for ${path}`,
|
||||
);
|
||||
cleanupFailure = ArtifactReaderFailure.withCleanup(
|
||||
cleanupFailure ??
|
||||
@@ -161,7 +161,7 @@ interface SnapshotBuildInput {
|
||||
readonly metadata: Stats;
|
||||
readonly rootFormat: ArtifactOccurrence["artifact_format"];
|
||||
readonly rootDigest: HashResult | null;
|
||||
readonly zipSource: StableRegularFileDescriptor | undefined;
|
||||
readonly rootSource: StableRegularFileDescriptor | undefined;
|
||||
readonly reader: ArtifactReader | undefined;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly nodes: Map<string, ArtifactNode>;
|
||||
@@ -173,7 +173,7 @@ interface SnapshotBuildInput {
|
||||
const buildInventorySnapshot = async (
|
||||
input: SnapshotBuildInput,
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const { path, metadata, rootFormat, rootDigest, zipSource, reader, signal } =
|
||||
const { path, metadata, rootFormat, rootDigest, rootSource, reader, signal } =
|
||||
input;
|
||||
materializeDirectoryNodes(input.occurrences, input.nodes);
|
||||
const rootNode = createRootNode({
|
||||
@@ -218,7 +218,7 @@ const buildInventorySnapshot = async (
|
||||
ordinal,
|
||||
}));
|
||||
|
||||
await verifyRootDigest(path, rootDigest, zipSource, signal);
|
||||
await verifyRootDigest(path, rootDigest, rootSource, signal);
|
||||
|
||||
const graphSha256 = artifactGraphDigest({
|
||||
nodes: orderedNodes,
|
||||
@@ -293,17 +293,17 @@ const buildIntegrityContradictions = (
|
||||
const verifyRootDigest = async (
|
||||
path: string,
|
||||
rootDigest: HashResult | null,
|
||||
zipSource: StableRegularFileDescriptor | undefined,
|
||||
rootSource: StableRegularFileDescriptor | undefined,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<void> => {
|
||||
if (rootDigest === null) return;
|
||||
const verified =
|
||||
zipSource === undefined
|
||||
rootSource === undefined
|
||||
? await hashStableRootArtifact(path, signal)
|
||||
: await hashStableRootArtifactHandle(
|
||||
path,
|
||||
zipSource.handle,
|
||||
zipSource.initial,
|
||||
rootSource.handle,
|
||||
rootSource.initial,
|
||||
signal,
|
||||
);
|
||||
if (
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
createArtifactNode,
|
||||
createOccurrence,
|
||||
noteUnreadContainerSuffix,
|
||||
nearestParent,
|
||||
resolveOccurrenceParents,
|
||||
type MutableOccurrence,
|
||||
} from "./ArtifactGraphConstruction.js";
|
||||
import {
|
||||
@@ -91,13 +91,11 @@ export const scanReader = async (
|
||||
await visitArtifactEntries(context, reader, "");
|
||||
// Archive directories may appear after their children. Resolve containment
|
||||
// against the complete index before directory identities are materialized.
|
||||
for (const occurrence of occurrences)
|
||||
occurrence.parent_occurrence_id =
|
||||
nearestParent(
|
||||
occurrence.logical_path,
|
||||
context.occurrenceByPath,
|
||||
context.expandedContainerIds,
|
||||
)?.occurrence_id ?? null;
|
||||
resolveOccurrenceParents(
|
||||
occurrences,
|
||||
context.occurrenceByPath,
|
||||
context.expandedContainerIds,
|
||||
);
|
||||
return {
|
||||
nodes,
|
||||
occurrences,
|
||||
|
||||
@@ -27,8 +27,7 @@ export const ingestResponseBodyShape = (
|
||||
invalidResponseBodyShape(state, requestId);
|
||||
return;
|
||||
}
|
||||
const inferred = inferBodyShape(decoded);
|
||||
updateResponseBodyShape(state, requestId, inferred.shape);
|
||||
updateResponseBodyShape(state, requestId, inferJsonShape(decoded));
|
||||
};
|
||||
|
||||
export const requestBodyShape = (
|
||||
@@ -40,10 +39,10 @@ export const requestBodyShape = (
|
||||
const body = cdpStringValue(request.postData);
|
||||
if (!isJsonContentType(recordValue(request.headers)) || body === undefined)
|
||||
return { status: "unavailable", request: null, response: null };
|
||||
const inferred = inferBodyShape(body);
|
||||
const shape = inferJsonShape(body);
|
||||
return {
|
||||
status: inferred.shape === null ? "unavailable" : "included",
|
||||
request: inferred.shape,
|
||||
status: shape === null ? "unavailable" : "included",
|
||||
request: shape,
|
||||
response: null,
|
||||
};
|
||||
};
|
||||
@@ -68,10 +67,6 @@ export const updateResponseBodyShape = (
|
||||
});
|
||||
};
|
||||
|
||||
const inferBodyShape = (text: string): { readonly shape: JsonShape | null } => {
|
||||
return { shape: inferJsonShape(text) };
|
||||
};
|
||||
|
||||
const invalidResponseBodyShape = (
|
||||
state: CdpCaptureEventsState,
|
||||
requestId: string,
|
||||
|
||||
@@ -51,35 +51,41 @@ export const closeCdpTargetSession = async (
|
||||
): Promise<void> => {
|
||||
const { connection, sessionId } = targetSession;
|
||||
const cleanup = new AbortController();
|
||||
const domainSignal =
|
||||
signal === undefined
|
||||
? cleanup.signal
|
||||
: AbortSignal.any([cleanup.signal, signal]);
|
||||
const timeout = setTimeout(() => cleanup.abort(), 1_000);
|
||||
timeout.unref();
|
||||
try {
|
||||
if (signal?.aborted !== true) {
|
||||
for (const domain of enabledDomains) {
|
||||
if (cleanup.signal.aborted) break;
|
||||
if (domainSignal.aborted) break;
|
||||
try {
|
||||
await connection.send(
|
||||
`${domain}.disable`,
|
||||
{},
|
||||
sessionId,
|
||||
cleanup.signal,
|
||||
domainSignal,
|
||||
);
|
||||
} catch {
|
||||
// Best-effort domain cleanup; transport close is the definitive boundary.
|
||||
}
|
||||
}
|
||||
if (!cleanup.signal.aborted && sessionId !== undefined)
|
||||
try {
|
||||
await connection.send(
|
||||
"Target.detachFromTarget",
|
||||
{ sessionId },
|
||||
undefined,
|
||||
cleanup.signal,
|
||||
);
|
||||
} catch {
|
||||
// Best-effort detach; transport close is the definitive boundary.
|
||||
}
|
||||
}
|
||||
// Cancellation skips optional domain shutdown but still releases the
|
||||
// attached session using its independent, bounded cleanup signal.
|
||||
if (!cleanup.signal.aborted && sessionId !== undefined)
|
||||
try {
|
||||
await connection.send(
|
||||
"Target.detachFromTarget",
|
||||
{ sessionId },
|
||||
undefined,
|
||||
cleanup.signal,
|
||||
);
|
||||
} catch {
|
||||
// Best-effort detach; transport close is the definitive boundary.
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
cleanup.abort();
|
||||
|
||||
@@ -365,20 +365,30 @@ const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
|
||||
transientFrames,
|
||||
resolvedTransientFrames,
|
||||
} = options;
|
||||
if (
|
||||
event.method !== "WebMCP.toolsAdded" &&
|
||||
event.method !== "WebMCP.toolsRemoved"
|
||||
)
|
||||
return;
|
||||
const params = recordValue(event.params);
|
||||
if (params === undefined) return;
|
||||
if (params === undefined) {
|
||||
completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return;
|
||||
}
|
||||
if (event.method === "WebMCP.toolsRemoved") {
|
||||
for (const removed of recordsValue(params.tools)) {
|
||||
for (const removed of webMcpEventTools(params.tools, completeness)) {
|
||||
const name = cdpStringValue(removed.name);
|
||||
const frameId = cdpStringValue(removed.frameId);
|
||||
if (name === undefined || frameId === undefined) continue;
|
||||
if (name === undefined || frameId === undefined) {
|
||||
completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
continue;
|
||||
}
|
||||
for (const [key, tool] of tools)
|
||||
if (tool.name === name && tool.frame_id === frameId) tools.delete(key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.method !== "WebMCP.toolsAdded") return;
|
||||
for (const declared of recordsValue(params.tools)) {
|
||||
for (const declared of webMcpEventTools(params.tools, completeness)) {
|
||||
const frameId = cdpStringValue(declared.frameId);
|
||||
if (frameId !== undefined && transientFrames.has(frameId)) {
|
||||
if (!resolvedTransientFrames.has(frameId)) continue;
|
||||
@@ -391,6 +401,26 @@ const ingestWebMcpEvent = (options: WebMcpIngestOptions): void => {
|
||||
}
|
||||
};
|
||||
|
||||
const webMcpEventTools = (
|
||||
value: unknown,
|
||||
completeness: CdpCaptureCompleteness,
|
||||
): UnknownRecord[] => {
|
||||
if (!Array.isArray(value)) {
|
||||
completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return [];
|
||||
}
|
||||
const records: UnknownRecord[] = [];
|
||||
for (const item of value) {
|
||||
const record = recordValue(item);
|
||||
if (record === undefined) {
|
||||
completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
continue;
|
||||
}
|
||||
records.push(record);
|
||||
}
|
||||
return records;
|
||||
};
|
||||
|
||||
const normalizeTool = (
|
||||
value: UnknownRecord,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
@@ -403,12 +433,11 @@ const normalizeTool = (
|
||||
const frameId = cdpStringValue(value.frameId);
|
||||
const name = cdpStringValue(value.name);
|
||||
const frame = frameId === undefined ? undefined : frames.get(frameId);
|
||||
if (
|
||||
frameId === undefined ||
|
||||
name === undefined ||
|
||||
frame?.origin === null ||
|
||||
frame === undefined
|
||||
) {
|
||||
if (frameId === undefined || name === undefined) {
|
||||
completeness.exclude("webmcp_tools", "invalid_protocol_value");
|
||||
return undefined;
|
||||
}
|
||||
if (frame?.origin === null || frame === undefined) {
|
||||
completeness.exclude("webmcp_tools", "out_of_target_scope");
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -42,7 +42,6 @@ export class PlaywrightScenarioBrowserCleanupOwner {
|
||||
#profileRemoved: boolean;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
#eventFinalizationPromise: Promise<void> | undefined;
|
||||
#eventFinalizationFailureReported = false;
|
||||
|
||||
/** Keep the narrow provider actions needed to release one opened browser. */
|
||||
constructor(private readonly resources: PlaywrightScenarioCleanupResources) {
|
||||
@@ -98,10 +97,10 @@ export class PlaywrightScenarioBrowserCleanupOwner {
|
||||
try {
|
||||
await eventFinalization;
|
||||
} catch (cause: unknown) {
|
||||
if (!this.#eventFinalizationFailureReported) {
|
||||
failures.push(cause);
|
||||
this.#eventFinalizationFailureReported = true;
|
||||
}
|
||||
// A failed finalization stays failed: the memoized attempt rejects on
|
||||
// every retry so cleanup can never report success for unfinalized
|
||||
// events.
|
||||
failures.push(cause);
|
||||
}
|
||||
if (!this.#browserClosed) {
|
||||
try {
|
||||
|
||||
@@ -94,9 +94,9 @@ export const captureWebExecution = async (
|
||||
sources.belongsToDocument(id),
|
||||
);
|
||||
const sample =
|
||||
raw === undefined
|
||||
? undefined
|
||||
: normalizePreciseCoverage(raw, sources, retained);
|
||||
parsed?.success === true
|
||||
? normalizePreciseCoverage(parsed.data, sources, retained)
|
||||
: undefined;
|
||||
await session.options.progress?.report({
|
||||
phase: "browser_execution",
|
||||
completed: 2,
|
||||
|
||||
@@ -1,34 +1,30 @@
|
||||
import type { z } from "zod";
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { WebExecution } from "../../domain/webExecution.js";
|
||||
import type { WebRuntimeSource } from "../../domain/webRuntime.js";
|
||||
import { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
|
||||
import type { preciseCoverageSchema } from "./CdpRuntimeProtocol.js";
|
||||
import type { CdpRuntimeSources } from "./CdpRuntimeSources.js";
|
||||
|
||||
/** Validate source-range bounds against exact retained UTF-16 text without flattening nested counts. */
|
||||
export const normalizePreciseCoverage = (
|
||||
raw: unknown,
|
||||
parsed: z.infer<typeof preciseCoverageSchema>,
|
||||
sources: CdpRuntimeSources,
|
||||
retained: readonly WebRuntimeSource[],
|
||||
): {
|
||||
readonly coverage: WebExecution["coverage"];
|
||||
readonly timestamp: number;
|
||||
} => {
|
||||
const parsed = preciseCoverageSchema.safeParse(raw);
|
||||
if (!parsed.success)
|
||||
throw new AnalysisOutputError(
|
||||
sources.session.operation,
|
||||
`Malformed precise coverage: ${parsed.error.message}`,
|
||||
);
|
||||
const retainedSources = new Map(
|
||||
retained.map(({ script_id, source }) => [script_id, source]),
|
||||
);
|
||||
const scripts: WebExecution["coverage"]["scripts"] = [];
|
||||
let excluded = 0;
|
||||
for (const script of parsed.data.result) {
|
||||
for (const script of parsed.result) {
|
||||
if (!sources.belongsToDocument(script.scriptId)) {
|
||||
excluded += 1;
|
||||
continue;
|
||||
}
|
||||
const source = retained.find(
|
||||
(item) => item.script_id === script.scriptId,
|
||||
)?.source;
|
||||
const source = retainedSources.get(script.scriptId);
|
||||
scripts.push({
|
||||
script_id: script.scriptId,
|
||||
reported_url: sources.sourceUrl(script.scriptId, script.url),
|
||||
@@ -57,7 +53,7 @@ export const normalizePreciseCoverage = (
|
||||
});
|
||||
}
|
||||
return {
|
||||
timestamp: parsed.data.timestamp,
|
||||
timestamp: parsed.timestamp,
|
||||
coverage: {
|
||||
state: "captured",
|
||||
reason: null,
|
||||
|
||||
@@ -20,8 +20,12 @@ it.each([
|
||||
const stderr =
|
||||
"FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory\r\n";
|
||||
const cause = new OwnedCommandFailure("process", "Decoder failed", {
|
||||
stdout: { text: "", bytes: 0 },
|
||||
stderr: { text: stderr, bytes: Buffer.byteLength(stderr) },
|
||||
stdout: { text: "", bytes: 0, observedBytes: 0 },
|
||||
stderr: {
|
||||
text: stderr,
|
||||
bytes: Buffer.byteLength(stderr),
|
||||
observedBytes: Buffer.byteLength(stderr),
|
||||
},
|
||||
exitCode,
|
||||
signal,
|
||||
});
|
||||
@@ -70,8 +74,12 @@ it.each([
|
||||
format: "har",
|
||||
});
|
||||
const cause = new OwnedCommandFailure("process", "Decoder failed", {
|
||||
stdout: { text: "", bytes: 0 },
|
||||
stderr: { text: stderr, bytes: Buffer.byteLength(stderr) },
|
||||
stdout: { text: "", bytes: 0, observedBytes: 0 },
|
||||
stderr: {
|
||||
text: stderr,
|
||||
bytes: Buffer.byteLength(stderr),
|
||||
observedBytes: Buffer.byteLength(stderr),
|
||||
},
|
||||
exitCode,
|
||||
signal,
|
||||
});
|
||||
@@ -128,8 +136,16 @@ it("retains actual command status and both diagnostic streams when cleanup also
|
||||
"process",
|
||||
"Observed command failure",
|
||||
{
|
||||
stdout: { text: "original provider output", bytes: 24 },
|
||||
stderr: { text: "private-marker provider reason", bytes: 30 },
|
||||
stdout: {
|
||||
text: "original provider output",
|
||||
bytes: 24,
|
||||
observedBytes: 24,
|
||||
},
|
||||
stderr: {
|
||||
text: "private-marker provider reason",
|
||||
bytes: 30,
|
||||
observedBytes: 30,
|
||||
},
|
||||
exitCode: 2,
|
||||
signal: null,
|
||||
},
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { readCliJsonFile } from "./cliJsonFile.js";
|
||||
import { readJsonInputFile } from "./application/JsonInputFile.js";
|
||||
import { NonRegularFileReadError } from "./filesystem/RegularFile.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
@@ -21,7 +21,7 @@ export const parseCliJsonInput = async (
|
||||
const inline = safeParseJson(value);
|
||||
if (inline.ok) return { ok: true, value: inline.value };
|
||||
try {
|
||||
const parsed = await readCliJsonFile(value, operation);
|
||||
const parsed = await readJsonInputFile(value, operation);
|
||||
return parsed.ok
|
||||
? { ok: true, value: parsed.value }
|
||||
: {
|
||||
|
||||
@@ -94,7 +94,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"capture_process_scenario",
|
||||
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Environment keys cannot contain '=' or NUL, and REA_PROCESS_RUN_ID is reserved for process ownership. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
|
||||
"Run one caller-selected command under a PTY and return process capture Evidence with residual unknowns. The renderer admits at most 1,000,000 combined terminal cells, computed as columns × (rows + scrollback); every resize uses the selected scrollback and must fit the same budget. Supply a smaller terminal shape when that product is too large; dimensions are never clamped. A command name resolves through the inherited PATH; the working directory defaults to the caller's current directory; host environment variables are inherited with scenario overrides. Environment keys cannot contain '=' or NUL, and REA_PROCESS_RUN_ID is reserved for process ownership. Filesystem snapshots are opt-in through filesystem_observation_paths. The target runs with the current user's permissions; this is not a security sandbox.",
|
||||
processScenarioSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -699,3 +699,39 @@ export const adbResultSchemas = {
|
||||
package_name: packageNameSchema,
|
||||
}),
|
||||
} as const;
|
||||
|
||||
/** Acquired package facts retained when cancellation leaves caller-owned output. */
|
||||
export type AdbPackagePullPartialObservation = {
|
||||
readonly provider_id: "adb";
|
||||
readonly operation: "pull_adb_package";
|
||||
readonly result: z.infer<typeof adbResultSchemas.pull_adb_package>;
|
||||
};
|
||||
|
||||
/** A completed acquisition whose digest read was cancelled before verification. */
|
||||
export type AdbAcquiredFilePartialObservation =
|
||||
| {
|
||||
readonly provider_id: "adb";
|
||||
readonly operation: "pull_adb_file";
|
||||
readonly result: {
|
||||
readonly client: z.infer<
|
||||
typeof adbResultSchemas.pull_adb_file
|
||||
>["client"];
|
||||
readonly serial: string;
|
||||
readonly local_path: string;
|
||||
readonly device_path: string;
|
||||
readonly digest_status: "unknown";
|
||||
};
|
||||
}
|
||||
| {
|
||||
readonly provider_id: "adb";
|
||||
readonly operation: "collect_adb_bugreport";
|
||||
readonly result: {
|
||||
readonly client: z.infer<
|
||||
typeof adbResultSchemas.collect_adb_bugreport
|
||||
>["client"];
|
||||
readonly serial: string;
|
||||
readonly local_path: string;
|
||||
readonly adb_reported_path: string;
|
||||
readonly digest_status: "unknown";
|
||||
};
|
||||
};
|
||||
|
||||
@@ -99,6 +99,10 @@ import type { BrowserScenarioPartialObservation } from "./browserScenarioCapture
|
||||
import type { Evidence } from "./evidence.js";
|
||||
import type { AndroidPartialObservation } from "./android/androidPartialObservation.js";
|
||||
import type { FirmwarePartialObservation } from "./firmware/firmwareAnalysis.js";
|
||||
import type {
|
||||
AdbAcquiredFilePartialObservation,
|
||||
AdbPackagePullPartialObservation,
|
||||
} from "./adb/adbDeviceAnalysis.js";
|
||||
import type { NativeUiObservationResult } from "./native/nativeUiObservation.js";
|
||||
|
||||
/** Provider-neutral evidence collected before a typed analysis failure. */
|
||||
@@ -113,4 +117,6 @@ export type AnalysisPartialObservation =
|
||||
| Evidence
|
||||
| AndroidPartialObservation
|
||||
| FirmwarePartialObservation
|
||||
| NativeUiObservationResult;
|
||||
| NativeUiObservationResult
|
||||
| AdbAcquiredFilePartialObservation
|
||||
| AdbPackagePullPartialObservation;
|
||||
|
||||
@@ -25,6 +25,7 @@ export const resolveTreePath = async (
|
||||
let hops = 0;
|
||||
while (pending.length > 0) {
|
||||
const segment = pending.shift() ?? "";
|
||||
if (segment === ".") continue;
|
||||
if (segment === "..") {
|
||||
if (resolved.length === 0) return { kind: "escapes" };
|
||||
resolved.pop();
|
||||
@@ -50,8 +51,12 @@ export const resolveTreePath = async (
|
||||
: { kind: "not-file" };
|
||||
};
|
||||
|
||||
const segmentsOf = (path: string): string[] =>
|
||||
path.split("/").filter((segment) => segment !== "" && segment !== ".");
|
||||
const segmentsOf = (path: string): string[] => {
|
||||
const segments = path.split("/").filter((segment) => segment !== "");
|
||||
// a trailing slash requires a directory, just like a final dot component.
|
||||
if (path.endsWith("/")) segments.push(".");
|
||||
return segments;
|
||||
};
|
||||
|
||||
export const directoryOf = (path: string): string => {
|
||||
const index = path.lastIndexOf("/");
|
||||
|
||||
@@ -250,6 +250,49 @@ describe("dyld path expansion", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps directory requirements in symlink targets", async () => {
|
||||
const names = [
|
||||
"@loader_path/alias-slash",
|
||||
"@loader_path/alias-dot",
|
||||
"@loader_path/alias-directory/lib.dylib",
|
||||
];
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView(
|
||||
{
|
||||
[MAIN]: executable({
|
||||
dependencies: names.map((name) => dependency(name)),
|
||||
}),
|
||||
"Contents/MacOS/lib.dylib": parsed(slice()),
|
||||
},
|
||||
{
|
||||
"Contents/MacOS/alias-slash": "lib.dylib/",
|
||||
"Contents/MacOS/alias-dot": "lib.dylib/.",
|
||||
"Contents/MacOS/alias-directory": "./",
|
||||
},
|
||||
),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
expect(
|
||||
trace.edges.map(({ install_name, candidates, resolution }) => ({
|
||||
install_name,
|
||||
outcome: candidates[0]?.outcome,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual(
|
||||
names.map((name, index) => ({
|
||||
install_name: name,
|
||||
outcome: index < 2 ? "absent" : "resolved",
|
||||
resolution:
|
||||
index < 2
|
||||
? { status: "unresolved", image: null }
|
||||
: { status: "resolved", image: "Contents/MacOS/lib.dylib" },
|
||||
})),
|
||||
);
|
||||
expect(
|
||||
trace.findings.map(({ kind, edge_index }) => [kind, edge_index]),
|
||||
).toEqual([0, 1].map((index) => ["required-load-unresolved", index]));
|
||||
});
|
||||
|
||||
describe("dyld resolution outcomes: deriving path and weak-load outcomes", () => {
|
||||
it("keeps paths outside the root undetermined and in-root fallbacks conditional", async () => {
|
||||
const trace = await traceDylibLoading(
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
compatibleSlice,
|
||||
directoryOf,
|
||||
expandPrefix,
|
||||
joinPath,
|
||||
resolveTreePath,
|
||||
type Expansion,
|
||||
} from "./dyldPaths.js";
|
||||
@@ -275,7 +274,7 @@ const candidateTemplates = (
|
||||
path:
|
||||
base.scope === "outside"
|
||||
? `${base.path.replace(/\/+$/u, "")}/${rest}`
|
||||
: joinPath(base.path, rest),
|
||||
: `${base.path}${base.path === "" ? "" : "/"}${rest}`,
|
||||
};
|
||||
return { expansion, source: "rpath" as const, rpath, rpathOwner: owner };
|
||||
}),
|
||||
|
||||
@@ -99,6 +99,8 @@ const chunk = z.strictObject({
|
||||
export interface FirmwarePartialObservation {
|
||||
readonly kind: "firmware";
|
||||
readonly result: JsonValue;
|
||||
/** Completed producer data, artifact identity and analysis metadata. */
|
||||
readonly provenance?: JsonValue;
|
||||
}
|
||||
|
||||
/** Portable results retain reported boundaries, unknowns and extraction lineage. */
|
||||
|
||||
@@ -16,8 +16,17 @@ export abstract class HopperError extends AnalysisError {}
|
||||
export type HopperLauncherOutcome = {
|
||||
readonly exit_code: number | null;
|
||||
readonly signal: string | null;
|
||||
readonly stdout: { readonly text: string; readonly bytes: number };
|
||||
readonly stderr: { readonly text: string; readonly bytes: number };
|
||||
/** Total bytes drained from the stream; retained_bytes reports captured bytes. */
|
||||
readonly stdout: {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly retained_bytes: number;
|
||||
};
|
||||
readonly stderr: {
|
||||
readonly text: string;
|
||||
readonly bytes: number;
|
||||
readonly retained_bytes: number;
|
||||
};
|
||||
readonly output_closed: boolean;
|
||||
readonly diagnostic_truncated: boolean;
|
||||
};
|
||||
|
||||
@@ -39,6 +39,8 @@ export type ElectronBrowserWindowFinding = ElectronBrowserWindowPreload & {
|
||||
readonly web_preferences_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly web_preferences: readonly ElectronWebPreference[];
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
};
|
||||
|
||||
@@ -56,6 +58,8 @@ export type ElectronContextBridgeFinding = ElectronContextBridgeApiKey & {
|
||||
readonly members: readonly string[];
|
||||
readonly unknown_members: number;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
};
|
||||
|
||||
@@ -109,6 +113,8 @@ type ElectronIpcHandler =
|
||||
|
||||
interface ElectronIpcFindingContext {
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -134,12 +140,16 @@ export interface ElectronSenderValidationFinding {
|
||||
readonly expected: ElectronStaticValue;
|
||||
readonly enforcement: "unknown";
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
interface ElectronUtilityProcessFindingState {
|
||||
readonly service_name: string | null;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -169,6 +179,8 @@ export interface ElectronNativeAddonBindingFinding {
|
||||
readonly namespace_access?: boolean;
|
||||
readonly dynamic_member_access?: boolean;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
|
||||
@@ -62,9 +62,7 @@ const classifyLayer = (
|
||||
options.reconciliationComplete &&
|
||||
layer.graph.coverage.status === "complete" &&
|
||||
scopedEntities.length > 0 &&
|
||||
scopedEntities.every(({ capture }) =>
|
||||
captureScriptsComplete(capture.evidence.evidence_id, runtimeEntities),
|
||||
);
|
||||
scopedEntities.every(({ capture }) => capture.scriptsCompleteWithinScope);
|
||||
const states = nodes.map((node) => {
|
||||
const runtimeNodeIds = uniqueSorted(direct.get(node.node_id) ?? []);
|
||||
if (runtimeNodeIds.length > 0)
|
||||
@@ -134,13 +132,6 @@ const append = (
|
||||
else current.push(value);
|
||||
};
|
||||
|
||||
const captureScriptsComplete = (
|
||||
evidenceId: string,
|
||||
entities: readonly RuntimeReconciliationEntity[],
|
||||
): boolean =>
|
||||
entities.find(({ capture }) => capture.evidence.evidence_id === evidenceId)
|
||||
?.capture.scriptsCompleteWithinScope === true;
|
||||
|
||||
const isLoadStateNode = (
|
||||
node: ApplicationNode,
|
||||
): node is ApplicationNode & {
|
||||
|
||||
@@ -212,8 +212,11 @@ const graphCoverage = (
|
||||
|
||||
const mergeNodes = (nodes: readonly ApplicationNode[]): ApplicationNode[] => {
|
||||
const grouped = new Map<string, ApplicationNode[]>();
|
||||
for (const node of nodes)
|
||||
grouped.set(node.node_id, [...(grouped.get(node.node_id) ?? []), node]);
|
||||
for (const node of nodes) {
|
||||
const group = grouped.get(node.node_id);
|
||||
if (group === undefined) grouped.set(node.node_id, [node]);
|
||||
else group.push(node);
|
||||
}
|
||||
const merged = [...grouped.values()].map((group) => {
|
||||
const first = group[0];
|
||||
if (first === undefined) throw new TypeError("Empty JAG node group");
|
||||
|
||||
@@ -23,7 +23,12 @@ it("preserves a 12,000-member native import through both analyzers", () => {
|
||||
const ir = analyzeParsedJavaScriptSemantics(parsed);
|
||||
expect(staticAnalysis.parse_status).toBe("complete");
|
||||
expect(staticAnalysis.electron.native_addon_bindings).toEqual([
|
||||
expect.objectContaining({ specifier: "./addon.node", members: ["last"] }),
|
||||
expect.objectContaining({
|
||||
specifier: "./addon.node",
|
||||
members: ["next"],
|
||||
namespace_access: false,
|
||||
dynamic_member_access: false,
|
||||
}),
|
||||
]);
|
||||
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
|
||||
const path = origin(onlyBinding(ir, "value"));
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import { onlyBinding } from "./javascriptSemanticAnalysis.fixture.js";
|
||||
|
||||
it("bounds ancestry reads for repeated deep lexical references", () => {
|
||||
const ancestryReads = (depth: number): number => {
|
||||
const original = WeakMap.prototype.get;
|
||||
let reads = 0;
|
||||
const get = vi.spyOn(WeakMap.prototype, "get").mockImplementation(function (
|
||||
this: WeakMap<object, unknown>,
|
||||
key,
|
||||
) {
|
||||
const value: unknown = original.call(this, key);
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"type" in value &&
|
||||
typeof value.type === "string"
|
||||
)
|
||||
reads++;
|
||||
return value;
|
||||
});
|
||||
try {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`const a=1; module.exports.value=${"a+(".repeat(depth)}a${")".repeat(depth)};`,
|
||||
);
|
||||
expect(ir.coverage).toEqual({ status: "complete", omittedCount: 0 });
|
||||
expect(onlyBinding(ir, "a").value).toEqual({
|
||||
status: "literal",
|
||||
value: 1,
|
||||
});
|
||||
return reads;
|
||||
} finally {
|
||||
get.mockRestore();
|
||||
}
|
||||
};
|
||||
|
||||
const smaller = ancestryReads(80);
|
||||
const larger = ancestryReads(160);
|
||||
expect(smaller).toBeGreaterThan(0);
|
||||
expect(larger).toBeLessThan(3 * smaller);
|
||||
});
|
||||
@@ -444,6 +444,7 @@ function* collectDefinitionsSteps(
|
||||
}[] = [];
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node, parent, readAncestors) => {
|
||||
if (parent !== null) state.parentsByNode.set(node, parent);
|
||||
let parentScope = currentSemanticScope(stack);
|
||||
if (
|
||||
parent !== null &&
|
||||
@@ -493,7 +494,10 @@ function* collectDefinitionsSteps(
|
||||
});
|
||||
}
|
||||
const scope = currentSemanticScope(stack);
|
||||
state.scopeByNode.set(node, scope);
|
||||
// Other nodes inherit the nearest boundary through their AST parents.
|
||||
// Avoid a second full-tree index for the same lexical relationship.
|
||||
if (parent === null || openedScopes.has(node))
|
||||
state.scopeByNode.set(node, scope);
|
||||
collectSemanticCallable({
|
||||
node,
|
||||
parent,
|
||||
|
||||
@@ -428,4 +428,10 @@ const enclosingFunction = (
|
||||
const semanticCallSiteId = (
|
||||
node: t.CallExpression | t.OptionalCallExpression | t.NewExpression,
|
||||
): string =>
|
||||
`call:${t.isNewExpression(node) ? "construct" : "call"}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
|
||||
// Join once so retained IDs do not keep a chain of intermediate strings.
|
||||
[
|
||||
"call",
|
||||
t.isNewExpression(node) ? "construct" : "call",
|
||||
String(node.start ?? -1),
|
||||
String(node.end ?? -1),
|
||||
].join(":");
|
||||
|
||||
@@ -19,15 +19,11 @@ import {
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
|
||||
javaScriptSemanticFingerprintInputSchema,
|
||||
javaScriptSemanticFingerprintSchema,
|
||||
javaScriptSemanticGraphInputSchema,
|
||||
javaScriptSemanticGraphRecordSchema,
|
||||
javaScriptSemanticNodeInputSchema,
|
||||
javaScriptSemanticNodeSchema,
|
||||
javaScriptSemanticRelationInputSchema,
|
||||
javaScriptSemanticRelationSchema,
|
||||
javaScriptSemanticUnknownInputSchema,
|
||||
javaScriptSemanticUnknownSchema,
|
||||
type JavaScriptSemanticGraphInput,
|
||||
type JavaScriptSemanticGraphNode,
|
||||
type JavaScriptSemanticGraphRelation,
|
||||
@@ -132,10 +128,10 @@ export const createJavaScriptSemanticGraphNode = (
|
||||
application_node_ids: uniqueSorted(parsed.application_node_ids),
|
||||
evidence: evidenceContexts.intern(parsed.evidence),
|
||||
};
|
||||
return javaScriptSemanticNodeSchema.parse({
|
||||
return {
|
||||
...semantic,
|
||||
node_id: javaScriptSemanticNodeId(semantic),
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
/** Normalize one semantic relationship and derive its exact identifier. */
|
||||
@@ -148,10 +144,10 @@ export const createJavaScriptSemanticGraphRelation = (
|
||||
...parsed,
|
||||
evidence: evidenceContexts.intern(parsed.evidence),
|
||||
};
|
||||
return javaScriptSemanticRelationSchema.parse({
|
||||
return {
|
||||
...semantic,
|
||||
relation_id: `jsrg_relation_${digestCanonicalValue(semantic, "JavaScript semantic graph")}`,
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
/** Normalize one unresolved semantic frontier and derive its identifier. */
|
||||
@@ -166,10 +162,10 @@ export const createJavaScriptSemanticGraphUnknown = (
|
||||
candidate_node_ids: uniqueSorted(parsed.candidate_node_ids),
|
||||
evidence: evidenceContexts.intern(parsed.evidence),
|
||||
};
|
||||
return javaScriptSemanticUnknownSchema.parse({
|
||||
return {
|
||||
...semantic,
|
||||
unknown_id: `jsrg_unknown_${digestCanonicalValue(semantic, "JavaScript semantic graph")}`,
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
/** Normalize one function fingerprint and derive its component commitment. */
|
||||
@@ -191,7 +187,7 @@ export const createJavaScriptSemanticFingerprint = (
|
||||
semantic.components,
|
||||
"JavaScript semantic graph",
|
||||
);
|
||||
return javaScriptSemanticFingerprintSchema.parse({
|
||||
return {
|
||||
...semantic,
|
||||
fingerprint_sha256: fingerprintSha256,
|
||||
fingerprint_id: `jsrg_fingerprint_${digestCanonicalValue(
|
||||
@@ -202,7 +198,7 @@ export const createJavaScriptSemanticFingerprint = (
|
||||
},
|
||||
"JavaScript semantic graph",
|
||||
)}`,
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
type GraphRecord = z.infer<typeof javaScriptSemanticGraphRecordSchema>;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod";
|
||||
import { digestCanonicalValue } from "../canonicalDigest.js";
|
||||
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILY,
|
||||
JAVASCRIPT_SEMANTIC_NODE_KINDS,
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
|
||||
JAVASCRIPT_SEMANTIC_RELATIONS,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
parseJavaScriptSemanticGraph,
|
||||
serializeJavaScriptSemanticGraph,
|
||||
} from "./javascriptSemanticGraphSerialization.js";
|
||||
import { queryJavaScriptSemanticGraph } from "./javascriptSemanticQuery.js";
|
||||
|
||||
const SHA = "a".repeat(64);
|
||||
const JAG_ID = `jag_${"b".repeat(64)}`;
|
||||
@@ -140,6 +142,44 @@ it("accepts semantic module paths longer than the former schema ceiling", () =>
|
||||
).toBe(modulePath);
|
||||
});
|
||||
|
||||
it("captures caller-owned node identity, properties, and provenance", () => {
|
||||
const contexts = new JavaScriptSemanticEvidenceContextRegistry();
|
||||
const input = {
|
||||
kind: "literal",
|
||||
identity: {
|
||||
artifact_sha256: SHA,
|
||||
module_path: "bundle.js",
|
||||
source_range: null,
|
||||
role_key: "literal",
|
||||
},
|
||||
function_node_id: null,
|
||||
application_node_ids: [],
|
||||
label: "literal",
|
||||
properties: { nested: ["original"] },
|
||||
evidence: evidence(),
|
||||
};
|
||||
const captured = createJavaScriptSemanticGraphNode(input, contexts);
|
||||
const expected = structuredClone(captured);
|
||||
const expectedEvidence = structuredClone(input.evidence);
|
||||
|
||||
input.identity.module_path = "replaced.js";
|
||||
input.properties.nested[0] = "replaced";
|
||||
input.evidence.limitations.push("later mutation");
|
||||
if (input.evidence.location.available)
|
||||
input.evidence.location.value = {
|
||||
kind: "artifact-path",
|
||||
path: "replaced.js",
|
||||
};
|
||||
|
||||
expect(captured).toEqual(expected);
|
||||
expect(
|
||||
resolveJavaScriptSemanticEvidence(
|
||||
{ evidence_contexts: contexts.contexts },
|
||||
captured.evidence,
|
||||
),
|
||||
).toEqual(expectedEvidence);
|
||||
});
|
||||
|
||||
const fixtureInput = (withUnknown = false): JavaScriptSemanticGraphInput => {
|
||||
const evidenceContexts = new JavaScriptSemanticEvidenceContextRegistry();
|
||||
const module = node("module", "module", {}, evidenceContexts);
|
||||
@@ -285,6 +325,104 @@ const registryForGraph = (
|
||||
return registry;
|
||||
};
|
||||
|
||||
const graphWithCandidateRelations = (): JavaScriptSemanticGraph => {
|
||||
const base = fixtureGraph();
|
||||
const evidenceContexts = registryForGraph(base);
|
||||
const relations = base.relations.map(
|
||||
({ relation_id: _relationId, ...relation }) =>
|
||||
createJavaScriptSemanticGraphRelation(
|
||||
{
|
||||
...relation,
|
||||
resolution: "candidate",
|
||||
evidence: resolveJavaScriptSemanticEvidence(base, relation.evidence),
|
||||
},
|
||||
evidenceContexts,
|
||||
),
|
||||
);
|
||||
const binding = base.nodes.find(({ label }) => label === "binding");
|
||||
const callable = base.nodes.find(({ label }) => label === "function");
|
||||
if (binding === undefined || callable === undefined)
|
||||
throw new Error("Expected candidate-cycle endpoints");
|
||||
for (const [source, target] of [
|
||||
[binding, callable],
|
||||
[callable, binding],
|
||||
] as const)
|
||||
relations.push(
|
||||
createJavaScriptSemanticGraphRelation(
|
||||
{
|
||||
source_node_id: source.node_id,
|
||||
target_node_id: target.node_id,
|
||||
relation: "owns",
|
||||
resolution: "candidate",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
},
|
||||
evidenceContexts,
|
||||
),
|
||||
);
|
||||
|
||||
const { graph_id: _graphId, ...input } = base;
|
||||
return createJavaScriptSemanticGraph({
|
||||
...input,
|
||||
evidence_contexts: evidenceContexts.contexts,
|
||||
relations,
|
||||
coverage: {
|
||||
...input.coverage,
|
||||
families: input.coverage.families.map((family) => ({
|
||||
...family,
|
||||
retained_relations: relations.filter(
|
||||
({ relation }) =>
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILY[relation] === family.family,
|
||||
).length,
|
||||
})),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
it("counts candidate edges by query direction and relation filter", () => {
|
||||
const graph = graphWithCandidateRelations();
|
||||
const binding = graph.nodes.find(({ label }) => label === "binding");
|
||||
if (binding === undefined) throw new Error("Expected binding seed");
|
||||
const query = (
|
||||
direction: "forward-influence" | "backward-provenance",
|
||||
allowedRelations: (typeof JAVASCRIPT_SEMANTIC_RELATIONS)[number][],
|
||||
) =>
|
||||
queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "semantic-node", node_id: binding.node_id },
|
||||
direction,
|
||||
allowed_relations: allowedRelations,
|
||||
});
|
||||
|
||||
expect(query("forward-influence", ["captures"]).status).toBe("ambiguous");
|
||||
expect(query("forward-influence", ["defines"]).status).toBe("found");
|
||||
expect(query("backward-provenance", ["defines"]).status).toBe("ambiguous");
|
||||
expect(query("backward-provenance", ["captures"]).status).toBe("found");
|
||||
});
|
||||
|
||||
it("counts candidate ownership cycles once and traverses them finitely", () => {
|
||||
const graph = graphWithCandidateRelations();
|
||||
const binding = graph.nodes.find(({ label }) => label === "binding");
|
||||
if (binding === undefined) throw new Error("Expected binding seed");
|
||||
const result = queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "semantic-node", node_id: binding.node_id },
|
||||
direction: "ownership",
|
||||
allowed_relations: ["owns"],
|
||||
include_ambiguous_dynamic_edges: true,
|
||||
});
|
||||
|
||||
expect(result.status).toBe("ambiguous");
|
||||
expect(result.relations).toHaveLength(2);
|
||||
expect(result.summary.traversed_nodes).toBe(2);
|
||||
expect(result.summary.traversed_relations).toBe(2);
|
||||
expect(
|
||||
queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "semantic-node", node_id: binding.node_id },
|
||||
direction: "ownership",
|
||||
allowed_relations: ["constructs-request"],
|
||||
}).status,
|
||||
).toBe("found");
|
||||
});
|
||||
|
||||
it("defines every required relation family and canonicalizes records", () => {
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("argument-to-parameter");
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("detaches-task");
|
||||
|
||||
@@ -316,6 +316,20 @@ it("returns every relevant unknown inline", () => {
|
||||
expect(result.unknowns).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not admit a semantic-node seed absent from the graph", () => {
|
||||
const result = queryJavaScriptSemanticGraph(fixtureGraph(), {
|
||||
seed: { kind: "semantic-node", node_id: `jsrg_node_${"f".repeat(64)}` },
|
||||
direction: "forward-influence",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "no-match",
|
||||
seed_node_ids: [],
|
||||
nodes: [],
|
||||
summary: { total_seed_matches: 0, traversed_nodes: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns the complete deterministic forward influence result inline", () => {
|
||||
const graph = fixtureGraph();
|
||||
const input = {
|
||||
|
||||
@@ -40,11 +40,6 @@ export function* collectSemanticMemberMutationsSteps(
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
): Generator<void, void> {
|
||||
const parents = state.parentsByNode;
|
||||
yield* traverseJavaScriptAstSteps(program, {
|
||||
enter: (node, parent) => {
|
||||
if (parent !== null) parents.set(node, parent);
|
||||
},
|
||||
});
|
||||
const normalizePath = observableMutationPaths(state);
|
||||
const returnedReferences = createSemanticReturnedReferences(state);
|
||||
const recordedEffects = new Set<string>();
|
||||
@@ -670,10 +665,10 @@ type MutationObservableOrigin =
|
||||
| "opaque";
|
||||
|
||||
interface MutationObserverNode {
|
||||
readonly origins: Set<MutationObservableOrigin>;
|
||||
readonly sources: Set<MutationObserverNode>;
|
||||
readonly dependents: Set<MutationObserverNode>;
|
||||
readonly projections: Map<string, MutationObserverNode>;
|
||||
origins?: Set<MutationObservableOrigin>;
|
||||
sources?: Set<MutationObserverNode>;
|
||||
dependents?: Set<MutationObserverNode>;
|
||||
projections?: Map<string, MutationObserverNode>;
|
||||
readonly read?: {
|
||||
readonly source: MutationObserverNode;
|
||||
readonly key: PropertyPath[number];
|
||||
@@ -700,22 +695,17 @@ const observableMutationPaths = (
|
||||
queued.add(node);
|
||||
pending.push(node);
|
||||
};
|
||||
const create = (
|
||||
read?: MutationObserverNode["read"],
|
||||
): MutationObserverNode => ({
|
||||
origins: new Set(),
|
||||
sources: new Set(),
|
||||
dependents: new Set(),
|
||||
projections: new Map(),
|
||||
...(read === undefined ? {} : { read }),
|
||||
});
|
||||
const create = (read?: MutationObserverNode["read"]): MutationObserverNode =>
|
||||
// Most bindings have no object origin or property projection. Materialize
|
||||
// each collection only when it contains a fact or relationship.
|
||||
read === undefined ? {} : { read };
|
||||
const link = (
|
||||
source: MutationObserverNode,
|
||||
target: MutationObserverNode,
|
||||
): void => {
|
||||
if (target.sources.has(source)) return;
|
||||
target.sources.add(source);
|
||||
source.dependents.add(target);
|
||||
if (target.sources?.has(source) === true) return;
|
||||
(target.sources ??= new Set()).add(source);
|
||||
(source.dependents ??= new Set()).add(target);
|
||||
schedule(target);
|
||||
};
|
||||
const expressionNode = (node: t.Node): MutationObserverNode => {
|
||||
@@ -736,11 +726,11 @@ const observableMutationPaths = (
|
||||
const identity = JSON.stringify(
|
||||
key === null || typeof key === "object" ? key : String(key),
|
||||
);
|
||||
let selected = observer.projections.get(identity);
|
||||
let selected = observer.projections?.get(identity);
|
||||
if (selected === undefined) {
|
||||
selected = create({ source: observer, key });
|
||||
observer.projections.set(identity, selected);
|
||||
observer.dependents.add(selected);
|
||||
(observer.projections ??= new Map()).set(identity, selected);
|
||||
(observer.dependents ??= new Set()).add(selected);
|
||||
schedule(selected);
|
||||
}
|
||||
observer = selected;
|
||||
@@ -760,7 +750,7 @@ const observableMutationPaths = (
|
||||
// Preserve exact paths where copies, defaults or iteration need their
|
||||
// reference-specific projections; an opaque origin prevents pruning.
|
||||
if (binding.referenceInitializers.length > 0)
|
||||
observer.origins.add("opaque");
|
||||
(observer.origins ??= new Set()).add("opaque");
|
||||
for (const initializer of binding.referenceInitializers) {
|
||||
for (const source of [
|
||||
initializer,
|
||||
@@ -777,7 +767,7 @@ const observableMutationPaths = (
|
||||
if (selected === undefined) break;
|
||||
const { expression, observer } = selected;
|
||||
if (t.isObjectExpression(expression) || t.isArrayExpression(expression))
|
||||
observer.origins.add(expression);
|
||||
(observer.origins ??= new Set()).add(expression);
|
||||
else if (t.isIdentifier(expression)) {
|
||||
const binding = resolveSemanticBindingState(
|
||||
state,
|
||||
@@ -787,11 +777,12 @@ const observableMutationPaths = (
|
||||
if (binding !== undefined) {
|
||||
const origin = bindingNodes.get(binding.bindingId);
|
||||
if (origin !== undefined) link(origin, observer);
|
||||
} else if (expression.name === "Array") observer.origins.add("array");
|
||||
} else if (expression.name === "Array")
|
||||
(observer.origins ??= new Set()).add("array");
|
||||
else if (
|
||||
["globalThis", "global", "window", "self"].includes(expression.name)
|
||||
)
|
||||
observer.origins.add("ambient");
|
||||
(observer.origins ??= new Set()).add("ambient");
|
||||
} else if (
|
||||
t.isMemberExpression(expression) ||
|
||||
t.isOptionalMemberExpression(expression)
|
||||
@@ -818,21 +809,21 @@ const observableMutationPaths = (
|
||||
queued.delete(observer);
|
||||
let changed = false;
|
||||
const add = (origin: MutationObservableOrigin): void => {
|
||||
if (observer.origins.has(origin)) return;
|
||||
observer.origins.add(origin);
|
||||
if (observer.origins?.has(origin) === true) return;
|
||||
(observer.origins ??= new Set()).add(origin);
|
||||
changed = true;
|
||||
};
|
||||
for (const source of observer.sources)
|
||||
for (const origin of source.origins) add(origin);
|
||||
for (const source of observer.sources ?? [])
|
||||
for (const origin of source.origins ?? []) add(origin);
|
||||
if (observer.read !== undefined) {
|
||||
const { source, key } = observer.read;
|
||||
if (key === null || typeof key === "object") {
|
||||
// Dynamic keys and copied-slot masks retain their original paths.
|
||||
// Enumerating their exclusion combinations would recreate the growth
|
||||
// that the mutation collector's selection union already prevents.
|
||||
if (source.origins.size > 0) add("opaque");
|
||||
if ((source.origins?.size ?? 0) > 0) add("opaque");
|
||||
} else
|
||||
for (const origin of source.origins) {
|
||||
for (const origin of source.origins ?? []) {
|
||||
if (typeof origin === "string") {
|
||||
if (origin === "array-prototype" || origin === "opaque")
|
||||
add(origin);
|
||||
@@ -869,7 +860,7 @@ const observableMutationPaths = (
|
||||
}
|
||||
}
|
||||
if (changed)
|
||||
for (const dependent of observer.dependents) schedule(dependent);
|
||||
for (const dependent of observer.dependents ?? []) schedule(dependent);
|
||||
}
|
||||
};
|
||||
settle();
|
||||
@@ -881,15 +872,16 @@ const observableMutationPaths = (
|
||||
if (effect === "escape") {
|
||||
observer = project(observer, path);
|
||||
settle();
|
||||
return observer.origins.size === 0 ? null : path;
|
||||
return (observer.origins?.size ?? 0) === 0 ? null : path;
|
||||
}
|
||||
if (observer.origins.size === 0) return path.length === 0 ? path : [null];
|
||||
if ((observer.origins?.size ?? 0) === 0)
|
||||
return path.length === 0 ? path : [null];
|
||||
for (let offset = 0; offset < path.length; offset++) {
|
||||
const key = path[offset];
|
||||
if (key === undefined) break;
|
||||
observer = project(observer, [key]);
|
||||
settle();
|
||||
if (observer.origins.size === 0 && offset + 1 < path.length)
|
||||
if ((observer.origins?.size ?? 0) === 0 && offset + 1 < path.length)
|
||||
return [...path.slice(0, offset + 1), null];
|
||||
}
|
||||
return path;
|
||||
|
||||
@@ -179,7 +179,13 @@ const addObjectOperation = (
|
||||
output: JavaScriptSemanticObjectOperation[],
|
||||
): void => {
|
||||
output.push({
|
||||
objectOperationId: `object:${input.kind}:${String(input.node.start ?? -1)}:${String(input.node.end ?? -1)}`,
|
||||
// These high-volume IDs must not retain intermediate concatenations.
|
||||
objectOperationId: [
|
||||
"object",
|
||||
input.kind,
|
||||
String(input.node.start ?? -1),
|
||||
String(input.node.end ?? -1),
|
||||
].join(":"),
|
||||
kind: input.kind,
|
||||
location: range(input.node),
|
||||
ownerCallableId: input.ownerCallableId,
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
JavaScriptSemanticGraphNode,
|
||||
JavaScriptSemanticGraphRelation,
|
||||
} from "./javascriptSemanticGraphSchemas.js";
|
||||
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
|
||||
import type { JavaScriptSemanticGraphUnknown } from "./javascriptSemanticGraphSchemas.js";
|
||||
import { isJavaScriptSemanticOwnershipRelation as ownershipRelation } from "./javascriptSemanticQueryRelations.js";
|
||||
import {
|
||||
@@ -30,10 +29,6 @@ interface Traversal {
|
||||
readonly modules: Set<string>;
|
||||
}
|
||||
|
||||
interface SeedAdmission {
|
||||
readonly nodeIds: string[];
|
||||
}
|
||||
|
||||
interface QueryResult {
|
||||
readonly retainedNodes: JavaScriptSemanticGraphNode[];
|
||||
readonly retainedRelations: JavaScriptSemanticGraphRelation[];
|
||||
@@ -47,17 +42,15 @@ export const queryJavaScriptSemanticGraph = (
|
||||
const input = javaScriptSemanticQueryInputSchema.parse(rawInput);
|
||||
const queryId = queryIdentifier(graph, input);
|
||||
const seeds = resolveSeeds(graph, input);
|
||||
const admission = admitSeeds(graph, seeds);
|
||||
const retainedSeeds = admission.nodeIds;
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const adjacency = buildAdjacency(graph.relations, input);
|
||||
const traversal = traverse(graph, retainedSeeds, adjacency);
|
||||
const traversal = traverse(nodes, seeds, adjacency);
|
||||
const result = createQueryResult(graph, traversal);
|
||||
const allRelevantUnknowns = relevantUnknownFrontiers(
|
||||
const relevantUnknowns = relevantUnknownFrontiers(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
input,
|
||||
);
|
||||
const relevantUnknowns = allRelevantUnknowns;
|
||||
const candidateRelations = relevantCandidateRelationCount(
|
||||
graph,
|
||||
traversal.nodeIds,
|
||||
@@ -87,7 +80,7 @@ export const queryJavaScriptSemanticGraph = (
|
||||
seed: input.seed,
|
||||
direction: input.direction,
|
||||
status: assessment.status,
|
||||
seed_node_ids: retainedSeeds,
|
||||
seed_node_ids: seeds,
|
||||
evidence_contexts: graph.evidence_contexts.filter(({ context_id }) =>
|
||||
retainedContextIds.has(context_id),
|
||||
),
|
||||
@@ -101,7 +94,7 @@ export const queryJavaScriptSemanticGraph = (
|
||||
traversed_relations: traversal.relationIds.size,
|
||||
traversed_functions: traversal.functionIds.size,
|
||||
traversed_modules: traversal.modules.size,
|
||||
relevant_unknowns: allRelevantUnknowns.length,
|
||||
relevant_unknowns: relevantUnknowns.length,
|
||||
},
|
||||
coverage: assessment.coverage,
|
||||
limitations: assessment.limitations,
|
||||
@@ -121,20 +114,6 @@ const createQueryResult = (
|
||||
return { retainedNodes, retainedRelations };
|
||||
};
|
||||
|
||||
const admitSeeds = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
seeds: readonly string[],
|
||||
): SeedAdmission => {
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const retained: string[] = [];
|
||||
for (const nodeId of seeds) {
|
||||
const node = nodes.get(nodeId);
|
||||
if (node === undefined) continue;
|
||||
retained.push(nodeId);
|
||||
}
|
||||
return { nodeIds: retained };
|
||||
};
|
||||
|
||||
const buildAdjacency = (
|
||||
relations: readonly JavaScriptSemanticGraphRelation[],
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
@@ -153,13 +132,6 @@ const buildAdjacency = (
|
||||
continue;
|
||||
addDirectedEntries(adjacency, relation, input.direction);
|
||||
}
|
||||
for (const entries of adjacency.values())
|
||||
entries.sort((left, right) =>
|
||||
compareUnicodeCodePoints(
|
||||
`${left.relation.relation_id}\0${left.nextNodeId}`,
|
||||
`${right.relation.relation_id}\0${right.nextNodeId}`,
|
||||
),
|
||||
);
|
||||
return adjacency;
|
||||
};
|
||||
|
||||
@@ -222,11 +194,10 @@ const addEntry = (
|
||||
};
|
||||
|
||||
const traverse = (
|
||||
graph: JavaScriptSemanticGraph,
|
||||
nodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
|
||||
seeds: readonly string[],
|
||||
adjacency: ReadonlyMap<string, TraversalEntry[]>,
|
||||
): Traversal => {
|
||||
const nodes = new Map(graph.nodes.map((node) => [node.node_id, node]));
|
||||
const nodeIds = new Set(seeds);
|
||||
const relationIds = new Set<string>();
|
||||
const functionIds = new Set<string>();
|
||||
@@ -289,15 +260,32 @@ const relevantCandidateRelationCount = (
|
||||
nodeIds: ReadonlySet<string>,
|
||||
input: JavaScriptSemanticQueryInput,
|
||||
): number => {
|
||||
const adjacency = buildAdjacency(
|
||||
graph.relations.filter(({ resolution }) => resolution === "candidate"),
|
||||
{ ...input, include_ambiguous_dynamic_edges: true },
|
||||
);
|
||||
const relevant = new Set<string>();
|
||||
for (const nodeId of nodeIds)
|
||||
for (const { relation } of adjacency.get(nodeId) ?? [])
|
||||
relevant.add(relation.relation_id);
|
||||
return relevant.size;
|
||||
const allowed =
|
||||
input.allowed_relations === undefined
|
||||
? null
|
||||
: new Set(input.allowed_relations);
|
||||
let relevant = 0;
|
||||
for (const relation of graph.relations) {
|
||||
if (
|
||||
relation.resolution !== "candidate" ||
|
||||
(allowed !== null && !allowed.has(relation.relation))
|
||||
)
|
||||
continue;
|
||||
const sourceIsRelevant = nodeIds.has(relation.source_node_id);
|
||||
const targetIsRelevant = nodeIds.has(relation.target_node_id);
|
||||
if (
|
||||
(input.direction === "callers" &&
|
||||
relation.relation === "calls" &&
|
||||
targetIsRelevant) ||
|
||||
(input.direction === "ownership" &&
|
||||
ownershipRelation(relation.relation) &&
|
||||
(sourceIsRelevant || targetIsRelevant)) ||
|
||||
(input.direction === "backward-provenance" && targetIsRelevant) ||
|
||||
(input.direction === "forward-influence" && sourceIsRelevant)
|
||||
)
|
||||
relevant += 1;
|
||||
}
|
||||
return relevant;
|
||||
};
|
||||
|
||||
const expectedMatchesFor = (
|
||||
|
||||
@@ -83,7 +83,14 @@ const semanticReturnSiteId = (
|
||||
callableId: string,
|
||||
location: JavaScriptSemanticReturnSite["location"],
|
||||
): string =>
|
||||
`${callableId}:return:${String(location.start.line)}:${String(location.start.column)}:${String(location.end.line)}:${String(location.end.column)}`;
|
||||
[
|
||||
callableId,
|
||||
"return",
|
||||
String(location.start.line),
|
||||
String(location.start.column),
|
||||
String(location.end.line),
|
||||
String(location.end.column),
|
||||
].join(":");
|
||||
|
||||
/** Link exports to callables only when lexical resolution is unique and exact. */
|
||||
export const resolveSemanticModuleCallables = (
|
||||
|
||||
@@ -60,6 +60,7 @@ export interface JavaScriptSemanticAnalysisState {
|
||||
readonly parentsByNode: WeakMap<t.Node, t.Node>;
|
||||
readonly scopes: JavaScriptSemanticScopeState[];
|
||||
readonly scopesById: Map<string, JavaScriptSemanticScopeState>;
|
||||
/** Scope boundaries and descendant scopes resolved on demand. */
|
||||
readonly scopeByNode: WeakMap<t.Node, JavaScriptSemanticScopeState>;
|
||||
readonly bindingsById: Map<string, JavaScriptSemanticBindingState>;
|
||||
readonly callables: JavaScriptSemanticCallable[];
|
||||
@@ -94,7 +95,7 @@ export const resolveSemanticBindingState = (
|
||||
node: t.Node,
|
||||
name: string,
|
||||
): JavaScriptSemanticBindingState | undefined => {
|
||||
let scope = state.scopeByNode.get(node);
|
||||
let scope = semanticScopeForNode(state, node);
|
||||
while (scope !== undefined) {
|
||||
const binding = scope.bindings.get(name);
|
||||
if (binding !== undefined) return binding;
|
||||
@@ -113,7 +114,7 @@ export const semanticResolutionBlocked = (
|
||||
node: t.Node,
|
||||
name: string,
|
||||
): boolean => {
|
||||
let scope = state.scopeByNode.get(node);
|
||||
let scope = semanticScopeForNode(state, node);
|
||||
while (scope !== undefined) {
|
||||
if (scope.bindings.has(name)) return false;
|
||||
if (!scope.bindingsComplete) return true;
|
||||
@@ -125,6 +126,28 @@ export const semanticResolutionBlocked = (
|
||||
return false;
|
||||
};
|
||||
|
||||
const semanticScopeForNode = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
node: t.Node,
|
||||
): JavaScriptSemanticScopeState | undefined => {
|
||||
let candidate: t.Node | undefined = node;
|
||||
while (candidate !== undefined) {
|
||||
const scope = state.scopeByNode.get(candidate);
|
||||
if (scope !== undefined) {
|
||||
// Repeated references in a deep expression share this ancestry. Cache
|
||||
// the traversed path without eagerly indexing nodes never resolved.
|
||||
let descendant: t.Node | undefined = node;
|
||||
while (descendant !== undefined && descendant !== candidate) {
|
||||
state.scopeByNode.set(descendant, scope);
|
||||
descendant = state.parentsByNode.get(descendant);
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
candidate = state.parentsByNode.get(candidate);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
/** Resolve one name starting from an explicitly selected lexical scope. */
|
||||
export const resolveSemanticBindingFromScope = (
|
||||
scope: JavaScriptSemanticScopeState,
|
||||
|
||||
@@ -40,7 +40,7 @@ export const inspectBundlerRegistration = (
|
||||
const table = entry.elements[1];
|
||||
const runtimeValue = runtimeMetadata(entry.elements[2]);
|
||||
if (!t.isArrayExpression(chunkIds) || !t.isObjectExpression(table)) return;
|
||||
const recovered = recoverBundlerModules(source, table, accumulator);
|
||||
const recovered = recoverBundlerModules(source, table, runtime, accumulator);
|
||||
const chunkKeys = staticArrayValues(chunkIds);
|
||||
accumulator.unknownFindings += chunkKeys.unknown;
|
||||
accumulator.unknownFindings +=
|
||||
@@ -92,12 +92,13 @@ export const inspectEsbuildWrapper = (
|
||||
: null;
|
||||
const table = call.arguments[0];
|
||||
if (wrapperKind === null || !t.isObjectExpression(table)) return;
|
||||
const recovered = recoverBundlerModules(source, table, accumulator);
|
||||
const runtime = `esbuild-${wrapperKind}`;
|
||||
const recovered = recoverBundlerModules(source, table, runtime, accumulator);
|
||||
if (recovered.modules.length === 0) return;
|
||||
accumulator.unknownFindings += recovered.unknownAsyncChunkKeys;
|
||||
const registration: JavaScriptBundlerRegistration = {
|
||||
bundler: "esbuild",
|
||||
runtime: `esbuild-${wrapperKind}`,
|
||||
runtime,
|
||||
chunk_keys: [`${wrapperKind}@${String(call.start ?? 0)}`],
|
||||
unknown_chunk_keys: 0,
|
||||
runtime_require_name: null,
|
||||
@@ -127,13 +128,19 @@ interface RecoveredBundlerModules {
|
||||
const recoverBundlerModules = (
|
||||
source: string,
|
||||
table: t.ObjectExpression,
|
||||
runtime: string,
|
||||
accumulator: AnalysisAccumulator,
|
||||
): RecoveredBundlerModules => {
|
||||
const modules: JavaScriptBundlerModule[] = [];
|
||||
const asyncChunkKeys: string[] = [];
|
||||
let unknownAsyncChunkKeys = 0;
|
||||
for (const property of table.properties) {
|
||||
const recovered = recoverBundlerModule(source, property, accumulator);
|
||||
const recovered = recoverBundlerModule(
|
||||
source,
|
||||
property,
|
||||
runtime,
|
||||
accumulator,
|
||||
);
|
||||
if (recovered === null) continue;
|
||||
modules.push(recovered.module);
|
||||
asyncChunkKeys.push(...recovered.asyncChunkKeys);
|
||||
@@ -149,6 +156,7 @@ const recoverBundlerModules = (
|
||||
const recoverBundlerModule = (
|
||||
source: string,
|
||||
property: t.ObjectMethod | t.ObjectProperty | t.SpreadElement,
|
||||
runtime: string,
|
||||
accumulator: AnalysisAccumulator,
|
||||
): {
|
||||
readonly module: JavaScriptBundlerModule;
|
||||
@@ -169,6 +177,7 @@ const recoverBundlerModule = (
|
||||
start: factory.start,
|
||||
end: factory.end,
|
||||
key,
|
||||
runtime,
|
||||
requireName,
|
||||
};
|
||||
accumulator.moduleRangeIndex.add(moduleRange);
|
||||
|
||||
@@ -130,7 +130,11 @@ export const finalizeLocatedFindings = <
|
||||
values: readonly LocatedJavaScriptFinding<Value>[],
|
||||
modules: JavaScriptModuleRangeIndex,
|
||||
): Value[] =>
|
||||
values.map(({ offset, value }) => ({
|
||||
...value,
|
||||
module_key: modules.find(offset)?.key ?? null,
|
||||
}));
|
||||
values.map(({ offset, value }) => {
|
||||
const module = modules.find(offset);
|
||||
return {
|
||||
...value,
|
||||
module_key: module?.key ?? null,
|
||||
...(module === undefined ? {} : { module_runtime: module.runtime }),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -6,9 +6,27 @@ import { analyzeJavaScriptStaticSource } from "./javascriptStaticAnalysis.js";
|
||||
it("preserves first insertion precedence and inclusive interval bounds", () => {
|
||||
const nested = new JavaScriptModuleRangeIndex(100);
|
||||
expect(nested.find(0)).toBeUndefined();
|
||||
nested.add({ start: 10, end: 90, key: "outer-first", requireName: null });
|
||||
nested.add({ start: 20, end: 30, key: "inner-second", requireName: null });
|
||||
nested.add({ start: 30, end: 40, key: "later-overlap", requireName: null });
|
||||
nested.add({
|
||||
start: 10,
|
||||
end: 90,
|
||||
key: "outer-first",
|
||||
runtime: "webpackChunkApp",
|
||||
requireName: null,
|
||||
});
|
||||
nested.add({
|
||||
start: 20,
|
||||
end: 30,
|
||||
key: "inner-second",
|
||||
runtime: "webpackChunkApp",
|
||||
requireName: null,
|
||||
});
|
||||
nested.add({
|
||||
start: 30,
|
||||
end: 40,
|
||||
key: "later-overlap",
|
||||
runtime: "webpackChunkApp",
|
||||
requireName: null,
|
||||
});
|
||||
expect(nested.find(9)).toBeUndefined();
|
||||
expect(nested.find(10)?.key).toBe("outer-first");
|
||||
expect(nested.find(20)?.key).toBe("outer-first");
|
||||
@@ -20,7 +38,13 @@ it("preserves first insertion precedence and inclusive interval bounds", () => {
|
||||
|
||||
it("rejects missing and out-of-range lookup offsets", () => {
|
||||
const index = new JavaScriptModuleRangeIndex(20);
|
||||
index.add({ start: 5, end: 10, key: "bounded", requireName: null });
|
||||
index.add({
|
||||
start: 5,
|
||||
end: 10,
|
||||
key: "bounded",
|
||||
runtime: "webpackChunkApp",
|
||||
requireName: null,
|
||||
});
|
||||
expect(index.find(undefined)).toBeUndefined();
|
||||
expect(index.find(null)).toBeUndefined();
|
||||
expect(index.find(-1)).toBeUndefined();
|
||||
@@ -58,8 +82,11 @@ it("keeps module references attributed across many real factory ranges", () => {
|
||||
expect(
|
||||
analysis.references.find(
|
||||
({ specifier }) => specifier === `dependency-${index}`,
|
||||
)?.module_key,
|
||||
).toBe(`module-${index}`);
|
||||
),
|
||||
).toMatchObject({
|
||||
module_key: `module-${index}`,
|
||||
module_runtime: "webpackChunkApp",
|
||||
});
|
||||
}
|
||||
expect(
|
||||
analysis.references.find(
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface JavaScriptModuleRange {
|
||||
readonly start: number;
|
||||
readonly end: number;
|
||||
readonly key: string;
|
||||
readonly runtime: string;
|
||||
readonly requireName: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ interface JavaScriptStaticReferenceState {
|
||||
| "worker"
|
||||
| "service-worker";
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -41,6 +43,8 @@ export interface JavaScriptStaticEndpoint {
|
||||
readonly value: string;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -55,6 +59,8 @@ export interface JavaScriptStaticStorage {
|
||||
readonly name: string | null;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
@@ -95,6 +101,8 @@ export interface JavaScriptRolePath {
|
||||
readonly resolution_context: JavaScriptStaticPathContext;
|
||||
readonly mechanism: string;
|
||||
readonly module_key: string | null;
|
||||
/** Recovered factory runtime; absent in older or unbundled findings. */
|
||||
readonly module_runtime?: string;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
|
||||
+47
-38
@@ -33,6 +33,15 @@ export const jsonShapeSchema = z.object({
|
||||
});
|
||||
export type JsonShape = z.infer<typeof jsonShapeSchema>;
|
||||
|
||||
const arrayElementKey = Symbol("array-element");
|
||||
|
||||
interface ShapeNode {
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly types: Set<JsonValueType>;
|
||||
observations: number;
|
||||
children?: Map<string | typeof arrayElementKey, ShapeNode>;
|
||||
}
|
||||
|
||||
/** Parse approved JSON and immediately discard values after iterative shape inference. */
|
||||
export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
let root: unknown;
|
||||
@@ -43,48 +52,52 @@ export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
void cause;
|
||||
return null;
|
||||
}
|
||||
const properties = new Map<
|
||||
string,
|
||||
{
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly types: Set<JsonValueType>;
|
||||
observations: number;
|
||||
}
|
||||
>();
|
||||
const properties: ShapeNode[] = [];
|
||||
const rootShape: ShapeNode = {
|
||||
path: [],
|
||||
types: new Set(),
|
||||
observations: 0,
|
||||
};
|
||||
// Each structural path owns one accumulator, shared by all matching array rows.
|
||||
const childShape = (
|
||||
parent: ShapeNode,
|
||||
key: string | typeof arrayElementKey,
|
||||
): ShapeNode => {
|
||||
const children = (parent.children ??= new Map());
|
||||
const existing = children.get(key);
|
||||
if (existing !== undefined) return existing;
|
||||
const node: ShapeNode = {
|
||||
path: [
|
||||
...parent.path,
|
||||
typeof key === "string"
|
||||
? { kind: "property", name: key }
|
||||
: { kind: "array-element" },
|
||||
],
|
||||
types: new Set(),
|
||||
observations: 0,
|
||||
};
|
||||
children.set(key, node);
|
||||
properties.push(node);
|
||||
return node;
|
||||
};
|
||||
const pending: Array<{
|
||||
readonly value: unknown;
|
||||
readonly path: JsonShapePathSegment[];
|
||||
readonly depth: number;
|
||||
}> = [{ value: root, path: [], depth: 0 }];
|
||||
readonly shape: ShapeNode;
|
||||
}> = [{ value: root, shape: rootShape }];
|
||||
let nodeCount = 0;
|
||||
let maxDepthObserved = 0;
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (current === undefined) break;
|
||||
nodeCount += 1;
|
||||
maxDepthObserved = Math.max(maxDepthObserved, current.depth);
|
||||
if (current.path.length > 0) {
|
||||
const key = JSON.stringify(current.path);
|
||||
const type = jsonValueType(current.value);
|
||||
const existing = properties.get(key);
|
||||
if (existing === undefined)
|
||||
properties.set(key, {
|
||||
path: current.path,
|
||||
types: new Set([type]),
|
||||
observations: 1,
|
||||
});
|
||||
else {
|
||||
existing.types.add(type);
|
||||
existing.observations += 1;
|
||||
}
|
||||
}
|
||||
maxDepthObserved = Math.max(maxDepthObserved, current.shape.path.length);
|
||||
current.shape.types.add(jsonValueType(current.value));
|
||||
current.shape.observations += 1;
|
||||
if (Array.isArray(current.value)) {
|
||||
if (current.value.length === 0) continue;
|
||||
const shape = childShape(current.shape, arrayElementKey);
|
||||
for (let index = current.value.length - 1; index >= 0; index -= 1)
|
||||
pending.push({
|
||||
value: current.value[index],
|
||||
path: [...current.path, { kind: "array-element" }],
|
||||
depth: current.depth + 1,
|
||||
});
|
||||
pending.push({ value: current.value[index], shape });
|
||||
continue;
|
||||
}
|
||||
if (!isRecord(current.value)) continue;
|
||||
@@ -93,18 +106,14 @@ export const inferJsonShape = (text: string): JsonShape | null => {
|
||||
const entry = allEntries[index];
|
||||
if (entry === undefined) continue;
|
||||
const [name, value] = entry;
|
||||
const path: JsonShapePathSegment[] = [
|
||||
...current.path,
|
||||
{ kind: "property", name },
|
||||
];
|
||||
pending.push({ value, path, depth: current.depth + 1 });
|
||||
pending.push({ value, shape: childShape(current.shape, name) });
|
||||
}
|
||||
}
|
||||
return jsonShapeSchema.parse({
|
||||
root_type: jsonValueType(root),
|
||||
node_count: nodeCount,
|
||||
max_depth_observed: maxDepthObserved,
|
||||
properties: [...properties.values()]
|
||||
properties: properties
|
||||
.map((value) => ({
|
||||
path: value.path,
|
||||
types: [...value.types].sort(),
|
||||
|
||||
@@ -134,6 +134,7 @@ export const projectManagedApplicationGraph = (
|
||||
const parsed = parseManagedInputs(input);
|
||||
const artifactIdentity = chooseArtifact(parsed);
|
||||
assertSameArtifact(parsed, artifactIdentity.sha256);
|
||||
assertConsistentModuleIdentity(parsed);
|
||||
const evidenceLinks = [
|
||||
parsed.artifact?.evidence.evidence_id,
|
||||
parsed.members?.evidence.evidence_id,
|
||||
@@ -258,6 +259,52 @@ const assertSameArtifact = (
|
||||
);
|
||||
};
|
||||
|
||||
/** Reject contradictory known module identities while leaving null fields unknown. */
|
||||
const assertConsistentModuleIdentity = (
|
||||
parsed: ParsedManagedGraphInput,
|
||||
): void => {
|
||||
const mvidClaims = [
|
||||
parsed.artifact?.result.module?.mvid,
|
||||
parsed.members?.result.module?.mvid,
|
||||
parsed.members?.result.identity_scope.requires_mvid,
|
||||
parsed.boundaries?.result.module?.mvid,
|
||||
parsed.boundaries?.result.identity_scope.requires_mvid,
|
||||
]
|
||||
.filter((mvid): mvid is string => mvid !== undefined && mvid !== null)
|
||||
.map((mvid) => mvid.toLowerCase());
|
||||
if (new Set(mvidClaims).size > 1)
|
||||
throw new TypeError(
|
||||
"Managed graph inputs report conflicting known module MVIDs or token scopes",
|
||||
);
|
||||
|
||||
const modules = [
|
||||
parsed.artifact?.result.module,
|
||||
parsed.members?.result.module,
|
||||
parsed.boundaries?.result.module,
|
||||
].filter(
|
||||
(module): module is NonNullable<ManagedArtifactInspection["module"]> =>
|
||||
module !== undefined && module !== null,
|
||||
);
|
||||
for (const field of ["name", "generation", "token", "row_offset"] as const) {
|
||||
const values = new Set(modules.map((module) => module[field]));
|
||||
if (values.size > 1)
|
||||
throw new TypeError(
|
||||
`Managed graph inputs report conflicting module ${field} values`,
|
||||
);
|
||||
}
|
||||
for (const field of ["enc_id", "enc_base_id"] as const) {
|
||||
const values = new Set(
|
||||
modules
|
||||
.map((module) => module[field]?.toLowerCase())
|
||||
.filter((value): value is string => value !== undefined),
|
||||
);
|
||||
if (values.size > 1)
|
||||
throw new TypeError(
|
||||
`Managed graph inputs report conflicting module ${field} values`,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const omittedCounts = (parsed: ParsedManagedGraphInput) =>
|
||||
assessManagedGraphOmissions({
|
||||
artifact: parsed.artifact?.result ?? null,
|
||||
@@ -288,4 +335,9 @@ const projectionLimitations = (
|
||||
...(omissions.partialInput
|
||||
? ["At least one supplied managed Evidence record has partial coverage."]
|
||||
: []),
|
||||
...(omissions.unscopedTokenRelationships
|
||||
? [
|
||||
"Managed boundary tokens were not linked to member nodes because matching module MVID scope was not established.",
|
||||
]
|
||||
: []),
|
||||
];
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
ManagedMemberInspection,
|
||||
ManagedNativeBoundaryInspection,
|
||||
} from "./managedArtifact.js";
|
||||
import { managedTokenScopesMatch } from "./managedInspectionEvidence.js";
|
||||
|
||||
type ManagedCoverageState = "complete" | "partial" | "unavailable";
|
||||
|
||||
@@ -17,6 +18,7 @@ export interface ManagedGraphCoverageSources {
|
||||
/** Whether any supplied source has incomplete coverage. */
|
||||
export interface ManagedGraphProjectionOmissions {
|
||||
readonly partialInput: boolean;
|
||||
readonly unscopedTokenRelationships: boolean;
|
||||
}
|
||||
|
||||
const completeCoverage = (): ApplicationGraphEvidence["coverage"] => ({
|
||||
@@ -43,6 +45,17 @@ export const managedSourceCoverage = (
|
||||
export const assessManagedGraphOmissions = (
|
||||
sources: ManagedGraphCoverageSources,
|
||||
): ManagedGraphProjectionOmissions => ({
|
||||
unscopedTokenRelationships:
|
||||
sources.members !== null &&
|
||||
sources.boundaries !== null &&
|
||||
(sources.boundaries.pinvoke_imports.some(
|
||||
({ member_token }) => member_token !== null,
|
||||
) ||
|
||||
sources.boundaries.native_implementations.length > 0) &&
|
||||
!managedTokenScopesMatch(
|
||||
sources.members.identity_scope.requires_mvid,
|
||||
sources.boundaries.identity_scope.requires_mvid,
|
||||
),
|
||||
partialInput: [
|
||||
sources.members?.coverage.state,
|
||||
sources.boundaries?.coverage.state,
|
||||
@@ -54,7 +67,7 @@ export const assessManagedGraphOmissions = (
|
||||
export const managedGraphEvidenceCoverage = (
|
||||
omissions: ManagedGraphProjectionOmissions,
|
||||
): ApplicationGraphEvidence["coverage"] =>
|
||||
omissions.partialInput
|
||||
omissions.partialInput || omissions.unscopedTokenRelationships
|
||||
? {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
@@ -67,7 +80,8 @@ export const managedGraphEvidenceCoverage = (
|
||||
export const managedGraphResultCoverage = (
|
||||
omissions: ManagedGraphProjectionOmissions,
|
||||
) => ({
|
||||
status: omissions.partialInput
|
||||
? ("partial" as const)
|
||||
: ("complete-within-inputs" as const),
|
||||
status:
|
||||
omissions.partialInput || omissions.unscopedTokenRelationships
|
||||
? ("partial" as const)
|
||||
: ("complete-within-inputs" as const),
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { ApplicationGraphEvidence } from "../javascript/javascriptApplicati
|
||||
import type { ApplicationNode } from "../javascript/javascriptApplicationGraphSchemas.js";
|
||||
import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js";
|
||||
import type { Evidence } from "../evidence.js";
|
||||
import { managedTokenScopesMatch } from "./managedInspectionEvidence.js";
|
||||
import {
|
||||
type ManagedArtifactInspection,
|
||||
type ManagedMemberInspection,
|
||||
@@ -106,7 +107,7 @@ export const addArtifactIdentityNodes = (
|
||||
identity: artifactLocalIdentity(
|
||||
state.artifactSha256,
|
||||
"managed-module",
|
||||
module.mvid ?? module.token,
|
||||
module.mvid?.toLowerCase() ?? module.token,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
@@ -138,25 +139,32 @@ interface ManagedModuleSource {
|
||||
const selectModuleSource = (
|
||||
parsed: ParsedManagedGraphInput,
|
||||
): ManagedModuleSource | null => {
|
||||
if (parsed.artifact?.result.module != null)
|
||||
return {
|
||||
module: parsed.artifact.result.module,
|
||||
evidence: parsed.artifact.evidence,
|
||||
coverageState: parsed.artifact.result.coverage.state,
|
||||
};
|
||||
if (parsed.members?.result.module != null)
|
||||
return {
|
||||
module: parsed.members.result.module,
|
||||
evidence: parsed.members.evidence,
|
||||
coverageState: parsed.members.result.coverage.state,
|
||||
};
|
||||
if (parsed.boundaries?.result.module != null)
|
||||
return {
|
||||
module: parsed.boundaries.result.module,
|
||||
evidence: parsed.boundaries.evidence,
|
||||
coverageState: parsed.boundaries.result.coverage.state,
|
||||
};
|
||||
return null;
|
||||
const sources = [
|
||||
parsed.artifact?.result.module == null
|
||||
? null
|
||||
: {
|
||||
module: parsed.artifact.result.module,
|
||||
evidence: parsed.artifact.evidence,
|
||||
coverageState: parsed.artifact.result.coverage.state,
|
||||
},
|
||||
parsed.members?.result.module == null
|
||||
? null
|
||||
: {
|
||||
module: parsed.members.result.module,
|
||||
evidence: parsed.members.evidence,
|
||||
coverageState: parsed.members.result.coverage.state,
|
||||
},
|
||||
parsed.boundaries?.result.module == null
|
||||
? null
|
||||
: {
|
||||
module: parsed.boundaries.result.module,
|
||||
evidence: parsed.boundaries.evidence,
|
||||
coverageState: parsed.boundaries.result.coverage.state,
|
||||
},
|
||||
].filter((source): source is ManagedModuleSource => source !== null);
|
||||
return (
|
||||
sources.find(({ module }) => module.mvid !== null) ?? sources[0] ?? null
|
||||
);
|
||||
};
|
||||
|
||||
/** Add managed type, method, and field nodes from member evidence. */
|
||||
@@ -332,11 +340,17 @@ export const addBoundaryNodes = (
|
||||
boundaryInput.evidence,
|
||||
boundaries.coverage.state,
|
||||
);
|
||||
const canJoinMemberTokens =
|
||||
parsed.members !== null &&
|
||||
managedTokenScopesMatch(
|
||||
parsed.members.result.identity_scope.requires_mvid,
|
||||
boundaries.identity_scope.requires_mvid,
|
||||
);
|
||||
for (const pinvoke of pinvokes) {
|
||||
const node = pinvokeNode(state, pinvoke, sourceEvidence);
|
||||
state.nodes.push(node);
|
||||
const method =
|
||||
pinvoke.member_token === null
|
||||
pinvoke.member_token === null || !canJoinMemberTokens
|
||||
? undefined
|
||||
: state.methodNodes.get(pinvoke.member_token);
|
||||
const memberEvidence =
|
||||
@@ -370,7 +384,10 @@ export const addBoundaryNodes = (
|
||||
sourceEvidence,
|
||||
);
|
||||
state.nodes.push(node);
|
||||
const owner = state.methodNodes.get(implementation.token) ?? artifactNode;
|
||||
const owner =
|
||||
(canJoinMemberTokens
|
||||
? state.methodNodes.get(implementation.token)
|
||||
: undefined) ?? artifactNode;
|
||||
addContainsEdge(state, owner, node, {
|
||||
kind: "declares-managed-native-implementation",
|
||||
coverage: implementationCoverage,
|
||||
|
||||
@@ -1,12 +1,28 @@
|
||||
import { parseEvidence, type Evidence } from "../evidence.js";
|
||||
import type { z } from "zod";
|
||||
|
||||
/** Build-local metadata tokens join only under a known, matching module MVID. */
|
||||
export const managedTokenScopesMatch = (
|
||||
leftMvid: string | null,
|
||||
rightMvid: string | null,
|
||||
): boolean =>
|
||||
leftMvid !== null &&
|
||||
rightMvid !== null &&
|
||||
leftMvid.toLowerCase() === rightMvid.toLowerCase();
|
||||
|
||||
/**
|
||||
* Parse managed inspection Evidence and bind its artifact to any available subject.
|
||||
* A null subject remains valid and means there is no digest to cross-check.
|
||||
*/
|
||||
export const parseManagedInspectionEvidence = <
|
||||
Result extends { readonly artifact: { readonly sha256: string } },
|
||||
Result extends {
|
||||
readonly artifact: { readonly sha256: string };
|
||||
readonly identity_scope?: {
|
||||
readonly requires_artifact_sha256: string;
|
||||
readonly requires_mvid: string | null;
|
||||
};
|
||||
readonly module?: { readonly mvid: string | null } | null;
|
||||
},
|
||||
>(
|
||||
rawEvidence: unknown,
|
||||
operation: string,
|
||||
@@ -22,5 +38,20 @@ export const parseManagedInspectionEvidence = <
|
||||
throw new TypeError(
|
||||
`Managed Evidence ${operation} (${evidence.evidence_id}) subject SHA-256 ${subjectSha256} does not match normalized artifact SHA-256 ${artifactSha256}`,
|
||||
);
|
||||
const scope = result.identity_scope;
|
||||
if (scope !== undefined && scope.requires_artifact_sha256 !== artifactSha256)
|
||||
throw new TypeError(
|
||||
`Managed Evidence ${operation} (${evidence.evidence_id}) token scope SHA-256 ${scope.requires_artifact_sha256} does not match normalized artifact SHA-256 ${artifactSha256}`,
|
||||
);
|
||||
if (
|
||||
scope?.requires_mvid !== undefined &&
|
||||
scope.requires_mvid !== null &&
|
||||
result.module?.mvid !== undefined &&
|
||||
result.module.mvid !== null &&
|
||||
scope.requires_mvid.toLowerCase() !== result.module.mvid.toLowerCase()
|
||||
)
|
||||
throw new TypeError(
|
||||
`Managed Evidence ${operation} (${evidence.evidence_id}) token scope MVID ${scope.requires_mvid} does not match module MVID ${result.module.mvid}`,
|
||||
);
|
||||
return { evidence, result };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseProcessScenario,
|
||||
PROCESS_TERMINAL_CELL_BUDGET,
|
||||
processScenarioSchema,
|
||||
} from "./processScenario.js";
|
||||
|
||||
it("admits the default and the exact combined terminal-cell budget", () => {
|
||||
expect(parseProcessScenario({ executable: "/bin/true" }).terminal).toEqual({
|
||||
columns: 80,
|
||||
rows: 24,
|
||||
scrollback: 1_000,
|
||||
});
|
||||
|
||||
expect(
|
||||
processScenarioSchema.safeParse({
|
||||
executable: "/bin/true",
|
||||
terminal: {
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
scrollback: PROCESS_TERMINAL_CELL_BUDGET - 1,
|
||||
},
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an oversized initial buffer without clamping caller dimensions", () => {
|
||||
const input = {
|
||||
executable: "/bin/true",
|
||||
terminal: { columns: 1_000, rows: 1, scrollback: 1_000 },
|
||||
};
|
||||
const parsed = processScenarioSchema.safeParse(input);
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected terminal capacity rejection");
|
||||
expect(parsed.error.issues).toContainEqual(
|
||||
expect.objectContaining({
|
||||
code: "custom",
|
||||
path: ["terminal"],
|
||||
message: expect.stringContaining(
|
||||
`${String(PROCESS_TERMINAL_CELL_BUDGET)} renderer cells`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("applies the selected scrollback budget to every scheduled resize", () => {
|
||||
const parsed = processScenarioSchema.safeParse({
|
||||
executable: "/bin/true",
|
||||
events: [{ type: "resize", at_ms: 10, columns: 1_000, rows: 1 }],
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (parsed.success) throw new Error("expected resize capacity rejection");
|
||||
expect(parsed.error.issues).toContainEqual(
|
||||
expect.objectContaining({
|
||||
code: "custom",
|
||||
path: ["events", 0],
|
||||
message: expect.stringContaining("resize event at 10 ms"),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(
|
||||
processScenarioSchema.safeParse({
|
||||
executable: "/bin/true",
|
||||
terminal: { columns: 1, rows: 1, scrollback: 0 },
|
||||
events: [{ type: "resize", at_ms: 10, columns: 1_000, rows: 1 }],
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
const positiveBudget = z.number().int().safe().positive();
|
||||
/**
|
||||
* Maximum xterm backing cells for one visible-plus-scrollback buffer. Each
|
||||
* xterm BufferLine stores three Uint32 words per cell (12 MB at this cap),
|
||||
* before row objects, serialization strings, and retained frame copies.
|
||||
*/
|
||||
export const PROCESS_TERMINAL_CELL_BUDGET = 1_000_000;
|
||||
const timedEventBase = { at_ms: z.number().int().safe().nonnegative() };
|
||||
const reservedRunIdEnvironmentName = "REA_PROCESS_RUN_ID";
|
||||
const ENVIRONMENT_NAME_CHARACTER = "[^=\\x00]";
|
||||
@@ -41,6 +47,14 @@ const childProcessString = z
|
||||
/^[^\x00]*$/u,
|
||||
"Values passed to operating-system APIs cannot contain NUL",
|
||||
);
|
||||
|
||||
const fitsProcessTerminalCellBudget = (
|
||||
columns: number,
|
||||
rows: number,
|
||||
scrollback: number,
|
||||
): boolean =>
|
||||
rows + scrollback <= Math.floor(PROCESS_TERMINAL_CELL_BUDGET / columns);
|
||||
|
||||
export const normalizationSchema = z.object({
|
||||
paths: z.boolean(),
|
||||
pids: z.boolean(),
|
||||
@@ -131,8 +145,11 @@ export const processScenarioSchema = z
|
||||
.strictObject({
|
||||
columns: z.number().int().min(1).max(65_535).default(80),
|
||||
rows: z.number().int().min(1).max(65_535).default(24),
|
||||
scrollback: z.number().int().min(0).default(1_000),
|
||||
scrollback: z.number().int().safe().nonnegative().default(1_000),
|
||||
})
|
||||
.describe(
|
||||
"The visible terminal and scrollback together must use at most 1,000,000 xterm renderer cells: columns × (rows + scrollback). Resize events use the same scrollback and limit.",
|
||||
)
|
||||
.default({ columns: 80, rows: 24, scrollback: 1_000 }),
|
||||
events: z
|
||||
.array(
|
||||
@@ -204,6 +221,18 @@ export const processScenarioSchema = z
|
||||
}),
|
||||
})
|
||||
.superRefine((scenario, context) => {
|
||||
if (
|
||||
!fitsProcessTerminalCellBudget(
|
||||
scenario.terminal.columns,
|
||||
scenario.terminal.rows,
|
||||
scenario.terminal.scrollback,
|
||||
)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["terminal"],
|
||||
message: `terminal columns × (rows + scrollback) must not exceed ${String(PROCESS_TERMINAL_CELL_BUDGET)} renderer cells`,
|
||||
});
|
||||
for (let index = 1; index < scenario.events.length; index += 1) {
|
||||
const event = scenario.events[index];
|
||||
const previous = scenario.events[index - 1];
|
||||
@@ -215,7 +244,20 @@ export const processScenarioSchema = z
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const event of scenario.events) {
|
||||
for (const [index, event] of scenario.events.entries()) {
|
||||
if (
|
||||
event.type === "resize" &&
|
||||
!fitsProcessTerminalCellBudget(
|
||||
event.columns,
|
||||
event.rows,
|
||||
scenario.terminal.scrollback,
|
||||
)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["events", index],
|
||||
message: `resize event at ${String(event.at_ms)} ms exceeds the ${String(PROCESS_TERMINAL_CELL_BUDGET)}-cell renderer budget with the selected scrollback`,
|
||||
});
|
||||
if (event.at_ms > scenario.timeout_ms) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
|
||||
@@ -3,6 +3,9 @@ export type FixtureCorrectness = "passed" | "failed" | "not_assessed";
|
||||
|
||||
/** Measurements consumed by the evaluation runner's release gate. */
|
||||
export interface AgentEvaluationGateResult {
|
||||
/** Explicit null requires a target clarification with no REA calls. */
|
||||
readonly expectedFirstTool?: string | null;
|
||||
readonly targetClarificationPassed?: boolean;
|
||||
readonly exitCode: number;
|
||||
readonly naturalUse: boolean;
|
||||
readonly correctFirstTool: boolean;
|
||||
@@ -20,16 +23,20 @@ export const agentEvaluationPassed = (
|
||||
result: AgentEvaluationGateResult,
|
||||
): boolean =>
|
||||
result.exitCode === 0 &&
|
||||
result.naturalUse &&
|
||||
(result.expectedFirstTool === null
|
||||
? !result.naturalUse
|
||||
: result.naturalUse) &&
|
||||
result.correctFirstTool &&
|
||||
result.repeatedCallCount === 0 &&
|
||||
result.inputValidationFailureCount === 0 &&
|
||||
result.requiredToolSubsequenceMet &&
|
||||
result.inputTokens > 0 &&
|
||||
(result.factualCorrectness === "passed" ||
|
||||
(result.factualCorrectness === "not_assessed" &&
|
||||
result.answerHeuristicsMet &&
|
||||
result.epistemicCuePresent));
|
||||
(result.expectedFirstTool === null
|
||||
? result.targetClarificationPassed === true
|
||||
: result.factualCorrectness === "passed" ||
|
||||
(result.factualCorrectness === "not_assessed" &&
|
||||
result.answerHeuristicsMet &&
|
||||
result.epistemicCuePresent));
|
||||
|
||||
/** Keep assessed fixture outcomes and scenarios without truth oracles distinct. */
|
||||
export const summarizeFactualCorrectness = (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user