Files
reverse-engineering-anything/src/application/environment/environmentReplay.ts
T
3fca2e0ca6 feat(environment): extract the initial state a capture's reads observed (#5319)
* feat(environment): extract the initial state a capture's reads observed

Add the environment-state analysis view. From the parents the environment
manifest accepts, it extracts the data the capture's reads observed before
the first related write: entity types with an identity field (proved by a
path parameter or inferred from an identity name), entities with their
recorded values and provenance, documents for written non-entity paths, and
a render plan per read tool that is kept only when it reproduces the tool's
latest initial recordings from the state; every other read tool is a
recorded view with the reason. The Evidence is always inferred.

Response-body decoding moves to a domain owner shared with replay, exact
JSON parsing moves to the owner of the exact-number policy, the manifest and
state views share parent admission and record grouping, and
projectAnalysisView takes its accumulators as one object.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): bound state at redacted writes; infer identity only from items

A scenario write whose URL was redacted has no request line, so it was
dropped and reads after it counted as initial state. Such a successful
write now joins the timeline with an empty path, whose root relates to
every type, so it ends every type's state; a limitation counts them.

A list whose recordings were all empty passed the "every listed item
carries it" check vacuously and published an identity field nothing
showed; it now needs at least one item, else the view stays recorded
as no-identity.

A value that differed between two request lines of one item tool, such
as a query variant, was called volatile, and the gate then substituted
each recording's own value; only repeats of one request line now show
volatility, so differing lines go through fields-differ.

List membership is compared only while a list can still be the whole
collection, and merged entities are indexed by type and collection once,
so paged captures no longer cost pages times entities (8,000 pages of
40,000 entities: 5.7 s to 0.23 s).

Docs and the tool contract say scenario state keeps the capture's
redaction markers and how redacted writes bound it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): keep first sightings, one list pointer and linear field unions

Entities took the order of the first plan observed, and item plans run
before list plans, so a complete list read before its detail reads came
out reordered and lost "all" membership; each entity now keeps its
earliest recorded sighting.

A list plan reused the first recording's pointer for later recordings,
so a later response that was itself an entity wrapping a list was read
as that list; every recording must now locate the same list.

The field union scanned its ordered list for every key, quadratic in an
object's width; a set now answers membership.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): keep post-write values and partial lists out of the initial state

A value that changed between repeats of one request line was named
volatile whenever no write under the type's own root lay between, so a
write under another root (for example POST /api/dashboards/db before a
second GET /api/search) left its effect in the initial state. Any
recorded write between the two observations now leaves every tool of the
type recorded with reason fields-differ instead.

A list was published with membership "all" even when a total or count
envelope member exceeded the number it listed. Such a counter now makes
the membership "recorded".

Also drop a stale doc comment on ObservedEntity.order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(environment): scope item-shaped and deleted written paths out of documents

State documents are held only for list-shaped paths a POST, PUT or PATCH
tool writes. Reads of item-shaped written paths and of paths that are only
deleted stay recorded views; the guide now says so and the spec defers them
to a later increment of #4933.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): count writes in flight when a value changes between reads

The volatility check compared write start positions with the two reads,
so a write already in flight when the earlier read started was missed and
its effect was named volatile. A write now counts when its interval
overlaps the span from the earlier read's start to the later read's end.

The check also ran once per changed field and scanned every write. It now
runs once per pair of observations, answered by a binary search over the
writes in timeline order and the latest end among each prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): catch cross-tool changes across writes; read only item totals

A value that changed across a write was caught only between repeats of
one tool's request line, so a list read before a write and an item read
after it put the post-write value into the initial state. Changes are
now classified per entity in timeline order after observation: across
any recorded write, a change between repeats of a line or between two
lines of the type rewrites the type (every tool recorded as
fields-differ); with no write between, a repeat's change is volatile.
The classification lives in environmentStateMerge.ts.

Any numeric member whose name contained "total" or "count" counted as
an item total, so total_pages, account_id or page_count made complete
lists partial. Item totals are now members whose name tokens include
total or count and none of page, pages or per; a string of digits counts
as a number; and a set has_more, next or next-page token member also
marks the list partial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(environment): keep post-write observations out of initial state

* fix(environment): retain field provenance and bound state inference work

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com>
2026-10-19 20:33:46 -07:00

249 lines
8.9 KiB
TypeScript

import { isJsonLike } from "../../domain/analysisView/EnvironmentManifestAccumulator.js";
import { mediaTypeEssence } from "../../domain/analysisView/webNetworkRouteTemplates.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { parseExactJson } from "../../domain/exactJsonNumber.js";
import type { JsonValue } from "../../domain/jsonValue.js";
import {
iterateUrlQueryParameters,
recordedPathSegments,
} from "../../domain/recordedTransportUrl.js";
import { err, ok, type Result } from "../../domain/result.js";
import { environmentToolArguments } from "./environmentTools.js";
import {
REPLAY_BODY_LIMIT_BYTES,
ENVIRONMENT_SERVE_OPERATION,
type EnvironmentManifestTool,
type EnvironmentSource,
type RecordedExchange,
} from "./environmentSource.js";
export { REPLAY_BODY_LIMIT_BYTES } from "./environmentSource.js";
/** Caller arguments as the MCP tool receives them. */
export type ReplayArguments = Readonly<Record<string, unknown>>;
/** What one tool call returns: the recorded response and where it came from. */
export interface ReplayResult {
readonly status: number | null;
readonly content_type: string | null;
readonly body: JsonValue;
readonly replay: {
readonly record_ordinal: number;
readonly evidence_id: string;
readonly exact_match: boolean;
readonly recorded_path: string;
readonly recorded_query: string | null;
/** Set when the recorded path or query was cut to REPLAY_METADATA_LIMIT_BYTES; the Evidence record keeps it whole. */
readonly recorded_line_truncated: boolean;
readonly content_type_truncated: boolean;
readonly body_recorded: boolean;
readonly body_encoding: "utf-8" | "base64";
readonly truncated: boolean;
};
}
interface MatchScore {
readonly pathMatches: number;
/** Path matches whose recorded segment equals the value as given, not only after decoding. */
readonly verbatimMatches: number;
readonly queryMatches: number;
readonly exact: boolean;
}
const decoded = (segment: string): string => {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
};
/** Count how many supplied path and query values the recorded request line satisfies. */
const scoreExchange = (
tool: EnvironmentManifestTool,
pathArguments: ReadonlyMap<string, string>,
queryArguments: ReadonlyMap<string, string>,
exchange: RecordedExchange,
args: ReplayArguments,
): MatchScore => {
const providedPaths: { index: number; value: string }[] = [];
for (const param of tool.params) {
const value = args[pathArguments.get(param.name) ?? param.name];
if (typeof value === "string")
providedPaths.push({ index: param.index, value });
}
const segments =
providedPaths.length === 0
? new Map<number, string>()
: recordedPathSegments(
exchange.path,
providedPaths.map((param) => param.index),
);
const pathProvided = providedPaths.length;
let pathMatches = 0;
let verbatimMatches = 0;
for (const { index, value } of providedPaths) {
const segment = segments.get(index);
if (segment === value) verbatimMatches += 1;
if (
segment !== undefined &&
(segment === value || decoded(segment) === value)
)
pathMatches += 1;
}
const supplied = new Map<string, string>();
for (const [name, argument] of queryArguments) {
const value = args[argument];
if (typeof value === "string") supplied.set(name, value);
}
const matched = new Set<string>();
if (supplied.size > 0)
for (const [name, value] of iterateUrlQueryParameters(
exchange.query ?? "",
)) {
if (supplied.get(name) === value) matched.add(name);
if (matched.size === supplied.size) break;
}
const queryProvided = supplied.size;
const queryMatches = matched.size;
return {
pathMatches,
verbatimMatches,
queryMatches,
exact: pathMatches === pathProvided && queryMatches === queryProvided,
};
};
const outranks = (score: MatchScore, best: MatchScore): boolean =>
score.pathMatches !== best.pathMatches
? score.pathMatches > best.pathMatches
: score.verbatimMatches !== best.verbatimMatches
? score.verbatimMatches > best.verbatimMatches
: score.queryMatches > best.queryMatches;
/** Choose the record whose path segments, then verbatim spellings, then query values best match the call; ties keep manifest order. */
export const selectReplayExchange = (
tool: EnvironmentManifestTool,
exchanges: ReadonlyMap<number, RecordedExchange>,
args: ReplayArguments,
):
| { readonly exchange: RecordedExchange; readonly exact: boolean }
| undefined => {
let best: { exchange: RecordedExchange; score: MatchScore } | undefined;
const argumentsMap = environmentToolArguments(tool);
for (const ordinal of tool.record_ordinals) {
const exchange = exchanges.get(ordinal);
if (exchange === undefined) continue;
const score = scoreExchange(
tool,
argumentsMap.path,
argumentsMap.query,
exchange,
args,
);
if (best === undefined || outranks(score, best.score))
best = { exchange, score };
}
return best === undefined
? undefined
: { exchange: best.exchange, exact: best.score.exact };
};
/** The longest prefix of text whose UTF-8 encoding fits the byte limit, encoding only that prefix. */
const utf8Prefix = (text: string, maxBytes: number): string => {
// encodeInto stops before the first character that does not fit, so `read` ends on a boundary.
const { read } = new TextEncoder().encodeInto(text, new Uint8Array(maxBytes));
return text.slice(0, read);
};
/** Bytes a padded base64 string decodes to. */
const decodedBase64Bytes = (encoded: string): number =>
Math.floor((encoded.length * 3) / 4) -
(encoded.endsWith("==") ? 2 : encoded.endsWith("=") ? 1 : 0);
/** Base64 characters, in whole groups, whose bytes fit the replay limit. */
const BASE64_LIMIT_CHARS = Math.floor(REPLAY_BODY_LIMIT_BYTES / 3) * 4;
/** The limit applies to the recorded bytes, not to their base64 spelling. */
const replayBase64Body = (
encoded: string,
cut: boolean,
): { readonly body: JsonValue; readonly truncated: boolean } =>
!cut && decodedBase64Bytes(encoded) <= REPLAY_BODY_LIMIT_BYTES
? { body: encoded, truncated: false }
: { body: encoded.slice(0, BASE64_LIMIT_CHARS), truncated: true };
/** Parse a retained body as JSON when its content type is JSON-like; otherwise return the text. */
const replayBody = (
exchange: RecordedExchange,
): { readonly body: JsonValue; readonly truncated: boolean } => {
const text = exchange.bodyText;
if (text === null) return { body: null, truncated: false };
if (exchange.bodyEncoding === "base64")
return replayBase64Body(text, exchange.bodyCut === true);
const prefix = utf8Prefix(text, REPLAY_BODY_LIMIT_BYTES);
if (prefix.length < text.length || exchange.bodyCut === true)
return { body: prefix, truncated: true };
if (
exchange.contentType !== null &&
isJsonLike(mediaTypeEssence(exchange.contentType))
) {
const value = parseExactJson(text);
if (value !== undefined) return { body: value, truncated: false };
}
return { body: text, truncated: false };
};
/** Recorded paths and queries are cut to this many UTF-8 bytes in replies. */
export const REPLAY_METADATA_LIMIT_BYTES = 1024;
/** Replay one tool call from the retained record that best matches its arguments. */
export const replayEnvironmentTool = (
source: EnvironmentSource,
tool: EnvironmentManifestTool,
args: ReplayArguments,
): Result<ReplayResult, AnalysisError> => {
const selected = selectReplayExchange(tool, source.exchanges, args);
if (selected === undefined)
return err(
new AnalysisInputError(
ENVIRONMENT_SERVE_OPERATION,
{
userMessage: `Tool ${tool.name} cites no retained record to replay.`,
},
[{ path: ["tool"], reason: "invalid_value", expected: tool.name }],
),
);
const { exchange, exact } = selected;
const { body, truncated } = replayBody(exchange);
const recordedPath = utf8Prefix(exchange.path, REPLAY_METADATA_LIMIT_BYTES);
const recordedQuery =
exchange.query === null
? null
: utf8Prefix(exchange.query, REPLAY_METADATA_LIMIT_BYTES);
const contentType =
exchange.contentType === null
? null
: utf8Prefix(exchange.contentType, REPLAY_METADATA_LIMIT_BYTES);
return ok({
status: exchange.status,
content_type: contentType,
body,
replay: {
record_ordinal: exchange.ordinal,
evidence_id: source.evidenceId,
exact_match: exact,
recorded_path: recordedPath,
recorded_query: recordedQuery,
recorded_line_truncated:
recordedPath.length < exchange.path.length ||
(recordedQuery?.length ?? 0) < (exchange.query?.length ?? 0),
content_type_truncated: contentType !== exchange.contentType,
body_recorded: exchange.bodyText !== null,
body_encoding: exchange.bodyEncoding ?? "utf-8",
truncated,
},
});
};