mirror of
https://github.com/morluto/rea.git
synced 2026-11-30 18:39:24 +00:00
910 lines
59 KiB
Markdown
910 lines
59 KiB
Markdown
# MCP tool design
|
|
|
|
## Decide whether to add a tool
|
|
|
|
Design around the analyst question. Inspect the current canonical contracts,
|
|
provider capabilities, and nearest existing tool before changing the surface.
|
|
Extend a tool when intent and result contract match; add one for a distinct
|
|
outcome or materially different authority. Public names and semantics remain
|
|
provider-neutral, with exact coverage reported per provider.
|
|
|
|
Keep the discoverable inventory complete within the caller's selected scope;
|
|
report capability/session availability independently of catalog visibility.
|
|
An opt-in dynamic catalog must retain canonical named contracts and provide
|
|
discovery and recovery for clients without refresh. Serialized bytes alone do
|
|
not establish agent usability.
|
|
|
|
## Choose the tool shape
|
|
|
|
| Shape | Use it for | Result |
|
|
| --------------------- | ------------------------------------------- | ------------------------------------------------------------------------- |
|
|
| `inspect` | Facts about one target, object, or resource | Relevant fields, locations, and facet availability |
|
|
| `search` / `list` | Candidate discovery | Stable ordering and context; pagination when the query or format needs it |
|
|
| `trace` | Relationships across evidence | Typed edges, supporting facts, and unresolved paths |
|
|
| `compare` | Explicitly paired artifacts or observations | Identity, comparable coverage, and supported deltas |
|
|
| `workflow` | A recurring outcome needing composition | Inline answer, contributing evidence, and partial facets |
|
|
| `observe` / `capture` | Runtime behavior | Authority, launch/attach effects, lifecycle, and cleanup status |
|
|
|
|
These are task shapes, not mandatory prefixes. Name tools for the action and
|
|
object callers reason about. Avoid unrelated discovery/execution/mutation modes
|
|
inside one tool.
|
|
|
|
## Prefer primitives; compose workflows
|
|
|
|
A primitive reports a reusable fact about an identified object or relationship.
|
|
A format-specific decoder qualifies; one application's business interpretation
|
|
belongs outside the general contract. The format owner reports source
|
|
observations and structural validation; the application or workflow owner
|
|
applies use-case-specific admission policy without reinterpreting raw fields.
|
|
For example, DOS MZ structure and Windows-header evidence stay separate, while
|
|
target resolution decides whether the unresolved header permits admission.
|
|
Expose provider APIs when they add a useful capability that existing tools
|
|
cannot express.
|
|
|
|
Compose a workflow when repeated use demonstrates a multi-source outcome REA
|
|
can join without hiding caller choices or uncertainty. Batch homogeneous reads
|
|
when that removes repeated work while preserving per-item outcomes. Keep prompts
|
|
optional and avoid prescribing call sequences that a direct tool can replace.
|
|
|
|
Agents can compose experiments with ordinary commands, scripts, and local
|
|
fixture servers. Custom orchestration languages, replay engines, or separate
|
|
prepare/execute plans need an observed requirement those primitives cannot
|
|
satisfy. A plan without execution does not establish runtime behavior.
|
|
|
|
## Exercise the analyst workflow
|
|
|
|
Before defining a new provider-backed tool, state the analyst's question, what
|
|
they already have, the intended result and authority, and what must stay
|
|
unknown. Try the nearest REA workflow, then the native provider or a plain
|
|
script. Name the gap and what a new or extended contract adds. An upstream
|
|
capability alone does not justify a new tool or equal support on every
|
|
provider.
|
|
|
|
Use the caller's selected target and authority. Follow
|
|
[provider-backed workflow verification](testing.md#provider-backed-workflow-verification)
|
|
for independent observations, boundary controls and reporting unavailable
|
|
provider coverage. A scripted tool sequence does not establish agent selection;
|
|
that claim requires an actual agent evaluation.
|
|
|
|
## Audit existing tools
|
|
|
|
Scope an audit by analyst tasks, not by counting upstream commands.
|
|
|
|
- **Record what you ran.** Note the source revision and, when used, the running
|
|
server, catalog and provider versions; a connected server can differ from the
|
|
checkout.
|
|
- **Check the live surface.** Read the CLI help or MCP descriptions and schemas,
|
|
rendered prompts, guided workflows and skill advice in the versions in use.
|
|
Compare them with the owning contracts and docs.
|
|
- **Follow the handoffs.** Check source identity, session lifetime and
|
|
alternatives between producer and consumer against the live contracts.
|
|
Matching text in two renderers does not prove the advice is correct.
|
|
- **Start from first contact.** Begin each task with the call an agent makes on
|
|
an unfamiliar target, and check routing as well as the final answer.
|
|
- **Use real public artifacts as well as synthetic ones.** See
|
|
[public-corpus checks](testing.md#public-corpus-checks).
|
|
- **Verify before and after.** Use
|
|
[workflow verification](testing.md#provider-backed-workflow-verification) for
|
|
returned facts, partial outcomes, recovery and provider scope.
|
|
|
|
Report working routes as well as findings. Separate a reproduced contract bug,
|
|
an intentional limitation, a design opportunity and an unverified hypothesis,
|
|
with the smallest useful reproduction, impact and coverage limits. A scripted
|
|
trace does not show which tool an agent would choose. Check related reports
|
|
first, and don't treat a lack of API parity as a bug.
|
|
|
|
### Write descriptions for selection and a valid first call
|
|
|
|
Start with the analyst task, selected source and useful result. Put material
|
|
effects and the deciding boundary between neighboring tools early. Progressive
|
|
discovery previews the first 240 characters, so those characters should identify
|
|
the operation without requiring the rest of its reference documentation.
|
|
|
|
Keep exact call syntax where the advertised schema cannot convey it. The compact
|
|
input profile strips most annotation prose and can reduce nested controls to
|
|
`{type: "object"}`. Moving selectors into parameter descriptions alone does not
|
|
make them available to those clients. For example, retained pseudocode needs
|
|
both `source.kind: "retained-evidence"` and `view: {kind: "native", facet:
|
|
"pseudocode"}`; a short exact example can be more useful than many paragraphs.
|
|
Use the producer's handoff for other supported views rather than maintaining
|
|
another supposedly exhaustive list in the shared consumer description.
|
|
|
|
Make an input refusal teach the rule it applies. Below the first level the
|
|
compact profile keeps no refinement, `pattern`, `not` or description, so a
|
|
nested rule reaches the agent only when a call is refused. Report the issue
|
|
at the field path, and state the rule and the accepted form in one sentence,
|
|
as in `A page's fetch cannot set Sec-Trace: names starting with Proxy- or Sec-
|
|
are reserved for the browser.` A bare `Invalid value` costs another round trip.
|
|
Do not echo a refused value that may carry a secret, such as a URL or an
|
|
endpoint identifier. Restating the rule in the tool description costs tokens
|
|
on every listing; do that only for a rule most calls need.
|
|
|
|
Keep configuration tutorials and detailed matching algorithms with their owning
|
|
parameter contracts, product guides and actionable failures. Retain applicability,
|
|
source identity, uncertainty, authority and cleanup facts needed to choose or
|
|
safely continue the operation. An unresolved symbol lookup is not a completed
|
|
reference search; an exhausted page does not establish absence in unexamined
|
|
source. Shorter copy must preserve these distinctions.
|
|
|
|
For wording changes, use a small set of representative agent tasks at the affected
|
|
boundaries. Hold schemas, tool order, fixtures and host configuration fixed when
|
|
comparing copy; add repetitions only for failures or ambiguous outcomes. Score
|
|
actual arguments, corrective calls and supported final claims separately. A
|
|
correct eventual answer can conceal malformed-call loops, while a valid call
|
|
can still produce an overstated answer. Report whole-task usage, including
|
|
retries and cached input, rather than treating fewer description bytes as proof
|
|
of lower token cost.
|
|
|
|
## Route first contact by parsed facts
|
|
|
|
The first call on an unfamiliar target decides whether an agent finds the right
|
|
tool. Treat a dead end there as a defect.
|
|
|
|
- **Return facts, not a bare refusal.** For an unrecognised input, return what
|
|
is known: size, digest, leading bytes and any bounded signature candidates.
|
|
Keep `unrecognised`, `malformed` and `unsupported` distinct.
|
|
- **Recognise every format a dedicated tool parses.** If REA can read a format,
|
|
first-contact inspection names that tool instead of rejecting the file.
|
|
- **Derive next probes from the owner's parsed facts.** Rank them and list only
|
|
operations that apply. A file can be several things at once, such as an
|
|
executable that carries a package; report each reading in a useful order
|
|
rather than hiding one.
|
|
- **Never fall back silently to another lane.** A workflow that finds none of
|
|
its inputs says so and names what it did find, as counts, instead of
|
|
returning an empty success.
|
|
- **Skip checks that cannot apply.** A format-gated check that cannot apply to
|
|
the detected format is omitted, not reported as `not_applicable` with a
|
|
next probe for another format.
|
|
|
|
## Design recovery around the failure
|
|
|
|
Distinguish a request that violates its input contract from a valid selection
|
|
that the current target, provider inventory, or project cannot resolve. The
|
|
same `invalid_request` code can represent either. Suggest schema inspection
|
|
only when the input contract is the problem; for a valid lookup, preserve the
|
|
caller's exact selector, the observed reason and any candidates, and give a
|
|
next step that addresses that outcome. An inventory miss does not prove that
|
|
the artifact lacks the requested item.
|
|
|
|
Malformed or unsupported target bytes are a target problem, not a request
|
|
problem. Report them in the target category, with recovery that names another
|
|
target or operation. A selector that resolves to the wrong kind of object, such
|
|
as an import slot passed where a procedure is expected, reports what it
|
|
resolved to and names the operations that answer it on that provider.
|
|
|
|
For prerequisite failures, identify what the requested operation actually needs.
|
|
A missing executable, a wrong path, an incompatible host or version, denied
|
|
permission, and a download timeout need different repairs. Preserve the observed
|
|
failure instead of calling all of them "not installed".
|
|
|
|
Derive the required engine from the operation's execution contract. For example,
|
|
`inspect_firmware_regions` needs Binwalk; `extract_firmware` needs Unblob.
|
|
Configuring the other tool cannot enable the requested operation. An installed
|
|
JDK outside the selected PATH may need `JAVA_HOME`, not another installation.
|
|
Say where a setting must change: a shell export does not change an already
|
|
running MCP server's environment.
|
|
|
|
Keep repair instructions with the contract that owns the failure, and preserve
|
|
them through provider readiness, capability discovery, doctor and CLI/MCP output.
|
|
An error description is not a repair instruction. Do not make each consumer
|
|
guess the fix from diagnostic text or invent another list of prerequisites.
|
|
|
|
Keep recovery within the selected target, provider, project and authority. If
|
|
another context could help, describe it as an explicit choice and state any
|
|
relevant loss of state; do not switch or select a candidate automatically.
|
|
Preserve uncertainty, partial observations, and session or cleanup state. A
|
|
suggested retry must be safe and explain any required change or wait.
|
|
`retryable` claims only an idempotent retry. If a timed-out or cancelled
|
|
operation may already have taken effect, say so instead of offering a blind
|
|
retry.
|
|
|
|
Verify recovery through the public workflow: reproduce the failure, follow
|
|
the suggested next step when feasible, and check the result and session state.
|
|
Include a malformed-input control so schema guidance remains available when it
|
|
is actually needed. Compare CLI and MCP when both expose the operation.
|
|
|
|
For each confirmed bug, check sibling adapters and other consumers of the same
|
|
facts. Reproduce suspected matches and retain a working comparison where one
|
|
exists. Group reports and fixes around the shared cause; similar wording alone
|
|
does not establish another instance.
|
|
|
|
## Define the contract
|
|
|
|
- Use strict inputs with explicit target identity and required fields. Preserve
|
|
meaningful target, action, capture, and output choices; remove ignored options
|
|
and repeated permission declarations.
|
|
One-shot binary CLI analysis retains the caller's verbatim target spelling in
|
|
Evidence `caller_input_path`, including a result loaded from a snapshot. The
|
|
subject keeps the inspected file identity. Provider inspections also retain
|
|
the established `parameters.input_path` field for existing consumers. Keep
|
|
request provenance separate from provider arguments and snapshot queries.
|
|
- Return the requested facts inline with artifact/provider identity, source
|
|
locations, Evidence references, coverage, and relevant confidence and
|
|
limitations. Use supported selection, summaries or views when they answer
|
|
the question; preserve access to complete source Evidence and honor existing
|
|
contracts and requested detail. Missing coverage is unknown, not absence.
|
|
Avoid extra lookups solely to understand the answer or its provenance.
|
|
- Keep result semantics provider-neutral. If an operation means the same
|
|
thing on several providers, it resolves the same selector the same way on
|
|
each. Otherwise the contract declares the difference.
|
|
- Page cursors over mutable state, such as a live provider session that accepts
|
|
annotations, carry the source revision. A cursor from an older revision fails
|
|
instead of returning shifted rows.
|
|
- Name the address space of every location: RVA, virtual address or file
|
|
offset, in one documented spelling. Report the image base wherever results
|
|
mix those spaces.
|
|
- State session-scoped facts, such as provider defect notes and analysis-profile
|
|
caveats, once per session and reference them afterwards. Attach a scoped
|
|
caveat only to the architectures, formats or operations it applies to.
|
|
- Keep observed, derived, and inferred relationships distinct. Preserve
|
|
unresolved edges and partial provider facts instead of requiring every
|
|
provider to supply the same metadata.
|
|
When a format constructor changes defaults or flags, retain the source
|
|
values and use separately derived effective values only for operations
|
|
whose semantics require them.
|
|
- For caller/callee reads, `relationship_coverage` describes only the
|
|
provider-observed direct relationship set. `complete` means that set was
|
|
returned without a known read limit; it does not claim every possible runtime
|
|
edge. Provider and execution caveats stay in `limitations` and do not imply
|
|
incomplete relationship coverage. Directional `discovery` separately describes
|
|
whether applicable static relationships could have been missed by discovery;
|
|
missing discovery is unknown. Preserve paths supported by observed edges,
|
|
and qualify negative and shortest-path claims by discovery scope. Missing
|
|
relationship coverage remains `unknown`. Computed candidates and unestablished incoming targets qualify directional discovery; they do not by themselves mean that recorded edges were omitted.
|
|
- Declare process, filesystem, network, UI, and mutation effects truthfully;
|
|
enforce the requested target and lifecycle. A private temporary copy is a
|
|
filesystem write even when the selected artifact remains untouched. Derive
|
|
overlapping tool and provider effect declarations from the same fact.
|
|
- Separate **admission limits** from **delivery budgets**:
|
|
- An admission limit refuses or stops work. Add one only for a real format,
|
|
protocol, authority or measured resource constraint, and measure what the
|
|
operation actually reads. A header reader is bounded by the bytes it reads,
|
|
not by file size. Name the ceiling and its recovery as described in
|
|
[admission limits and recovery](../reference/limits-and-recovery.md).
|
|
- Choose the limit's control. Give it a per-call parameter. Also register
|
|
one analysis setting per limit family an agent plausibly raises
|
|
repeatedly in a session, such as member or entry counts,
|
|
decompressed or retained bytes, and producer output bytes, not one per
|
|
sub-limit: every setting ID is enumerated in `update_analysis_settings`'
|
|
advertised schema and costs tokens in every session. One-off structural
|
|
limits, such as nesting depth or a single document, stay per-call. A
|
|
limit that is a real format, protocol or representation fact stays fixed
|
|
with its stated reason.
|
|
- Set `required_value` whenever the producer measured the complete need (not
|
|
a lower bound), and let the
|
|
typed refusal generate the recovery
|
|
([adjustable budget recovery](../reference/limits-and-recovery.md#adjustable-budget-recovery));
|
|
do not author duplicate recovery prose.
|
|
- A delivery budget never refuses. It sizes the inline answer for the
|
|
agent's context, retains the complete result as Evidence, and returns a
|
|
summary, the Evidence ID and a cursor. The agent's context is a valid
|
|
reason for a delivery budget, not for an admission limit.
|
|
- Report pagination, truncation, cancellation and partial failure either way.
|
|
- Give high-cardinality discovery (`list_*`, `search_*`, `find_xrefs_*`),
|
|
inventory and graph-traversal (`get_call_graph`, `trace_call_path`) tools
|
|
per-call bounds (`limit`/`offset` or `max_depth`/`max_nodes`). With no bounds
|
|
supplied, return a bounded summary within the delivery budget and keep the
|
|
complete result available through retained Evidence; return everything
|
|
inline only when the caller asks for complete detail. Supplied bounds should
|
|
stop producer work early where possible, mark truncated coverage or discovery
|
|
`partial`, and report continuation facts (`total_*`, `truncated`,
|
|
`limitations` or `residual_unknowns`). Selectors narrow every collection they
|
|
touch, not only the primary one.
|
|
- Keep input schemas flat for compact advertisement: avoid redundant root
|
|
unions (`z.discriminatedUnion` whose branches share identical properties
|
|
differing only by a boolean), which double schema size and introduce root
|
|
`anyOf` violations that force compact-profile reduction.
|
|
- Keep application ownership flat: reuse shared runners
|
|
(`executeArtifactInspection`, `executeProviderOperation`,
|
|
`executeRetainedSummaryOperation`) instead of
|
|
duplicating per-operation wrappers. When moving or extracting symbols, migrate
|
|
all callers directly rather than leaving re-export shims or pure barrel files
|
|
outside enforced module-boundary entrypoints (`src/resources/index.ts`).
|
|
|
|
### Compose declared Evidence inputs
|
|
|
|
Declare each logical Evidence source with the shared `evidenceInputSchema`:
|
|
complete inline Evidence or an exact
|
|
`{kind: "retained-evidence", evidence_id}` reference. Use that declaration in
|
|
single, optional, array and nested source fields across domains. Keep complete
|
|
record schemas for stored Evidence, bundle records and pure semantic inputs;
|
|
request alternatives do not change those representations. Ordinary IDs in
|
|
parameters or result data are not implicitly source selectors.
|
|
|
|
Derive borrowing request validation and source resolution from the canonical
|
|
request schema with `getEvidenceInputContract` and `resolveEvidenceRequest`.
|
|
The shared application entrypoint selects references for CLI and MCP before the
|
|
format owner admits, authenticates and interprets their records. Preserve
|
|
admission before copying large source payloads. Do not maintain a second list
|
|
of source paths or resolve references only in an adapter. A resolved reference
|
|
has the same identity, caller-selected observations, provenance, coverage and
|
|
partial or unknown facts as its complete inline record; it never reruns a
|
|
producer or upgrades incomplete evidence.
|
|
Keep Evidence-bearing request unions outside skipping `default` wrappers;
|
|
use `prefault` when a default must pass through branch selection. Catalog
|
|
conformance rejects unsupported source containers rather than silently losing
|
|
their references.
|
|
|
|
Return authenticated source records alongside derived workflow Evidence when
|
|
the adapter must retain them. Keep links to those exact sources and require the
|
|
source closure when the workflow follows their links. Missing references and
|
|
incompatible workflow roles are explicit failures; do not infer a substitute
|
|
from ledger order, display names or the active target. A summary or inspection
|
|
page has its own identity: consumers needing complete source facts use its
|
|
`normalized_result.parent_evidence_id`, unless their contract explicitly accepts
|
|
that view.
|
|
|
|
New provider-owned source observations require a retention owner. Existing
|
|
caller-owned inputs can also compose on a fixed port without a recorder;
|
|
when a recorder is available, preserve its acceptance or rejection and retain
|
|
completed sources through cancellation.
|
|
|
|
MCP supplies the current ledger lookup. CLI commands that advertise
|
|
`--evidence-bundle` use one explicitly selected, authenticated bundle for the
|
|
command's lifetime. Keep cleanup with that owner. A retained reference does not
|
|
grant filesystem access: file selectors remain separate, explicit contracts
|
|
where supported. See [retained Evidence inputs](../reference/mcp-contracts.md#retained-application-evidence-inputs)
|
|
and [CLI reuse](../getting-started/cli.md#import-export-and-compare-evidence).
|
|
|
|
### Interpret boundary facts once
|
|
|
|
The format or protocol reader owns interpretation. Pass its parsed facts and
|
|
explicit uncertainty to consumers; do not make adapters reparse display text,
|
|
reconstruct omitted values, or infer success from missing diagnostics.
|
|
Client registration inspections, for example, carry command identity and
|
|
activation independently of readiness. An owned registration may be disabled
|
|
or stale; unresolved ownership remains unknown. Consumers use those facts
|
|
instead of reclassifying the raw command.
|
|
|
|
During review, name the fact or resource whose ownership must agree across
|
|
entry points. Trace where it is established, which consumers rely on it,
|
|
and where fallback, retry, or cleanup can change the outcome. Search for
|
|
other code that derives the same fact or claims the same responsibility.
|
|
Different implementations can still make the same decision independently.
|
|
Sibling readers of one format share its header parser and the structural checks
|
|
for the fields they read. Each operation keeps its own required fields and
|
|
admission policy; don't duplicate parsing to enforce those differences.
|
|
|
|
Have the owner carry the result, its source and scope, and any uncertainty.
|
|
Each consumer applies its own policy to those shared facts. Keep proof of
|
|
identity and ownership separate from validity, readiness, and authority to
|
|
act. For an operation that needs fresh evidence, ask the same owner to
|
|
revalidate. For a proposed change, use the owner's rules to evaluate what
|
|
would remain before applying it.
|
|
|
|
Keep the reader's observation independent of the operation that needs it.
|
|
For example, the Evidence file reader can recognize the shape of an
|
|
analysis snapshot before authenticating it. Import and comparison can
|
|
recommend different next steps while reporting the same observed kind.
|
|
The reader also retains disagreements in the input. If two observed header
|
|
fields conflict, carry that uncertainty forward before projecting the fields
|
|
into a single value. A command launcher likewise needs the parser's token
|
|
boundaries so an option value cannot select a transport mode.
|
|
|
|
When one operation can show partial results and another requires a complete
|
|
document, share the grammar and give each operation an explicit policy for
|
|
handling diagnostics. Preserve source spelling and offset units alongside any
|
|
normalized lookup value. Use the stored name when a package format requires
|
|
an exact member path. Verify both operations with the same authored inputs and
|
|
independently specified expectations. See [boundary regressions](testing.md#boundary-regressions).
|
|
|
|
For example, APT one-line sources can spell a suite as `"stable"` and a
|
|
component as `main%2Cextra`. With APT 2.8.4, those words select suite
|
|
`stable` and component `main,extra`. The source reader owns the word
|
|
decoding. Capture retains the authored spelling and uses the effective
|
|
identity to match the observed index. Replay uses that same identity
|
|
when deciding what it can write to a deb822 declaration.
|
|
|
|
Test an accepted pair and a refusal. The quoted suite and escaped
|
|
component should select the same index as their deb822 equivalents.
|
|
A one-line component written as `"main extra"` should be withheld from
|
|
replay because deb822 would read it as two components. Check the captured
|
|
facts and the emitted or withheld declaration. Pin the reference reader
|
|
version and record which steps ran. The [offline APT reproduction](https://github.com/morluto/rea/issues/12694)
|
|
checked source and index identity without installing or deploying the app.
|
|
|
|
Keep format recognition, validation, and the operation's decision separate.
|
|
A recognizable PTX header can identify a candidate even when its text is
|
|
invalid or only a prefix was examined. Derive effective fields and completeness
|
|
from the validated extent. Likewise, retain fields for tolerant Desktop Entry
|
|
inspection while carrying group diagnostics to application-ID lookup, where
|
|
an invalid entry cannot establish that the application is hidden.
|
|
|
|
When Evidence includes a source digest, bind it to the admitted bytes used
|
|
by the parser and any converter. A pathname identifies a selection whose
|
|
contents can change between reads. If a native command needs a file, give it
|
|
the same owned byte snapshot used for the digest. Keep the Evidence subject
|
|
and selected source distinct when they identify different artifacts.
|
|
|
|
Give each nested parser the admitted extent of its containing record.
|
|
Check a child's declared encoded range against that extent before applying
|
|
its decoding allowance. If the format declares more fields or rows after the
|
|
child, leave room for their minimum required framing. When the range cannot
|
|
fit, report the format failure even if the decoded size would also exceed a
|
|
budget. Keep encoded ranges separate from declared decoded lengths so an
|
|
expansion limit can preserve the source range and any independently readable
|
|
siblings.
|
|
Retain the source offset and the reason when a field is malformed or its
|
|
encoding is unsupported. A stream may need more bytes to complete a frame.
|
|
A completed artifact with the same missing bytes has truncated data. Carry
|
|
that distinction into coverage and preserve any independently observed facts.
|
|
|
|
When consumers in different runtimes receive raw input independently, reuse
|
|
the same reader where the runtime is available. If separate implementations
|
|
are needed, prefer generating them from one authored set of parsing rules.
|
|
For example, desktop capture and an offline AppImage installer need the same
|
|
rules to locate the executable after an `env` prefix. The installer also needs
|
|
the executable's source span so it can replace that token while preserving the
|
|
rest of the entry. Use shared fixtures with explicit expected results to check
|
|
the common interpretation through both entry points.
|
|
|
|
Owned provider commands follow the same rule. `providerOutcomeOf` in
|
|
`src/process/ProviderOutcome.ts` reads what the supervisor observed (launch
|
|
refusal, cancellation, deadline, output or memory limit, resource signal, exit
|
|
status with the owner's stop state, or stream failure) together with the
|
|
retained output and whether it was truncated. `classifyProviderOutcome` maps
|
|
that outcome to a typed error once; a provider supplies only its settings,
|
|
recovery text and a dialect for what an exit or launch refusal means.
|
|
`classifyProviderFailure` in `src/providers/classifyProviderFailure.ts` is the
|
|
one entry for a raw failure: typed analysis errors pass through, command
|
|
outcomes go to `classifyProviderOutcome`, selected-file failures go to the
|
|
shared stable-artifact projections, and only what none of them recognises
|
|
reaches the provider's `unclassified` report. A provider supplies a dialect,
|
|
not a classifier. A phase that armed its own deadline throws that deadline's
|
|
timeout where it observes the abort; for a read its signal cancelled, it
|
|
supplies the timeout as the dialect's `interruption`, so classification never
|
|
rereads a cancellation's reason as a timeout. A provider whose cleanup report
|
|
has its own shape supplies `readCleanup` or `commandCleanup`; otherwise the
|
|
unresolved cleanup is attached to the reported failure. The
|
|
`rea/provider-failure-classifier` lint rule keeps new
|
|
`(cause: unknown) => AnalysisError` functions out of `src/` except in that
|
|
owner; existing ones are counted in a baseline that may only shrink.
|
|
|
|
A completed read can establish byte identity even when decoding or format
|
|
validation fails. State which representation a digest identifies, such as file
|
|
bytes, Fetch response-body bytes, or UTF-8 text. Preserve admitted source values
|
|
separately from normalized lookup and display values. When the retention
|
|
contract keeps only a digest and size, state that the bytes or text are
|
|
unavailable; the digest does not establish format validity.
|
|
|
|
Comparison needs separate proofs for lookup, correspondence, content, and
|
|
coverage. A hash cannot supply the proof that two retained values belong to
|
|
corresponding objects.
|
|
|
|
| Comparison fact | What it establishes | What remains unknown |
|
|
| ----------------------------------------------------------------------------- | ----------------------------------------------- | --------------------------------------------- |
|
|
| Same capture-local frame or request ID | Lookup within that capture | Cross-capture identity |
|
|
| Same HTTP method, URL, and resource type | A repeated-request group | Which individual responses correspond |
|
|
| A partial HTTP response multiset is contained in a complete peer | Omissions can explain every retained sample | Equality or modification |
|
|
| A retained HTTP sample is absent from a complete peer group | An observed difference independent of omissions | Other unobserved differences |
|
|
| Complete WebSocket connection/frame inventories and matching metadata streams | Ordered payload positions can be compared | Equality of unavailable payload facts |
|
|
| Unique WebMCP name, owner origin, and frame URL | Tool correspondence without transient frame IDs | Correspondence between duplicate owners |
|
|
| A complete source digest or decoded storage value | Comparable content | Missing source bytes or opaque remote objects |
|
|
|
|
Complete traversal or inventory does not make unavailable values equal. A
|
|
partial aggregate fingerprint difference cannot establish modification when
|
|
omissions alone explain it; independently proven differences still survive.
|
|
|
|
A byte-format parser reports failure with `ParseFailureError` from
|
|
`src/domain/parseFailure.ts`: `malformed`, `truncated`, `unsupported`, or
|
|
`limit`, with the format and, when known, the offset and field. Read bounded
|
|
fields through `BinaryReader` (`src/domain/binaryContainer.ts`), which
|
|
raises that failure instead of a bare `RangeError`. Providers project the
|
|
failure with `parseFailureAnalysisError` rather than their own `instanceof`
|
|
ladder. The producing reader identifies the named limit and effective maximum.
|
|
Use those facts for the public refusal and recovery. When decoding stops before
|
|
the reader can measure the final allowance, report the bound that actually
|
|
stopped it.
|
|
|
|
For retained managed metadata rows, use `metadataRowCursor` in
|
|
`src/domain/managed/managedMetadataHeaps.ts`. Its column reads use
|
|
`BinaryReader` within the admitted row and preserve managed issue offsets and
|
|
per-row budget accounting.
|
|
|
|
Do not use `RangeError` as a failure channel: a stack overflow, a host string
|
|
or buffer limit, and an unchecked read past the end of a buffer are all
|
|
`RangeError`s. `hostRangeErrorKind` is the one interpreter of a host
|
|
`RangeError`, and `parseFailureFromCause` admits only a reported parse failure
|
|
as evidence about the input. Readers report bounds failures at the read site;
|
|
host error codes alone cannot distinguish a read from a write or allocation.
|
|
`scripts/verify/architecture-guards.mjs` counts the remaining raw `Buffer` and
|
|
`DataView` reads, plain `Error` throws in parser folders, plain `JSON.parse`
|
|
of parser input, and direct `instanceof RangeError` checks against their
|
|
per-guard baselines in `scripts/verify/baselines/`. A
|
|
file may not exceed its count; after removing copies, run
|
|
`node scripts/verify/architecture-guards.mjs --shrink-baselines`.
|
|
|
|
Keep format recognition separate from provider admission. A recognizable header
|
|
can supply useful observations while later structure remains unresolved or a
|
|
provider cannot accept the artifact. Report the reason at the affected boundary
|
|
without erasing earlier observations or labeling unresolved input malformed.
|
|
|
|
Derive validation from the field's own format and revision. A runtime API's
|
|
narrower argument range need not constrain a wider on-disk field. A shared layout,
|
|
magic, or version label need not identify every constructor or equality rule.
|
|
When supported producer revisions differ, retain what the input establishes and
|
|
state what it cannot distinguish. Static inspection does not establish that the
|
|
artifact can execute successfully.
|
|
|
|
## Own the lifecycle
|
|
|
|
The investigation owns authenticated Evidence and complete Unknown revision
|
|
history independently of an engine. `close_binary` drains earlier admitted work,
|
|
releases engine resources and clears replay/invalidation state; investigation
|
|
references survive, including target-free closes and cleanup failures. A target
|
|
switch does not make historical observations current for its new engine.
|
|
|
|
`reset_investigation` is the explicit destructive boundary. It drains earlier
|
|
analysis, imports, exports and Unknown operations, then clears investigation and
|
|
replay/source bindings while retaining a healthy active engine. Metadata mutation
|
|
invalidation remains in force until that engine is recreated. Later admitted work
|
|
waits for the transition; earlier late results cannot repopulate cleared history.
|
|
Runtime disposal seals new acquisitions and releases records after successful
|
|
owned engine/file cleanup; failed cleanup keeps the owner available for retry.
|
|
|
|
Records are retained in memory under a fixed per-owner representation allowance
|
|
derived from one quarter of initial available V8 heap. Admission accounts for
|
|
Evidence, Unknown history and indexes before atomic commit; metadata replacement
|
|
uses its size delta and duplicates do not accumulate. There is no silent eviction.
|
|
`binary_session.investigation` reports committed counts, estimated representation
|
|
bytes and the allowance; these estimates are not process RSS measurements. Live
|
|
authentication headroom is checked separately. On refusal, export a checkpoint,
|
|
reset, and import only the required investigation, or start a process with a
|
|
larger heap. Retention does not promise automatic persistence.
|
|
|
|
An MCP request retains its original session admission until its handler cleanup
|
|
and response send settle. A reset queued behind that request therefore cannot
|
|
invalidate Evidence before its reply is sent. Nested work borrows the same
|
|
admission. Cancellation before sending releases a suppressed reply after handler
|
|
cleanup; cancellation after sending starts still waits for transport settlement.
|
|
Lifecycle tools drain earlier admissions without acquiring one themselves.
|
|
|
|
`reset_investigation(save_path)` saves the complete cross-domain canonical bundle
|
|
once before clearing. It awaits file sync, atomic publication and staging cleanup;
|
|
failed save, incomplete cleanup or cancellation observed before reset commit
|
|
preserves all records. Publication
|
|
can precede cancellation or cleanup failure; the error retains its committed file
|
|
receipt. Import that bundle to restore original Evidence IDs and all Unknown
|
|
revisions in a new process. Engine replay snapshots remain a separate target and
|
|
profile-bound mechanism. This checkpoint contract does not promise recovery from
|
|
an uncheckpointed process exit or parent-directory loss after a host crash.
|
|
|
|
`SafeOutputTree` publishes only after file readback, nested-directory fsync
|
|
from children to parents, and root-parent fsync on hosts that support directory
|
|
syncing. Windows skips directory fsync. Failed writes retain a separate pending
|
|
identity admission only until identity is captured; rollback retries retain
|
|
unremoved file/directory identities and open handles independently, so confirmed
|
|
unlink progress cannot be re-admitted through a closed descriptor.
|
|
|
|
For tools that acquire resources, identify the owner and the observations that
|
|
establish each transition. Include temporary files and one-shot commands, as
|
|
well as persistent engine sessions. Use the existing provider contracts;
|
|
providers need not expose identical state machines.
|
|
|
|
In multi-stage work, retain each completed, admitted observation before awaiting
|
|
the next stage. Later reads, validation, cancellation, or finalization can fail
|
|
without erasing those facts. Carry them through typed failure outcomes with
|
|
explicit coverage of unperformed work; do not construct a successful result for
|
|
stages that never ran. For concurrent reads, the batch owner settles every
|
|
admitted peer before reporting a failure. Retain completed observations together with each
|
|
failed request's physical, cancellation and cleanup facts.
|
|
|
|
- Keep target admission, provider readiness, active work, observed process exit,
|
|
and resource release separate. A valid process handle, successful launcher,
|
|
or selected target establishes only its own fact. Publish available identity
|
|
and exit observations even when launch fails; retain unknown ownership.
|
|
- Process exit does not establish output closure. The
|
|
[shared supervisor](https://github.com/morluto/rea/blob/main/src/process/ProviderProcess.ts)
|
|
owns diagnostic retention and bounded draining through cleanup and retries.
|
|
Report incomplete output separately from process cleanup. After verified stop
|
|
and bounded draining, release owned event-loop references even if output closure
|
|
stays unconfirmed. Keep the output capture owned for retry while process cleanup
|
|
is unresolved. Borrowed processes and streams retain their own lifetime and
|
|
reference state; select the matching
|
|
[supervision controls](testing.md#lifecycle-regressions) when changing this code.
|
|
- Authenticate and capture identity through the same boundary on initial and
|
|
recovery handshakes. Bound abandoned unauthenticated listeners where the
|
|
protocol permits it; that deadline must not expire authenticated idle sessions
|
|
or long-running native work. Listener expiry does not prove target closure.
|
|
- Readiness observations may await owned prerequisite commands. Status must
|
|
remain readable during owner finalization without starting replacement work;
|
|
report readiness as unknown when it cannot be re-observed.
|
|
- Shared startup has one producer and independently cancellable caller waits.
|
|
Keep it running while any caller still needs it. The final departing caller
|
|
waits for owned cleanup and retains its failure. Provider closure is distinct
|
|
from caller cancellation. Retained cleanup capabilities block replacement;
|
|
derive readiness from the current startup's completion and live connection.
|
|
- Session `cleanup_pending` includes retained blockers from external mutation
|
|
owners until those owners confirm release. Closing the analysis session does
|
|
not release resources owned by an external debugger. Reading a selected
|
|
analysis snapshot is part of `open_binary`; cancellation keeps that operation
|
|
and the caller's reason through the shared JSON reader.
|
|
- For cancellable observations, carry cancellation through result consumption
|
|
and awaited cleanup. Check the signal after the last awaited finalization step
|
|
unless the operation has passed its documented commit cutoff. Preserve the
|
|
owning operation's committed outcome and receipt after that cutoff.
|
|
Retain collected observations under typed cancellation. Preserve an existing
|
|
primary failure and let incomplete cleanup retain its own classification.
|
|
Preserve the caller's abort reason as the typed cancellation error's cause,
|
|
including when cancellation is observed only after provider completion.
|
|
The producing boundary records cancellation separately from physical failures
|
|
and cleanup ownership. A caller's abort reason is opaque: its value, error
|
|
type, name or cause chain cannot establish failure origin or cleanup authority.
|
|
Consumers use the owner's parsed facts. An established command timeout keeps
|
|
its timeout or refusal policy when preparation records a cancellation.
|
|
Failure wrapping and operation rebinding preserve these facts and already
|
|
classified secondary failures.
|
|
Client cancellation alone does not prove native work stopped.
|
|
For atomic publication, document the cancellation cutoff and preserve any
|
|
committed output's publication receipt.
|
|
Queued and retried work must retain the complete accepted execution controls,
|
|
including non-default lifecycle deadlines and cancellation signals.
|
|
- Release only owned resources. Attaching owns a connection or session unless
|
|
the provider contract explicitly establishes target ownership. A helper exit,
|
|
missing reply, or missing PID does not establish target exit.
|
|
- Retain successful child cleanup and retry only unresolved children, including
|
|
when close options change. Preserve observed child failure or activity when
|
|
another child's health is unavailable; idle plus missing coverage stays
|
|
unknown.
|
|
Bind cleanup failures to their exact resource owner. Resolve current cleanup
|
|
uncertainty only after that owner confirms release, while preserving the
|
|
original failure and completed observations. Later failure composition must
|
|
report only resources whose cleanup remains unresolved. Carry cleanup
|
|
capabilities explicitly in typed outcomes so consumers can bind returned errors
|
|
to exact owners without reparsing diagnostic cause chains. A cleanup-status
|
|
observer does not replace a callable close capability retained by the caller's
|
|
scope.
|
|
Bind every caller-visible retry error and aggregate, including an error already
|
|
produced by the provider. An aggregate remains incomplete until all owners it
|
|
reports are released; releasing one child cannot clear another child's status.
|
|
- Await one-shot cleanup without discarding the completed result or primary
|
|
diagnostic. Preserve partial observations, remaining resources, and the cleanup
|
|
owner's recovery instructions. While cleanup remains unconfirmed, canonical
|
|
errors keep `cleanup_incomplete` and live resources while taking category,
|
|
operation and failure details from the retained typed primary. Nested cleanup
|
|
composition does not replace that semantic identity. Finalization reports
|
|
remain attached to their owning envelope while cleanup is pending and after
|
|
confirmed release. CLI adapters should reuse
|
|
[`finishAnalysisCommand`](https://github.com/morluto/rea/blob/main/src/cli/finishAnalysisCommand.ts) where its contract
|
|
applies rather than duplicate close/finally handling. It projects
|
|
[`runOwned`](https://github.com/morluto/rea/blob/main/src/providers/runOwned.ts),
|
|
which owns this precedence for owned work: a recorded failure stays primary,
|
|
cancellation before commit keeps the completed value as a partial
|
|
observation, cancellation after commit keeps the value, and unconfirmed
|
|
cleanup reports `cleanup_incomplete` while keeping the completed value.
|
|
SQLite keeps a failed close primary when cancellation arrives during that
|
|
close, and retains the caller's cancellation as a secondary failure.
|
|
Startup deadlines own the readiness cutoff for sessions that remain open
|
|
after a successful handshake.
|
|
- Give descriptor-backed reads an owner before opening the file. A rejected
|
|
close must retain the exact handle and preserve any earlier failure.
|
|
Carry [`openRegularFile`](https://github.com/morluto/rea/blob/main/src/filesystem/RegularFile.ts)'s
|
|
admitted handle and initial metadata rather than restatting only to rebuild
|
|
those facts. Keep fresh descriptor and selected-path identity checks after
|
|
work, comparing against the original baseline instead of replacing it with
|
|
a later stat. Preserve explicit bigint reads when ordinary admission metadata
|
|
cannot supply the required size or timestamp precision.
|
|
Stable file reads expose completed values separately from cancellation so
|
|
consumers retain acquired identity facts after successful close or cleanup retry.
|
|
If an abortable caller stops waiting, keep the underlying work in that owner's
|
|
lifetime so shutdown cannot report release before finalization settles.
|
|
Admit the entire inspection once, including later reads and finalization.
|
|
Helpers must borrow that admission or use an operation child scope; re-entering
|
|
the same draining scope can make cleanup wait for its own caller.
|
|
Retry retained cleanup before admitting new work and keep admission blocked
|
|
while it remains unresolved. Link the originating cleanup error to its exact
|
|
owner so confirmed release resolves its cleanup marker while preserving the
|
|
earlier diagnostic. Shared CLI/MCP adapters cannot infer that confirmation.
|
|
- Provider profile selection owns every asynchronous candidate through its
|
|
terminal result and finalization. The registry owns profile-file cleanup,
|
|
joins all automatic-selection children, and closes those file owners before
|
|
reporting candidate shutdown. Final caller cancellation joins the selection;
|
|
an adapter that ignores cancellation remains active and owned until it settles.
|
|
Block new admission during shutdown and while cleanup remains unresolved;
|
|
reopen after confirmed retry. Preserve failed results before considering a
|
|
later signal, and retain every child's attributed cleanup in mixed outcomes.
|
|
- Release child descriptors before removing their containing root. Retain a
|
|
composite owner when either stage fails so retry preserves that ordering.
|
|
A Windows command leader's exit does not establish Job Object closure. Keep
|
|
the process-tree observer and command lock alive through failed cleanup retries
|
|
until the owned tree's close event.
|
|
|
|
Exercise the applicable [lifecycle regression scenarios](testing.md#lifecycle-regressions)
|
|
through the producing owner and affected CLI/MCP consumers.
|
|
|
|
## Implement and evaluate
|
|
|
|
Put provider wire-protocol parsing in adapters and shared CLI/MCP workflows in
|
|
the application layer.
|
|
|
|
CLI commands register through
|
|
[`cliCommandRegistrations.ts`](https://github.com/morluto/rea/blob/main/src/cli/cliCommandRegistrations.ts):
|
|
add the registrar to its family there and its module to `src/cli.ts`. The build
|
|
records which registrar defines each top-level command, and running a known
|
|
non-built-in command (including single-command discovery with `--help`, `-h`,
|
|
`--schema`, `--llms`, or `--llms-full`) loads only that registrar's module
|
|
graph. Root discovery, unknown command names, built-in requests (`completions`,
|
|
`mcp` CLI subcommands, shell completion, and other built-in flags outside
|
|
standalone `--version` and retired per-command `--mcp`), and a missing or
|
|
unusable recording load the complete CLI. A registrar's command definitions must not depend
|
|
on other registrars, and `tests/boundary/cli/cliLazyRegistration.test.ts` checks
|
|
that each one registers alone with the definitions the complete CLI gives it.
|
|
Modules that every registrar imports set the startup cost of every command; load
|
|
optional heavy services where a command needs them. Reusable format declarations may live in pure domain
|
|
owners: [`peOptionalHeader.ts`](https://github.com/morluto/rea/blob/main/src/domain/peOptionalHeader.ts)
|
|
decodes PE structure, while consumers retain machine admission, directory-address
|
|
interpretation, and file/mapping bounds. Share Evidence provenance, unknown
|
|
projection, and session retention semantics; matching payloads alone do not
|
|
establish parity.
|
|
|
|
Let `createEvidence` own JSON validation and snapshotting of ordinary observation
|
|
payloads. `EvidenceObservationInput` accepts semantically parsed parameters,
|
|
results, and raw results whose JSON validity still needs admission. Keep format,
|
|
selection, and identity validation at their producing boundary. Invalid JSON
|
|
issues are rooted at `parameters`, `normalized_result`, or `raw_result` in the
|
|
Evidence envelope.
|
|
|
|
`EvidenceObservation` retains the stronger JSON contract used by producer
|
|
helpers and `createImmutableEvidenceSteps`. The cooperative constructor also
|
|
requires an authenticated immutable result; preserve that ownership proof.
|
|
For objects, proof comes from completed sealing by
|
|
[`immutableJson.ts`](https://github.com/morluto/rea/blob/main/src/domain/immutableJson.ts);
|
|
`readonly` or `Object.freeze` alone does not establish it. JSON primitives are
|
|
directly eligible. Seal owned data and complete cooperative sealing before
|
|
reusing its result.
|
|
|
|
When a failed or cancelled operation retains completed, valid partial Evidence,
|
|
use the shared [`ToolResultDelivery`](https://github.com/morluto/rea/blob/main/src/server/ToolResultDelivery.ts)
|
|
path with the session's Evidence writer. Keep the original failure and the
|
|
named contract's target-content marking; replace the inline partial with a
|
|
retained reference only after recording succeeds. An absent writer or a writer
|
|
returning a failure `Result` leaves the partial inline, as does a partial that
|
|
is not valid Evidence. Unexpected recorder exceptions propagate. An `evidence_id`
|
|
member alone does not establish Evidence validity or retention.
|
|
|
|
### Design hot paths for single-pass work and zero redundant copies
|
|
|
|
Apply these general patterns when implementing providers, bridges, adapters,
|
|
and shared application workflows so performance is built into the owning
|
|
boundary rather than patched downstream:
|
|
|
|
- **Validate once at the trust boundary; avoid full-tree deep-clones on owned
|
|
payloads.** Use `ownedJsonValueSchema` / `ownedJsonObjectSchema` (in-place
|
|
validation without cloning) for freshly constructed, exclusively owned
|
|
objects instead of `jsonValueSchema.parse` / `jsonObjectSchema.parse`. Keep
|
|
cloning only when a downstream consumer mutates or freezes shared input
|
|
(such as `freezeJsonSnapshot`). When an upstream decoder has already
|
|
validated a large payload schema (for example `binaryLayoutPayloadSchema` or
|
|
`recordedCrashPayloadSchema`), validate only the added envelope fields and
|
|
cross-field invariants rather than re-parsing the full payload tree. Hoist
|
|
Zod schemas, regular expressions, and constant lookup `Set`s to module scope;
|
|
never construct `z.object(...)` inside per-record or per-field loops.
|
|
- **Derive classifications, counts, and pruning summaries in a single pass.**
|
|
Fuse independent `.filter()`, `.some()`, and `.flatMap()` passes over the
|
|
same inventory or stream into one loop, and count matches with a loop rather
|
|
than allocating `.filter(...).length` intermediate arrays. Compute tiny
|
|
derived existence summaries during pass 1 (such as whether any packet uses a
|
|
protocol or whether any managed directory exists) to short-circuit expensive
|
|
secondary subprocesses or scans when no matching records exist.
|
|
- **Use hash joins and reuse existing indexes instead of nested-loop scans.**
|
|
Before calling `.find()`, `.includes()`, or `.indexOf()` inside a loop over
|
|
another collection, reuse an existing `Map`/`Set` index on the context or
|
|
build one once outside the loop. In bridges (Java/Python), index tables,
|
|
procedures, and tokens by address or type path during analysis/loading (using
|
|
`putIfAbsent` when first-match precedence matters) and gate expensive engine
|
|
queries (such as SLEIGH p-code or flow resolution) behind cheap control-flow
|
|
checks.
|
|
- **Bound I/O and cache freshness without breaking cancellation or cleanup
|
|
contracts.** Prefer single-pass streaming reads/hashes (such as
|
|
`ArtifactAnalysisResources.hash()` via `streamStableArtifact` with
|
|
`retainBytes: () => 0` when only identity and byte length are needed) and pass
|
|
`expectedSize` to `readBoundedFileBytes` for regular files so reads avoid
|
|
double-allocation copies. Bound concurrent filesystem and process fan-out
|
|
rather than issuing unbounded `Promise.all` over variable-length path or PID
|
|
lists, and prefer event-driven wakeups (`AbortSignal` or `WorkerFrameSignal`)
|
|
over fixed polling intervals. When caching external tool digests or PATH
|
|
probes with `(dev, ino, size, mtimeNs, ctimeNs)` stat verification, bypass the
|
|
fast path when a caller or test injects a custom `artifactReader`, and never
|
|
skip a read whose contract requires observing mid-read cancellation or access
|
|
errors on every call.
|
|
- **Reuse binary/stream primitives and avoid full-chunk or per-record copies.**
|
|
Hold or `WeakMap`-cache `BinaryReader` per `Buffer` instead of allocating one
|
|
per symbol, note, GUID, or header field; reuse `strictUtf8Decoder`
|
|
(`src/domain/strictUtf8.ts`) for stateless UTF-8 decoding (never cache
|
|
`{ stream: true }` decoders); use `FifoQueue` (`src/kernel/FifoQueue.ts`)
|
|
rather than `Array.shift()` for message/frame queues; scan streaming binary
|
|
payloads with `Buffer.prototype.indexOf` and tiny fixed seam buffers instead
|
|
of copying full chunks or concatenating strings per byte; and write framed IPC
|
|
headers separately from large body buffers rather than copying multi-megabyte
|
|
payloads into one combined frame.
|
|
- **Keep analysis views and MCP wire delivery O(limit) and lazy.** Reuse
|
|
validated immutable parent snapshots through `createAnalysisViewResultReader`
|
|
and `WeakMap` lookup indexes. Pass candidate indices to `selectViewRows` for
|
|
explicit selections and omit the predicate on unfiltered pages. Use
|
|
`pickFields` to project columns without enumerating each row. On the MCP delivery path, skip
|
|
duplicate Zod validation when the SDK already admitted `inputSchema`, evaluate
|
|
overflow recovery metadata lazily only when a response exceeds its budget, and
|
|
measure wire sizes without joining discarded JSON strings.
|
|
|
|
Measure the resource before choosing a budget and enforce it before the costly
|
|
step. Account for value alternatives, trace-frame products, retained records,
|
|
serialization expansion, and temporary-file growth separately. Derive facet
|
|
completeness from examined records and exhaustiveness, rather than diagnostic
|
|
prose or an empty failure list. Preserve observations independently of cleanup
|
|
success.
|
|
|
|
Price mutually exclusive success and failure representations separately.
|
|
Replace a reserved failure envelope when pricing success, and release discarded
|
|
decoding state from retained-output accounting. Retaining additional failed-body
|
|
text changes the capacity available to later results; treat that as a contract
|
|
change and cover its effect on later valid items.
|
|
|
|
For example, if ten applicable records are discovered, eight are examined, and
|
|
five are returned, the five returned records do not establish complete coverage
|
|
of the ten. Keep discovered, applicable, examined, and retained scope distinct.
|
|
A filtered page can be complete for its selection while the parent inventory
|
|
remains partial. Carry the upstream coverage and unresolved reasons through
|
|
filtering and paging; an item missing from that page is not proved absent from
|
|
the target. Structured completeness and absence fields must agree with the
|
|
stated limitations.
|
|
|
|
File-error wrappers retain the format owner's specific diagnostic and recovery
|
|
text. Strict JSON file input, for example, keeps the byte-order-mark explanation
|
|
and UTF-8 recovery through CLI/MCP projection rather than replacing it with
|
|
generic invalid-file advice. Consumers do not classify parser message text.
|
|
When an artifact boundary falls back to an I/O error, retain the original cause
|
|
on the typed error so provider callers can inspect its filesystem evidence.
|
|
Keep public error fields under the canonical projector's ownership; retaining
|
|
a cause does not require exposing it in transport output.
|
|
|
|
Update canonical contracts, output schemas, examples, generated artifacts, and
|
|
relevant docs together. Verify converted advertised schemas and success,
|
|
malformed, unavailable, cancellation, and partial outcomes through affected
|
|
consumers. Real-engine claims require the matching provider lane; see
|
|
[testing.md](testing.md).
|
|
|
|
For fixed tuples in public contracts, use `src/domain/fixedTupleSchema.ts`:
|
|
Zod's tuple projection omits implicit length bounds and Draft 2020-12 `items`,
|
|
which some clients require even alongside `prefixItems`. Tuples with a rest
|
|
schema also need explicit minimum lengths. Check parser/schema parity for empty,
|
|
short, overlong, and malformed values in both input and output projections.
|
|
|
|
A CLI command for a tool contract is described by `describeContractCommand` in
|
|
[`contractCliDescription.ts`](https://github.com/morluto/rea/blob/main/src/cli/contractCliDescription.ts)
|
|
and rendered for the CLI framework by `registerContractCommand` in
|
|
[`contractCommand.ts`](https://github.com/morluto/rea/blob/main/src/cli/contractCommand.ts).
|
|
A contract with `cli: true` names its own command, the kebab-case spelling of
|
|
its name; the CLI command inventory in `catalogIdentity.ts` is derived from
|
|
those declarations, and the projection omits `command` for it. `CLI_COMMANDS`
|
|
holds only the commands no contract names.
|
|
The projection names only what the CLI spells differently: positionals,
|
|
caller-relative path fields, option renames and short flags, CLI help wording,
|
|
omitted optional fields with a reason, Evidence delivery options, and whether the contract's cross-field
|
|
rules refuse at argv parsing or at the service's contract parse. A delivery
|
|
`view` is JSON text decoded when the command runs; the contract input then
|
|
admits the view with its `detail` before any target is opened, including a
|
|
`detail`-discriminated union input. Field schemas and decimal argv tokens are
|
|
derived, and
|
|
`tests/boundary/cli/cliContractCommandParity.test.ts` checks that each projected
|
|
command admits what its contract admits.
|
|
|
|
CLI translations must reuse the canonical semantic fields, enum membership and
|
|
list bounds. Document transport differences such as relative path spelling and
|
|
JSON text decoding; reject empty selections before path normalization. Preserve
|
|
required alternatives across positional arguments and options. When the CLI
|
|
schema format separates those groups and cannot express their relationship,
|
|
state the required choice in command discovery/help and retain aggregate admission
|
|
before target access. Test emitted schemas and parser behavior together, including
|
|
omission, empty strings, alternatives, conflicts and boundary list counts.
|
|
|
|
Expected input failures must retain caller field/index paths and safe constraints.
|
|
Internal operation/input envelopes are not caller paths. Reuse the input issue
|
|
projector at the admission owner; a schema cause alone does not supply correction
|
|
metadata to either adapter.
|
|
|
|
When discoverability changes, evaluate representative broad, direct, and negative
|
|
tasks on the intended host. Record host/model/catalog, selected tools, arguments,
|
|
errors, retries, and task outcomes. Schema validity and keyword heuristics do not
|
|
establish successful tool selection. See [mcp-contracts.md](../reference/mcp-contracts.md) for
|
|
shipped runtime behavior.
|