Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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.**
47 changes: 47 additions & 0 deletions docs/specs/agent-environments/write-views/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 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, or microseconds of one), and no longer confirms the create. One that disagrees on another value,
or omits an answer field its item view renders, 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. Generated clocks in the create answer retain that answer's recorded precision independently of
the stored read-back precision.
- **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.
- **Compatible saves.** A call that echoes an already-derived slug or holds a clock in its own recorded second does
not conflict with a demonstrated derivation, in either call order. A slug derivation must reproduce earlier saves
as well; an explicit custom slug that disagrees still withholds the update.

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.
20 changes: 18 additions & 2 deletions docs/web-network-captures.md
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,16 @@ 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 or omits an answer field its
item view renders still checks it. Clock agreement uses the coarser recorded
precision, including microseconds. A list read
only adds fields the answer lacks and still checks it. Serving answers a create
in its answer's shape and clock precision and stores the fields of both with
the item read-back's clock precision. 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 +787,14 @@ 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. A save that echoes an
already-derived slug or holds a clock in its own second remains compatible
with that derivation in either call order; earlier saves must also reproduce
a newly learned slug. 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
75 changes: 75 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,72 @@ 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",
created: firstServedClock(READ_BACK_TAG_ROWS).replace("Z", ".000000000Z"),
});
expect(
tags.answer("get_tags_by_id", { id: String(created["id"]) }).body,
).toMatchObject({
name: "Saltmarsh Gate",
document_count: 0,
created: firstServedClock(READ_BACK_TAG_ROWS),
});
});

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)),
);
});
});
36 changes: 29 additions & 7 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 Expand Up @@ -347,7 +361,15 @@ export const writeAnswer = (
: writtenResponse(
plan.response,
recorded,
rendered,
{
...rendered,
clocks:
plan.observation?.read?.shape === "item"
? plan.rules.flatMap((rule) =>
rule.rule === "clock" ? [rule.field] : [],
)
: [],
},
optionalFields(plan),
);
if (!body.ok) return err(refused(tool, body.error));
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
20 changes: 18 additions & 2 deletions src/domain/analysisView/environmentStateWriteApply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
echoed,
integerOf,
readClock,
respellClock,
isUuid,
replaceDelimited,
slugOf,
Expand Down Expand Up @@ -488,7 +489,12 @@ export const optionalFields = (
export const writtenResponse = (
response: WriteResponse,
recorded: JsonValue | undefined,
written: { readonly fields: JsonObject | undefined; readonly id: string },
written: {
readonly fields: JsonObject | undefined;
readonly id: string;
/** Generated clocks keep the response's spelling independently of the stored entity's. */
readonly clocks?: readonly string[];
},
optional: readonly string[] = [],
): Applied<JsonValue | undefined> => {
if (response.shape === "empty") return ok(undefined);
Expand Down Expand Up @@ -525,7 +531,17 @@ export const writtenResponse = (
recorded,
pointer,
Object.fromEntries(
fields.map((field) => [field, written.fields![field]!]),
fields.map((field) => {
const value = written.fields![field]!;
const clock =
written.clocks?.includes(field) === true
? readClock(shown[field])
: undefined;
return [
field,
clock === undefined ? value : respellClock(value, clock.format),
];
}),
),
),
);
Expand Down
Loading
Loading