Files
rea/src/domain/analysisView/environmentStateWriteCreate.ts
T
131fbe0754 feat(environment): serve writes whose calls send different members (#7539)
* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* docs(environment): record verification for blank members and sorted writes

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* docs(environment): record the census with main's unknown-clock rule merged

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* docs(environment): verify query values, counted values and made objects

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* docs(environment): record the call-values checks at #7274 93821024

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* docs(environment): record the call-values checks at #7274 45832406

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* chore(environment): bump the skill to 52 above #7260's 51

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: morluto <[email protected]>
2026-10-29 16:14:05 +08:00

1014 lines
33 KiB
TypeScript

import { jsonTextCodeUnits } from "../jsonSerialization.js";
import type { JsonValue } from "../jsonValue.js";
import {
ownMember,
collectionPathOf,
isObject,
isParam,
normalizedPath,
same,
scalarText,
segmentsOf,
selectedCollection,
type JsonObject,
type StateEntity,
type SuppliedSegment,
} from "./environmentStateRules.js";
import {
createdFields,
recordedGeneratedValue,
} from "./environmentStateWriteApply.js";
import {
createdToken,
heldObjects,
isOpaqueToken,
nextMadeCount,
restampedFields,
stampedBy,
} from "./environmentStateWriteStamps.js";
import {
anyLinkedSource,
recordedPathValues,
respondedIds,
sameLinkedSource,
} from "./environmentStateWriteLinks.js";
import {
collectionTarget,
entityTarget,
} from "./environmentStateWriteChecks.js";
import {
built,
callOf,
clockEvidence,
fail,
referencedIn,
itemReads,
refuse,
requestBodyPlan,
retainFixed,
retainCreateExemplar,
searchFrom,
startOf,
UNKNOWN,
type EffectContext,
type EffectResult,
type WriteDraft,
type WriteStep,
} from "./environmentStateWriteEffects.js";
import {
createdInteger,
explainCreate,
type CreateEvidence,
insertCandidates,
insertIndex,
randomIdentities,
nextInteger,
responseShapeOf,
} from "./environmentStateWriteExplain.js";
import {
laterObservation,
newEntityIn,
loadedLater,
unloadedPointers,
withRead,
type Observed,
} from "./environmentStateWriteObserve.js";
import {
keptOrders,
pathValuesOf,
siblingTrimmedClocks,
type FieldRule,
type WriteCall,
} from "./environmentStateWriteRules.js";
import {
fittedClockFormat,
noteFixedWidths,
} from "./environmentStateWriteClockFormats.js";
import {
mergedCreatePlan,
noteAmpersands,
noteHeldAmpersands,
} from "./environmentStateWriteCreateCalls.js";
import {
containsDelimited,
generatedIntegerDigits,
isUuid,
likeGeneratedInteger,
nextSequence,
startedSequence,
sequenceNumber,
spelledLike,
} from "./environmentStateWriteValues.js";
/** The id a response names alone: a scalar body, or an object's id field or single scalar member. */
const respondedId = (
body: JsonValue | undefined,
idField: string,
): string | undefined => {
if (body === undefined) return undefined;
if (!isObject(body)) return scalarText(body);
if (Object.hasOwn(body, idField)) return scalarText(body[idField]);
const members = Object.values(body);
return members.length === 1 ? scalarText(members[0]) : undefined;
};
/**
* A create's answer with the first read of its entity before the next write over it, when that read shows fields the
* answer lacks or spells its clocks to another precision: the state holds what reads show. An item read that agrees
* with the answer otherwise lends it its fields and then observes rather than checks; one that disagrees still checks
* the create. A list read, which may show fewer keys of an object, only adds fields the answer lacks and still checks.
*/
const withReadBack = (
context: EffectContext,
step: WriteStep,
target: {
readonly type: string;
readonly collection: string;
readonly idField: string;
},
own: Observed,
): Observed => {
const later = laterObservation(searchFrom(context, step), {
type: target.type,
collection: target.collection,
idField: target.idField,
id: own.id,
held: () => false,
isWrite: context.isWrite,
});
if (later === undefined) return own;
const view = context.viewOf(later.ordinal);
if (
view?.shape === "item" &&
(view.fields.some(
(field) =>
Object.hasOwn(own.object, field) && !Object.hasOwn(later.object, field),
) ||
Object.entries(later.object).some(
([field, value]) =>
Object.hasOwn(own.object, field) &&
!loadedLater(own.object[field], value),
))
)
return own;
const shape = view?.shape === "item" ? "item" : "list";
const object = withRead(own.object, later.object, shape);
if (same(object, own.object)) return own;
if (shape === "item") context.observed(later.ordinal);
// Answers keep the values the response had not loaded, which the state holds as the item read shows them.
const unloaded =
shape === "item" ? unloadedPointers(own.object, later.object) : [];
return {
...own,
object,
read: {
ordinal: later.ordinal,
pointer: later.pointer,
shape,
...(unloaded.length === 0 ? {} : { unloaded }),
},
};
};
/**
* The written entity a create's response or a later read shows. A linked create's read must name an
* id its response returned, as the read that linked it did, envelopes included.
*/
const createdObservation = (
context: EffectContext,
step: WriteStep,
target: {
readonly type: string;
readonly collection: string;
readonly idField: string;
readonly linked: boolean;
},
): Observed | undefined => {
const held = (id: string) =>
context.state.entity(target.type, target.collection, id) !== undefined;
const own = context.io.withBody(step.record.ordinal, (body) =>
newEntityIn(step.record.ordinal, body, target.idField, held),
);
if (own !== undefined) return withReadBack(context, step, target, own);
const { id, ids } = context.io.withBody(step.record.ordinal, (body) => {
const returned = target.linked ? respondedIds(body) : [];
// A response that names the created id alone ties the later read to that id.
const named =
respondedId(body, target.idField) ??
(returned.length === 1 ? returned[0] : undefined);
return { id: named, ids: returned };
});
const later = laterObservation(searchFrom(context, step), {
type: target.type,
collection: target.collection,
idField: target.idField,
...(id === undefined ? {} : { id }),
held,
isWrite: context.isWrite,
});
// A read named by the id is tied already; otherwise a linked create's read must name a returned id.
if (
later === undefined ||
(target.linked && id === undefined && !ids.includes(later.id))
)
return undefined;
context.observed(later.ordinal);
return later;
};
const fieldsOf = (entities: readonly StateEntity[]): JsonObject[] =>
entities.map((entity) => entity.fields);
/** Whether a created field holds a generated token or integer that another field holds too, which no rule rebuilds. */
const linkedGenerated = (
field: string,
entity: JsonObject,
type: readonly JsonObject[],
): boolean =>
createdToken(field, entity, type) === "linked" ||
createdInteger(field, entity, type) === "linked";
/** Whether a field's rule rebuilds it from `source`, as a template or a composition does. */
const rebuiltFrom = (rule: FieldRule | undefined, source: string): boolean =>
rule?.rule === "template"
? rule.from === source
: rule?.rule === "composed" &&
rule.parts.some((part) => "from" in part && part.from === source);
/** Whether a unique integer's digits show in another string whose rule does not rebuild them from it, which seeding would leave behind. */
const strandedInteger = (
rules: readonly FieldRule[],
entity: JsonObject,
): boolean =>
rules.some((rule) => {
const digits =
rule.rule === "unique"
? generatedIntegerDigits(ownMember(entity, rule.field))
: undefined;
return (
digits !== undefined &&
Object.entries(entity).some(
([other, kept]) =>
other !== rule.field &&
typeof kept === "string" &&
containsDelimited(kept, digits) &&
!rebuiltFrom(
rules.find((candidate) => candidate.field === other),
rule.field,
),
)
);
});
/** Whether a created field no rule explains holds a generated value another field links to, or a unique integer another string strands, which serving cannot keep consistent. */
const linkedUnexplained = (
rules: readonly FieldRule[],
entity: JsonObject,
held: readonly JsonObject[],
): boolean => {
const explained = new Set(rules.map((rule) => rule.field));
return (
Object.keys(entity).some(
(field) => !explained.has(field) && linkedGenerated(field, entity, held),
) || strandedInteger(rules, entity)
);
};
/** Widen a create plan by a later call, when that call explained on its own agrees with it; whether it did. */
const refineCreate = (
context: EffectContext,
draft: WriteDraft,
step: WriteStep,
evidence: CreateCallEvidence,
): boolean => {
const { explained, held } = explainedCall(context, draft, step, evidence);
for (const member of keptOrders(evidence.call.body, evidence.observed.object))
draft.kept.add(member);
if (
(explained.tied && draft.plan.collection === null) ||
linkedUnexplained(explained.rules, evidence.observed.object, held)
)
return false;
const later = laterOf(evidence, explained);
const widened =
mergedCreatePlan(
{ rules: draft.plan.rules, body: draft.plan.body! },
draft.observed!,
later,
earlierOf(draft, evidence.collection),
) ?? reexplained(draft, explained.rules, later, evidence.collection);
if (widened === undefined) return false;
retainFixed(context, widened.body.fixed.slice(draft.plan.body!.fixed.length));
draft.plan.rules = widened.rules;
draft.plan.body = widened.body;
draft.exemplarInput = undefined;
noteAmpersands(draft.ampersands, explained.rules, evidence.observed.object);
return true;
};
/** What the plan's earlier calls showed, for merging a later one. */
const earlierOf = (draft: WriteDraft, collection: string) => ({
kept: draft.kept,
clockOf: (field: string) => clockEvidence(draft, field),
startOf: (field: string) => draft.starts.get(field),
createCollections: draft.createCollections,
sentLargest: (field: string, scope: "collection" | "type") =>
draft.sentLargest.get(
scope === "collection" ? `${field} ${collection}` : field,
),
ampersands: draft.ampersands,
});
/** A later create as the plan merge reads it. */
const laterOf = (
evidence: CreateCallEvidence,
explained: ReturnType<typeof explainCreate>,
) => ({
entity: evidence.observed.object,
body: evidence.call.body,
rules: explained.rules,
contract: {
...explained.body,
...(evidence.envelope === undefined ? {} : { envelope: evidence.envelope }),
},
});
/**
* The plan its exemplar gives again with the composed rules a later call learned for fields the exemplar left
* unexplained, such as an address spelled from an id that equals the title's slug, merged with that call. Undefined
* once a later call widened the plan, or unless the rules spell the exemplar's own values.
*/
const reexplained = (
draft: WriteDraft,
learned: readonly FieldRule[],
later: ReturnType<typeof laterOf>,
collection: string,
) => {
const input = draft.exemplarInput;
if (input === undefined) return undefined;
const hints = learned.filter(
(rule) =>
rule.rule === "composed" &&
!draft.plan.rules.some((held) => held.field === rule.field),
);
if (hints.length === 0) return undefined;
const again = explainCreate({ ...input, hints });
if (!hints.every((hint) => again.rules.includes(hint))) return undefined;
const envelope = draft.plan.body!.envelope;
return mergedCreatePlan(
{
rules: again.rules,
body: {
...again.body,
...(envelope === undefined ? {} : { envelope }),
},
},
draft.observed!,
later,
earlierOf(draft, collection),
);
};
type CreateCallEvidence = {
readonly observed: Observed;
readonly call: WriteCall & { readonly body: JsonObject };
readonly collection: string;
readonly envelope: string | undefined;
};
/** Explain one recorded create on its own, against the entities its collection and type held before it. */
const explainedCall = (
context: EffectContext,
draft: WriteDraft,
step: WriteStep,
evidence: CreateCallEvidence,
) => {
const type = draft.plan.target!;
const members = fieldsOf(context.state.members(type, evidence.collection));
const held = fieldsOf(context.state.ofType(type));
const input: CreateEvidence = {
entity: evidence.observed.object,
call: evidence.call,
idField: context.idField(type),
startMs: startOf(context, step),
collection: members,
type: held,
named: (id) => context.state.named(id),
};
return { explained: explainCreate(input), members, held, input };
};
/** Build a create plan from its exemplar's observation. */
const buildCreate = (
context: EffectContext,
draft: WriteDraft,
step: WriteStep,
evidence: CreateCallEvidence,
): boolean => {
const type = draft.plan.target!;
const idField = context.idField(type);
const { explained, members, held, input } = explainedCall(
context,
draft,
step,
evidence,
);
if (linkedUnexplained(explained.rules, evidence.observed.object, held)) {
refuse(draft, step, "unexplained-change");
return false;
}
const clocks = explained.rules.flatMap((rule) =>
rule.rule === "clock" ? [rule.field] : [],
);
// Identity and clock orders first, then any other scalar field the collection may be sorted by.
const scalars = Object.keys(members[0] ?? {}).filter((field) =>
members.every((member) =>
["string", "number"].includes(typeof ownMember(member, field)),
),
);
const generated = explained.rules.some(
(rule) =>
rule.rule === "identity" &&
rule.field === idField &&
rule.generator !== "sequence",
);
draft.candidates = insertCandidates(
members,
[...new Set([idField, ...clocks, ...scalars])],
{
...(generated && randomIdentities(members, idField, clocks)
? { random: idField }
: {}),
created: evidence.observed.object,
},
);
retainFixed(context, explained.body.fixed);
for (const member of keptOrders(evidence.call.body, evidence.observed.object))
draft.kept.add(member);
Object.assign(draft.plan, {
exemplar_ordinal: step.record.ordinal,
observation: {
ordinal: evidence.observed.ordinal,
pointer: evidence.observed.pointer,
...(evidence.observed.read === undefined
? {}
: { read: evidence.observed.read }),
},
response: context.io.withBody(step.record.ordinal, (body) =>
responseShapeOf(
step.record.ordinal,
body,
context.io.emptyResponse(step.record.ordinal),
{ idField, id: evidence.observed.id },
),
),
body: {
...explained.body,
...(evidence.envelope === undefined
? {}
: { envelope: evidence.envelope }),
},
rules: explained.rules,
collection:
explained.tied || draft.linked !== undefined ? evidence.collection : null,
insert: draft.candidates[0]!,
});
draft.observed = evidence.observed.object;
draft.exemplarInput = retainCreateExemplar(context, input, explained.rules);
noteHeldAmpersands(draft.ampersands, explained.rules, held);
noteAmpersands(draft.ampersands, explained.rules, evidence.observed.object);
for (const entity of held) noteFixedWidths(draft.fixedWidth, entity);
const ruled = new Set(explained.rules.map((rule) => rule.field));
for (const [field, value] of Object.entries(evidence.observed.object)) {
const integer = sequenceNumber(value);
if (ruled.has(field) || integer === undefined) continue;
const next = nextInteger(held, field, value);
if (next === undefined || integer >= next) draft.starts.set(field, integer);
}
return true;
};
type SequenceRule = Extract<FieldRule, { rule: "sequence" }>;
/** The sequences a create's plan generates, each with the key serving counts it under. */
const sequencesOf = (
draft: WriteDraft,
collection: string,
): { readonly rule: SequenceRule; readonly key: string }[] =>
draft.plan.rules.flatMap((rule) =>
rule.rule === "sequence"
? [
{
rule,
key:
rule.scope === "collection"
? `${rule.field} ${collection}`
: rule.field,
},
]
: [],
);
/** Whether a later call's sequences hold what serving generates: one past the largest value their scope holds or started with and past the plan's last, spelled as the exemplar spells it; or, for one that takes a sent value, the value the call sent. */
const followsSequences = (
context: EffectContext,
draft: WriteDraft,
created: Pick<StateEntity, "type" | "collection" | "fields"> & {
readonly sent: JsonObject;
readonly observed: JsonObject;
},
): boolean =>
sequencesOf(draft, created.collection).every(({ rule, key }) => {
if (rule.sent === true && Object.hasOwn(created.sent, rule.field))
return (
!Object.hasOwn(created.observed, rule.field) ||
same(ownMember(created.observed, rule.field), created.sent[rule.field])
);
const scope = [
...context.state.ofType(created.type),
...context.startedWith(created.type),
].filter(
(entity) =>
rule.scope === "type" || entity.collection === created.collection,
);
const next = nextSequence(
startedSequence(
nextInteger(
fieldsOf(scope),
rule.field,
ownMember(draft.observed, rule.field),
),
rule.start,
),
draft.sequences.get(key),
);
return (
ownMember(created.fields, rule.field) ===
spelledLike(ownMember(draft.observed, rule.field) ?? "", next)
);
});
/** Whether a later call's rules reproduce its observed fields and its omitted members agree with the learned defaults. */
const agreesLater = (
context: EffectContext,
draft: WriteDraft,
created: Pick<StateEntity, "type" | "collection" | "fields">,
call: {
readonly body: JsonObject;
readonly observed: JsonObject;
readonly startMs: number | undefined;
},
): boolean =>
followsCreateRules(context, draft, {
...created,
observed: call.observed,
startMs: call.startMs,
sent: call.body,
}) &&
!contradictsDefault(draft.plan.rules, call, created.fields) &&
!unruledDiffers(draft.plan.rules, call.observed, {
written: created.fields,
volatile: context.volatileOf(created.type),
});
/** Whether the call stored a field no rule writes and no read leaves unchecked otherwise than the plan keeps it, as the exemplar stored it. */
const unruledDiffers = (
rules: readonly FieldRule[],
observed: JsonObject,
plan: {
readonly written: JsonObject;
readonly volatile: ReadonlySet<string>;
},
): boolean => {
const { written, volatile } = plan;
const ruled = new Set(rules.map((rule) => rule.field));
return Object.keys(observed).some(
(field) =>
!ruled.has(field) &&
!volatile.has(field) &&
Object.hasOwn(written, field) &&
!same(observed[field], ownMember(written, field)),
);
};
/** Whether an echoed member the call left out was stored otherwise than its learned default. */
const contradictsDefault = (
rules: readonly FieldRule[],
call: { readonly body: JsonObject; readonly observed: JsonObject },
written: JsonObject,
): boolean =>
rules.some(
(rule) =>
rule.rule === "echo" &&
!Object.hasOwn(call.body, rule.field) &&
Object.hasOwn(call.observed, rule.field) &&
!same(call.observed[rule.field], ownMember(written, rule.field)),
);
/** Whether a later create preserves generation shapes and its derived fields reproduce the captured observation. */
const followsCreateRules = (
context: EffectContext,
draft: WriteDraft,
created: Pick<StateEntity, "type" | "collection" | "fields"> & {
readonly observed: JsonObject;
readonly startMs: number | undefined;
readonly sent: JsonObject;
},
): boolean =>
draft.plan.rules.every((rule) => {
const value = ownMember(created.fields, rule.field);
const exemplar = ownMember(draft.observed, rule.field);
// Serving always rebuilds a composed or templated field, so a response that leaves it out contradicts the plan.
if (rule.rule === "composed" || rule.rule === "template")
return value === ownMember(created.observed, rule.field);
if (rule.rule === "reference")
return (
!Object.hasOwn(created.observed, rule.field) ||
same(value, ownMember(created.observed, rule.field))
);
if (rule.rule === "clock")
return (
fittedClockFormat(
rule.format,
value,
clockEvidence(draft, rule.field),
) !== undefined
);
if (rule.rule === "unique")
return (
(isUuid(exemplar)
? isUuid(value)
: generatedIntegerDigits(exemplar) !== undefined
? likeGeneratedInteger(value, exemplar)
: isOpaqueToken(value, exemplar)) &&
!context.state
.ofType(created.type)
.some((held) => ownMember(held.fields, rule.field) === value)
);
return (
rule.rule !== "identity" || rule.generator !== "uuid" || isUuid(value)
);
}) &&
followsSequences(context, draft, created) &&
followsMadeObjects(context, draft, created);
/** The key a made object's count is taken under in a plan's sequences. */
const madeKey = (field: string, member: string): string => `${field}/${member}`;
/** Whether a later call's recorded made objects hold what serving makes: the exemplar's members, the entity's identity, clocks, and each count one past what held objects show or started with, past the plan's last. */
const followsMadeObjects = (
context: EffectContext,
draft: WriteDraft,
created: Pick<StateEntity, "type" | "collection" | "fields"> & {
readonly observed: JsonObject;
readonly startMs: number | undefined;
},
): boolean =>
draft.plan.rules.every((rule) => {
if (rule.rule !== "made-object") return true;
const made = ownMember(created.observed, rule.field);
const exemplar = ownMember(draft.observed, rule.field);
if (!isObject(made) || !isObject(exemplar)) return false;
const id = scalarText(
ownMember(created.fields, context.idField(created.type)),
);
const held = heldObjects(
[
...context.state.ofType(created.type),
...context.startedWith(created.type),
].map((entity) => entity.fields),
rule.field,
);
return [...new Set([...Object.keys(exemplar), ...Object.keys(made)])].every(
(member) => {
const value = ownMember(made, member);
if (rule.clocks.includes(member))
return stampedBy(value, rule.format, created.startMs);
if (rule.own.includes(member)) return scalarText(value) === id;
const count = rule.counts.find((entry) => entry.member === member);
if (count === undefined)
return same(value, ownMember(exemplar, member));
return (
sequenceNumber(value) ===
nextSequence(
nextMadeCount(held, count, ownMember(exemplar, member)),
draft.sequences.get(madeKey(rule.field, member)),
)
);
},
);
});
/** Widen the plan's clock formats to the trimmed spelling a later call showed, and its other clocks with them unless a value the plan saw shows them at a fixed width. */
const fitClocks = (draft: WriteDraft, fields: JsonObject): void => {
const fitted = draft.plan.rules.map((rule) => {
if (rule.rule !== "clock") return rule;
const format = fittedClockFormat(
rule.format,
ownMember(fields, rule.field),
clockEvidence(draft, rule.field),
);
return format === undefined || format === rule.format
? rule
: { ...rule, format };
});
draft.plan.rules = siblingTrimmedClocks(
fitted,
draft.observed,
fields,
Object.fromEntries(draft.fixedWidth),
);
noteFixedWidths(draft.fixedWidth, fields);
};
/** Record the values a create's sequences took, which the next call follows; as serving does, the largest stays, so a lower sent value does not lower it. */
const takeSequences = (
draft: WriteDraft,
created: Pick<StateEntity, "collection" | "fields">,
): void => {
const take = (key: string, value: number | undefined) => {
if (value === undefined) return;
const taken = draft.sequences.get(key);
draft.sequences.set(
key,
taken === undefined ? value : Math.max(taken, value),
);
};
for (const { rule, key } of sequencesOf(draft, created.collection))
take(
key,
sequenceNumber(
ownMember(created.fields, rule.field),
ownMember(draft.observed, rule.field),
),
);
for (const rule of draft.plan.rules) {
if (rule.rule !== "made-object") continue;
const made = ownMember(created.fields, rule.field);
for (const { member } of rule.counts) {
take(
madeKey(rule.field, member),
isObject(made) ? sequenceNumber(ownMember(made, member)) : undefined,
);
}
}
for (const rule of draft.plan.rules) {
if (rule.rule !== "echo") continue;
const value = sequenceNumber(ownMember(created.fields, rule.field));
// By type and by collection, as a sequence adopted later may count either.
for (const key of [rule.field, `${rule.field} ${created.collection}`]) {
const held = draft.sentLargest.get(key);
if (value !== undefined && (held === undefined || value > held))
draft.sentLargest.set(key, value);
}
}
};
/** Segments of a recorded path as a create call supplies them: template literals, and each parameter's recorded spelling. */
const recordedSegments = (
template: string,
path: string,
): SuppliedSegment[] | undefined => {
const pattern = segmentsOf(template);
const concrete = segmentsOf(path);
if (pattern.length !== concrete.length) return undefined;
const segments: SuppliedSegment[] = [];
for (const [index, part] of pattern.entries()) {
const value = concrete[index]!;
if (!isParam(part)) {
if (part !== value) return undefined;
segments.push({ text: part, supplied: false });
continue;
}
if (value.length === 0) return undefined;
segments.push({ text: value, supplied: true });
}
return segments;
};
/** Collections a create may join, in serving's order: held ones, then emptied ones as first known, then checked list lines. */
const createCandidates = (context: EffectContext, type: string): string[] => {
const candidates: string[] = [];
const seen = new Set<string>();
const add = (collection: string): void => {
if (seen.has(collection)) return;
seen.add(collection);
candidates.push(collection);
};
for (const entity of context.state.ofType(type)) add(entity.collection);
for (const collection of context.state.knownCollections(type))
add(collection);
for (const record of context.records) {
const view = context.viewOf(record.ordinal);
if (
view?.shape === "list" &&
view.type === type &&
view.checked_record_ordinals.includes(record.ordinal)
)
add(collectionPathOf(record, false));
}
return candidates;
};
/** The collection serving would write this recorded create into, when the path instantiates the tool. */
const servedCollection = (
context: EffectContext,
step: WriteStep,
type: string,
): string | undefined => {
const segments = recordedSegments(step.tool.path_template, step.record.path);
return segments === undefined
? undefined
: selectedCollection(segments, createCandidates(context, type));
};
/** Whether a linked create's call sends the source path values its exemplar did, the only ones its link holds for. */
const fromLinkedSource = (
context: EffectContext,
draft: WriteDraft,
step: WriteStep,
): boolean =>
anyLinkedSource(draft.plan, step.tool.path_template) ||
sameLinkedSource(
step.tool.path_template,
context.records.find(
(record) => record.ordinal === draft.plan.exemplar_ordinal,
)?.path,
recordedPathValues(step.tool.path_template, step.record.path),
);
/** Add a created entity to the state at the plan's insert position, or last before the plan has one. */
const insertCreated = (
context: EffectContext,
draft: WriteDraft,
entity: StateEntity,
): string => {
const members = fieldsOf(
context.state.members(entity.type, entity.collection),
);
context.io.retain(64 + jsonTextCodeUnits(entity.fields) * 2);
context.state.put(
entity,
draft.plan.insert === null
? members.length
: insertIndex(draft.plan.insert, members, entity.fields),
);
return entityTarget(entity.type, entity.collection, entity.id);
};
/** Apply a recorded create, with the values it recorded for generated fields; an unexplained create adds what it recorded. */
export const applyCreate = (
context: EffectContext,
draft: WriteDraft,
step: WriteStep,
): EffectResult => {
const type = draft.plan.target!;
const idField = context.idField(type);
const spelled = normalizedPath(step.record.path);
// Serving writes a create into the collection it chooses for the path, and a tied plan refuses any other, so a create there is not counted.
const collection =
draft.linked ?? servedCollection(context, step, type) ?? spelled;
// A linked plan's collection holds only for its exemplar's source path, so serving refuses any other.
if (
built(draft) &&
((draft.plan.collection !== null && draft.plan.collection !== collection) ||
(draft.linked !== undefined && !fromLinkedSource(context, draft, step)))
)
return UNKNOWN;
const observed = createdObservation(context, step, {
type,
collection,
idField,
linked: draft.linked !== undefined,
});
const request = requestBodyPlan(context, step, draft, observed?.object);
const body = request?.object;
if (observed === undefined) {
fail(draft, step, body === undefined ? "body-unusable" : "no-observation");
return UNKNOWN;
}
const entity = (fields: JsonObject, id: string): StateEntity => ({
type,
collection,
id,
fields,
view_fields: [],
record_ordinals: [],
});
const recorded = (): EffectResult => {
const inserted = insertCreated(
context,
draft,
entity(observed.object, observed.id),
);
return {
kind: "observed",
targets: [inserted, collectionTarget(type, collection)],
entity: { type, collection, id: observed.id },
};
};
if (step.observeOnly || body === undefined) {
fail(draft, step, "body-unusable");
return recorded();
}
const call = { ...callOf(step, body), body };
// The exemplar defines the plan's sequences; each later call must follow them.
const later = built(draft);
if (
later &&
(draft.plan.rules.some(
(rule) =>
rule.rule === "unique" &&
linkedGenerated(
rule.field,
observed.object,
fieldsOf(context.state.ofType(type)),
),
) ||
strandedInteger(draft.plan.rules, observed.object))
) {
refuse(draft, step, "unexplained-change");
return recorded();
}
if (
!later &&
!buildCreate(context, draft, step, {
observed,
call,
collection,
envelope: request?.envelope,
})
)
return recorded();
// Rules learn from the recorded path; serving fills path fields from the collection it selects.
const created = {
...call,
pathValues:
pathValuesOf(step.tool.path_template, collection) ?? call.pathValues,
};
const fieldsOfCall = () =>
createdFields(
draft.plan,
draft.observed!,
created,
(rule) =>
recordedGeneratedValue(
rule,
ownMember(draft.observed!, rule.field),
ownMember(observed.object, rule.field) ?? null,
),
referencedIn(context),
idField,
);
// A later call that agrees with the plan widens it, as a later update does: to members it alone sent or left out, an
// array it showed sorted, or a clock spelling. One that disagrees leaves the plan as it was.
if (later)
refineCreate(context, draft, step, {
observed,
call,
collection,
envelope: request?.envelope,
});
const fields = fieldsOfCall();
const id = fields.ok
? scalarText(ownMember(fields.value, idField))
: undefined;
if (
!fields.ok ||
id === undefined ||
context.state.entity(type, collection, id) !== undefined ||
(later &&
!agreesLater(
context,
draft,
{ type, collection, fields: fields.value },
{
body: call.body,
observed: observed.object,
startMs: startOf(context, step),
},
))
) {
refuse(draft, step, "unexplained-change");
return recorded();
}
takeSequences(draft, { collection, fields: fields.value });
fitClocks(draft, fields.value);
// The call's own values follow the forms serving generates; the state holds a nested clock as the read-back restamped it, as an update's.
const stored = restampedFields(
searchFrom(context, step),
itemReads(context, { type, idField, collection, id }),
fields.value,
draft.plan.rules,
);
const inserted = insertCreated(context, draft, entity(stored, id));
context.io.retain(collection.length * 2 + 16);
draft.createCollections.push(collection);
return {
kind: "applied",
targets: [inserted, collectionTarget(type, collection)],
entity: { type, collection, id },
inserted,
};
};