Files
reverse-engineering-anything/src/domain/analysisView/environmentCoverageView.ts
T
41cf869949 fix(environment): bound create learning and invalidate stale write proofs (#6929)
* feat(environment): report what an environment serves with an environment-coverage view

A new inspect_analysis_view kind over capture Evidence. It projects the
state an environment derives with the given template rules and reports
each tool as answered from state, replayed with its view reason, a served
write, or a withheld write with its reason, the records behind it and a
hint about what to record next. The hints cover every write reason, so a
new reason without one fails to compile.

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

* feat(environment): build an environment bundle in one command

rea environment-build <capture> [directory] inspects a HAR (or reads
capture Evidence), projects the environment manifest from the in-memory
Evidence, authenticates the pair, prepares the state and writes the bundle
environment-export writes. Every bundle file is byte-identical to the
three-step path for the same capture and options.

The report adds the capture and manifest identities, the coverage summary,
warnings (a loopback capture named after its file, credential-named body
members by pointer) and the next command. --dry-run writes nothing. The
default template rules are the four the published environments use.

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

* test(environment): cover environment-build and the coverage view

Domain tests check the hint table against the state view's reasons, the
summary, and the view against the environment-state view it summarizes.
Service tests build the fixture capture and compare every file with the
three-step path, a dry run, loopback naming and the refusals. A CLI test
compares a HAR built in one step with the three CLI steps byte for byte,
and an MCP test projects the view from every source kind.

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

* test(environment): build the real-agentenv lane's bundle with environment-build

The lane now runs the command users run: it builds the Grafana-shaped HAR
with environment-build and the packed checkout, checks the report, then
runs the bundle with agent-env as before.

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

* docs(environment): document environment-build and the coverage view

The agent environments guide opens with the one-step build: the report,
the hint for each withheld write reason, and what a bundle ships. The CLI
guide, the capture guide and the skill reference name the command and the
environment-coverage view.

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

* fix(environment): harden environment-build after review

- The credential scan walks with its own stack, so a deeply nested body
  cannot crash the build, and it also reports credential-named header
  names, query names, form body members and string arrays.
- The build checks SIGINT between stages: cancelled before the bundle
  stage it writes nothing, during the write it names the written bundle.
- A dry run opens the package tarball, so it refuses what a build refuses.
- Repeated template rules are refused, a HAR saved as .json gets a hint,
  file-derived names follow the bundle name rules, `localhost.` counts as
  a loopback origin, and the next command is shell-quoted.
- --capture-timeout-ms passes through to the HAR inspection, and a
  missing directory is refused before inspection.
- The no-observation hint covers updates and deletes of entities the state
  never held; the coverage view states that it does not apply the
  serve-time admission checks; the inspect_analysis_view description
  names the view.

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

* docs(environment): state the build's conditions and record its verification

The guides now state when the one-step bundle equals the three-step one,
which headers inspection excludes, what the credential warning scans, how
cancellation behaves, and that the coverage view does not apply the
serve-time admission checks. The spec folder records the census, the end
to end runs, the gates and the review.

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

* fix(environment): dispatch a pending interrupt before each build stage check

The manifest, state and coverage stages run synchronously, so a SIGINT
that arrived during them was only dispatched once the bundle write had
begun. Each check now yields first, so an interrupt before the bundle
stage cancels the build with nothing written.

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

* fix(environment): scan scenario credentials, own the dry-run tarball and serialize Evidence once

A browser scenario's retained header values and the query parameters of its recorded URLs are scanned for credential
names as a HAR's are, through a review projection of its records. A dry run admits and releases the package tarball
through the export's regular-file scope, so a close it cannot confirm keeps its owner, and checks for cancellation
after that last await. Evidence is written into one exactly sized buffer instead of chunks joined by a copy.

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

* docs(environment): record the review round's checks

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

* style(environment): format the build spec

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

* fix(environment): scan every form occurrence and MIME-less scenario bodies

The build's credential scan collapsed form bodies with Object.fromEntries, so a
repeated field kept only its last occurrence: `api_key=secret&api_key=` warned
about nothing although the Evidence ships the value, and repeated values were
undercounted. Form fields are now scanned as ordered name/value pairs, as
headers and query strings already are.

The review projection of a capture_browser_scenario dropped a request body
recorded without a media type, so the scan never saw it. Review keeps such a
body's text with an empty media type; the manifest projection still reads only
bodies it can classify.

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

* fix(environment): scan structured HAR form params and the request side of unattributed scenario transactions

A HAR request recorded with postData.params and no text is scanned by those parameters, each occurrence counting, and
the review projection keeps the request side of a scenario transaction whose response cannot be attributed, so the
credential warning covers what evidence.json ships in both cases.

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

* fix(environment): validate build paths and read dry-run tarballs

* fix(environment): report bodies too large for the credential scan

Text bodies over the scan's 4 MiB limit, including a response decoded only as a prefix, are reported as a
credential-scan-incomplete warning by record and side, never by content, so an absent credential-named-members
warning no longer reads as a complete check. The spec and agent-environments guide also state the path validation and
dry-run tarball read that e52ae1cd added.

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

* fix(verification): release cold source transform services

* fix(javascript): retain capture context along covered mutation paths

* fix(environment): admit serialized exports and scan HAR form fallbacks

* fix(environment): admit in-memory build inputs against heap headroom and scan SaveHar null-text forms

The inspected HAR's Evidence and the projected manifest are checked against live heap headroom before they are
serialized, with the same check the file route uses, so a capture too large to parse and seal is refused as
resource_constraint before anything is written. A request whose postData text is SaveHar's null is scanned by its
structured params.

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

* fix(environment): measure the credential scan limit in UTF-8 bytes

A body counts against the 4 MiB limit by its UTF-8 length, not its UTF-16 code units, so multibyte text over the
limit is reported as unscanned instead of parsed.

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

* fix(javascript): erase inline type imports before binding values

* fix(environment): parse credential form bodies by their media type

* fix(environment): review untyped retained form fields

* fix(environment): bound request comparisons and preserve write proofs

* fix(environment): keep write proofs and bundle review complete

* fix(environment): finalize entity overrides with simulated views

* test(environment): restore 0895c89b's untyped form tests and hint

Integrating main took main's credential scan and coverage view, which
dropped 0895c89b's tests and its body-unusable hint. Main's scan passes
the tests, now reading the scenario by event. The hint names the
response too, since extraction and serving also withhold a write as
body-unusable when its recorded response cannot be read.

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

* test(environment): scan a scenario content event recorded twice

Main's event scan reads both content events of a transaction whose
content the capture recorded twice; the test fails on 0895c89b, whose
review projection dropped that transaction's response. The spec names
event pointers among the first 20.

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

* docs(environment): record the review round's checks

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

* fix(environment): retain contradictions and trim retired state

* fix(environment): distinguish mixed array order from changed values

* fix(environment): keep dependent create state pinned

* fix(environment): keep checking retired view observations

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-10-24 23:57:30 +08:00

188 lines
7.3 KiB
TypeScript

import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { ok, type Result } from "../result.js";
import type {
AnalysisViewParent,
AnalysisViewRequest,
UnsignedAnalysisView,
} from "./analysisView.js";
import { templateRulesSchema } from "./environmentManifestView.js";
import type { StateView } from "./environmentStateRules.js";
import {
createEnvironmentStateAccumulator,
environmentStateFields,
projectEnvironmentStateView,
} from "./environmentStateView.js";
import type {
StateWritePlan,
WriteEffect,
WriteReason,
} from "./environmentStateWriteRules.js";
export const environmentCoverageViewRequestSchema = z.strictObject({
kind: z.literal("environment-coverage"),
template_rules: templateRulesSchema.describe(
"Opt-in template rules as for environment-manifest, each listed at most once. Use the rules of the manifest the environment serves so tool names match.",
),
});
/** What to record next for each reason a write tool is withheld; advice only, it never changes what is served. */
export const WITHHELD_WRITE_HINTS = {
"no-state-target":
"The write's path names no collection or item the capture reads. Read the collection or item it changes.",
"no-call":
"No recorded call of this tool was modelled, for example because every call failed. Record a successful call.",
"body-unusable":
"The retained request or response cannot be modelled. Record a successful call with a complete supported request and reproducible response.",
"no-observation":
"Nothing showed the entity or document this write changed. Read a created entity back by id right after the write; for an update or delete the state must already hold the entity, so read it before the write or record the create that made it.",
"unexplained-change":
"The write changed fields it did not send, in a way no rule explains. A second, different call of the same tool can show the pattern.",
contradicted:
"A later read disagreed with the modelled effect. Check the read at contradicted_by.",
"side-effect":
"The write changed something besides its own entity, which the environment does not model.",
unconfirmed:
"No later read showed the effect. Read the entity and its list after the write.",
"incomplete-entities":
"The write is confirmed, but the views that show its entity cannot render it in full. Read the written entity through every view that lists it.",
} as const satisfies Record<WriteReason, string>;
const writeReasons = Object.keys(WITHHELD_WRITE_HINTS) as [
WriteReason,
...WriteReason[],
];
const effectSchema = z.enum(["create", "update", "delete", "document", "none"]);
const ordinalSchema = z.number().int().nonnegative();
/** Which tools an environment answers from its state, which replay their recordings, and why each write is withheld. */
export const environmentCoverageSchema = z.strictObject({
reads: z.strictObject({
state: z
.number()
.int()
.nonnegative()
.describe("Read tools answered from the state."),
recorded: z
.number()
.int()
.nonnegative()
.describe("Read tools that replay their recordings."),
recorded_reasons: z
.record(z.string(), z.number().int().positive())
.describe(
"Replayed read tools per reason, as the environment-state view names the reasons.",
),
}),
writes: z.strictObject({
served: z.array(z.strictObject({ tool: z.string(), effect: effectSchema })),
withheld: z.array(
z.strictObject({
tool: z.string(),
effect: effectSchema,
reason: z.enum(writeReasons),
hint: z
.string()
.describe(
"What to record next; advice that never changes what is served.",
),
exemplar_ordinal: ordinalSchema
.nullable()
.describe(
"The first successful recorded call the plan was built from.",
),
contradicted_by: ordinalSchema
.nullable()
.describe("The read that disagreed with the modelled effect."),
}),
),
}),
});
export type EnvironmentCoverage = z.infer<typeof environmentCoverageSchema>;
export const environmentCoverageFields = {
origin: environmentStateFields.origin,
name: environmentStateFields.name,
...environmentCoverageSchema.shape,
unknowns: environmentStateFields.unknowns,
};
/** Summarize a state's read views and write plans as served, replayed and withheld tools. */
export const summarizeEnvironmentCoverage = (state: {
readonly views: Iterable<StateView>;
readonly writes: Iterable<StateWritePlan>;
}): EnvironmentCoverage => {
let answered = 0;
let recorded = 0;
const reasons: Record<string, number> = {};
for (const view of state.views)
if (view.shape === "recorded") {
recorded++;
reasons[view.reason] = (reasons[view.reason] ?? 0) + 1;
} else answered++;
const served: { tool: string; effect: WriteEffect }[] = [];
const withheld: EnvironmentCoverage["writes"]["withheld"] = [];
for (const plan of state.writes)
if (plan.served || plan.reason === null)
served.push({ tool: plan.tool, effect: plan.effect });
else
withheld.push({
tool: plan.tool,
effect: plan.effect,
reason: plan.reason,
hint: WITHHELD_WRITE_HINTS[plan.reason],
exemplar_ordinal: plan.exemplar_ordinal,
contradicted_by: plan.contradicted_by,
});
return {
reads: {
state: answered,
recorded,
recorded_reasons: Object.fromEntries(
Object.entries(reasons).sort(([left], [right]) =>
left < right ? -1 : left > right ? 1 : 0,
),
),
},
writes: { served, withheld },
};
};
/** Project the state an environment would serve and summarize which tools it answers from that state. */
export const projectEnvironmentCoverageView = (
parent: AnalysisViewParent,
view: Extract<AnalysisViewRequest, { kind: "environment-coverage" }>,
accumulator = createEnvironmentStateAccumulator(view),
): Result<UnsignedAnalysisView, AnalysisError> => {
const projected = projectEnvironmentStateView(
parent,
{ kind: "environment-state", template_rules: view.template_rules },
accumulator,
);
if (!projected.ok) return projected;
const state = projected.value;
return ok({
kind: "environment-coverage",
view,
parent_evidence_id: state.parent_evidence_id,
parent_operation: state.parent_operation,
parent_digest: state.parent_digest,
artifact: state.artifact,
coverage: state.coverage,
limitations: [
...state.limitations,
"Coverage summarizes the environment-state view an environment derives at startup; it does not run the environment. An environment whose served catalog exceeds the discovery budget, or whose state exceeds what data/add loads, serves replay instead, which this view does not check. Hints are advice about what to record next.",
...(state.timeline === "record-order"
? [
"Not every record carries a start time, so the state learns no clock: a write whose response changes a timestamp the server sets, such as a modification time, is withheld as unexplained-change however often it is recorded.",
]
: []),
],
unknowns: state.unknowns,
origin: state.origin,
name: state.name,
...summarizeEnvironmentCoverage(state),
});
};