Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
40 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
9f60e54
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
e96484b
Merge main (#5319 squashed, #5349) into feat/environment-state-serve
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
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
5a61853
fix(environment): release batch replies as they are encoded; judge ex…
earakely-scale Oct 20, 2026
c00fde4
fix(environment): keep room for refusals and framing in the reply budget
earakely-scale Oct 20, 2026
25b6622
chore: merge main (335c042d) into environment state serve
earakely-scale Oct 21, 2026
6b8db19
fix(environment): refuse a loaded state that data/get would write pas…
earakely-scale Oct 21, 2026
31a618e
chore: merge main (d9767eb4) into environment state serve
cursoragent Oct 21, 2026
96ce6c6
fix(environment): keep merged export checks on the shared test graph
cursoragent Oct 21, 2026
bfe9d4b
chore: merge main into environment state serve
morluto Oct 21, 2026
0da8e23
fix(environment): keep a state file whose close failed owned until it…
earakely-scale Oct 21, 2026
98a7511
fix(environment): attempt all state cleanup on close
morluto Oct 21, 2026
d681bfd
fix(environment): bound wide state JSON traversal
morluto Oct 21, 2026
e4a0fc6
chore: merge current main into state server fixes
morluto Oct 21, 2026
467828e
fix(environment): scope cached state reply sizes to requests
morluto Oct 21, 2026
05deae3
fix(domain): preserve JSON depth diagnostic guidance
morluto Oct 21, 2026
7c3d0e9
chore: merge current main into state server fixes
morluto Oct 21, 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
57 changes: 57 additions & 0 deletions src/application/environment/environmentState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,30 @@ describe("EnvironmentStateStore", () => {
});
});

describe("caller-owned state replacement", () => {
it("does not retain mutable data from a caller-owned replacement", () => {
const store = new EnvironmentStateStore(state);
const document = documentWith((value) => {
const entity = value.rea_state.entities.find((item) => item.id === "2");
if (!entity) throw new Error("Expected the user entity");
entity.fields = { ...(entity.fields as object), login: "renamed" };
});
expect(store.replace(document).ok).toBe(true);
const callerEntity = document.rea_state.entities.find(
(entity) => entity.id === "2",
);
if (!callerEntity) throw new Error("Expected the caller's user entity");
(callerEntity.fields as Record<string, unknown>).login = "later edit";

expect(store.snapshot().rea_state.entities).toContainEqual(
expect.objectContaining({
id: "2",
fields: expect.objectContaining({ login: "renamed" }),
}),
);
});
});

describe("rea-state/v1 validation", () => {
it.each([
[
Expand Down Expand Up @@ -570,3 +594,36 @@ describe("rea-state/v1 validation", () => {
).toMatchObject({ path: "rea_state/version" });
});
});

describe("wide state value validation", () => {
it("preserves a wide caller value through the state replacement boundary", () => {
const wide = Array.from({ length: 200_000 }, (_, index) => index % 10);
const wideObject = Object.fromEntries(
Array.from({ length: 20_000 }, (_, index) => [
`field_${String(index)}`,
index,
]),
);
const document = documentWith((value) => {
const fields = value.rea_state.entities[0]!.fields as Record<
string,
unknown
>;
value.rea_state.entities[0]!.fields = {
...fields,
caller_wide: wide,
caller_wide_object: wideObject,
};
});
const store = new EnvironmentStateStore(state);

expect(store.replace(document).ok).toBe(true);
const retained = store.snapshot().rea_state.entities[0]?.fields.caller_wide;
if (!Array.isArray(retained)) throw new Error("Expected the wide value");
expect(retained).toHaveLength(wide.length);
expect(retained.at(-1)).toBe(wide.at(-1));
const retainedObject =
store.snapshot().rea_state.entities[0]?.fields.caller_wide_object;
expect(retainedObject).toEqual(wideObject);
});
});
156 changes: 110 additions & 46 deletions src/application/environment/environmentStateDocument.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { types } from "node:util";
import { z } from "zod";

import {
Expand All @@ -16,7 +17,11 @@ import {
} from "../../domain/analysisErrorCore.js";
import { canonicalJson } from "../../domain/comparisonSemantics.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import {
jsonValueSchema,
ownedJsonValueSchema,
type JsonValue,
} from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import { compositeKey } from "../../domain/unicodeCodePointOrder.js";
import type { EnvironmentState } from "./environmentState.js";
Expand All @@ -37,37 +42,42 @@ export interface StateContent {
readonly documents: readonly HeldDocument[];
}

const fieldsSchema = z.record(z.string(), jsonValueSchema);
const ordinalSchema = z.number().int().nonnegative();
const stateDocumentSchemaFor = (jsonValue: z.ZodType<JsonValue, unknown>) => {
const fieldsSchema = z.record(z.string(), jsonValue);
const ordinalSchema = z.number().int().nonnegative();

const stateDocumentSchema = z.strictObject({
rea_state: z.strictObject({
version: z.literal(1),
// `data/get` reports these; accepting them back lets its output be loaded unchanged.
state_evidence_id: z.string().optional(),
types: z.array(jsonValueSchema).optional(),
entities: z.array(
z.strictObject({
type: z.string(),
collection: z.string(),
id: z.string(),
fields: fieldsSchema,
view_fields: z
.array(z.strictObject({ tool: z.string(), fields: fieldsSchema }))
.optional(),
record_ordinals: z.array(ordinalSchema).optional(),
}),
),
documents: z.array(
z.strictObject({
tool: z.string(),
path: z.string(),
value: jsonValueSchema,
record_ordinal: ordinalSchema.optional(),
}),
),
}),
});
return z.strictObject({
rea_state: z.strictObject({
version: z.literal(1),
// `data/get` reports these; accepting them back lets its output be loaded unchanged.
state_evidence_id: z.string().optional(),
types: z.array(jsonValue).optional(),
entities: z.array(
z.strictObject({
type: z.string(),
collection: z.string(),
id: z.string(),
fields: fieldsSchema,
view_fields: z
.array(z.strictObject({ tool: z.string(), fields: fieldsSchema }))
.optional(),
record_ordinals: z.array(ordinalSchema).optional(),
}),
),
documents: z.array(
z.strictObject({
tool: z.string(),
path: z.string(),
value: jsonValue,
record_ordinal: ordinalSchema.optional(),
}),
),
}),
});
};

const stateDocumentSchema = stateDocumentSchemaFor(jsonValueSchema);
const ownedStateDocumentSchema = stateDocumentSchemaFor(ownedJsonValueSchema);

type ParsedDocument = z.output<typeof stateDocumentSchema>["rea_state"];
type ParsedEntity = ParsedDocument["entities"][number];
Expand Down Expand Up @@ -105,31 +115,82 @@ const memberProblem = (path: Path): AnalysisInputIssue => {

/** The path of the first `__proto__` member in document order; schema parsing would drop such a member rather than refuse it. */
const prototypeMemberPath = (root: unknown): Path | undefined => {
interface Node {
interface Cursor {
readonly value: unknown;
readonly parent: Node | undefined;
readonly parent: Cursor | undefined;
readonly key: string | number;
readonly entries?: Generator<string>;
index: number;
}
const pathOf = (node: Node): (string | number)[] => {
const pathOf = (node: Cursor): (string | number)[] => {
const path: (string | number)[] = [];
for (let at: Node = node; at.parent !== undefined; at = at.parent)
for (let at: Cursor = node; at.parent !== undefined; at = at.parent)
path.push(at.key);
return path.reverse();
};
const pending: Node[] = [{ value: root, parent: undefined, key: "" }];
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
function* ownKeys(value: Record<string, unknown>): Generator<string> {
// `for...in` is lazy. The ownership check keeps inherited enumerable
// properties out, matching Object.entries without allocating all entries.
for (const key in value) if (Object.hasOwn(value, key)) yield key;
}
const cursor = (
value: unknown,
parent: Cursor | undefined,
key: string | number,
): Cursor => ({
value,
parent,
key,
index: 0,
...(!Array.isArray(value) && typeof value === "object" && value !== null
? { entries: ownKeys(value as Record<string, unknown>) }
: {}),
});
const pending: Cursor[] = [cursor(root, undefined, "")];
while (pending.length > 0) {
const node = pending[pending.length - 1]!;
const { value } = node;
if (typeof value !== "object" || value === null) continue;
if (typeof value !== "object" || value === null) {
pending.pop();
continue;
}
// The canonical JSON validator reports proxies without invoking their traps.
if (types.isProxy(value)) {
pending.pop();
continue;
}
const array = Array.isArray(value);
if (!array && Object.hasOwn(value, "__proto__"))
return [...pathOf(node), "__proto__"];
const entries = Object.entries(value);
for (let index = entries.length - 1; index >= 0; index -= 1)
pending.push({
value: entries[index]![1],
parent: node,
key: array ? index : entries[index]![0],
});
if (array) {
if (node.index >= value.length) {
pending.pop();
continue;
}
const index = node.index++;
const descriptor = Object.getOwnPropertyDescriptor(value, index);
if (
descriptor?.enumerable !== true ||
!Object.hasOwn(descriptor, "value")
)
continue;
const child: unknown = descriptor.value;
if (typeof child === "object" && child !== null)
pending.push(cursor(child, node, index));
continue;
}
const next = node.entries?.next();
if (next === undefined || next.done) {
pending.pop();
continue;
}
const key = next.value;
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor?.enumerable !== true || !Object.hasOwn(descriptor, "value"))
continue;
const child: unknown = descriptor.value;
if (typeof child === "object" && child !== null)
pending.push(cursor(child, node, key));
}
return undefined;
};
Expand Down Expand Up @@ -365,9 +426,12 @@ const heldContent = (
export const parseStateDocument = (
state: EnvironmentState,
value: unknown,
owned = false,
): Result<StateContent, AnalysisInputError> => {
const prototype = prototypeMemberPath(value);
const parsed = stateDocumentSchema.safeParse(value);
const parsed = (
owned ? ownedStateDocumentSchema : stateDocumentSchema
).safeParse(value);
const initial = new Map(
state.entities.map((entity) => [entityKey(entity), entity]),
);
Expand Down
16 changes: 14 additions & 2 deletions src/application/environment/environmentStateStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,21 @@ export class EnvironmentStateStore {
this.#install(this.state);
}

/** Validate a `rea-state/v1` document and, only when it is valid, make it the whole state. */
/** Validate a caller-owned document and copy its JSON values before retaining them. */
replace(document: unknown): Result<void, AnalysisInputError> {
const content = parseStateDocument(this.state, document);
return this.#replace(document, false);
}

/** Validate and retain a JSON document created exclusively by the serving boundary. */
replaceOwnedDocument(document: unknown): Result<void, AnalysisInputError> {
return this.#replace(document, true);
}

#replace(
document: unknown,
owned: boolean,
): Result<void, AnalysisInputError> {
const content = parseStateDocument(this.state, document, owned);
if (!content.ok) return content;
// data/get writes members a document may omit, so the state it reports must still be one data/add loads.
if (jsonBytes(this.#snapshotOf(content.value)) > STATE_INTAKE_LIMIT_BYTES)
Expand Down
4 changes: 3 additions & 1 deletion src/domain/jsonValue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ describe("jsonValueSchema depth bound", () => {
const result = jsonValueSchema.safeParse(deepObject(MAX_JSON_DEPTH + 1));
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error.issues[0]?.message).toContain("maximum nesting depth");
expect(result.error.issues[0]?.message).toBe(
`JSON value exceeds maximum nesting depth of ${MAX_JSON_DEPTH}. This release has no runtime override.`,
);
});

it.each(["object", "array"])(
Expand Down
Loading
Loading