mirror of
https://github.com/morluto/rea.git
synced 2026-12-05 22:41:36 +00:00
* feat(environment): render more read tools from the state and describe responses
Keep main's environment serving and fold in coverage for non-entity reads,
response summaries, and MCP tool annotations.
Squashed rebase of #5352 onto main.
* fix(environment): keep rendered documents and quoted samples inside their budgets
A recorded body of exponential numbers can render past 256 KiB and turn a
working read into a state size error, so that document stays a recorded replay.
Description samples are measured after JSON quoting, and the replay-fallback
catalog check uses a tool count the longer response descriptions still separate.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* feat(environment): apply evidence-gated write effects to the served state
Serve write tools whose later reads confirm the effect, and keep main's
state-file ownership and part-wise reply measurement.
Squashed rebase of #5600 onto the rebased #5352 tip.
* fix(environment): bound and validate write state history
* feat(environment): render more read tools from the state and describe responses
Keep main's environment serving and fold in coverage for non-entity reads,
response summaries, and MCP tool annotations.
Squashed rebase of #5352 onto main.
* fix(environment): keep rendered documents and quoted samples inside their budgets
A recorded body of exponential numbers can render past 256 KiB and turn a
working read into a state size error, so that document stays a recorded replay.
Description samples are measured after JSON quoting, and the replay-fallback
catalog check uses a tool count the longer response descriptions still separate.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* feat(environment): apply evidence-gated write effects to the served state
Serve write tools whose later reads confirm the effect, and keep main's
state-file ownership and part-wise reply measurement.
Squashed rebase of #5600 onto the rebased #5352 tip.
* fix(environment): bound and validate write state history
* fix(environment): bound additional collection history
* fix(environment): credit sent fields, negative sequences, and encoded targets
A later overwrite copied surviving derived fields into the sent-member
claim, so a members-only check rejected an update whose sent field still
matched. Serving floored sequences at zero and stored missing history as
zero, so a collection sequence learned from negative ranks skipped the
next value. An absence after a delete forgot the resolved collection, and
an encoded read could not observe an update spelled with another
collection encoding.
Regression tests cover each case.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* test(environment): cover resolved encoded update identities
* fix: validate timed update observations
* fix(environment): share write overlap and check clocks on earlier calls
Observation search skips a read begun before the write ended. That
comparison now uses the same overlap as the check path.
A clock learned on a later call was not checked against earlier calls
that kept the field. Serving would stamp those calls too, so the plan
stays unserved. A clock learned earlier is still refused when a later
call does not advance it.
Regression tests cover an overlapping empty update and a published_at
clock that one recorded call leaves unchanged.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* fix: preserve partial update evidence
* fix(environment): let an unmodelled write explain only the list members that differ
A failed whole-list read now reports which members alone account for the
difference. An unmodelled write excuses the read's writes only when it came
after each such member's last check and pending writes, so an older change
elsewhere no longer hides a newer write the list shows undone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7b6aab9d7191e600051693f2c192afcfc743d083)
* fix(environment): explain added fields, tie creates to serving's collection, and bound write descriptions
An update explains a field the entity lacked before when the observing
view had shown the entity, so a server-filled field is not dropped. A
create is tied to the held collection serving picks for its path. Write
descriptions and body refusals quote member names and sample them within
a byte bound. The request body is indexed once per explanation, so copied
and slugged fields no longer rescan it.
Replays 07aca54e onto the restacked branch. Its rule that a read begun
before a write ended teaches nothing is already here (fb6785dc), so only
its test is kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): state how list reads weigh unmodelled writes, added update fields and quoted members
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(environment): keep the observing view helpers with the observations
shownBefore and the item-or-list fields check move to the observe module,
keeping the write effects within the line limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): resolve unmodelled writes onto the held collection
An unmodelled path kept the request's collection spelling. An archive under
the plain spelling of a collection held encoded marked only that plain
collection unknown, so a later update was blamed for the archive's fields
and dropped. Name that entity the way a modelled write does.
Co-authored-by: morluto <morluto@users.noreply.github.com>
* fix(environment): confirm no write through volatile fields or overwritten replacements, and bound the served clock
A members-only check no longer compares volatile fields, which render
from the read itself. A document replacement credits the members it
wrote or removed at its object, so a later merge that overwrites them
takes its confirmation away. A recorded time past the range of a date
gives no served clock instead of throwing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): leave unknown entities unchecked by failed reads, volatile fields and unchecked calls
A failed item read that is no absence leaves an unknown entity unknown, so
a later usable read still checks its writes. A read showing an unknown
entity again checks no write on a volatile field. An update of an unknown
entity takes its recorded outcome and adds nothing to a built plan. A later
update that does not answer with its entity is observed only by a read
whose view shows every learned clock; without one it is unmodelled.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): fill a create's path fields from the collection serving selects
The gate built a later create's path fields from the recorded request path,
while serving fills them from the held collection it selects for that path,
so a read showing the other spelling's parent could confirm a create serving
cannot reproduce. Rules still learn from the recorded path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): name unmodelled writes as modelled ones, count fields updates write, and keep later members' types
An unmodelled write below an item path names its entity through itemTarget,
and one at or above a collection resolves the held collection, as modelled
writes do, so an encoded spelling no longer hides the entity it changed.
An update's answer counts the fields its rules write, other than increments,
as available, so a field only the update writes no longer makes it
incomplete-entities. A member a later call first stores keeps that call's
JSON type in the body's kinds, which the body check falls back to.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): let a document replacement overwrite everything under its object
A replacement claims only the members it wrote or removed, but it now
overwrites every earlier effect under its object, so a merge that wrote
the object it replaces loses its confirmation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): start the served clock from the records whose times a date can hold
A record timed past the range of a date no longer leaves the served clock
without a start, which the store read as zero and stamped writes in 1970;
the clock starts after the latest record a date can hold.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.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>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
539 lines
18 KiB
TypeScript
539 lines
18 KiB
TypeScript
import { stateBodyJson } from "../../domain/analysisView/EnvironmentStateAccumulator.js";
|
|
import {
|
|
collectionPathOf,
|
|
listItems,
|
|
missingRequiredFields,
|
|
renderStateEntity,
|
|
renderStateList,
|
|
replaceAt,
|
|
scalarText,
|
|
segmentsOf,
|
|
type JsonObject,
|
|
type RecordedViewReason,
|
|
type StateEntity,
|
|
type StateItemView,
|
|
type StateListView,
|
|
type StateView,
|
|
} from "../../domain/analysisView/environmentStateRules.js";
|
|
import {
|
|
pageBound,
|
|
pagesOnly,
|
|
} from "../../domain/analysisView/environmentStatePaging.js";
|
|
import { isAbsence } from "../../domain/analysisView/environmentStateWriteChecks.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,
|
|
replayAnswer,
|
|
replayEnvironmentTool,
|
|
selectReplayExchange,
|
|
selectsRecordedLine,
|
|
type ReplayArguments,
|
|
type ReplayResult,
|
|
} from "./environmentReplay.js";
|
|
import {
|
|
ENVIRONMENT_SERVE_OPERATION,
|
|
REPLAY_BODY_LIMIT_BYTES,
|
|
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"
|
|
| "page-exceeded";
|
|
}
|
|
| {
|
|
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" | "document-write";
|
|
readonly path: string;
|
|
}
|
|
| {
|
|
readonly source: "state";
|
|
/** A write applied to the state, or the recorded answer for an entity it does not hold. */
|
|
readonly view: "create" | "update" | "delete" | "missing";
|
|
readonly type: string;
|
|
readonly collection: string;
|
|
readonly id: 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;
|
|
}
|
|
|
|
export 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 missing = missingRequiredFields(entity, view, volatile);
|
|
return missing.length === 0
|
|
? ok(renderStateEntity(entity, view, volatile))
|
|
: 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. */
|
|
export 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. */
|
|
export 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. */
|
|
export 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. */
|
|
export interface ItemCall {
|
|
readonly segments: readonly CallSegment[];
|
|
readonly id: string;
|
|
}
|
|
|
|
/** A call's path segments: template literals and supplied values, or undefined when a path argument is missing. */
|
|
export const callSegments = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): CallSegment[] | 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 });
|
|
}
|
|
return segments;
|
|
};
|
|
|
|
/** What an item call names, or undefined when a path argument is missing. */
|
|
export const itemCall = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): ItemCall | undefined => {
|
|
const segments = callSegments(tool, args);
|
|
const last = segments?.pop();
|
|
return segments !== undefined && 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. */
|
|
export 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. */
|
|
export 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;
|
|
};
|
|
|
|
/** The answer for an entity the state does not hold: the tool's latest recorded 400, 404 or 410, else a tool error. */
|
|
export const missingAnswer = (
|
|
serving: StateServing,
|
|
tool: EnvironmentManifestTool,
|
|
missing: {
|
|
readonly type: string;
|
|
readonly collection: string;
|
|
readonly id: string;
|
|
},
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
// A read also answers with a 2xx JSON null, the absence the write gate accepts; a write never does, as a 2xx would
|
|
// report success for an entity that is not there.
|
|
const nullAbsence = tool.method === "GET";
|
|
const latestAbsence = (ordinals: readonly number[]) =>
|
|
ordinals
|
|
.map((ordinal) => serving.source.exchanges.get(ordinal))
|
|
.filter(
|
|
(exchange): exchange is RecordedExchange =>
|
|
exchange !== undefined &&
|
|
(isAbsence(exchange.status) ||
|
|
(nullAbsence &&
|
|
exchange.status !== null &&
|
|
exchange.status >= 200 &&
|
|
exchange.status < 300 &&
|
|
recordedJson(exchange) === null)),
|
|
)
|
|
.at(-1);
|
|
// The tool's own recorded absence first, else that of an item view of the type.
|
|
const itemTools = new Set(
|
|
[...serving.store.state.views.values()].flatMap((view) =>
|
|
view.shape === "item" && view.type === missing.type ? [view.tool] : [],
|
|
),
|
|
);
|
|
const recorded =
|
|
latestAbsence(tool.record_ordinals) ??
|
|
latestAbsence(
|
|
serving.source.manifest.tools
|
|
.filter((candidate) => itemTools.has(candidate.name))
|
|
.flatMap((candidate) => candidate.record_ordinals),
|
|
);
|
|
if (recorded === undefined)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`The state holds no ${missing.type} entity ${missing.id} in ${missing.collection}.`,
|
|
),
|
|
);
|
|
return ok({
|
|
...replayAnswer(serving.source, recorded, false),
|
|
state: { source: "state", view: "missing", ...missing },
|
|
});
|
|
};
|
|
|
|
/** An item call renders the named entity into the recorded envelope; it never invents an entity; one the state does not hold answers the tool's recorded absence. */
|
|
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 missingAnswer(serving, tool, {
|
|
type: view.type,
|
|
collection: `/${call.segments.map(({ text }) => text).join("/")}`,
|
|
id: call.id,
|
|
});
|
|
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;
|
|
};
|
|
|
|
/** For a list of a whole collection, a call that supplies no query argument answers from a checked line of the collection its path arguments name that only pages it, chosen as replay chooses; a requested page answers from its recording. */
|
|
const unfilteredLine = (
|
|
source: EnvironmentSource,
|
|
tool: EnvironmentManifestTool,
|
|
checked: readonly number[],
|
|
args: ReplayArguments,
|
|
): RecordedExchange | undefined => {
|
|
const query = environmentToolArguments(tool).query;
|
|
const segments = callSegments(tool, args);
|
|
if (
|
|
segments === undefined ||
|
|
[...query.values()].some((argument) => args[argument] !== undefined)
|
|
)
|
|
return undefined;
|
|
const lines = new Map<number, RecordedExchange>();
|
|
for (const ordinal of checked) {
|
|
const exchange = source.exchanges.get(ordinal);
|
|
if (
|
|
exchange !== undefined &&
|
|
pagesOnly(exchange.query ?? undefined) &&
|
|
collectionMatch(collectionPathOf(exchange, false), segments) !== undefined
|
|
)
|
|
lines.set(ordinal, exchange);
|
|
}
|
|
return selectReplayExchange(tool, lines, args)?.exchange;
|
|
};
|
|
|
|
type StateDocumentView = Extract<StateView, { shape: "document" }>;
|
|
|
|
/** One tool call: the tool, the arguments it was called with, and whether they name the answering line exactly. */
|
|
interface ToolCall {
|
|
readonly tool: EnvironmentManifestTool;
|
|
readonly args: ReplayArguments;
|
|
readonly exact: boolean;
|
|
}
|
|
|
|
/** A list call renders the members of the checked line it names from the state. */
|
|
const answerList = (
|
|
serving: StateServing,
|
|
{ tool, args, exact }: 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);
|
|
// A requested page the collection has outgrown is answered as recorded, never with more items than it asked for.
|
|
const size = exact
|
|
? pageBound(base.query ?? undefined, recorded.length)
|
|
: undefined;
|
|
if (
|
|
view.membership === "all" &&
|
|
size !== undefined &&
|
|
store.inCollection(view.type, collection).length > size
|
|
)
|
|
return fromRecording(source, tool, args, "page-exceeded");
|
|
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 },
|
|
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 named = checkedLine(
|
|
serving.source,
|
|
tool,
|
|
view.checked_record_ordinals,
|
|
args,
|
|
);
|
|
const base =
|
|
named ??
|
|
(view.shape === "list" && view.membership === "all"
|
|
? unfilteredLine(serving.source, tool, view.checked_record_ordinals, args)
|
|
: undefined);
|
|
if (base === undefined)
|
|
return fromRecording(serving.source, tool, args, "unrecorded-request");
|
|
// An unfiltered call answers on a line it did not name, so its replay match is not exact.
|
|
return view.shape === "list"
|
|
? answerList(
|
|
serving,
|
|
{ tool, args, exact: named !== undefined },
|
|
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);
|
|
}
|
|
};
|