Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
155 commits
Select commit Hold shift + click to select a range
ad439bd
feat(environment): extract the initial state a capture's reads observed
earakely-scale Oct 20, 2026
7a668b7
Merge main into feat/environment-state-view
earakely-scale Oct 20, 2026
f2c9a2e
fix(environment): bound state at redacted writes; infer identity only…
earakely-scale Oct 20, 2026
2999128
fix(environment): keep first sightings, one list pointer and linear f…
earakely-scale Oct 20, 2026
a5c7b92
fix(environment): keep post-write values and partial lists out of the…
kaoru0822-kitauji Oct 20, 2026
4e93547
docs(environment): scope item-shaped and deleted written paths out of…
kaoru0822-kitauji Oct 20, 2026
aba9cb1
fix(environment): count writes in flight when a value changes between…
kaoru0822-kitauji Oct 20, 2026
856c8c0
Merge main into feat/environment-state-view
kaoru0822-kitauji Oct 20, 2026
55480bd
chore: merge main (5fa4defc) into environment state view
earakely-scale Oct 20, 2026
9fee36d
fix(environment): catch cross-tool changes across writes; read only i…
earakely-scale Oct 20, 2026
3c64cbe
chore: merge the branch's own main merge (856c8c0b), identical to 554…
earakely-scale Oct 20, 2026
47f8a27
chore: merge main (f93a0335, rich captures) into environment state view
earakely-scale Oct 20, 2026
32fbaa5
chore: merge main into environment state view
gensokyo-dev Oct 20, 2026
04e2c56
fix(environment): keep post-write observations out of initial state
gensokyo-dev Oct 20, 2026
3daeebb
chore: retain author main integration in environment state view
gensokyo-dev Oct 20, 2026
25923c3
chore: sync environment state view with latest main
gensokyo-dev Oct 20, 2026
6ad63bc
fix(environment): retain field provenance and bound state inference work
gensokyo-dev Oct 20, 2026
2bd0b3c
feat(environment): serve tool calls from the environment state
earakely-scale Oct 20, 2026
35aee7c
feat(environment): render more read tools from the state and describe…
earakely-scale Oct 20, 2026
9f60e54
Merge the environment state view's review fixes into feat/environment…
earakely-scale Oct 20, 2026
62708a8
Merge the environment state view's review fixes into feat/environment…
earakely-scale Oct 20, 2026
cb04dcd
docs(environment): record verification after merging the state view's…
earakely-scale Oct 20, 2026
9dfc05f
docs(environment): record verification after merging the state view's…
earakely-scale Oct 20, 2026
aa48c74
Merge main (#5319 squashed, #5349) into feat/environment-state-coverage
earakely-scale Oct 20, 2026
e96484b
Merge main (#5319 squashed, #5349) into feat/environment-state-serve
earakely-scale Oct 20, 2026
5bb7ca4
fix(environment): stop identity checks at the first missing or repeat…
earakely-scale Oct 20, 2026
6676582
feat(environment)!: serve the environment state by default
earakely-scale Oct 20, 2026
83fcc73
fix(environment): bound data-plane replies, keep batch order, cancel …
earakely-scale Oct 20, 2026
d9c0357
fix(environment): keep bodies too deep for the state's nesting out of…
earakely-scale Oct 20, 2026
d9a717e
Merge main (#5350 write cutoffs, #5031 protobuf bodies) into feat/env…
earakely-scale Oct 20, 2026
57b1168
fix(environment): measure data-plane replies before building them
earakely-scale Oct 20, 2026
5956e00
chore: merge main (d2a3269d) into environment state serve
earakely-scale Oct 20, 2026
bf0dd92
chore: merge environment state coverage into the state writes branch
earakely-scale Oct 20, 2026
a98df6c
chore: merge main (d2a3269d) into environment state coverage
earakely-scale Oct 20, 2026
ef49dca
fix(environment): keep changed documents out of the state; mark OPTIO…
earakely-scale Oct 20, 2026
306c3da
docs(specs): plan evidence-gated write effects on the served state
earakely-scale Oct 20, 2026
5a61853
fix(environment): release batch replies as they are encoded; judge ex…
earakely-scale Oct 20, 2026
b4b7ebc
perf(environment): intersect list identity candidates through a set
earakely-scale Oct 20, 2026
b9fbcd7
feat(environment): apply the write effects a capture confirms to the …
earakely-scale Oct 20, 2026
84291a0
fix(environment): count only applied writes and serve writes the held…
earakely-scale Oct 20, 2026
cbb7b61
test(environment): cover write plans, the write gate and served writes
earakely-scale Oct 20, 2026
e7bd24b
docs(specs): record the write effects verification
earakely-scale Oct 20, 2026
a0b3c55
Merge remote-tracking branch 'fork/feat/environment-state-serve' into…
earakely-scale Oct 20, 2026
0864bac
Merge remote-tracking branch 'fork/feat/environment-state-coverage' i…
earakely-scale Oct 20, 2026
2e89a39
Merge remote-tracking branch 'origin/main' into feat/environment-stat…
earakely-scale Oct 20, 2026
82dfd94
docs(specs): record the write effects checks after merging the base b…
earakely-scale Oct 20, 2026
ce12615
Merge remote-tracking branch 'origin/main' into feat/environment-stat…
earakely-scale Oct 20, 2026
52b6b78
docs(specs): record the checks after merging main again
earakely-scale Oct 20, 2026
dbd0dce
chore: merge main (1629266e) into environment state coverage
earakely-scale Oct 20, 2026
f6c756a
fix(environment): quote captured names in response summaries
earakely-scale Oct 20, 2026
370b9be
docs(specs): correct the showcase capture count to 50
earakely-scale Oct 20, 2026
c00fde4
fix(environment): keep room for refusals and framing in the reply budget
earakely-scale Oct 20, 2026
61c8e3e
chore: merge environment state serve (c00fde41) into environment stat…
earakely-scale Oct 20, 2026
862c88c
chore: merge environment state coverage (f6c756aa) into environment s…
earakely-scale Oct 20, 2026
b068b09
chore: merge main (1629266e) into environment state writes
earakely-scale Oct 20, 2026
82556cd
fix(environment): answer unfiltered lists from their own parent; desc…
earakely-scale Oct 20, 2026
138ea4b
fix(environment): judge writes by the full served response; model onl…
earakely-scale Oct 20, 2026
6d21b62
fix(environment): refuse writes the state could not hold or reload
earakely-scale Oct 20, 2026
f1b00f5
docs(environment): specify the write refusals, 2xx-only modelling and…
earakely-scale Oct 20, 2026
df2bded
test(environment): pin the replay card with quoted summary names; rec…
earakely-scale Oct 20, 2026
2086da6
fix(environment): make the write gate and serving agree on lines, rul…
earakely-scale Oct 20, 2026
7056f5f
docs(environment): record the second review round's verification
earakely-scale Oct 20, 2026
db8df45
fix(environment): keep checked lines' path spellings; check later slu…
earakely-scale Oct 20, 2026
5327e59
fix(environment): choose a read's checked line as replay chooses the …
earakely-scale Oct 20, 2026
b6c3b16
fix(environment): match document write paths, verbatim create collect…
earakely-scale Oct 20, 2026
f2b9535
fix(environment): answer a missing entity with a 2xx null only for reads
earakely-scale Oct 20, 2026
25b6622
chore: merge main (335c042d) into environment state serve
earakely-scale Oct 21, 2026
54d3d5e
feat(environment): decide a list's whole-collection membership per line
earakely-scale Oct 21, 2026
19ef539
chore: merge main (335c042d) into environment state coverage
earakely-scale Oct 21, 2026
87e94d1
test(environment): cover per-line list membership; document it
earakely-scale Oct 21, 2026
665112e
fix(environment): quote the prefix of a member name too long to show …
earakely-scale Oct 21, 2026
4aeefd9
chore: merge environment state serve (25b6622d) into environment stat…
earakely-scale Oct 21, 2026
9edbabe
chore: merge environment state coverage (665112e9) into environment s…
earakely-scale Oct 21, 2026
111556a
docs(specs): record per-line list membership measured on six environm…
earakely-scale Oct 21, 2026
6b8db19
fix(environment): refuse a loaded state that data/get would write pas…
earakely-scale Oct 21, 2026
fc403d9
chore: merge environment state serve (6b8db198) into environment stat…
earakely-scale Oct 21, 2026
1d1c478
fix(environment): confirm a write only by reads that still see it, an…
earakely-scale Oct 21, 2026
dc5e2aa
fix(environment): weigh an update's derived changes when a later writ…
earakely-scale Oct 21, 2026
8a374b6
Merge remote-tracking branch 'fork/feat/environment-state-writes' int…
earakely-scale Oct 21, 2026
4080063
fix(environment): count no write for a collection once a read shows i…
earakely-scale Oct 21, 2026
847b093
docs(specs): record per-line list membership over fifty captures and …
earakely-scale Oct 21, 2026
fe8ab58
fix(environment): erase overwritten fields from earlier write effects…
earakely-scale Oct 21, 2026
edc09db
Merge remote-tracking branch 'fork/feat/environment-state-writes' int…
earakely-scale Oct 21, 2026
73c0e9b
fix(environment): create in a held collection when an Evidence spelli…
earakely-scale Oct 21, 2026
b224462
chore: merge main into environment state writes
morluto Oct 21, 2026
19118fe
chore: merge environment state writes (73c0e9b5) into environment lis…
earakely-scale Oct 21, 2026
0a46f89
chore: merge main (4dfa1c67) into environment list lines
earakely-scale Oct 21, 2026
9f513d0
fix(environment): check reads on the lines serving answers, and refus…
earakely-scale Oct 21, 2026
6d28aa7
chore: merge the remote environment state writes (b2244622) into the …
earakely-scale Oct 21, 2026
2eb7be0
chore: merge environment state writes (6d28aa78) into environment lis…
earakely-scale Oct 21, 2026
7ffd077
fix(environment): take list counters from whole lines, per line, and …
earakely-scale Oct 21, 2026
bec65b3
chore: merge main (d8a9673f) into environment state writes
earakely-scale Oct 21, 2026
3580d85
fix(environment): confirm only the writes a read shows, and name and …
earakely-scale Oct 21, 2026
43d98ea
fix(environment): pin a create's observation to the id it answered, a…
earakely-scale Oct 21, 2026
3e18322
chore: merge environment state writes (43d98ea9) into environment lis…
earakely-scale Oct 21, 2026
de13b0c
docs(specs): record the list-lines re-run after the write-plan merge
earakely-scale Oct 21, 2026
264ce41
fix(environment): keep unseen writes pending, and hold later calls to…
earakely-scale Oct 21, 2026
2807278
chore: merge environment state writes (264ce410) into environment lis…
earakely-scale Oct 21, 2026
7d2587c
docs(specs): record the list-lines re-run after the third write-plan …
earakely-scale Oct 21, 2026
0ae6440
fix(environment): never rule an entity's identity, and read a zero pa…
earakely-scale Oct 21, 2026
34cbdd6
chore: merge environment state writes (0ae64400) into environment lis…
earakely-scale Oct 21, 2026
6257de9
refactor(environment): move the paging rules to environmentStatePagin…
earakely-scale Oct 21, 2026
4f40bff
chore: merge environment state writes (6257de93) into environment lis…
earakely-scale Oct 21, 2026
c68c63b
docs(specs): record the list-lines re-run after the later write-plan …
earakely-scale Oct 21, 2026
466ed8b
fix(environment): name entities and weigh interference per write as s…
earakely-scale Oct 21, 2026
f239fa3
chore: merge environment state writes (466ed8b4) into environment lis…
earakely-scale Oct 21, 2026
ed4b6db
docs(specs): record the list-lines re-run after the fourth write-plan…
earakely-scale Oct 21, 2026
7cef2fb
fix(environment): bound pages per size, refuse only read-observed rem…
earakely-scale Oct 21, 2026
8eea9f6
chore: merge environment state writes (7cef2fb2) into environment lis…
earakely-scale Oct 21, 2026
734786e
docs(specs): record the list-lines re-run after the 7cef2fb2 merge
earakely-scale Oct 21, 2026
45a5c8b
fix(environment): count interference on any target a read covers, and…
earakely-scale Oct 21, 2026
27dd606
chore: merge environment state writes (45a5c8b9) into environment lis…
earakely-scale Oct 21, 2026
325c128
fix(environment): weigh interference only where a tool's effect survives
earakely-scale Oct 21, 2026
9b868c0
chore: merge environment state writes (325c128f) into environment lis…
earakely-scale Oct 21, 2026
6c8f4f7
feat(environment): render more read tools from the state and describe…
cursoragent Oct 21, 2026
378a109
fix(environment): keep rendered documents and quoted samples inside t…
cursoragent Oct 21, 2026
cfb42dd
feat(environment): apply evidence-gated write effects to the served s…
cursoragent Oct 21, 2026
5d0e096
fix(environment): bound and validate write state history
morluto Oct 21, 2026
5b42469
feat(environment): render more read tools from the state and describe…
cursoragent Oct 21, 2026
54c8934
fix(environment): keep rendered documents and quoted samples inside t…
cursoragent Oct 21, 2026
19b50ea
feat(environment): apply evidence-gated write effects to the served s…
cursoragent Oct 21, 2026
a057ea9
fix(environment): bound and validate write state history
morluto Oct 21, 2026
f79f1e1
fix(environment): bound additional collection history
morluto Oct 21, 2026
4a678f1
Merge remote-tracking branch 'live-5600/feat/environment-state-writes…
morluto Oct 21, 2026
7de20bc
fix(environment): credit sent fields, negative sequences, and encoded…
cursoragent Oct 21, 2026
a1076ca
Merge live environment write verification fixes
morluto Oct 21, 2026
d3015d2
test(environment): cover resolved encoded update identities
morluto Oct 21, 2026
cddd3e6
fix: validate timed update observations
morluto Oct 21, 2026
fb6785d
fix(environment): share write overlap and check clocks on earlier calls
cursoragent Oct 21, 2026
d7c5c62
merge: restack environment state writes onto main after #5352
cursoragent Oct 21, 2026
3b34bbd
fix: preserve partial update evidence
morluto Oct 21, 2026
5d00ff3
Merge remote-tracking branch 'live-5600/feat/environment-state-writes…
morluto Oct 21, 2026
717ac2c
chore: merge main (8413ec08) into environment state writes
earakely-scale Oct 21, 2026
891f35e
chore: merge environment state writes (717ac2c4) into environment lis…
earakely-scale Oct 22, 2026
2013511
chore: merge main (2451e187) into environment list lines
earakely-scale Oct 22, 2026
e923fc7
fix(environment): let an unmodelled write explain only the list membe…
earakely-scale Oct 21, 2026
75d7bb0
fix(environment): explain added fields, tie creates to serving's coll…
earakely-scale Oct 21, 2026
cd26a76
docs(environment): state how list reads weigh unmodelled writes, adde…
earakely-scale Oct 22, 2026
2a125b7
chore: merge main (4a4bbab3) into environment state writes
earakely-scale Oct 22, 2026
ddab0a9
chore: merge environment state writes (2a125b71) into environment lis…
earakely-scale Oct 22, 2026
11e3f01
refactor(environment): keep the observing view helpers with the obser…
earakely-scale Oct 22, 2026
6685b37
chore: merge environment state writes (11e3f016) into environment lis…
earakely-scale Oct 22, 2026
53a7866
fix(environment): resolve unmodelled writes onto the held collection
cursoragent Oct 22, 2026
329aeed
fix(environment): confirm no write through volatile fields or overwri…
earakely-scale Oct 22, 2026
ccdf091
fix(environment): leave unknown entities unchecked by failed reads, v…
earakely-scale Oct 22, 2026
1c97933
fix(environment): fill a create's path fields from the collection ser…
earakely-scale Oct 22, 2026
90d9022
fix(environment): name unmodelled writes as modelled ones, count fiel…
earakely-scale Oct 22, 2026
ca88b5e
chore: merge environment state writes (90d90227) into environment lis…
earakely-scale Oct 22, 2026
0fe1738
refactor(environment): keep the written-field checks with the attribu…
earakely-scale Oct 22, 2026
756c631
fix(environment): let a document replacement overwrite everything und…
earakely-scale Oct 22, 2026
3f1f825
chore: merge the published environment state writes (756c6312)
earakely-scale Oct 22, 2026
79f0560
chore: merge environment state writes (3f1f825e) into environment lis…
earakely-scale Oct 22, 2026
1802e41
chore: merge main (b8c1b453) into environment list lines
earakely-scale Oct 22, 2026
0499ed1
chore: merge main (538017d1, #5600 squashed) into environment list lines
earakely-scale Oct 22, 2026
36571c4
fix(environment): preserve whole-list semantics when integrating late…
gensokyo-dev Oct 22, 2026
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
3 changes: 2 additions & 1 deletion docs/agent-environments.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,8 @@ A state that is unavailable does not stop the server: it logs a warning naming
the error `code` and message before it binds, then serves replay. The state is
unavailable when it cannot be derived, such as from a
`capture_browser_scenario` capture that selected header values but no response
bodies or over the view's budget, and when its catalog under the served name
bodies or over the view's budget, when `data/get` would write it past the 32 MiB
`data/add` intake limit, and when its catalog under the served name
exceeds the [discovery reservation](#what-a-manifest-is). That check runs
first, so no state is derived for it, and replay is then admitted exactly as
with `--replay-only`. `--replay-only`
Expand Down
33 changes: 22 additions & 11 deletions docs/specs/agent-environments/state-writes/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,11 @@ the value a recorded call sent it with, and then stores the value that call
recorded (its `constant` rule carries it). The type's identity field never
takes a rule: sent as the path's id it is the identity member, sent as another
value the application ignored it is accepted with that value and stores
nothing, and a stored id that changed is `unexplained-change`.
nothing, and a stored id that changed is `unexplained-change`. A plan whose
calls use a member both as the identity and as a fixed member, or fix it at
different values, is `unexplained-change`, as serving could not take every
recorded call. So is an update whose observation drops a field the entity
held, since serving keeps every field an update does not write.
`PUT` requires every member the exemplar sent; `PATCH` and `POST` require at
least one. A field the exemplar's update changed without sending it is
explained as one of:
Expand Down Expand Up @@ -159,9 +163,10 @@ the initial state.
**Writes.** Only a 2xx write is modelled. A modelled write applies its effect, using the values it recorded
for generated fields and the stored values for fields it transformed. A
modelled write whose call the plan does not explain brings its entity to the
recorded outcome instead, without attribution. A later create whose sequence
fields hold another value than serving would generate makes the plan
`unexplained-change`; identities are left to the id mapping. An update or
recorded outcome instead, without attribution. A later create whose generated
values take another form than serving gives them (a sequence value out of
order, a clock in another format, a non-UUID unique value) makes the plan
`unexplained-change`; integer identities are left to the id mapping. An update or
delete names its entity as an item read does (below).

Any other write that may have changed state, including a redirected or
Expand All @@ -183,8 +188,9 @@ members they sent.
from the state:

- an item read of a state-backed item view, of the entity serving would name:
the read's collection and id as written, else a held collection whose path
matches once percent-decoded;
in a held collection the read's path matches, each segment verbatim or once
percent-decoded and verbatim spellings first, the id percent-decoded once,
then as written;
- a list or document read on one of its view's checked request lines,
chosen as replay chooses the line for the read's call: each path parameter
the read's value verbatim or once percent-decoded, preferring verbatim
Expand All @@ -194,7 +200,8 @@ from the state:
different values is never chosen, since no call's arguments can name it; one
repeating a name with one value is, as a call naming it matches both. A list
is compared as served from the collection of that line. A read on a page
(`limit`, `size`, `per_page` and the like, a size of zero bounding nothing, or a `_start`–`_end` range) of a
(`limit`, `size`, `per_page` and the like, or a `_start`–`_end` range; a size
of zero bounds nothing on a line whose recording listed items under it) of a
whole list checks nothing once the collection holds more entities than the
page, which serving then answers from its recording.
- A read made while a modelled write to its entity or collection was still
Expand Down Expand Up @@ -224,15 +231,17 @@ refuses to answer with.
instead), a recorded outcome every field, and a create or delete the whole
entity. A document write's effect is the members it merged at its
object, or everything under the object it replaces, the whole document at the
root. A write with nothing left on an entity no
root; an entity's fields match by name only, whatever their names look like. A write with nothing left on an entity no
longer counts there, nor in a collection where no entity it changed keeps any
of its effect. A mismatch contradicts them. A pass confirms those it shows
something of: a create's or delete's membership, or a changed field the
read's view shows and does not treat as volatile; a read that shows none of
an update's changes confirms nothing of it, and leaves it for a later check
of that entity or collection.
- A mismatch after an unmodelled write that followed those writes is checked
only on the members they sent: such a write may explain the rest.
- A mismatch contradicts each exercised write that no unmodelled write came
after, whatever earlier write is still pending. When an unmodelled write
followed some of them, an item read checks those only on the members they
sent and a list is not checked again: such a write may explain the rest.
- A mismatch on an entity or collection that no write changed contradicts,
as `side-effect`, the modelled writes since that previous check whose paths
are segment-prefix related to the read's path.
Expand Down Expand Up @@ -305,7 +314,9 @@ installs and of the type's checked list lines (so a collection the capture
listed empty keeps its spelling), never those of a state it replaced. When two
spellings fit a call equally, the one holding entities wins. `data/add` refuses a document that `data/get` would write back past the
32 MiB intake limit once it adds the members a document may omit, such as
`types` and the state Evidence id.
`types` and the state Evidence id. A derived state `data/get` would write
past that limit is not served: the environment serves replay and reports the
state `unavailable`.

**Clock and generators.** The store's clock starts at `write_clock` and
advances one second before each served write; clock fields take its value in
Expand Down
19 changes: 19 additions & 0 deletions docs/specs/agent-environments/state-writes/verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,22 @@ A fourteenth round settled two findings Greptile raised on the list-queries bran

Both tests fail on the previous head. The verdicts over the 50 captures are unchanged plan by plan, the smoke applies
all 31 served write tools, and the gates passed again.

A fifteenth round settled nine findings Greptile raised on this branch, the fidelity branch and the list-lines branch,
five of them on the previous rounds' own changes:

- an entity field whose name looks like a pointer is matched by name; only a document's pointers cover the members
under them;
- a failed read contradicts each exercised write no unmodelled write came after, rather than skipping all of them
when the oldest pending write came before one;
- an item read, update or delete names its entity as serving does, decoding the id once, so `book%2531` no longer
reaches `book1`;
- a plan whose calls use a member both as the identity and as a fixed member, or fix it at different values, is
refused;
- a size of zero bounds nothing only on a line whose recording listed items under it;
- an update whose observation drops a field the entity held is refused;
- a later create whose clock takes another format, or whose unique value is not a UUID, is refused;
- a derived state `data/get` would write past 32 MiB is not served.

Each new test fails on the previous head. The verdicts over the 50 captures are unchanged plan by plan, the smoke
applies all 31 served write tools, and the gates passed again.
23 changes: 23 additions & 0 deletions src/application/environment/environmentState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
} from "../analysisView/AnalysisViewService.js";
import { loadEnvironmentSource } from "./environmentSource.js";
import {
admitServedState,
deriveEnvironmentState,
loadEnvironmentState,
prepareServedState,
Expand Down Expand Up @@ -272,6 +273,28 @@ describe("prepareServedState", () => {
});
});

describe("admitServedState", () => {
it("refuses a derived state data/get would write past what data/add loads back", () => {
expect(admitServedState(state, "environment_serve").ok).toBe(true);
// A euro sign is one UTF-16 unit but three bytes as data/get writes it.
const notes = "\u20ac".repeat(12_000_000);
const [first] = state.entities;
const large = {
...state,
entities: [
...state.entities,
{ ...first!, id: "large", fields: { ...first!.fields, notes } },
],
};
const admitted = admitServedState(large, "environment_serve");
if (admitted.ok) throw new Error("Expected the state to be refused");
expect(projectAnalysisError(admitted.error)).toMatchObject({
code: "resource_constraint",
message: expect.stringContaining("larger than data/add loads"),
});
});
});

describe("EnvironmentStateStore", () => {
it("reports its state as rea-state/v1, accepts that report back and resets to the initial state", () => {
const store = new EnvironmentStateStore(state);
Expand Down
31 changes: 29 additions & 2 deletions src/application/environment/environmentState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
} from "../../domain/analysisView/environmentStateRules.js";
import type { StateWritePlan } from "../../domain/analysisView/environmentStateWriteRules.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
AnalysisInputIssue,
import {
AnalysisResourceConstraintError,
type AnalysisInputIssue,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
Expand All @@ -23,6 +23,8 @@ import {
type EnvironmentManifestTool,
type EnvironmentSource,
} from "./environmentSource.js";
import { STATE_INTAKE_LIMIT_BYTES } from "./environmentStateDocument.js";
import { initialStateBytes } from "./environmentStateStore.js";
import { describeWrite } from "./environmentStateWriteDescription.js";
import {
environmentToolDefinitions,
Expand Down Expand Up @@ -238,6 +240,29 @@ export interface PreparedState extends ServedState {
>;
}

/** The derived state, unless data/get would write it past what data/add loads back, so its own report could not be restored. */
export const admitServedState = (
state: EnvironmentState,
operation: string,
): Result<EnvironmentState, AnalysisResourceConstraintError> => {
const bytes = initialStateBytes(state);
return bytes > STATE_INTAKE_LIMIT_BYTES
? err(
new AnalysisResourceConstraintError(
operation,
"capacity",
"The derived state is larger than data/add loads, so it cannot be served",
{ max_state_bytes: STATE_INTAKE_LIMIT_BYTES, state_bytes: bytes },
{
retryable: false,
remediationAction:
"Capture fewer or smaller responses, or serve the environment as replay only.",
},
),
)
: ok(state);
};

const unavailable = (error: AnalysisError): PreparedState => {
const { code, message } = projectAnalysisError(error);
return {
Expand All @@ -262,6 +287,8 @@ export const prepareServedState = (
if (!reads.ok) return unavailable(reads.error);
const derived = deriveEnvironmentState(source, captureValue, operation);
if (!derived.ok) return unavailable(derived.error);
const admitted = admitServedState(derived.value, operation);
if (!admitted.ok) return unavailable(admitted.error);
// Served write tools join the catalog, so the whole catalog is admitted again.
const catalog = servedCatalog(source, derived.value, name, operation);
return catalog.ok
Expand Down
6 changes: 4 additions & 2 deletions src/application/environment/environmentStateAnswer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
type StateView,
} from "../../domain/analysisView/environmentStateRules.js";
import {
pageSize,
pageBound,
pagesOnly,
} from "../../domain/analysisView/environmentStatePaging.js";
import { isAbsence } from "../../domain/analysisView/environmentStateWriteChecks.js";
Expand Down Expand Up @@ -431,7 +431,9 @@ const answerList = (
const type = store.type(view.type);
const all = listsAll(view, base.ordinal);
// A requested page the collection has outgrown is answered as recorded, never with more items than it asked for.
const size = exact ? pageSize(base.query ?? undefined) : undefined;
const size = exact
? pageBound(base.query ?? undefined, recorded.length)
: undefined;
if (
all &&
size !== undefined &&
Expand Down
46 changes: 28 additions & 18 deletions src/application/environment/environmentStateStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,27 @@ const itemsBytes = (items: readonly unknown[]): number =>
items.reduce<number>((sum, item) => sum + jsonBytes(item), 0) +
Math.max(0, items.length - 1);

/** What `data/get` reports for some content of a state. */
const snapshotOf = (
state: EnvironmentState,
entities: readonly StateEntity[],
documents: readonly HeldDocument[],
): StateSnapshot => ({
rea_state: {
version: 1,
state_evidence_id: state.evidenceId,
types: state.types,
entities,
documents,
},
});

/** What `data/get` writes for a state as the Evidence holds it, in UTF-8 bytes, summed item by item. */
export const initialStateBytes = (state: EnvironmentState): number =>
jsonBytes(snapshotOf(state, [], [])) +
itemsBytes(state.entities) +
itemsBytes(state.documents);

/**
* The live state one served environment answers from, shared by every MCP
* session and the data plane. Mutations are synchronous and swap the whole
Expand Down Expand Up @@ -74,8 +95,8 @@ export class EnvironmentStateStore {
);
this.#clockStart =
state.writeClock === null ? 0 : Date.parse(state.writeClock);
this.#frameBytes = jsonBytes(this.#snapshotOf([], []));
this.#initialBytes = this.#contentBytes(state);
this.#frameBytes = jsonBytes(snapshotOf(state, [], []));
this.#initialBytes = initialStateBytes(state);
this.reset();
}

Expand Down Expand Up @@ -303,29 +324,18 @@ export class EnvironmentStateStore {
}

snapshot(): StateSnapshot {
return this.#snapshotOf(this.#content.entities, this.#content.documents);
return snapshotOf(
this.state,
this.#content.entities,
this.#content.documents,
);
}

/** What `data/get` writes for the current state, in UTF-8 bytes. */
byteLength(): number {
return this.#bytes;
}

#snapshotOf(
entities: readonly StateEntity[],
documents: readonly HeldDocument[],
): StateSnapshot {
return {
rea_state: {
version: 1,
state_evidence_id: this.state.evidenceId,
types: this.state.types,
entities,
documents,
},
};
}

/** What `data/get` writes for some content, summed item by item so the whole state is never one string. */
#contentBytes(content: StateContent): number {
return (
Expand Down
20 changes: 20 additions & 0 deletions src/application/environment/environmentStateWriteAnswer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,26 @@ describe("paged lines", () => {
});
});

it("answers a zero limit a whole line recorded empty from that recording once a create fills its collection", () => {
const alpha = { id: 1, name: "Alpha", org: "1" };
const beta = { id: 2, name: "Beta", org: "2" };
const books = servedFrom([
["GET", "/api/orgs/1/books", [alpha]],
["GET", "/api/orgs/1/books/1", alpha],
["GET", "/api/orgs/2/books?limit=0", []],
["POST", "/api/orgs/2/books", beta, 201, { name: "Beta" }],
["GET", "/api/orgs/2/books/2", beta],
]);
books.answer("post_orgs_books_by_id", { id: "2", body: { name: "Gamma" } });
// Only a recording that listed items under it shows that zero lists every entity.
expect(
books.answer("get_orgs_books_by_id", { id: "2", limit: "0" }),
).toMatchObject({
body: [],
state: { source: "recording", reason: "page-exceeded" },
});
});

it("answers a range the collection has outgrown from its recording", () => {
const books = servedFrom([
["GET", "/api/books?_start=0&_end=2", [FIRST_BOOK, SECOND_BOOK]],
Expand Down
Loading