mirror of
https://github.com/morluto/rea.git
synced 2026-11-03 13:26:10 +00:00
* 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
* feat(environment): serve tool calls from the environment state
`environment-serve --state <state.json>` serves an environment from the
initial state an environment-state view extracted. Read tools whose views
are state-backed answer from a live state store: item views render the held
entity into the recorded envelope, list views render the collection or the
recorded members, and document views return the held value; a missing entity
or one lacking a required field is refused, and requests the state cannot
answer fall back to their recordings with the reason. The /agentenv data
plane implements data/reset, data/add (a rea-state/v1 document as a data
part, base64 bytes, a file:// path or an https URL, validated and replaced
atomically) and data/get, and the card advertises those operations and an
intake declaration. Stage 1 is read-only: write tools are not served in
state mode. Without --state nothing changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): record verification after merging the state view's review fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(environment)!: serve the environment state by default
environment-serve derives the environment state at startup by running the
environment-state view in-process on the capture with the manifest's
template rules, so an environment comes with its state and a user supplies
nothing extra. The derived Evidence is the same one inspect-analysis-view
produces by hand. --state is removed; --replay-only serves exactly the
stateless replay of main. When the state cannot be derived, or its catalog
does not fit the discovery budget, the server starts in replay mode, logs
the reason and reports it in the stop summary's `state`. Exported bundles
serve the state by default too: export derives it the same way, so the
verifier's tool count and checked answer match what is served, and the
README describes the served mode.
BREAKING CHANGE: environment-serve answers read tools from the derived
state and does not serve write tools unless --replay-only is given; the
stop summary reports `state` instead of `state_evidence_id`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): bound data-plane replies, keep batch order, cancel intake on stop
- One /agentenv response is held to 64 MiB: replies are measured as they
are produced and one past the budget becomes a -32000 error stating it.
- Every message of a batch enters the arrival-order queue on arrival, so
another request's reset never lands between them.
- Stopping the server, or a caller leaving, cancels the active download
and answers queued calls `cancelled` without running them.
- file:// URIs name only this host: another host or a network share is
refused before anything is opened.
- A loaded view value may not give an entity another identity.
- List answers refuse a member lacking a field every recording carried,
as item answers do.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep bodies too deep for the state's nesting out of the state
A recorded body at the JSON depth limit was accepted by extraction, then
nested a few levels deeper as a document or entity value, so sealing the
state Evidence threw and environment-serve and environment-export stopped
instead of falling back. stateBodyJson, the one rule extraction and
serving share, now treats a body nesting deeper than the limit minus 16
levels as unusable, so its tool stays a recorded view.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): measure data-plane replies before building them
83fcc739 bounded one /agentenv response to 64 MiB, but it still
serialized each reply whole before measuring it, so a batch of data/get
calls on a large state built every refused reply in full only to drop
it. Each reply is now measured in bounded JSON parts (the shared
jsonParts encoder), its parts kept only while it fits; a reply past the
budget is counted for its exact reply_bytes but never assembled. A test
checks that a refused read is never handed to JSON.stringify whole and
that its reply_bytes is exact.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): release batch replies as they are encoded; judge exact numbers by value
answerBatch kept every settled reply in its pending array until the
batch ended, so a batch alternating data/add and data/get held each
loaded state alive; each reply now leaves the queue as it is encoded.
The exact-number policy judged a number by its recorded spelling, so a
state loaded with 1e20 came back from data/get as
100000000000000000000, which data/add refused, breaking the promise
that data/get output loads back unchanged. A number is exact only when
both its recorded spelling and the one serialization writes are safe,
so integers from 2^53 below 1e21 are refused in any spelling; replay
keeps such bodies as recorded text. A domain test checks that every
accepted number is accepted again once written back.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep room for refusals and framing in the reply budget
The response budget counted accepted replies only: a budget error that
replaced a reply, and a batch's brackets and commas, were not charged,
so near 64 MiB later refusals pushed the body past the advertised
limit. Every reply still to come now keeps room for its own budget
error, and a batch keeps room for its framing, so a refusal always fits
and the body never passes the budget. Reply ids and which messages are
answered come from one place shared by the replies and the reserve.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): refuse a loaded state that data/get would write past the intake limit
data/add measured only the document it was given, while data/get
writes the state back with the members a document may omit (types, the
state Evidence id, view fields and record citations). A document just
under 32 MiB could therefore load and be reported larger than any intake
accepts, breaking the data/get then data/add round trip. replace now
measures the state as data/get writes it, part by part, and refuses it
past the limit, leaving the state unchanged. The limit moves to the
state document module, so the application store can read it; the
intake re-exports it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep merged export checks on the shared test graph
Main's export tests installed module mocks for the whole services
project, which reuses one module graph. A tarball read failure then
missed its importer, and a one-shot heap mock could be taken by another
file. Read those through bindings the tests replace for one case.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* fix(environment): keep a state file whose close failed owned until it closes
A file:// data/add that could not close its descriptor dropped the handle,
and an admission failure whose cleanup close failed dropped its owner, so
nothing could retry the close or report it.
The read now runs through withOwnedRegularFile, and a failed close is
retained in a server-lifetime ArtifactResourceScope. The next file read
retries it first and answers -32000 while it is still open; inline and
https documents still load. Closing the served environment retries it again
and rejects with the unfinished close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
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>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
426 lines
14 KiB
TypeScript
426 lines
14 KiB
TypeScript
import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumulator.js";
|
|
import {
|
|
collectionPathOf,
|
|
listItems,
|
|
renderStateEntity,
|
|
renderStateList,
|
|
replaceAt,
|
|
scalarText,
|
|
segmentsOf,
|
|
type JsonObject,
|
|
type RecordedViewReason,
|
|
type StateEntity,
|
|
type StateItemView,
|
|
type StateListView,
|
|
type StateView,
|
|
} from "../../domain/analysisView/environmentStateRules.js";
|
|
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
|
import {
|
|
AnalysisInputError,
|
|
AnalysisResourceConstraintError,
|
|
} from "../../domain/analysisErrorCore.js";
|
|
import type { JsonValue } from "../../domain/jsonValue.js";
|
|
import { err, ok, type Result } from "../../domain/result.js";
|
|
import {
|
|
decodedPathSegment,
|
|
pathValueMatches,
|
|
REPLAY_BODY_LIMIT_BYTES,
|
|
replayAnswer,
|
|
replayEnvironmentTool,
|
|
selectReplayExchange,
|
|
selectsRecordedLine,
|
|
type ReplayArguments,
|
|
type ReplayResult,
|
|
} from "./environmentReplay.js";
|
|
import {
|
|
ENVIRONMENT_SERVE_OPERATION,
|
|
type EnvironmentManifestTool,
|
|
type EnvironmentSource,
|
|
type RecordedExchange,
|
|
} from "./environmentSource.js";
|
|
import type { EnvironmentStateStore } from "./environmentStateStore.js";
|
|
import { environmentToolArguments } from "./environmentTools.js";
|
|
|
|
/** Where a served answer came from: the live state, or a recording and why. */
|
|
export type StateProvenance =
|
|
| {
|
|
readonly source: "recording";
|
|
readonly reason: RecordedViewReason | "no-view" | "unrecorded-request";
|
|
}
|
|
| {
|
|
readonly source: "state";
|
|
readonly view: "item";
|
|
readonly type: string;
|
|
readonly collection: string;
|
|
readonly id: string;
|
|
}
|
|
| {
|
|
readonly source: "state";
|
|
readonly view: "list";
|
|
readonly type: string;
|
|
readonly collection: string;
|
|
readonly membership: "all" | "recorded";
|
|
readonly listed: number;
|
|
}
|
|
| {
|
|
readonly source: "state";
|
|
readonly view: "document";
|
|
readonly path: string;
|
|
};
|
|
|
|
/** A replay answer that also says whether the state or a recording produced it. */
|
|
export interface StateAnswer extends ReplayResult {
|
|
readonly state: StateProvenance;
|
|
}
|
|
|
|
/** The manifest and capture a state answer cites, and the live state it reads. */
|
|
export interface StateServing {
|
|
readonly source: EnvironmentSource;
|
|
readonly store: EnvironmentStateStore;
|
|
}
|
|
|
|
const refused = (
|
|
tool: EnvironmentManifestTool,
|
|
userMessage: string,
|
|
): AnalysisError =>
|
|
new AnalysisInputError(ENVIRONMENT_SERVE_OPERATION, { userMessage }, [
|
|
{ path: ["tool"], reason: "invalid_value", expected: tool.name },
|
|
]);
|
|
|
|
/** One entity as an item or list view shows it, or a refusal when it lacks a field the view's every recording carried; a partial body is never answered. */
|
|
const shownEntity = (
|
|
tool: EnvironmentManifestTool,
|
|
view: StateItemView | StateListView,
|
|
entity: StateEntity,
|
|
volatile: ReadonlySet<string>,
|
|
): Result<JsonObject, AnalysisError> => {
|
|
const shown = renderStateEntity(entity, view, volatile);
|
|
const missing = view.required_fields.filter(
|
|
(name) => !Object.hasOwn(shown, name),
|
|
);
|
|
return missing.length === 0
|
|
? ok(shown)
|
|
: err(
|
|
refused(
|
|
tool,
|
|
`The state holds no complete ${view.type} entity ${entity.id} in ${entity.collection}: it lacks fields this tool's responses always carried: ${missing.join(", ")}.`,
|
|
),
|
|
);
|
|
};
|
|
|
|
/** The recorded answer, labelled with why the state did not produce it. */
|
|
const fromRecording = (
|
|
source: EnvironmentSource,
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
reason: Extract<StateProvenance, { source: "recording" }>["reason"],
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const replayed = replayEnvironmentTool(source, tool, args);
|
|
return replayed.ok
|
|
? ok({ ...replayed.value, state: { source: "recording", reason } })
|
|
: replayed;
|
|
};
|
|
|
|
/** A recorded body the state renders into, usable exactly when extraction could use it. */
|
|
const recordedJson = (exchange: RecordedExchange): JsonValue | undefined =>
|
|
stateBodyJson(exchange.contentType, exchange);
|
|
|
|
/** The rendered body on the base record's status, content type and provenance; never cut. */
|
|
const stateAnswer = (
|
|
serving: StateServing,
|
|
base: { readonly exchange: RecordedExchange; readonly exact: boolean },
|
|
body: JsonValue,
|
|
state: StateProvenance,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const bytes = Buffer.byteLength(JSON.stringify(body), "utf8");
|
|
if (bytes > REPLAY_BODY_LIMIT_BYTES)
|
|
return err(
|
|
new AnalysisResourceConstraintError(
|
|
ENVIRONMENT_SERVE_OPERATION,
|
|
"capacity",
|
|
"The answer rendered from the state exceeds the reply body limit",
|
|
{ max_body_bytes: REPLAY_BODY_LIMIT_BYTES, body_bytes: bytes },
|
|
{
|
|
retryable: false,
|
|
remediationAction:
|
|
"Load a smaller state with data/add; the state is not cut to fit.",
|
|
},
|
|
),
|
|
);
|
|
return ok({
|
|
...replayAnswer(serving.source, base.exchange, base.exact, {
|
|
body,
|
|
truncated: false,
|
|
}),
|
|
state,
|
|
});
|
|
};
|
|
|
|
/** One collection segment an item call names: a template literal, or a supplied path value. */
|
|
interface CallSegment {
|
|
readonly text: string;
|
|
readonly supplied: boolean;
|
|
}
|
|
|
|
/** An item call's collection segments and identity value, kept as supplied rather than joined and re-split. */
|
|
interface ItemCall {
|
|
readonly segments: readonly CallSegment[];
|
|
readonly id: string;
|
|
}
|
|
|
|
/** What an item call names, or undefined when a path argument is missing. */
|
|
const itemCall = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): ItemCall | undefined => {
|
|
const names = environmentToolArguments(tool).path;
|
|
const params = new Map(tool.params.map((param) => [param.index, param]));
|
|
const segments: CallSegment[] = [];
|
|
const template = tool.path_template
|
|
.slice(tool.path_template.indexOf("/") + 1)
|
|
.split("/");
|
|
for (const [index, text] of template.entries()) {
|
|
const param = params.get(index);
|
|
if (param === undefined) {
|
|
if (text !== "") segments.push({ text, supplied: false });
|
|
continue;
|
|
}
|
|
const value = args[names.get(param.name) ?? param.name];
|
|
if (typeof value !== "string") return undefined;
|
|
segments.push({ text: value, supplied: true });
|
|
}
|
|
const last = segments.pop();
|
|
return last?.supplied === true ? { segments, id: last.text } : undefined;
|
|
};
|
|
|
|
/** How many supplied segments a held collection matches verbatim, when it matches the call under replay's path rule. */
|
|
const collectionMatch = (
|
|
collection: string,
|
|
segments: readonly CallSegment[],
|
|
): number | undefined => {
|
|
const held = segmentsOf(collection);
|
|
if (held.length !== segments.length) return undefined;
|
|
let verbatim = 0;
|
|
for (const [index, { text, supplied }] of segments.entries()) {
|
|
const segment = held[index]!;
|
|
if (supplied ? !pathValueMatches(segment, text) : segment !== text)
|
|
return undefined;
|
|
if (supplied && segment === text) verbatim += 1;
|
|
}
|
|
return verbatim;
|
|
};
|
|
|
|
/** The entity an item call names, preferring verbatim collection spellings as replay does; the id is tried percent-decoded, then as written. */
|
|
const namedEntity = (
|
|
store: EnvironmentStateStore,
|
|
type: string,
|
|
call: ItemCall,
|
|
): StateEntity | undefined => {
|
|
const ids = [...new Set([decodedPathSegment(call.id), call.id])];
|
|
const candidates = store
|
|
.collectionsOf(type)
|
|
.flatMap((collection) => {
|
|
const verbatim = collectionMatch(collection, call.segments);
|
|
return verbatim === undefined ? [] : [{ collection, verbatim }];
|
|
})
|
|
.sort((left, right) => right.verbatim - left.verbatim);
|
|
for (const { collection } of candidates)
|
|
for (const id of ids) {
|
|
const entity = store.entity(type, collection, id);
|
|
if (entity !== undefined) return entity;
|
|
}
|
|
return undefined;
|
|
};
|
|
|
|
/** An item call renders the named entity into the recorded envelope; it never invents an entity. */
|
|
const answerItem = (
|
|
serving: StateServing,
|
|
tool: EnvironmentManifestTool,
|
|
view: StateItemView,
|
|
args: ReplayArguments,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { source, store } = serving;
|
|
const call = itemCall(tool, args);
|
|
if (call === undefined)
|
|
return err(refused(tool, `Tool ${tool.name} needs every path argument.`));
|
|
const entity = namedEntity(store, view.type, call);
|
|
if (entity === undefined)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`The state holds no ${view.type} entity ${call.id} in /${call.segments.map(({ text }) => text).join("/")}.`,
|
|
),
|
|
);
|
|
const shown = shownEntity(
|
|
tool,
|
|
view,
|
|
entity,
|
|
new Set(store.type(view.type)?.volatile_fields),
|
|
);
|
|
if (!shown.ok) return shown;
|
|
const base = source.exchanges.get(view.envelope_ordinal);
|
|
const envelope = base === undefined ? undefined : recordedJson(base);
|
|
if (base === undefined || envelope === undefined)
|
|
return err(
|
|
refused(tool, `Tool ${tool.name} has no usable recorded envelope.`),
|
|
);
|
|
const exact =
|
|
selectReplayExchange(tool, new Map([[base.ordinal, base]]), args)?.exact ===
|
|
true;
|
|
return stateAnswer(
|
|
serving,
|
|
{ exchange: base, exact },
|
|
replaceAt(envelope, view.pointer, shown.value),
|
|
{
|
|
source: "state",
|
|
view: "item",
|
|
type: view.type,
|
|
collection: entity.collection,
|
|
id: entity.id,
|
|
},
|
|
);
|
|
};
|
|
|
|
/** The checked recorded line a list or document call names exactly, chosen among them as replay chooses; later or filtered recordings never qualify. */
|
|
const checkedLine = (
|
|
source: EnvironmentSource,
|
|
tool: EnvironmentManifestTool,
|
|
checked: readonly number[],
|
|
args: ReplayArguments,
|
|
): RecordedExchange | undefined => {
|
|
const lines = new Map<number, RecordedExchange>();
|
|
for (const ordinal of checked) {
|
|
const exchange = source.exchanges.get(ordinal);
|
|
if (exchange !== undefined && selectsRecordedLine(tool, exchange, args))
|
|
lines.set(ordinal, exchange);
|
|
}
|
|
return selectReplayExchange(tool, lines, args)?.exchange;
|
|
};
|
|
|
|
type StateDocumentView = Extract<StateView, { shape: "document" }>;
|
|
|
|
/** One tool call: the tool and the arguments it was called with. */
|
|
interface ToolCall {
|
|
readonly tool: EnvironmentManifestTool;
|
|
readonly args: ReplayArguments;
|
|
}
|
|
|
|
/** A list call renders the members of the checked line it names from the state. */
|
|
const answerList = (
|
|
serving: StateServing,
|
|
{ tool, args }: ToolCall,
|
|
view: StateListView,
|
|
base: RecordedExchange,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { source, store } = serving;
|
|
const envelope = recordedJson(base);
|
|
const recorded =
|
|
envelope === undefined ? undefined : listItems(envelope, view.pointer);
|
|
if (envelope === undefined || recorded === undefined)
|
|
return fromRecording(source, tool, args, "body-unusable");
|
|
const collection = collectionPathOf(base, false);
|
|
const type = store.type(view.type);
|
|
const members: readonly StateEntity[] =
|
|
view.membership === "all"
|
|
? store.inCollection(view.type, collection)
|
|
: recorded.flatMap((item) => {
|
|
const id = scalarText(item[type?.id_field ?? ""]);
|
|
const entity =
|
|
id === undefined
|
|
? undefined
|
|
: store.entity(view.type, collection, id);
|
|
return entity === undefined ? [] : [entity];
|
|
});
|
|
const volatile = new Set(type?.volatile_fields);
|
|
const items: JsonObject[] = [];
|
|
for (const entity of members) {
|
|
const shown = shownEntity(tool, view, entity, volatile);
|
|
if (!shown.ok) return shown;
|
|
items.push(shown.value);
|
|
}
|
|
return stateAnswer(
|
|
serving,
|
|
{ exchange: base, exact: true },
|
|
renderStateList(view, envelope, items),
|
|
{
|
|
source: "state",
|
|
view: "list",
|
|
type: view.type,
|
|
collection,
|
|
membership: view.membership,
|
|
listed: items.length,
|
|
},
|
|
);
|
|
};
|
|
|
|
/** A document call answers the state's value for the document on its checked line's status and provenance. */
|
|
const answerDocument = (
|
|
serving: StateServing,
|
|
tool: EnvironmentManifestTool,
|
|
base: RecordedExchange,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const current = serving.store.document(tool.name);
|
|
if (current === undefined)
|
|
return err(refused(tool, `The state holds no document for ${tool.name}.`));
|
|
return stateAnswer(serving, { exchange: base, exact: true }, current.value, {
|
|
source: "state",
|
|
view: "document",
|
|
path: current.path,
|
|
});
|
|
};
|
|
|
|
/** A list or document call that names a checked line answers from the state; one that names none answers from its recording. */
|
|
const answerCheckedLine = (
|
|
serving: StateServing,
|
|
tool: EnvironmentManifestTool,
|
|
view: StateListView | StateDocumentView,
|
|
args: ReplayArguments,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const base = checkedLine(
|
|
serving.source,
|
|
tool,
|
|
view.checked_record_ordinals,
|
|
args,
|
|
);
|
|
if (base === undefined)
|
|
return fromRecording(serving.source, tool, args, "unrecorded-request");
|
|
return view.shape === "list"
|
|
? answerList(serving, { tool, args }, view, base)
|
|
: answerDocument(serving, tool, base);
|
|
};
|
|
|
|
/** Answer one read tool call from the live state where its view is state-backed, else from its recordings. */
|
|
export const answerFromState = (
|
|
serving: StateServing,
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const view = serving.store.state.views.get(tool.name);
|
|
if (view === undefined)
|
|
return fromRecording(serving.source, tool, args, "no-view");
|
|
switch (view.shape) {
|
|
case "recorded":
|
|
return fromRecording(serving.source, tool, args, view.reason);
|
|
case "item":
|
|
return answerItem(serving, tool, view, args);
|
|
case "list":
|
|
case "document":
|
|
return answerCheckedLine(serving, tool, view, args);
|
|
}
|
|
};
|
|
|
|
/** How a served environment answers one tool call. */
|
|
export type EnvironmentToolAnswer = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
) => Result<ReplayResult, AnalysisError>;
|
|
|
|
/** The answer a served environment gives: replay without a state store, the live state with one. */
|
|
export const environmentToolAnswer = (
|
|
source: EnvironmentSource,
|
|
store: EnvironmentStateStore | undefined,
|
|
): EnvironmentToolAnswer =>
|
|
store === undefined
|
|
? (tool, args) => replayEnvironmentTool(source, tool, args)
|
|
: (tool, args) => answerFromState({ source, store }, tool, args);
|