* feat(environment): serve the writes callers make without recorded form fields
- A create member a recording sent empty ("", null, false, [] or {}) is no
longer required; a call that leaves it out is applied as sending that value
(body.blank).
- List views render envelope members that list the listed entities' ids
(Paperless's `all`), so creates in such collections are confirmed.
- Updates move their entity in collections kept sorted by a field they write,
and a failed whole-collection read after an update can teach that order.
- A later create that stores an unruled field otherwise is withheld at the
create, and an item read may fill values a create's answer had not loaded.
- An unsent field respelled between null, [] and {} is unchanged.
- The skill asks for one create with every field and one with only what a
person must give.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(skill): show how to read signed-in pages before recording
Agents guessed capture keys (artifacts, dom, final) to see pages behind
sign-in, which inspect_web_page cannot reach.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): accept every empty spelling recorded creates sent
A create that fills only what a person must give sends `null` where the
full create sent a string, and `null` or `false` for the same flag. The
merged plan now accepts each recorded empty value, and a call that leaves
the member out is applied as the earliest call sent it.
Also adds the spec folder for this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(skill): keep the vary-fields step neutral on UI or API writes
Agents read "the form" as a cue to write through the UI, where some
applications' request bodies are not exposed; a body-unusable UI write
now re-records once with request steps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): record verification for blank members and sorted writes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): address review of blank members and sorted writes
- Bulk updates move their entities in turn against the others' earlier
values and install the final order once, as replay does.
- A member's recorded empty values stay accepted once a later call teaches
its default; a left-out member with a default keeps the default.
- Write answers spell empty lists and maps as their recorded answers did.
- A rename can teach a sort when the creates chose one by a field the
update did not write, such as ids that ascend with titles.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(environment): serve the writes that later reads explain
- An item read whose object is marked deleted (deleted, isDeleted or
is_deleted true) agrees with an absent entity, as EspoCRM answers a
deleted record; such an object never seeds or adopts an entity.
- maxSize, max_results and maxResults are page sizes, for whole-collection
list lines and the list query's limit role.
- An item view also shows the fields only reads after its type's first write
show, when no initial entity holds them (Vikunja's task subscription),
without requiring them; write answers leave such a field out for entities
without it, and it no longer withholds the write as incomplete-entities.
- The skill asks updates to change the fields a person would change, and
expects a deleted object to read back as 404 or marked deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): answer sent empty members as sent, and keep a placed create's order
- A write answer spells an empty list or map the call did not send as its
recorded answer did; one the call sent is answered as sent, so a create
sending `[]` is not answered `null` because the first recorded create was.
- A read listing the whole collection that placed a create leaves the create
only the sorted inserts whose order that read follows, so a later rename
cannot teach a sort an earlier read ruled out.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): answer bulk updates without fields only later reads show
A bulk update's answer renders each entity with the same allowance a single
update's answer has: a field only reads after the type's first write showed,
which no initial entity holds, is left out for an entity without it, so a
bulk update of a seeded task is no longer refused for lacking it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): correct how the EspoCRM contact update task passes
The agent trajectories show gpt-oss passes it by creating a replacement contact
and deleting the original, since the served update refuses emailAddress; the
update itself is refused in both builds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): answer a read of a served-deleted entity marked deleted
An application that soft-deletes still answers a deleted record by id, marked
deleted. Serving now keeps an entity a served delete removed from a type whose
recorded item reads show that, until a reset or load and within the size
data/add loads, and answers a read of it with its last fields and the flag
true, instead of refusing the read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep unloaded create answers, check bulk answers with sent members, narrow inserts only on collection-order reads
- A create whose item read loaded values its answer had not records them
(`observation.read.unloaded`), and a served create's answer keeps them as
the recorded answer showed them, a zero-time owner included, while the state
holds the read's.
- Replay checks a bulk update's recorded answers with each target's sent
members, as serving answers them, so echoed `null` and `[]` no longer make
the plan body-unusable.
- A whole-collection read whose query sorts it shows the query's order, so it
no longer narrows a create's sorted insert candidates.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): record the census with main's unknown-clock rule merged
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(environment): serve query numbers, counted values and made objects
- A query parameter accepts a number or boolean, which serving sends as its
JSON text, as agents send page sizes and flags.
- A sequence may start at the value its first create took above every value
its type held (Vikunja's per-project task index), and a later create's
composed, template or started-sequence rule is adopted when it also spells
the first create's value.
- A made-object rule explains an object the application makes with each
created entity: members the request stamped, members holding the entity's
own id, and counts one past the held objects' values.
- A create's answer names the id of the one object a one-element array member
holds, so bulk creates link to their type.
- The skill reads each listed object by id before writing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(environment): let a linked create take path values it stores
A create linked to its type's own collection, whose path has no parameters,
accepts any path values when its plan stores each one in a field, as a Vikunja
task stores its project; replay and serving apply it alike.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): learn a sort from a rename only when moving its entities reaches it
Serving moves only the entities a write changes in a collection kept sorted,
so replay now tries a sort after a rename only when the entities no write the
read exercised changed already follow it. Seeded folders listed out of title
order no longer teach a title sort that serving would answer with another
order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep unloaded create answers a sent value did not echo, and learn no sort from query-sorted reads
- A served create keeps a value its recorded answer had not loaded unless the
call sent that member and the plan stores it as sent, so a create sending
`active: false` is answered `false` as recorded while the state holds the
read's `true`.
- A rename no longer teaches a sort from a whole-collection read its query
sorts, whose ties need not follow the collection's own order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): verify query values, counted values and made objects
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): learn the soft-delete flag in the state view and serve by it
Extraction now records the member later item reads set true on a record the
application soft-deleted, and the item view carries it as `deleted_flag`.
Serving reads that fact instead of scanning recorded bodies itself, so one
owner decides what a soft delete looks like.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): record the call-values checks at #7274 93821024
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): learn the soft-delete flag from item reads with a query too
A client may read a deleted record back only with a query, such as a
cache-busting parameter. Every successful read of the item tool now shows the
flag; only plain later reads still add fields.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): record the call-values checks at #7274 45832406
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): learn sorts only from orders a list read confirmed
- A sort retry after a failed whole-collection read requires the entities no
write changed since a list last showed them to follow it already, rather than
excusing every entity the update's tool ever wrote: an earlier rename a list
confirmed in place stays where it was.
- An update takes its creates' sort only from a create a list read showed
placed; replay still tries a sort a create guessed from the initial order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): drop entities read back as deleted and answer soft deletes as deleted
- A held entity a later read shows marked deleted is dropped, not adopted with
the marked object's fields.
- Bulk-update replay renders answers with the optional and later-only fields
serving uses, so a bulk update of created and seeded entities replays.
- A served delete of a soft-deleting type answers with the entity marked
deleted, single and bulk.
- A deleted flag only query reads showed is a field of the item view, so a
served tombstone keeps it where live records omit it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): check made objects as recorded and keep their ids and clocks honest
- A made object's clock counts as a write clock, so a capture with no clock
anchor withholds the create instead of stamping 1970.
- Members holding the entity's identity follow the id written, generated or
sent, through the type's id field.
- A later create's made object is checked as recorded, before its own members
are rewritten, so one naming another entity withholds the plan.
- A later create's template is adopted only when it spells that create's value
too, not just when the first create's text holds its source value.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): move updated entities only by placed sorts and keep query-sorted reads from confirming order
Replay moved an updated entity by a sort a create only guessed, while the
update plan exported only placed sorts, so a read could confirm an update
by a move serving would not make. Both now use the placed sort. A passing
list read clears its entities from the moved set only when the state
decides the order of every entity it lists, so a read whose query sorts
it no longer hides an earlier move from a later sort check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(environment): count six withheld plans that explain more, not seven
The bulk task create counted among them is served on this branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): try a learned sort by moving each pending write in turn, as serving does
#retrySort sorted the whole collection, which a list could match while
serving, moving each renamed entity in turn against the others' values
before their own writes, gave another order. The state now records the
values each write replaced, and the retry replays the writes since a
list in collection order last showed their entities.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): answer a served delete with the deleted flag its recorded answer showed
An application may answer a delete with the record as it was and mark it
deleted only on later reads. Delete answers, single and bulk, now take
the flag's value from the recorded answer; reads of a served-deleted
entity still show it marked deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(environment): set aside two hunks next to lines main's saved-values change rewrites
Main's #7267 changes the lines beside the blank-member docs and the
empty-spelling check in explainUpdate. Setting them aside lets that merge
apply cleanly; the commit after it puts them back on top of main's text.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(environment): restore the set-aside hunks on main and bump the skill to 51
Puts the blank-member docs and the empty-spelling check back beside main's
slug and composed text and heldSlugRule. Main is at skill 50 with
different text, so this branch's skill changes take 51.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(environment): bump the skill to 52 above #7260's 51
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore(environment): put back the call-values hunks main's merge took its side for, and bump the skill to 53
The merge of main kept main's side where it overlapped this branch, so it
could commit without a conflict. This restores this branch's side next to
main's: made-object agreement beside the & slug spellings, sequence starts
in the earlier evidence (now built by earlierOf), the combined value
imports, and recording step 2 beside main's UI-first step 3. Main is at
skill 50 and #7274 at 52, so this branch takes 53.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep sorts a list showed in place ruled out, and created answers' nested members as recorded
A whole list in collection order that showed a renamed entity where a
sort by the renamed field would have moved it now rules that sort out, so
a later rename of the same entity cannot teach it. A create's answer
leaves out members its item read added inside an object the answer
showed, as the recorded answer did; the state still stores them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(environment): serve writes whose calls send different members
Recordings now vary what a type's two creates and updates send, and REA
withheld writes where a later call left out what the first sent. An update
plan's required members narrow to those every call sent; a member one create
sent and another left for the application to number is a sequence that
takes the value a call sends; a PUT's left-out member the application
cleared becomes that member's default; and an update's clock is held as
the read after it spells it. The skill spaces creates (skill 54).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep a later create's made object only with clocks its request stamped
followsMadeObjects only checked that a made object's clocks parsed, so a
later create whose object showed an older clock still passed, while serving
stamps the write's clock. Its clocks must now be in the rule's format and
within the stamp window of that create's request.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): accept sent values either way, check defaults against every call, and store update clocks as reads spell them
A sequence that takes sent values now accepts one a later create sent
after the first left the member to be numbered. A default an update learned
must agree with every update that left its member out, else the plan is
withheld. An update plan whose read-back spells a stamped clock at a coarser
precision keeps that read as observation.read, and serving stores the
update's clocks in its spelling while answers keep the response's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): check recorded member and sequence values
* fix(environment): compare soft-deleted read fields
* fix(environment): reject contradictory learned sequences
* fix(environment): preserve initially deleted item observations
* fix(environment): index stored deleted entities separately
* fix(environment): replay lists that include deleted records
* fix(environment): count a sequence number a create sends, as replay does
Serving now records a number a call sends for a `sequence` with `sent` in the
same count history it generates from, so after that entity is deleted the next
generated number still follows it, as replay's takeSequences does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): make no count of a made-object member earlier creates held alike
A count only a later create shows starts at the exemplar's value, which is
right only while the exemplar is the one create accepted: creates accepted
after it showed the member unchanged, which a count would have moved. The
merge now refuses such a count, as the top-level sequence check does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): check PUT defaults against reads, and respell update clocks by serving's rule
A default a PUT learns must also agree with what the read after an earlier or
the current call showed for the member its answer left out, so a call whose
read showed the member kept withholds a later clearing default.
Replay and serving now choose an update clock's stored spelling by one rule,
readSpellsCoarser: the read after it at a coarser precision in the same zone
and separator. A read in another zone or separator is no longer adopted by
replay, which serving could not store, and a create's plain clocks stay as
answered, as serving makes them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep the largest sequence value in replay, and store update clocks by the kept read
Replay now keeps the largest value a sequence took, as serving's commitWrite
does, so a lower sent value no longer lowers the next number.
Serving stores every update's clocks in the spelling of the read the plan
keeps as observation.read; replay now does the same through
readSpelledClocks, instead of adopting each update's own read, so a later
update whose read spells its clock otherwise contradicts the plan. The plain
clock branch of restampedFields, which no caller used any more, is gone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): keep a left-out default from numbering, a read's sub-millisecond digits, and references named by member
A member a call left out and the application stored a fixed value for is no
longer turned into a numbered sequence by a later call that left it out.
Serving shortens an update's clock to the read's precision from the answer's
own digits, keeping microseconds. A PUT that names a reference field's entity
by its member supplies that field, for the default check and in serving.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): count a reference a later PUT names toward the default an earlier one cleared
The default check now reads the reference rules the current call shows as
well as the plan's, so a PUT naming the owner by ownerId after one that
cleared it is served, as in the other order.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): number a left-out member past every sent value, and never fill it with a sent blank
A later create the application numbered at or below a value an earlier create
sent no longer turns the echo into a numbered sequence, since serving counts
past every sent value. A member a numbered sequence covers is not filled with
an empty value another call sent when a call leaves it out.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(environment): count sent values in the sequence's scope before numbering a left-out member
The largest value earlier creates sent is kept by type and by collection, and
a collection-scoped sequence adopted later checks only its own collection, so
a number sent in another collection no longer withholds a create numbered
within its own.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
895 lines
28 KiB
TypeScript
895 lines
28 KiB
TypeScript
import {
|
|
createdFields,
|
|
documentBodyProblem,
|
|
laterItemFields,
|
|
optionalFields,
|
|
renewUuids,
|
|
updatedEntity,
|
|
updatedFields,
|
|
valueAt,
|
|
writtenDocument,
|
|
writtenResponse,
|
|
type GenerateValue,
|
|
} from "../../domain/analysisView/environmentStateWriteApply.js";
|
|
import {
|
|
insertIndex,
|
|
resortedMembers,
|
|
nextInteger,
|
|
} from "../../domain/analysisView/environmentStateWriteExplain.js";
|
|
import { callRenewal } from "../../domain/analysisView/environmentStateWriteGenerated.js";
|
|
import {
|
|
heldObjects,
|
|
madeObjectValue,
|
|
nestedClockValue,
|
|
nextMadeCount,
|
|
unenveloped,
|
|
readSpelledClocks,
|
|
} from "../../domain/analysisView/environmentStateWriteStamps.js";
|
|
import {
|
|
anyLinkedSource,
|
|
linkedCollection,
|
|
sameLinkedSource,
|
|
} from "../../domain/analysisView/environmentStateWriteLinks.js";
|
|
import {
|
|
pathValuesOf,
|
|
type GeneratedRule,
|
|
type StateWritePlan,
|
|
type WriteCall,
|
|
} from "../../domain/analysisView/environmentStateWriteRules.js";
|
|
import { withRead } from "../../domain/analysisView/environmentStateWriteObserve.js";
|
|
import {
|
|
formatClock,
|
|
generatedIntegerDigits,
|
|
seededInteger,
|
|
seededLike,
|
|
sequenceNumber,
|
|
spelledLike,
|
|
startedSequence,
|
|
} from "../../domain/analysisView/environmentStateWriteValues.js";
|
|
import {
|
|
at,
|
|
ownMember,
|
|
collectionMatch,
|
|
decodedSegment,
|
|
isObject,
|
|
pointerTokens,
|
|
scalarText,
|
|
type JsonObject,
|
|
type StateEntity,
|
|
} from "../../domain/analysisView/environmentStateRules.js";
|
|
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
|
import type { JsonValue } from "../../domain/jsonValue.js";
|
|
import { err, ok, type Result } from "../../domain/result.js";
|
|
import {
|
|
replayAnswer,
|
|
selectReplayExchange,
|
|
type ObservedQuery,
|
|
type ReplayArguments,
|
|
} from "./environmentReplay.js";
|
|
import type { EnvironmentManifestTool } from "./environmentSource.js";
|
|
import { callSegments } from "./environmentStateCallLines.js";
|
|
import {
|
|
itemCall,
|
|
missingAnswer,
|
|
namedEntity,
|
|
recordedJson,
|
|
refused,
|
|
deleteAnswerFields,
|
|
softDeleteFlag,
|
|
stateAnswer,
|
|
type StateAnswer,
|
|
type StateProvenance,
|
|
type StateServing,
|
|
} from "./environmentStateAnswer.js";
|
|
import { createdCollection } from "./environmentStateCollections.js";
|
|
import {
|
|
isLoadableValue,
|
|
unloadableMember,
|
|
type HeldDocument,
|
|
} from "./environmentStateDocument.js";
|
|
import { environmentToolArguments } from "./environmentTools.js";
|
|
|
|
/** Attempts at a generated UUID or token before a collision with held values is refused. */
|
|
const GENERATION_ATTEMPTS = 64;
|
|
|
|
/** One served write call: the tool, its plan and its arguments. */
|
|
export interface WriteRequest {
|
|
readonly tool: EnvironmentManifestTool;
|
|
readonly plan: StateWritePlan;
|
|
readonly args: ReplayArguments;
|
|
readonly observedQuery?: ObservedQuery;
|
|
}
|
|
|
|
/** The path values a call supplies, keyed by template segment as write plans name them. */
|
|
export const pathValues = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): Map<string, string> => {
|
|
const names = environmentToolArguments(tool).path;
|
|
const template = tool.path_template
|
|
.slice(tool.path_template.indexOf("/") + 1)
|
|
.split("/");
|
|
const values = new Map<string, string>();
|
|
for (const param of tool.params) {
|
|
const value = ownMember(args, names.get(param.name) ?? param.name);
|
|
const segment = template[param.index] ?? "";
|
|
if (typeof value === "string") values.set(segment.slice(1, -1), value);
|
|
}
|
|
return values;
|
|
};
|
|
|
|
/** A refusal for a value `data/add` would refuse, so `data/get` always reports a state that loads back. */
|
|
export const unloadable = (
|
|
tool: EnvironmentManifestTool,
|
|
holder: string,
|
|
): AnalysisError =>
|
|
refused(
|
|
tool,
|
|
`${holder} would hold a value that is not exactly representable JSON, which data/add could not load back.`,
|
|
);
|
|
|
|
/** The call's body: an object, unwrapped from the envelope the capture sent it in, nothing, or a refusal for any other value or one holding a value the state cannot hold. */
|
|
const callBody = ({
|
|
tool,
|
|
args,
|
|
plan,
|
|
}: WriteRequest): Result<JsonObject | undefined, AnalysisError> => {
|
|
const name = environmentToolArguments(tool).body;
|
|
const sent = name === undefined ? undefined : ownMember(args, name);
|
|
if (sent === undefined) return ok(undefined);
|
|
const envelope = plan.body?.envelope ?? "";
|
|
const value = unenveloped(sent as JsonValue, plan.body?.envelope);
|
|
if (value === undefined)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`Tool ${tool.name} takes its JSON object body wrapped as {"${envelope}":[{...}]}, as the capture sent it.`,
|
|
),
|
|
);
|
|
if (!isObject(value))
|
|
return err(refused(tool, `Tool ${tool.name} takes a JSON object body.`));
|
|
const member = unloadableMember(value as JsonObject);
|
|
return member === undefined
|
|
? ok(value as JsonObject)
|
|
: err(unloadable(tool, `Member ${member}`));
|
|
};
|
|
|
|
/** The object a recorded response shows at a pointer. */
|
|
const recordedObject = (
|
|
serving: StateServing,
|
|
at: { readonly ordinal: number; readonly pointer: string },
|
|
): JsonObject | undefined => {
|
|
const exchange = serving.source.exchanges.get(at.ordinal);
|
|
const body = exchange === undefined ? undefined : recordedJson(exchange);
|
|
const object = body === undefined ? undefined : valueAt(body, at.pointer);
|
|
return isObject(object) ? object : undefined;
|
|
};
|
|
|
|
/** The entity a recorded observation shows, with a create's read-back over it: the values a create keeps and an update's constants. */
|
|
export const observedEntity = (
|
|
serving: StateServing,
|
|
plan: StateWritePlan,
|
|
): JsonObject | undefined => {
|
|
if (plan.observation === null) return undefined;
|
|
const object = recordedObject(serving, plan.observation);
|
|
if (object === undefined || plan.observation.read === undefined)
|
|
return object;
|
|
const read = recordedObject(serving, plan.observation.read);
|
|
return read === undefined
|
|
? undefined
|
|
: withRead(object, read, plan.observation.read.shape);
|
|
};
|
|
|
|
/** One past the largest integer these entities hold in the field, read as the exemplar spells it, or undefined when none holds one. */
|
|
const nextHeld = (
|
|
entities: readonly StateEntity[],
|
|
field: string,
|
|
exemplar: JsonValue,
|
|
) =>
|
|
nextInteger(
|
|
entities.map((entity) => entity.fields),
|
|
field,
|
|
exemplar,
|
|
);
|
|
|
|
/** The entity a write generates values for: its collection, the observed entity and, for an update, the entity it writes. */
|
|
export interface GeneratedTarget {
|
|
readonly name: string;
|
|
readonly collection: readonly StateEntity[];
|
|
readonly observed: JsonObject;
|
|
/** The entity an update writes, whose values a renewed field keeps. */
|
|
readonly current?: JsonObject;
|
|
}
|
|
|
|
/** The fields of each entity of a type with an id the live state holds, which a referencing write repeats. */
|
|
export const heldEntity =
|
|
(serving: StateServing) =>
|
|
(type: string, id: string): JsonObject[] =>
|
|
serving.store
|
|
.ofType(type)
|
|
.flatMap((entity) => (entity.id === id ? [entity.fields] : []));
|
|
|
|
/** What an update generates values for: the entity it writes, in its collection. */
|
|
export const updateTarget = (
|
|
serving: StateServing,
|
|
entity: StateEntity,
|
|
observed: JsonObject,
|
|
): GeneratedTarget => ({
|
|
name: entity.collection,
|
|
collection: serving.store.inCollection(entity.type, entity.collection),
|
|
observed,
|
|
current: entity.fields,
|
|
});
|
|
|
|
/**
|
|
* Values one served write generates: its clock instant, sequences one past the largest held
|
|
* value, and UUIDs and tokens seeded by the state Evidence, tool, field and write count,
|
|
* skipping values the type already holds. Every entity the call writes shares them.
|
|
*/
|
|
export const generator = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
): {
|
|
readonly forTarget: (target: GeneratedTarget) => GenerateValue;
|
|
readonly taken: Map<string, number>;
|
|
/** Count a number the call sent for a sequence, as replay does, so later generated ones follow it. */
|
|
readonly sentSequence: (
|
|
target: string,
|
|
rule: Extract<GeneratedRule, { rule: "sequence" }>,
|
|
value: JsonValue | undefined,
|
|
) => void;
|
|
} => {
|
|
const { store } = serving;
|
|
const write = store.pendingWrite();
|
|
const taken = new Map<string, number>();
|
|
const sequence = (key: string, held: number | undefined): number => {
|
|
const value = store.sequenceAfter(key, held);
|
|
taken.set(key, value);
|
|
return value;
|
|
};
|
|
const sequenceKey = (
|
|
rule: Extract<GeneratedRule, { rule: "sequence" }>,
|
|
target: string,
|
|
) =>
|
|
`${request.tool.name} ${rule.field} ${rule.scope === "collection" ? target : ""}`;
|
|
const ofType = store.ofType(request.plan.target ?? "");
|
|
// A sequence never reuses a value the state started with, even after its entity was deleted.
|
|
const started = store.startedWith(request.plan.target ?? "");
|
|
const startedIn = (collection: string) =>
|
|
started.filter((held) => held.collection === collection);
|
|
const renewed = callRenewal(
|
|
`${store.state.evidenceId}:${request.tool.name}:renewed:${String(write.count)}`,
|
|
);
|
|
const unused = (
|
|
field: string,
|
|
make: (attempt: number) => JsonValue,
|
|
): Result<JsonValue, string> => {
|
|
const held = new Set(
|
|
ofType.map((entity) => scalarText(ownMember(entity.fields, field))),
|
|
);
|
|
for (let attempt = 0; attempt < GENERATION_ATTEMPTS; attempt += 1) {
|
|
const value = make(attempt);
|
|
if (!held.has(scalarText(value))) return ok(value);
|
|
}
|
|
return err(
|
|
`Could not generate a unique value for ${field} after ${String(GENERATION_ATTEMPTS)} attempts without colliding with the held state.`,
|
|
);
|
|
};
|
|
const generate = (
|
|
target: GeneratedTarget,
|
|
rule: GeneratedRule,
|
|
): Result<JsonValue, string> => {
|
|
const exemplar = ownMember(target.observed, rule.field) ?? "";
|
|
const seed = (attempt: number) =>
|
|
`${store.state.evidenceId}:${request.tool.name}:${rule.field}:${String(write.count)}:${String(attempt)}`;
|
|
switch (rule.rule) {
|
|
case "clock":
|
|
case "held-clock":
|
|
case "nested-clock": {
|
|
const value = formatClock(write.clockMs, rule.format);
|
|
if (value === undefined)
|
|
return err(
|
|
`The generated clock for ${rule.field} is outside its recorded four-digit year format.`,
|
|
);
|
|
return rule.rule === "nested-clock"
|
|
? nestedClockValue(
|
|
ownMember(target.current ?? target.observed, rule.field),
|
|
rule,
|
|
value,
|
|
)
|
|
: ok(value);
|
|
}
|
|
case "sequence":
|
|
return ok(
|
|
spelledLike(
|
|
exemplar,
|
|
sequence(
|
|
sequenceKey(rule, target.name),
|
|
startedSequence(
|
|
nextHeld(
|
|
rule.scope === "collection"
|
|
? [...target.collection, ...startedIn(target.name)]
|
|
: [...ofType, ...started],
|
|
rule.field,
|
|
exemplar,
|
|
),
|
|
rule.start,
|
|
),
|
|
),
|
|
),
|
|
);
|
|
case "made-object": {
|
|
const clock = formatClock(write.clockMs, rule.format);
|
|
if (clock === undefined)
|
|
return err(
|
|
`The generated clock for ${rule.field} is outside its recorded four-digit year format.`,
|
|
);
|
|
const base = ownMember(target.observed, rule.field);
|
|
const held = heldObjects(
|
|
[...ofType, ...started].map((entity) => entity.fields),
|
|
rule.field,
|
|
);
|
|
return madeObjectValue(base, rule, clock, (count) =>
|
|
sequence(
|
|
`${request.tool.name} ${rule.field}/${count.member}`,
|
|
nextMadeCount(
|
|
held,
|
|
count,
|
|
isObject(base) ? ownMember(base, count.member) : undefined,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
case "unique":
|
|
return unused(rule.field, (attempt) =>
|
|
generatedIntegerDigits(exemplar) === undefined
|
|
? seededLike(seed(attempt), exemplar)
|
|
: seededInteger(seed(attempt), exemplar),
|
|
);
|
|
case "renewed":
|
|
return ok(
|
|
renewUuids(
|
|
ownMember(target.current, rule.field) ?? null,
|
|
rule.pointers,
|
|
renewed,
|
|
),
|
|
);
|
|
case "identity":
|
|
if (rule.generator === "sequence")
|
|
return ok(
|
|
spelledLike(
|
|
exemplar,
|
|
sequence(
|
|
`${request.plan.target ?? ""} ${rule.field} ${target.name}`,
|
|
nextHeld(
|
|
[...target.collection, ...startedIn(target.name)],
|
|
rule.field,
|
|
exemplar,
|
|
),
|
|
),
|
|
),
|
|
);
|
|
return unused(rule.field, (attempt) =>
|
|
seededLike(seed(attempt), exemplar, rule.generator === "uuid"),
|
|
);
|
|
}
|
|
};
|
|
return {
|
|
forTarget: (target) => (rule) => generate(target, rule),
|
|
taken,
|
|
sentSequence: (target, rule, value) => {
|
|
const number = sequenceNumber(value);
|
|
if (number === undefined) return;
|
|
const key = sequenceKey(rule, target);
|
|
// commitWrite keeps the larger of this and the values taken before.
|
|
taken.set(key, Math.max(taken.get(key) ?? number, number));
|
|
},
|
|
};
|
|
};
|
|
|
|
/** A write's answer on its recorded response's status and content type: a rendered body, none, or the recorded one. */
|
|
export const writeAnswer = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
rendered:
|
|
| {
|
|
readonly fields: JsonObject | undefined;
|
|
readonly id: string;
|
|
readonly sent?: readonly string[];
|
|
}
|
|
| ((
|
|
recorded: JsonValue | undefined,
|
|
) => Result<JsonValue | undefined, string>),
|
|
state: StateProvenance,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { plan, tool, args } = request;
|
|
const exchange =
|
|
plan.response === null
|
|
? undefined
|
|
: serving.source.exchanges.get(plan.response.ordinal);
|
|
if (plan.response === null || exchange === undefined)
|
|
return err(refused(tool, `Tool ${tool.name} has no recorded response.`));
|
|
const exact =
|
|
selectReplayExchange(
|
|
tool,
|
|
new Map([[exchange.ordinal, exchange]]),
|
|
args,
|
|
request.observedQuery,
|
|
)?.exact === true;
|
|
if (plan.response.shape === "recorded")
|
|
return ok({ ...replayAnswer(serving.source, exchange, exact), state });
|
|
const recorded = recordedJson(exchange);
|
|
const body =
|
|
typeof rendered === "function"
|
|
? rendered(recorded)
|
|
: writtenResponse(
|
|
plan.response,
|
|
recorded,
|
|
{
|
|
...rendered,
|
|
clocks:
|
|
plan.observation?.read?.shape === "item"
|
|
? plan.rules.flatMap((rule) =>
|
|
rule.rule === "clock" ? [rule.field] : [],
|
|
)
|
|
: [],
|
|
// A member the call sent and the plan stores as sent is answered as sent; any other keeps the recorded answer.
|
|
unloaded: (plan.observation?.read?.unloaded ?? []).filter(
|
|
(path) => {
|
|
const [field] = pointerTokens(path);
|
|
return !(
|
|
rendered.sent?.includes(field!) === true &&
|
|
plan.rules.some(
|
|
(rule) => rule.field === field && rule.rule === "echo",
|
|
)
|
|
);
|
|
},
|
|
),
|
|
},
|
|
optionalFields(plan),
|
|
laterItemFields(
|
|
serving.store.state.views.values(),
|
|
serving.store.state.entities,
|
|
plan.target,
|
|
),
|
|
);
|
|
if (!body.ok) return err(refused(tool, body.error));
|
|
return stateAnswer(serving, { exchange, exact }, body.value ?? null, state);
|
|
};
|
|
|
|
/** The path arguments a call supplies as given, by the template segment each fills. */
|
|
const pathArguments = (
|
|
tool: EnvironmentManifestTool,
|
|
args: ReplayArguments,
|
|
): Map<number, string> => {
|
|
const names = environmentToolArguments(tool).path;
|
|
return new Map(
|
|
tool.params.flatMap((param) => {
|
|
const value = ownMember(args, names.get(param.name) ?? param.name);
|
|
return typeof value === "string" ? [[param.index, value] as const] : [];
|
|
}),
|
|
);
|
|
};
|
|
|
|
/** The path of the recorded call a plan was built from. */
|
|
const exemplarPath = (
|
|
serving: StateServing,
|
|
plan: StateWritePlan,
|
|
): string | undefined =>
|
|
plan.exemplar_ordinal === null
|
|
? undefined
|
|
: serving.source.exchanges.get(plan.exemplar_ordinal)?.path;
|
|
|
|
/** The collection a create writes into: a linked plan's, only for its exemplar's path arguments, else the one the call's path selects. */
|
|
const writtenCollection = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
): Result<string | undefined, AnalysisError> => {
|
|
const { tool, plan } = request;
|
|
const linked = linkedCollection(plan, tool.path_template);
|
|
if (linked === undefined)
|
|
return ok(
|
|
createdCollection(serving, tool, request.args, plan.target ?? ""),
|
|
);
|
|
// No read showed where other path arguments create, unless they cannot change it.
|
|
return anyLinkedSource(plan, tool.path_template) ||
|
|
sameLinkedSource(
|
|
tool.path_template,
|
|
exemplarPath(serving, plan),
|
|
pathArguments(tool, request.args),
|
|
)
|
|
? ok(linked)
|
|
: err(
|
|
refused(
|
|
tool,
|
|
`Tool ${tool.name} creates into ${linked} only with the path arguments its recording sent.`,
|
|
),
|
|
);
|
|
};
|
|
|
|
/**
|
|
* The path values a create's path fields take, decoded once as the gate learned them: a linked
|
|
* create that accepts its exemplar's source only takes that; another the collection this call
|
|
* selects, else its own arguments.
|
|
*/
|
|
const createdPathValues = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
call: WriteCall,
|
|
collection: string,
|
|
): ReadonlyMap<string, string> => {
|
|
const { tool, plan } = request;
|
|
const exemplar =
|
|
linkedCollection(plan, tool.path_template) === undefined ||
|
|
anyLinkedSource(plan, tool.path_template)
|
|
? undefined
|
|
: exemplarPath(serving, plan);
|
|
return (
|
|
(exemplar === undefined
|
|
? undefined
|
|
: pathValuesOf(tool.path_template, exemplar)) ??
|
|
pathValuesOf(tool.path_template, collection) ??
|
|
new Map(
|
|
[...call.pathValues].map(([name, value]) => [
|
|
name,
|
|
decodedSegment(value),
|
|
]),
|
|
)
|
|
);
|
|
};
|
|
|
|
const answerCreate = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
call: WriteCall,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { tool, plan } = request;
|
|
const type = plan.target ?? "";
|
|
const idField = serving.store.type(type)?.id_field ?? "";
|
|
const target = writtenCollection(serving, request);
|
|
if (!target.ok) return target;
|
|
const collection = target.value;
|
|
const observed = observedEntity(serving, plan);
|
|
if (collection === undefined || observed === undefined)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`Tool ${tool.name} needs every path argument to be non-empty.`,
|
|
),
|
|
);
|
|
if (plan.collection !== null && plan.collection !== collection)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`The recorded create's values are tied to ${plan.collection}; the environment models creates only there.`,
|
|
),
|
|
);
|
|
const members = serving.store.inCollection(type, collection);
|
|
const values = generator(serving, request);
|
|
const created = {
|
|
...call,
|
|
pathValues: createdPathValues(serving, request, call, collection),
|
|
};
|
|
const fields = createdFields(
|
|
plan,
|
|
observed,
|
|
created,
|
|
values.forTarget({ name: collection, collection: members, observed }),
|
|
heldEntity(serving),
|
|
idField,
|
|
);
|
|
if (!fields.ok) return err(refused(tool, fields.error));
|
|
for (const rule of plan.rules)
|
|
if (
|
|
rule.rule === "sequence" &&
|
|
rule.sent === true &&
|
|
Object.hasOwn(call.body ?? {}, rule.field)
|
|
)
|
|
values.sentSequence(
|
|
collection,
|
|
rule,
|
|
ownMember(fields.value, rule.field),
|
|
);
|
|
const field = unloadableMember(fields.value);
|
|
if (field !== undefined) return err(unloadable(tool, `Field ${field}`));
|
|
const id = scalarText(ownMember(fields.value, idField));
|
|
if (
|
|
id === undefined ||
|
|
serving.store.entity(type, collection, id) !== undefined
|
|
)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`The state already holds a ${type} entity ${id ?? ""} in ${collection}.`,
|
|
),
|
|
);
|
|
const state = {
|
|
source: "state",
|
|
view: "create",
|
|
type,
|
|
collection,
|
|
id,
|
|
} as const;
|
|
const answer = writeAnswer(
|
|
serving,
|
|
request,
|
|
{ fields: fields.value, id, sent: Object.keys(call.body ?? {}) },
|
|
state,
|
|
);
|
|
if (!answer.ok) return answer;
|
|
const inserted = serving.store.insert(
|
|
{
|
|
type,
|
|
collection,
|
|
id,
|
|
fields: fields.value,
|
|
view_fields: [],
|
|
record_ordinals: [],
|
|
},
|
|
insertIndex(
|
|
plan.insert ?? { rule: "last" },
|
|
members.map((entity) => entity.fields),
|
|
fields.value,
|
|
),
|
|
);
|
|
if (!inserted.ok) return inserted;
|
|
serving.store.commitWrite(values.taken);
|
|
return answer;
|
|
};
|
|
|
|
/** The held entity an update or delete names, or the answer for one the state does not hold. */
|
|
const targetEntity = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
): Result<StateEntity, Result<StateAnswer, AnalysisError>> => {
|
|
const { tool, plan, args } = request;
|
|
const call = itemCall(tool, args, plan.address?.by === "action");
|
|
if (call === undefined)
|
|
return err(
|
|
err(refused(tool, `Tool ${tool.name} needs every path argument.`)),
|
|
);
|
|
const entity = namedEntity(serving.store, plan.target ?? "", call);
|
|
return entity === undefined
|
|
? err(
|
|
missingAnswer(serving, tool, {
|
|
type: plan.target ?? "",
|
|
collection: `/${call.segments.map(({ text }) => text).join("/")}`,
|
|
id: call.id,
|
|
}),
|
|
)
|
|
: ok(entity);
|
|
};
|
|
|
|
const answerUpdate = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
call: WriteCall,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { tool, plan } = request;
|
|
const target = targetEntity(serving, request);
|
|
if (!target.ok) return target.error;
|
|
const entity = target.value;
|
|
const observed = observedEntity(serving, plan) ?? {};
|
|
const values = generator(serving, request);
|
|
const written = updatedFields(
|
|
plan,
|
|
{ before: entity.fields, observed },
|
|
{ ...call, id: entity.id },
|
|
values.forTarget(updateTarget(serving, entity, observed)),
|
|
heldEntity(serving),
|
|
);
|
|
if (!written.ok) return err(refused(tool, written.error));
|
|
// An increment can pass the exact integers.
|
|
const field = unloadableMember(written.value);
|
|
if (field !== undefined) return err(unloadable(tool, `Field ${field}`));
|
|
const answer = writeAnswer(
|
|
serving,
|
|
request,
|
|
{
|
|
fields: written.value,
|
|
id: entity.id,
|
|
sent: Object.keys(call.body ?? {}),
|
|
},
|
|
{
|
|
source: "state",
|
|
view: "update",
|
|
type: entity.type,
|
|
collection: entity.collection,
|
|
id: entity.id,
|
|
},
|
|
);
|
|
if (!answer.ok) return answer;
|
|
const after = updatedEntity(
|
|
entity,
|
|
storedUpdate(serving, plan, written.value),
|
|
);
|
|
const updated = serving.store.updateAll(
|
|
[after],
|
|
sortedOrder(serving, plan, [{ before: entity, after }]),
|
|
);
|
|
if (!updated.ok) return updated;
|
|
serving.store.commitWrite(values.taken);
|
|
return answer;
|
|
};
|
|
|
|
/** An update's fields as the state stores them: its clocks spelled as the plan's read-back spelled them. */
|
|
export const storedUpdate = (
|
|
serving: StateServing,
|
|
plan: StateWritePlan,
|
|
written: JsonObject,
|
|
): JsonObject =>
|
|
readSpelledClocks(
|
|
plan.rules,
|
|
written,
|
|
plan.observation?.read === undefined
|
|
? undefined
|
|
: recordedObject(serving, plan.observation.read),
|
|
);
|
|
|
|
/** The collection's members in the order a sorted collection holds them after these writes; empty when the plan keeps them in place. */
|
|
export const sortedOrder = (
|
|
serving: StateServing,
|
|
plan: StateWritePlan,
|
|
writes: readonly {
|
|
readonly before: StateEntity;
|
|
readonly after: StateEntity;
|
|
}[],
|
|
): StateEntity[] => {
|
|
const [first] = writes;
|
|
if (plan.insert?.rule !== "sorted" || first === undefined) return [];
|
|
return resortedMembers(
|
|
plan.insert,
|
|
serving.store.inCollection(first.before.type, first.before.collection),
|
|
writes,
|
|
);
|
|
};
|
|
|
|
const answerDelete = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const target = targetEntity(serving, request);
|
|
if (!target.ok) return target.error;
|
|
const entity = target.value;
|
|
const { response } = request.plan;
|
|
const exchange =
|
|
response === null
|
|
? undefined
|
|
: serving.source.exchanges.get(response.ordinal);
|
|
const recorded = exchange === undefined ? undefined : recordedJson(exchange);
|
|
// A soft-deleting application answers with the entity's deleted flag as its recorded answer showed it.
|
|
const answer = writeAnswer(
|
|
serving,
|
|
request,
|
|
{
|
|
fields: deleteAnswerFields(
|
|
serving,
|
|
entity.type,
|
|
entity.fields,
|
|
recorded === undefined
|
|
? undefined
|
|
: at(recorded, response!.pointer ?? ""),
|
|
),
|
|
id: entity.id,
|
|
},
|
|
{
|
|
source: "state",
|
|
view: "delete",
|
|
type: entity.type,
|
|
collection: entity.collection,
|
|
id: entity.id,
|
|
},
|
|
);
|
|
if (answer.ok) {
|
|
// An application that soft-deletes still answers the entity by id, so its last fields are kept for that read.
|
|
serving.store.remove(
|
|
entity,
|
|
softDeleteFlag(serving, entity.type) !== undefined,
|
|
);
|
|
serving.store.commitWrite(new Map());
|
|
}
|
|
return answer;
|
|
};
|
|
|
|
/** The held document a call changes: only at the path the state holds it, with members the capture sent as the JSON types the document holds. */
|
|
const documentTarget = (
|
|
serving: StateServing,
|
|
{ tool, plan, args }: WriteRequest,
|
|
call: WriteCall,
|
|
): Result<HeldDocument, AnalysisError> => {
|
|
const held = serving.store.document(plan.target ?? "");
|
|
const segments = callSegments(tool, args);
|
|
if (held === undefined || plan.body === null)
|
|
return err(
|
|
refused(tool, `The state holds no document for ${plan.target ?? ""}.`),
|
|
);
|
|
if (segments === undefined)
|
|
return err(refused(tool, `Tool ${tool.name} needs every path argument.`));
|
|
// Document reads answer only on their recorded line, so a write elsewhere has no document to change.
|
|
if (collectionMatch(held.path, segments) === undefined)
|
|
return err(
|
|
refused(
|
|
tool,
|
|
`The state holds this document only at ${held.path}; the environment models writes to it only there.`,
|
|
),
|
|
);
|
|
const initial = serving.store.state.documents.find(
|
|
(document) => document.tool === held.tool,
|
|
);
|
|
const problem = documentBodyProblem(plan, call, {
|
|
initial: initial?.value,
|
|
current: held.value,
|
|
});
|
|
return problem === undefined ? ok(held) : err(refused(tool, problem));
|
|
};
|
|
|
|
const answerDocument = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
call: WriteCall,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const { tool, plan } = request;
|
|
const target = documentTarget(serving, request, call);
|
|
if (!target.ok) return target;
|
|
const held = target.value;
|
|
const written = writtenDocument(plan, held.value, call);
|
|
if (!written.ok) return err(refused(tool, written.error));
|
|
if (!isLoadableValue(written.value))
|
|
return err(unloadable(tool, "The document"));
|
|
const state = {
|
|
source: "state",
|
|
view: "document-write",
|
|
path: held.path,
|
|
} as const;
|
|
const answer =
|
|
plan.response?.shape === "entity"
|
|
? (() => {
|
|
const exchange = serving.source.exchanges.get(plan.response.ordinal);
|
|
return exchange === undefined
|
|
? err(refused(tool, `Tool ${tool.name} has no recorded response.`))
|
|
: stateAnswer(
|
|
serving,
|
|
{ exchange, exact: true },
|
|
written.value,
|
|
state,
|
|
);
|
|
})()
|
|
: writeAnswer(serving, request, { fields: undefined, id: "" }, state);
|
|
if (!answer.ok) return answer;
|
|
const set = serving.store.setDocument(held.tool, written.value);
|
|
if (!set.ok) return set;
|
|
serving.store.commitWrite(new Map());
|
|
return answer;
|
|
};
|
|
|
|
/** Apply one served write tool call to the live state and answer it; a refused call leaves the state unchanged. */
|
|
export const answerWrite = (
|
|
serving: StateServing,
|
|
request: WriteRequest,
|
|
): Result<StateAnswer, AnalysisError> => {
|
|
const body = callBody(request);
|
|
if (!body.ok) return body;
|
|
const call: WriteCall = {
|
|
path: request.tool.path_template,
|
|
pathValues: pathValues(request.tool, request.args),
|
|
body: body.value,
|
|
};
|
|
switch (request.plan.effect) {
|
|
case "create":
|
|
return answerCreate(serving, request, call);
|
|
case "update":
|
|
return answerUpdate(serving, request, call);
|
|
case "delete":
|
|
return answerDelete(serving, request);
|
|
case "document":
|
|
return answerDocument(serving, request, call);
|
|
case "none":
|
|
return err(
|
|
refused(
|
|
request.tool,
|
|
`Tool ${request.tool.name} is not served from the state.`,
|
|
),
|
|
);
|
|
}
|
|
};
|