Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/specs/agent-environments/write-views/plan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Implementation plan

1. **Read-backs.** A create's observation looks for the first read of its entity before the next write; an item read's
fields and clock spellings are taken when it agrees otherwise, and the read observes; a list read adds fields only. The plan's observation records the
read and its shape, and serving merges the same objects.
2. **Sent members.** An update's sent member stored as a fresh clock after it sent back the held one is a `clock`; one
stored as the slug of another member stored as sent is a `slug`.
3. **Schema, tests and docs.**
43 changes: 43 additions & 0 deletions docs/specs/agent-environments/write-views/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Writes whose answers show the entity otherwise than reads, and whole-object updates

Issue: https://github.com/morluto/rea/issues/4933

## Outcome

Agents built environments from a prompt for five applications the prompt flow had never seen (Vikunja, Ghost, EspoCRM,
Paperless-ngx and Miniflux). Two write-model gaps withheld most of their creates and edits:

- **A create's answer is another view of the entity than its reads.** Paperless answers a tag create without the
`document_count` its item read shows. EspoCRM answers a contact create without nine fields its item read shows.
Vikunja answers a label create with a partial `created_by` and clocks to the nanosecond, where reads show the full
user and whole seconds. Ghost answers a tag create without the `count` its list shows. The state built the entity from
the answer alone, so the read-back contradicted the create.
- **A whole-object update sends back what the application derives.** Paperless's UI sends the tag's old `slug` with a
new name, and the application slugs the name anew. Ghost's UI sends the `updated_at` it read, and the application
stamps a new one. The update was withheld as `unexplained-change`, or its first call's value was pinned so that later
calls conflicted.

## Behaviour

- **Read-backs.** When the first read of a created entity before the next write shows fields the create's answer lacks,
or spells its clocks to another precision, the observed entity takes them, and the plan records the read
(`observation.read`, with its shape).
- An item read that agrees with the answer otherwise lends its fields and its clock spellings (whole seconds of a
nanosecond clock), and no longer confirms the create. One that disagrees on another value still checks the create,
which it contradicts.
- A list read, which may show fewer keys of an object, only adds fields the answer lacks and still checks the create.
- A read that shows nothing new leaves the observation as it was and still confirms the create.
- Serving merges the same two recorded objects, so a served create answers in its answer's shape and stores the
fields of both.
- **Restamped clocks.** An update member sent back as the clock the entity held, and stored as a fresh clock near the
call, is a `clock` rule, accepted with any value.
- **Re-derived slugs.** An update member stored as the slug of another member the call stored as sent is a `slug` rule
from that member, accepted with any value.

Plans and views that need none of this are unchanged.

## Acceptance

- The held-out recordings serve EspoCRM's contact create and Paperless's tag edit.
- A create whose item read-back disagrees with its answer on another value is still contradicted.
- No write tool of the 69 recorded captures goes from served to withheld.
8 changes: 8 additions & 0 deletions docs/specs/agent-environments/write-views/tasks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Tasks

- [x] Take a create's read-back fields into its observation, and serve the same merge.
- [x] Learn restamped clocks and re-derived slugs for sent update members.
- [x] Add view and serving tests that fail without the change.
- [x] Document the observation member and the rules.
- [x] Measure the held-out and recorded captures.
- [x] Run static, formatting, documentation and test gates.
48 changes: 48 additions & 0 deletions docs/specs/agent-environments/write-views/verification.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Verification

Executed on macOS with Node v24.22.1 at `2f807efb` (main `8e6a9578` and this branch).

## Gates

- `npm run check` (build, typecheck, format, lint, typed lint, module boundaries, architecture guards) and
`npm run docs:check`: passed.
- `npx vitest run --project domain --project services --project adapters`: 17,624 passed, 25 skipped, 1 failed ("stops
Inspector target authorization after the current stat settles"), which fails the same way on main in this environment.
- `npm run test:focused --` the analysis-view, environment build, compare, export and serve CLI boundaries, the
analysis-view, environment bundle, serve and served-writes MCP boundaries, tool schema validity, output schema profile
and MCP schema validation: 12 files, 106 passed.
- The eight new view and serving tests fail on main and pass here.

## Recorded captures

The 69 recorded captures and the five held-out agent recordings, built as environment-state views on main and on this
branch:

| Captures | Served on main | Served here | Served to withheld |
| ----------------------------------------- | -------------- | ----------- | ------------------ |
| 69 recorded | 132 | 132 | none |
| 5 held-out (20 write tools with a target) | 8 | 10 | none |

- **Now served:** EspoCRM's contact create (its read-back adds nine fields the answer lacks) and Paperless's tag edit
(the stale slug is slugged anew from the name).
- **Past the read-back, withheld by other gaps:**
- Paperless's tag create: its list's `all` member lists every id, which state rendering does not model.
- Ghost's tag create and edit: the state does not list the created tags in Ghost's tag lists.
- **Still contradicted:** Vikunja's label create, whose item read-back shows a fully loaded `created_by` where the answer
showed a partial one.
- Three plans of the recorded captures (Airbyte, BookStack, PhotoPrism) now record a read-back; their served state is
unchanged.

## Served write tasks

The held-out round's write tasks, rebuilt from the same agent recordings with this branch, with
`fireworks_ai/gpt-oss-120b` and `fireworks_ai/glm-5p3-flash`:

| Application | Main (gpt-oss, GLM) | This branch (gpt-oss, GLM) |
| ---------------------------------------------- | ------------------- | -------------------------- |
| EspoCRM contacts: create, update email, delete | 0/3, 0/3 | 1/3, 1/3 (create) |
| Paperless tags: create, rename, delete | 1/3, 1/3 | 1/3, 2/3 (rename with GLM) |

- gpt-oss's rename did not apply. Its trajectory was not kept, so the cause is unconfirmed. A served `PUT` requires
every member the recorded call sent (about 14 here), and GLM sent them all.
- EspoCRM's served update accepts only the members its recording edited, so the email change is refused, as on main.
14 changes: 12 additions & 2 deletions docs/web-network-captures.md
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,13 @@ integer of 10 or more digits that no entity of the type holds (where every one
holds a distinct integer of the same length, as time-based ids do), a
`nested-clock` object whose clocks the request stamped, a `template` around
a generated value, a `reference` to an entity, or a `composed` string; other
fields keep the observed value. A `reference` is an object holding fields of the
fields keep the observed value. When the first read of a created entity before
the next write shows fields the create's answer lacks, or its clocks to another
precision, the observed entity takes them (`observation.read`). An item read
that agrees with the answer otherwise lends its fields and clock spellings and
no longer confirms the create; one that disagrees still checks it. A list read
only adds fields the answer lacks and still checks it. Serving answers a create
in its answer's shape and stores the fields of both. A `reference` is an object holding fields of the
entity a sent member names, as the state holds it (a parent beside `parentId`):
the member is accepted with any value, serving looks the entity up and refuses a
call naming one the environment does not hold or holds in more than one
Expand Down Expand Up @@ -778,7 +784,11 @@ with them. Other clocks the plan stamps take that spelling too unless their own
value shows a fixed width. A body that wraps one
object in a one-element array is that object, wrapped so on every call
(`body.envelope`). An update's members
echo when stored as sent; a member stored differently is accepted only with its
echo when stored as sent. A clock sent back as the entity held it and stored as
a fresh clock near the call is a `clock`, and a member stored as the slug of
another member stored as sent is a `slug`, both accepted with any value, as a
whole-object write that sends what it read shows. Any other member stored
differently is accepted only with its
recorded value (`body.fixed`) and stores the value the call that showed it
recorded (the `value` of its `constant` rule), and a field it changed without
sending must be a clock, a nested clock, an increment, a slug, a fresh `unique`
Expand Down
70 changes: 70 additions & 0 deletions src/application/environment/environmentStateDerivedAnswer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import {
referencedCreateRows,
shelvedRows,
} from "../../../tests/fixtures/environmentStateDerivedValues.js";
import {
LISTED_LABEL_ROWS,
READ_BACK_TAG_ROWS,
RESTAMPED_ROWS,
STALE_SLUG_ROWS,
} from "../../../tests/fixtures/environmentStateWriteViews.js";
import { servedFrom } from "../../../tests/fixtures/environmentStateServing.js";
import {
bookClock,
Expand Down Expand Up @@ -180,3 +186,67 @@ describe("served objects that repeat a named entity, and sorted arrays", () => {
).toEqual(["fog", "ice", "wind"]);
});
});

describe("served writes whose answers show the entity otherwise than reads do", () => {
it("answers a create as the application answered it and holds the fields its read-back showed", () => {
const tags = servedFrom(READ_BACK_TAG_ROWS);
const created = objectOf(
tags.answer("post_tags", { body: { name: "Saltmarsh Gate" } }).body,
);
expect(Object.keys(created).sort()).toEqual(
["created", "id", "name", "slug"].sort(),
);
expect(created).toMatchObject({
name: "Saltmarsh Gate",
slug: "saltmarsh-gate",
});
expect(
tags.answer("get_tags_by_id", { id: String(created["id"]) }).body,
).toMatchObject({ name: "Saltmarsh Gate", document_count: 0 });
});

it("lists a created label with the count its list read showed", () => {
const labels = servedFrom(LISTED_LABEL_ROWS);
labels.answer("post_labels", { body: { title: "Slipway" } });
expect((labels.answer("get_labels").body as JsonValue[]).at(-1)).toEqual({
id: 3,
title: "Slipway",
count: { posts: 0 },
});
});

it("slugs a renamed tag anew whatever slug the call sends back", () => {
const tags = servedFrom(STALE_SLUG_ROWS);
const renamed = objectOf(
tags.answer("put_tags_by_id", {
id: "2",
body: {
id: 2,
slug: "tide-tables",
name: "Neap Tide Tables",
document_count: 0,
created: "2026-10-01T10:00:00Z",
},
}).body,
);
expect(renamed).toMatchObject({
name: "Neap Tide Tables",
slug: "neap-tide-tables",
});
});

it("stamps a post's modification time anew rather than storing the one the call sends back", () => {
const posts = servedFrom(RESTAMPED_ROWS);
const edited = objectOf(
posts.answer("put_posts_by_id", {
id: "1",
body: { id: 1, title: "Winter rota v4", updated_at: bookClock(4) },
}).body,
);
expect(edited["title"]).toBe("Winter rota v4");
expect(edited["updated_at"]).not.toBe(bookClock(4));
expect(Date.parse(String(edited["updated_at"]))).toBeGreaterThan(
Date.parse(bookClock(4)),
);
});
});
26 changes: 20 additions & 6 deletions src/application/environment/environmentStateWriteAnswer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
type StateWritePlan,
type WriteCall,
} from "../../domain/analysisView/environmentStateWriteRules.js";
import { withRead } from "../../domain/analysisView/environmentStateWriteObserve.js";
import {
formatClock,
generatedIntegerDigits,
Expand Down Expand Up @@ -139,17 +140,30 @@ const callBody = ({
: err(unloadable(tool, `Member ${member}`));
};

/** The entity a recorded observation shows: the values a create keeps and an update's constants. */
/** 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 exchange = serving.source.exchanges.get(plan.observation.ordinal);
const body = exchange === undefined ? undefined : recordedJson(exchange);
const object =
body === undefined ? undefined : valueAt(body, plan.observation.pointer);
return isObject(object) ? object : 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);
Comment thread
morluto marked this conversation as resolved.
Resolved
};

/** One past the largest integer these entities hold in the field, read as the exemplar spells it, or undefined when none holds one. */
Expand Down
15 changes: 14 additions & 1 deletion src/domain/analysisView/environmentStateView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,20 @@ const writePlanSchema = z.strictObject({
.nullable()
.describe("The first successful recorded call the plan was built from."),
observation: z
.strictObject({ ordinal: ordinalSchema, pointer: z.string() })
.strictObject({
ordinal: ordinalSchema,
pointer: z.string(),
read: z
.strictObject({
ordinal: ordinalSchema,
pointer: z.string(),
shape: z.enum(["item", "list"]),
})
.exactOptional()
.describe(
"A create's later read of the entity: an item read lends fields the response lacks and its clock spellings, a list read only adds fields the response lacks.",
),
})
.nullable()
.describe(
"The record whose response showed the written entity or document, and a JSON pointer to it.",
Expand Down
39 changes: 38 additions & 1 deletion src/domain/analysisView/environmentStateWriteChanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type { FieldRule, WriteCall } from "./environmentStateWriteRules.js";
import {
integerOf,
readClock,
slugOf,
sortedStrings,
} from "./environmentStateWriteValues.js";
import { freshUuid, renewedRule } from "./environmentStateWriteGenerated.js";
Expand Down Expand Up @@ -139,7 +140,35 @@ export const sameSecondClocks = (evidence: UpdateEvidence): string[] =>
inCallSecond(evidence.after[field], evidence.startMs),
);

/** How an update stored a sent member: stamped anew as the one held clock it sent back other than a creation clock, echoed, renewed as a fresh UUID, or as a constant. */
/** Another sent member stored as sent whose slug the application stored in place of what this member sent. */
const sentSlugSource = (
evidence: UpdateEvidence,
member: string,
): string | undefined => {
const stored = evidence.after[member];
if (typeof stored !== "string") return undefined;
return Object.entries(evidence.call.body).find(
([other, value]) =>
other !== member &&
typeof value === "string" &&
same(evidence.after[other], value) &&
slugOf(value) === stored,
)?.[0];
};

/** Whether a call sent back the clock the entity held, as a whole-object write does, and the application stamped it anew near the call. */
const restampedClock = (
evidence: UpdateEvidence,
member: string,
sent: JsonValue,
): boolean =>
!CREATION_CLOCK.test(member) &&
readClock(sent) !== undefined &&
same(evidence.before[member], sent) &&
readClock(evidence.after[member]) !== undefined &&
isClockNear(evidence.after[member]!, evidence.startMs);

/** How an update stored a sent member: stamped anew as the one held clock it sent back other than a creation clock, echoed, stamped anew or slugged from another member in place of what it sent, renewed as a fresh UUID, or as a constant. */
export const sentRule = (
evidence: UpdateEvidence,
member: string,
Expand All @@ -156,6 +185,14 @@ export const sentRule = (
return { field: member, rule: "echo" };
if (same(evidence.after[member], sortedStrings(sent)))
return { field: member, rule: "echo", sorted: true };
if (restampedClock(evidence, member, sent))
return {
field: member,
rule: "clock",
format: readClock(evidence.after[member])!.format,
};
const from = sentSlugSource(evidence, member);
if (from !== undefined) return { field: member, rule: "slug", from };
Comment thread
morluto marked this conversation as resolved.
Resolved
return freshUuid(evidence, member)
? { field: member, rule: "unique" }
: { field: member, rule: "constant", value: evidence.after[member]! };
Expand Down
Loading
Loading