Skip to content

feat(environment): extract the initial state a capture's reads observed - #5319

Merged
kaoru0822-kitauji merged 17 commits into
morluto:mainfrom
earakely-scale:feat/environment-state-view
Oct 20, 2026
Merged

kaoru0822-kitauji merged 17 commits into
morluto:mainfrom
earakely-scale:feat/environment-state-view

Conversation

@earakely-scale

@earakely-scale earakely-scale commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add the read-only environment-state analysis view for HAR and browser-scenario Evidence. It reports observed initial entities, documents and checked read plans, using the same grouping and template rules as the environment manifest. It does not serve tools from state or implement write effects / the AgentEnv data plane.

Refs #4933. Scope is local inspection of already-captured Evidence: no new provider, target execution, injection, network access or mutation.

Changes

  • Bound initial reads by recorded writes and preserve identity, artifact provenance, record ordinals, redaction markers and explicit recorded-view fallback reasons. File, inline and retained sources share the application workflow.
  • Reject state-backed plans when membership changes across a recorded write, including empty lists, or entity fields are added/removed. Keep each field's last observation across sparse projections so omitted fields cannot hide a write effect. Query strings remain distinct.
  • Recognize compact totalcount/itemcount envelope totals while excluding page counts and account IDs.
  • Remove repeated growing-array copies in API-base grouping and quadratic identity-key intersections. Keep byte admission and bounded membership sets at the owning boundary.
  • Preserve main's authenticated Evidence-file input and file-relative errors. Preserve the author's concurrent main merge and integrate current main. Documents remain limited to non-parameterized non-entity paths written by POST/PUT/PATCH; item-shaped and delete-only paths stay recorded. Public tool text and regression coverage state this limit.

Validation

  • 39 relevant source files: 493 tests passed, 3 existing skips. Eight cases reproduced before their fixes.
  • Broader CLI/MCP/environment/schema/qlog boundaries: 65 passed, 1 existing skip; both final state CLI/MCP cases rerun successfully. Default/compact schemas validate within the provider input budget.
  • Final serial static/build/artifact gate: 11 tasks passed. Final docs/catalog/format checks: 9 tasks passed; architecture guards and 5 README consistency tests passed.
  • Real Gitea 28.2.0: the same 3-exchange capture produces one erroneous post-create entity before the fix and none afterward; an 11-exchange CRUD capture preserves two initial issues and one document, with 6 exact HTTP replays. Fresh actual Chromium capture produces one entity and list/item plans. File CLI/default stdio MCP agree for both parent kinds.
  • Measured grouping and 15,001-field item projection improved with equal output digests; the 2,000-collection whole projection had overlapping warm timings. Peak memory did not decrease in the benchmark. One CPU/worker; maximum static/build process-family RSS about 4.6 GiB; no workspace OOM. Model token usage unmeasured.

Detailed results and scope: verification.md. The author's earlier 44-capture experiments are historical evidence, not rerun claims. No new macOS/Windows, model-task scoring, state serving or AgentEnv data-plane verification is claimed. A type first read only after a write under another root can still lack the earlier observation needed to detect the write's effect.

Author readiness

Human owner: @earakely-scale

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

🤖 Generated with Claude Code

earakely-scale and others added 2 commits October 19, 2026 17:29
Add the environment-state analysis view. From the parents the environment
manifest accepts, it extracts the data the capture's reads observed before
the first related write: entity types with an identity field (proved by a
path parameter or inferred from an identity name), entities with their
recorded values and provenance, documents for written non-entity paths, and
a render plan per read tool that is kept only when it reproduces the tool's
latest initial recordings from the state; every other read tool is a
recorded view with the reason. The Evidence is always inferred.

Response-body decoding moves to a domain owner shared with replay, exact
JSON parsing moves to the owner of the exact-number policy, the manifest and
state views share parent admission and record grouping, and
projectAnalysisView takes its accumulators as one object.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the IL2CPP metadata view's edits to the shared refusal message and
the inspect_analysis_view description alongside the environment-state view.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@earakely-scale
earakely-scale marked this pull request as ready for review October 20, 2026 00:33
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-20T00:33:51.800783Z 7a668b7 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with a non-blocking performance improvement recommended for repeated write-root scans.

Findings

  1. P2 Write roots get rebuilt repeatedly ▶
Fix with agent prompt
### Issue 1
src/domain/analysisView/EnvironmentStateExtraction.ts:189-193
`#initLimit` scans every write and rebuilds its root for each read tool, then repeats the scan when building each output type. With 2,000 collection tools and 2,000 writes under an unrelated root, this performs roughly eight million root calculations. Small responses and repeated writes can fit the byte budget, so users still pay this avoidable CPU cost.

Precompute write roots, index the first write affecting each root, and reuse each type's cutoff.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds the read-only environment-state view for retained HAR and browser-scenario Evidence.

  • Captured reads now produce a checked initial state and read plan.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[HAR or browser-scenario Evidence] --> B[Authenticate and admit]
  B --> C[Shared manifest grouping]
  C --> D[Bound reads by recorded writes]
  D --> E[Observe and merge values]
  E --> F[Check read plans]
  F --> G[Entities and documents]
  F --> H[State-backed or recorded views]
Loading

Reviews (8) · Last reviewed commit: "fix(environment): retain field provenanc..." · Reviewed by Greptile

earakely-scale and others added 2 commits October 19, 2026 17:46
… from items

A scenario write whose URL was redacted has no request line, so it was
dropped and reads after it counted as initial state. Such a successful
write now joins the timeline with an empty path, whose root relates to
every type, so it ends every type's state; a limitation counts them.

A list whose recordings were all empty passed the "every listed item
carries it" check vacuously and published an identity field nothing
showed; it now needs at least one item, else the view stays recorded
as no-identity.

A value that differed between two request lines of one item tool, such
as a query variant, was called volatile, and the gate then substituted
each recording's own value; only repeats of one request line now show
volatility, so differing lines go through fields-differ.

List membership is compared only while a list can still be the whole
collection, and merged entities are indexed by type and collection once,
so paged captures no longer cost pages times entities (8,000 pages of
40,000 entities: 5.7 s to 0.23 s).

Docs and the tool contract say scenario state keeps the capture's
redaction markers and how redacted writes bound it.

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

Entities took the order of the first plan observed, and item plans run
before list plans, so a complete list read before its detail reads came
out reordered and lost "all" membership; each entity now keeps its
earliest recorded sighting.

A list plan reused the first recording's pointer for later recordings,
so a later response that was itself an entity wrapping a list was read
as that list; every recording must now locate the same list.

The field union scanned its ordered list for every key, quadratic in an
object's width; a set now answers membership.

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

@kaoru0822-kitauji kaoru0822-kitauji left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this is a careful increment. The ownership refactors are clean: recordedResponseBody.ts and parseExactJson replace the replay-local copies without behavior changes, and the gate design leaves anything it cannot reproduce as a recorded view. I read the extraction, gate, merge, accumulator and view code. Two inference gaps turn up where the view's published claims go further than its evidence, and I'd like those fixed before merge.

Requested changes

  1. A write under another root shows up as initial state, labelled volatile (inline on EnvironmentStateExtraction.ts). With GET /api/search → POST /api/dashboards/db → GET /api/search, the result reports /api/search with init_before_ordinal: null, volatile_fields: ["title"], and the entity's title is the post-write value. Grafana's /api/search lists folders and dashboards, so the PR's own example application has this pattern. The spec does say cross-type effects are not tied to the state, but this result does more than leave them out: it presents a post-write value as the initial state. Suggestion: infer volatility only when no successful write of any root lies between the two observations. When one does, either bound the type at that write or keep the earlier value, so init_before_ordinal stays accurate.
  2. membership: "all" while the envelope reports a larger total (inline on environmentStateGate.ts). GET /api/items → {"total":50,"items":[{id:1},{id:2}]} gives membership: "all" and counters: []. The contract says all means "every entity of the collection", and the response itself says otherwise. listFacts already scans for total|count members. A member like that whose value differs from the item count should make the membership recorded.

Before merge (process)

  • The open Greptile P1 thread (item-shaped written documents and DELETE targets) has a reply that leaves it "for the author". The reply comes from the author account, so @earakely-scale, please make that call. The fallback is fail-closed (the tools stay recorded, which I confirmed: no-identity / not-entity), so scoping it out is fine by me. If you do, add it to Not included and the docs, then resolve the thread.
  • Scope: the PR says the scope decision was requested in #4933, but I can't find a request there for this increment. The last request covers items 1–4, all now merged. The Material scope… resolved box is ticked. This is a read-only analysis view, so I don't think the mandatory pre-implementation decision applies. Still, the deferred data/reset / data/add / write-effects direction is a product choice (one #4933 comment argued for stateless v1). @morluto / @gensokyo-dev, can you confirm the state direction is wanted? Otherwise please change the wording or the checkbox.

Nits

  • environmentStateMerge.ts:23-24: a stale doc comment was left above the new one on order.
  • Each body is parsed up to about 4 times (plan, observe, gate, documents). This is fine at the measured sizes. A polled list of 1,500 × 50 items took about 260 ms locally.

What I ran (head 2999128b; Node 26.5.0 locally, not the pinned 24.18.0): npm run test:local on environmentStateView, AnalysisViewService, scenarioCaptureRecords and environmentScenario: 66 passed. I also ran throwaway probe tests for the cases above (not committed). CI is all green and the PR is mergeable/CLEAN. I did not run the compiled CLI/MCP boundaries or any real captures.

Verdict: close. Once 1 and 2 are fixed and the thread and scope items are settled, it looks mergeable to me.

… initial state

A value that changed between repeats of one request line was named
volatile whenever no write under the type's own root lay between, so a
write under another root (for example POST /api/dashboards/db before a
second GET /api/search) left its effect in the initial state. Any
recorded write between the two observations now leaves every tool of the
type recorded with reason fields-differ instead.

A list was published with membership "all" even when a total or count
envelope member exceeded the number it listed. Such a counter now makes
the membership "recorded".

Also drop a stale doc comment on ObservedEntity.order.

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

Copy link
Copy Markdown
Collaborator

I pushed a5c7b92 to this branch with maintainer edits. It fixes the two issues from my review:

  • Volatility across writes. A value that changed across any recorded write between two observations is no longer called volatile. Every tool of that type now stays recorded with reason fields-differ. This keeps post-write values out of the initial state, for example /api/search after POST /api/dashboards/db.
  • all membership. A list now has all membership only when no numeric total/count member differs from the number listed.
  • Removed the stale doc comment on ObservedEntity.order. Updated the docs and spec wording and the volatile_fields description, and added two domain tests.

Validation (local, Node 26.5.0): vitest over src/domain/analysisView, src/application/analysisView, src/application/environment and src/contracts: 449 passed, 3 skipped. tsc, oxlint, oxfmt and module boundaries are clean. I did not run check:fast or docs:check locally because they need a fresh npm ci, so CI covers those.

Remaining: a tool that read the type only once after such a write can't be detected, because it has no earlier read to compare. Ending the type's state at that write and planning it again is the fuller fix. I left that, and the open Greptile thread on written documents, for @earakely-scale to decide.

kaoru0822-kitauji and others added 4 commits October 20, 2026 02:12
… documents

State documents are held only for list-shaped paths a POST, PUT or PATCH
tool writes. Reads of item-shaped written paths and of paths that are only
deleted stay recorded views; the guide now says so and the spec defers them
to a later increment of morluto#4933.

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

The volatility check compared write start positions with the two reads,
so a write already in flight when the earlier read started was missed and
its effect was named volatile. A write now counts when its interval
overlaps the span from the earlier read's start to the later read's end.

The check also ran once per changed field and scanned every write. It now
runs once per pair of observations, answered by a binary search over the
writes in timeline order and the latest end among each prefix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the inspect_analysis_view description conflict with morluto#3634 by
keeping main's inventory wording and adding the environment-state
sentence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The inspect_analysis_view contract text conflicted: main's Godot PCK and
inventory wording and this branch's environment-state sentence touch
separate parts of it and are both kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
earakely-scale and others added 2 commits October 19, 2026 19:32
…tem totals

A value that changed across a write was caught only between repeats of
one tool's request line, so a list read before a write and an item read
after it put the post-write value into the initial state. Changes are
now classified per entity in timeline order after observation: across
any recorded write, a change between repeats of a line or between two
lines of the type rewrites the type (every tool recorded as
fields-differ); with no write between, a repeat's change is volatile.
The classification lives in environmentStateMerge.ts.

Any numeric member whose name contained "total" or "count" counted as
an item total, so total_pages, account_id or page_count made complete
lists partial. Item totals are now members whose name tokens include
total or count and none of page, pages or per; a string of digits counts
as a number; and a set has_more, next or next-page token member also
marks the list partial.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolved against both sides' intent: the shared templateRulesSchema
keeps main's description naming sibling-pair-variance; scenario
admission keeps main's derived-text reservation and this branch's
response-body requirement for the state view; the MCP test keeps the
state test and main's renamed file-source manifest test; the contract
text keeps both insertions. main's new scenario admission test passes
the view kind the state view added to admitScenarioCaptureParent.

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

@gensokyo-dev gensokyo-dev left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed with Codex assistance at 6ad63bc. The final scope is read-only projection of completed HAR/browser-scenario Evidence, with no state serving, write effects or new transport default. Membership and field provenance are checked before publishing initial data; sparse projections, key presence and compact item totals now fail closed when appropriate. Growing-array and wide-key quadratic work was removed at the producing owners. The author’s concurrent main integration is preserved and current main d72021b is included.

Executed validation: 493 relevant source tests; broader 65-test CLI/MCP/environment/schema/qlog boundary pass plus both final state CLI/MCP cases rerun; final static/build and docs/catalog gates; architecture guards and README consistency. Real Gitea HAR CRUD and cross-root-create captures, a fresh Chromium scenario capture, default stdio MCP parity, and six exact HTTP replays passed. Before/after normalized outputs match on equivalent synthetic performance tasks; full-workflow timing and memory limits are reported without claiming a general speedup. The remaining unrelated-root write/no-earlier-observation limit is documented.

@kaoru0822-kitauji
kaoru0822-kitauji merged commit 3fca2e0 into morluto:main Oct 20, 2026
42 of 44 checks passed
@github-actions github-actions Bot mentioned this pull request Oct 20, 2026
3 tasks done
kangyishuai pushed a commit to kangyishuai/rea that referenced this pull request Oct 20, 2026
…ansition-view

Main's environment-state view (morluto#5319) also reads capture_browser_scenario
parents. Grouping views still route first, and this branch's projector
serves summary and browser-scenario views. Its refusal now names all four
supported views. Main's two-view fallback stays unreachable, so the
generic unsupported-parent message is kept.

Resolve the remaining conflicts by keeping both sides. The MCP contract
docs place the environment-state paragraph right after the
environment-manifest paragraph it refers to, followed by this branch's
paragraph. The tool description is main's text plus this branch's
additions. environmentScenario.test.ts keeps this branch's
summary-succeeds check with the four-view message.

The shared scenario fixture now records content-event headers as captured
when header_values is selected. It records no header names, so the list is
empty. This satisfies the capture invariant that main's new header-values
fixture variant exercises.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
earakely-scale added a commit to earakely-scale/rea that referenced this pull request Oct 20, 2026
…t-state-serve

morluto#5319 is on main as one squashed commit with the same content as the
branch this work was stacked on, so the branch's side of each overlapping
hunk is kept; morluto#5349's analysis-view changes merge as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
earakely-scale added a commit to earakely-scale/rea that referenced this pull request Oct 20, 2026
…t-state-coverage

morluto#5319 is on main as one squashed commit with the same content as the
branch this work was stacked on, so the branch's side of each overlapping
hunk is kept; morluto#5349's analysis-view changes merge as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
gensokyo-dev added a commit that referenced this pull request Oct 20, 2026
Index parsed recorded-write roots once per state projection and reuse positive and negative type cutoffs. Preserve wildcard, ancestor/descendant, canonical timeline and Evidence semantics under the existing representation budget.

Follow-up to the final performance thread on #5319, which was merged while this optimization was being validated.

Validated with 508 relevant source tests, compiled state CLI/MCP cases, real Gitea HAR CRUD/search captures and Chromium captures, static/build/docs/catalog gates, and equivalent completed before/after projections.
Deepakdogra07 pushed a commit to Deepakdogra07/rea that referenced this pull request Nov 19, 2026
Index parsed recorded-write roots once per state projection and reuse positive and negative type cutoffs. Preserve wildcard, ancestor/descendant, canonical timeline and Evidence semantics under the existing representation budget.

Follow-up to the final performance thread on morluto#5319, which was merged while this optimization was being validated.

Validated with 508 relevant source tests, compiled state CLI/MCP cases, real Gitea HAR CRUD/search captures and Chromium captures, static/build/docs/catalog gates, and equivalent completed before/after projections.
@morluto morluto added area: runtime Process capture and runtime observation enhancement New feature or request labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants