Repository navigation
fix(core): persist ConfirmResult rules into session permission context - #3377
Conversation
When a ConfirmResult accepts a tool call together with rules, those rules were only registered with the in-memory PermissionEngine and never reached AgentState.permissionContext. With a state store configured, every call rebuilds the engine from the stored context, so an accepted rule was lost at the next call boundary: 'always allow for this session' did not outlive the call that granted it (issue agentscope-ai#3369). - PermissionContextState.withAddedRules: returns a copy with rules routed by behavior into the allow/deny/ask tables - AgentState.updatePermissionContext: replaces the persisted context - ReActAgent.applyConfirmResults: after registering accepted rules with the engine, merges them into the session state so saveStateToSession persists them; valid ConfirmResult rules (non-null) are merged - ReActAgentHitlTest: with InMemoryAgentStateStore configured, a confirmed rule is now present in the stored permission context and the next call with the same tool runs without re-asking Fixes agentscope-ai#3369
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Fixes #3369: rules accepted through a ConfirmResult are now routed into the persisted AgentState.permissionContext (via a new immutable PermissionContextState.withAddedRules) in addition to the live PermissionEngine, so "always allow for this session" survives the next call boundary when a state store is configured. The approach is correct, minimal, and reuses the existing save path and rule format — no wire-format change.
Verified locally on head dfafdd3d (Java 17 / Maven offline build): ReActAgentHitlTest → Tests run: 20, Failures: 0, Errors: 0, including the new cross-call confirmedRulesPersistAcrossCallsWithStateStore. license/cla is green.
Findings are non-blocking (2 warnings on the duplicated null-tolerant setter and un-deduplicated rule append, 2 informational). CLA signed, no conflicts (mergeable=MERGEABLE); the BLOCKED merge state is just the missing approving review plus required checks.
Automated review by github-manager-bot
…ccept path - PermissionContextStateTest: withAddedRules routes ALLOW/DENY/ASK by behavior, preserves mode/workingDirectories/declared rules, skips PASSTHROUGH and null entries, returns this for null/empty input and never mutates the original - AgentStateTest: updatePermissionContext null is a no-op, replacement is visible via getPermissionContext - ReActAgentHitlTest: ConfirmResult carrying deny/ask/passthrough rules and null entries persists the routed rules and skips nothing-accepted merges Modified-line and branch coverage for the issue agentscope-ai#3369 change now at 100% (JaCoCo: withAddedRules 16/16 lines 12/12 branches; updatePermissionContext 3/3 lines 2/2 branches; the applyConfirmResults rule-merge block fully covered — the one remaining uncovered line is the pre-existing null-toolCall guard, unreachable through the public API since ConfirmResult validates in its constructor).
|
Coverage follow-up: JaCoCo now reports 100% line and branch coverage on all modified code — |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the new commit f22cf826 (test-only). It closes most of the coverage gaps flagged on dfafdd3d: withAddedRules now has a direct unit test (behavior routing, PASSTHROUGH/null skipped, mode + workingDirectories + pre-existing rules preserved, original not mutated, null/empty returns the same instance), the DENY/ASK persist paths are covered, and the end-to-end test reads assertions back from the state store and proves a remembered rule survives the engine-rebuild boundary — i.e. it tests persistence, not just in-memory fields. No flaky-risk patterns found (scripted model, disjoint per-agent store keys, no sleeps/time/random/shared mutable fixtures).
Three non-blocking follow-ups remain: one negative test is tautological as written, the AgentState javadoc/behaviour mismatch is now pinned by a test instead of fixed, and duplicate re-confirm (rule growth) is still untested.
Carried over from the previous review (still open, production code unchanged)
AgentState.java:220—updatePermissionContextduplicatessetPermissionContextand toleratesnullwhile the javadoc says "must not be null". The newAgentStateTestnow asserts the silent no-op, so the two public mutators keep divergent contracts; please align the javadoc (or collapse the methods) rather than freezing the mismatch.ReActAgent.java:2156— accepted rules are appended without dedup, so repeatedConfirmResults for the same tool growallow_rulesmonotonically in persisted state. A duplicate re-confirm assertion would close both this and the coverage hole.PermissionContextState.java:152— the threeforEachcopy blocks still re-implement the privatecopyIntohelper.
CLA license/cla is green and the 5 checks on the current head are passing; mergeable=MERGEABLE, the BLOCKED merge state is just the missing approving review plus required checks. No blocking issues — the three items above are non-blocking polish.
Automated review by github-manager-bot
- PermissionContextState.withAddedRules: reuse the existing copyInto helper instead of re-implementing the three forEach copies - AgentState: collapse updatePermissionContext into the existing setPermissionContext (null now rejected consistently with its javadoc); AgentStateTest asserts the NPE instead of pinning the silent no-op - ReActAgentHitlTest: the nothing-accepted assertion now checks the ask table is empty directly (previous noneMatch was tautological), and a stale re-confirm of an already-ALLOWED call is covered — the framework rejects it, no reply is produced and the persisted rule table does not grow
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Third bot pass — incremental re-review of the new commit 6913bf71 ("address round-7 review polish") on top of the previously reviewed f22cf826. Head is now 6913bf71; all checks green (build ubuntu/windows, license, module sync, codecov/patch) and license/cla is signed.
Both production-side items from the previous round are fixed, and the fix is the right shape rather than a patch-around:
AgentState.updatePermissionContextis gone — the duplicated mutator with the silent-null no-op that contradicted its own javadoc collapsed into the existingsetPermissionContext, whoserequireNonNullnow matches the documented contract. The call site inReActAgent.applyConfirmResultsis the only runtime consumer and cannot pass null (getPermissionContext()is non-null by the builder/constructor invariant,withAddedRulesnever returns null), so tightening it to throw is safe. Thepermission_contextJSON shape is untouched — Jackson round-trips through the@JsonCreator/builder path, not through the mutator.withAddedRulesnow delegates tocopyIntoinstead of re-implementing the threeforEachcopies, matchingfromJsonandwithMode; the helper additionally tolerates null per-tool lists, which the inline copies did not.
Three things hold this at COMMENT instead of APPROVE:
- The two assertions the commit adds for the stale re-confirm case do not test what their comments say they test. Because the remembered ALLOW rule suppresses the follow-up ask,
pendingIdsis empty on both re-confirm calls, so they take the normal-message branch (ReActAgent.java:1878-1881) andConfirmResultmetadata is never read —withAddedRulesis not invoked at all. TheassertEquals(1, …)therefore pins nothing about rule growth, and thenullreply comes from the scripted model running out of responses, not from the framework rejecting the stale confirm. Both pass today; both would keep passing if de-dup landed or if the ReAct loop's model-call count changed. - The un-deduplicated rule append is still open.
Builder.appendRuleis a plainlist.add, so a rule accepted repeatedly across pauses is appended repeatedly into persisted state. It is reachable through the ASK-rule path (an ASK rule does not suppress the ask, so the same suggested rule gets accepted again and again), which is exactly the loop a long-running session drives. - A leftover
sentinellocal is now dead code.
None of these are blockers on the production behaviour itself, which looks correct for issue #3369: the persisted rule genuinely survives the engine-rebuild boundary, and the cross-instance case added here (a second ReActAgent over the same store, no re-confirm) is the strongest evidence in the PR that the fix works for the right reason rather than through in-memory state. The tautological "nothing accepted" assertion is also properly fixed — it now checks the persisted ask table directly.
Findings
- [Warning]
ReActAgentHitlTest.java:1085— stale re-confirm is ignored, not rejected:pendingIdsis empty sovalidateAndAcceptConfirmResultsis never reached; thenullreply is script exhaustion via thetextResponse("")fallback, coupled to the exact model-call count. - [Warning]
ReActAgentHitlTest.java:1094—assertEquals(1, …)is causally vacuous: the append path (withAddedRules) never runs in these calls, so the assertion cannot fail whether or not rules de-duplicate. - [Warning]
PermissionContextState.java:166— repeated acceptance of an identical rule still appends duplicates into persistedpermission_context(unbounded growth on the ASK-rule re-pause path); still untested. - [Info]
ReActAgentHitlTest.java:1044—sentinelis now dead after the assertion was rewritten. - [Info]
ReActAgentHitlTest.java:1069— the replacementisEmpty()assertion is correct and does exercise theaccepted.isEmpty()guard.
Suggestions
For the re-confirm case, make it actually reach the permission path — e.g. confirm with a rule that cannot suppress the next ask (an ASK-behaviour rule on a tool that keeps pausing), then assert the persisted table for that tool. That converts the pair of always-green assertions into one that distinguishes "append" from "de-duplicate", and lets you pin whichever semantics you intend:
// two genuinely accepted confirms carrying the identical rule
int before = saved.getPermissionContext().getAskRules().get("write").size();
// … confirm the next pause with the same suggested rule …
assertEquals(1, after.getAskRules().get("write").size(), "re-accepting a rule must not duplicate it");If de-dup is deliberately out of scope for this PR, then drop the two new assertions and their comments instead of keeping them: a green assertion whose stated mechanism is wrong is worse than no assertion, because the next reader will believe re-confirm growth is already pinned.
Carried-over status: AgentState duplicated mutator — resolved. withAddedRules inline copies — resolved. Rule de-dup — open. Test tautology — resolved.
Automated review by github-manager-bot — round 3 of this sweep series, incremental on 6913bf71.
Address round-8 review: re-accepting an identical rule grew the persisted permission tables without bound. checkPermission evaluates deny -> ask -> tool self-check -> allow, so a configured ASK rule wins over an accepted ALLOW rule every cycle — each re-accept appended another duplicate to permission_context JSON (and to the engine's in-memory tables). - PermissionContextState.withAddedRules: merge accepted rules into mutable copies of the current tables, skipping rules already present (PermissionRule is a record — equals compares toolName/ruleContent/behavior/source) - PermissionEngine.addRule: same containment check via addUnique, so the in-memory engine tables cannot grow either - tests: withAddedRules dedups identical rules and preserves mode/ workingDirectories/declared rules; PermissionEngine.addRule ignores exact duplicates; HITL flow asserts a stale re-confirm of an already-ALLOWED call produces no reply and does not grow the persisted table
|
All three round-8 items addressed in 11e902b:
The vacuous stale-re-confirm assertions from the previous block were removed — as you noted, both re-confirms arrive with |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Fourth bot pass — incremental re-review of the new commit 11e902ba on top of the previously reviewed 6913bf71. All three items from the last round are addressed, and the fix is in the right place: withAddedRules merges through mutableCopy/mergeRule and PermissionEngine.addRule goes through addUnique, while the Builder is deliberately left appending (so fromJson still round-trips whatever was persisted and rulesAccumulateUnderSameToolName still holds). De-duplication cannot change any decision — checkAllowRules/checkDenyRules/checkAskRules all short-circuit on the first match — and key/bucket ordering is byte-identical to the old path because mutableCopy uses the same LinkedHashMap the Builder does. Both new tests genuinely fail without the fix. CI is green (build ubuntu/windows, license, module sync, codecov/patch) and license/cla is signed.
Holding at COMMENT for two cleanups; neither blocks the production behaviour.
Findings
- [Warning]
ReActAgentHitlTest.java:1069-1080— the assertions were deleted but the call they justified survives, and the comment above it now states the opposite of what this commit ships ("current semantics append … flagged for dedup"). - [Warning]
PermissionContextState.java:180— the de-dup key is whole-record equality, which is narrower than the growth bound the comment claims:nullvs""ruleContentare equivalent at evaluation time but unequal as records, andsourcealso participates. - [Info]
PermissionEngine.java:115—addUniqueandPermissionContextState.mergeRuleare the same six lines and must stay in lockstep; worth one shared helper.
Also worth stating explicitly rather than leaving implicit: sessions persisted before this fix never shrink. fromJson → Builder.appendRule does not de-duplicate, so duplicates already written to a state store are reloaded as-is and preserved by every later withAddedRules. That is a defensible no-migration choice, but if #3369's growth issue is being closed, the boundary should be in the PR description.
Suggestions
The one thing I would fix before merge is the leftover in ReActAgentHitlTest — either drop lines 1069-1080 together, or keep the re-confirm call and correct the comment. Re-adding a size assertion there would not work: the re-confirm targets an already-resolved block and never reaches the rule-persist path, which is exactly why the previous assertions were vacuous. Real integration coverage needs a fresh PERMISSION_ASKING pause confirmed twice with the identical rule across two calls; if that is out of scope here, say so in the PR body so the next reader does not believe the confirm path is pinned.
If semantic de-duplication is the intent, normalize the key (toolName + behavior + ruleContent == null || isEmpty() ? null : ruleContent) and add one test for the null vs "" case; if exact de-duplication is the intent, narrow the comment on lines 151-152 to "byte-identical rule". Either is fine — the gap is that the comment currently promises the wider guarantee while the code implements the narrower one.
Carried-over status: rule de-dup — resolved (exact-match). Test tautology — resolved (removed). Dead sentinel local — resolved. Semantic de-dup key + stale test comment — open, non-blocking.
Automated review by github-manager-bot — round 4 of this sweep series, incremental on 11e902ba.
Unify the two dedup paths (withAddedRules' merge and addRule's addUnique) into one package-private PermissionContextState.addIfAbsent, so both entry points share the same equivalence rule: a null ruleContent and an empty one are identical (ruleMatches evaluates both as unconditional), which record-equality alone missed. PermissionEngine.addRule now delegates to addIfAbsent and its private addUnique duplicate is removed. The HitlTest stale re-confirm call — whose comment described the pre-dedup append behavior — is dropped; equivalence and comparison coverage is pinned by three new PermissionContextStateTest cases (null/'' equivalence, source-differs append, and the synthetic-table unit test covering every sameRule short-circuit arm). Touched methods are at 100% line and branch coverage per JaCoCo.
|
Round-9 polish pushed (8574eed): the two dedup paths now share one implementation — |
Adds confirmedIdenticalRuleTwiceKeepsSinglePersistedEntry: a scoped ALLOW rule (query=foo) is confirmed, a differently-parameterized ask (query=bar) pauses again because the scoped rule does not match, and the identical rule is confirmed a second time — asserting the persisted permission context still holds exactly one entry. QueryScopedTool overrides matchRule to make the conditional rule meaningful, so the second pause is reachable (an unconditional null rule would suppress it); AskingTool loses its final modifier to allow the subclass.
|
Integration pin added per the round-4 finding (b76d9f7): |
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Fifth bot pass — delta re-review of 8574eed4 on top of the previously-reviewed 11e902ba. The consolidation is correct: both call sites now share one PermissionContextState.addIfAbsent, and the null↔"" normalization is provably safe — ruleMatches treats both as unconditional and every check*Rules loop short-circuits on the first match, so de-duplication cannot change a decision. Key/source() null-safety holds because PermissionRule's compact constructor already rejects null toolName/behavior/source, so replacing bucket.contains(rule) with sameRule does not narrow it. PASSTHROUGH skipping, LinkedHashMap/ArrayList ordering stability and the removed addUnique duplication are all as intended. LGTM.
Findings
- [Info]
PermissionEngine.java:102— engine-site coverage for the normalized equivalence only exists transitively; the exact-duplicate case is pinned inPermissionEngineTest, which this commit does not touch (inline).
Prior findings status
PermissionContextState.java:180(de-dup key narrower than the comment promised) — resolved: key normalized onruleContent, comment updated to match.ReActAgentHitlTest.java:1069-1080(deleted assertions, surviving call + contradictory comment) — resolved: the re-confirm call and the stale comment are gone together, and the remaining assertions still cover confirm→persist across instances. No coverage lost.PermissionEngine.java:115(addUniqueduplicatedmergeRule) — resolved: single shared helper.- Carried-over observation, unchanged by this commit: sessions persisted before this fix never shrink —
fromJson→Builder.appendRulestill does not de-duplicate, so duplicates already written to a state store reload as-is. Defensible as a no-migration choice; worth one sentence in the PR body if #3369 is being closed by this.
CI: mergeStateStatus=BLOCKED with checks not yet complete at this SHA; license/cla signed. Merging stays with the maintainers.
Automated review by github-manager-bot — round 5 of this sweep series, incremental on 8574eed4.
|
Post-approval addendum — The review above was authored against
Approval stands. The one open item is still the engine-site Automated review by github-manager-bot — addendum to round 5. |
The shared addIfAbsent normalization is pinned at the PermissionContextState level; this adds the engine-site counterpart so a regression that re-splits the two dedup call sites cannot pass CI. The new case fails under a record-equality dedup (null and empty ruleContent are distinct records) while addRuleIgnoresExactDuplicates still passes.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the single commit since my approval on b76d9f7f: f1faf083 adds PermissionEngineTest.addRuleTreatsNullAndEmptyContentAsEquivalent, pinning the null/empty ruleContent equivalence at the addRule call site. Delta is test-only (+22/-0, one file) and matches the dedup semantics already approved — no production code touched.
Findings
- [Info]
agentscope-core/src/test/java/io/agentscope/core/permission/PermissionEngineTest.java:400— the assertion duplicates the surrounding style (org.junit.jupiter.api.Assertions.assertEqualsfully qualified) rather than the file's staticassertEqualsimport; consistent with the neighbouring test in this PR, so fine to leave as is. No behavioural concern: the test exercises exactly thenormalizedContentpath inPermissionContextState.addIfAbsent, and the ASK rule seeded in the context confirms dedup is per-behaviour-table, not cross-table.
Verdict
APPROVED. CLA signed (license/cla pass). Note: build (ubuntu-latest) / build (windows-latest) were still pending on f1faf083 when this review was submitted — the two Check License / Check Module Sync gates passed. Merge remains a maintainer action.
Automated review by github-manager-bot
juruoO-o
left a comment
There was a problem hiding this comment.
Reviewed head f1faf08 against latest main: accepted ConfirmResult rules are persisted via withAddedRules, dedup shared between PermissionEngine and PermissionContextState with null/empty ruleContent normalization; AgentState.permissionContext is non-null by default and PermissionRule enforces non-null toolName/behavior/source, so no NPE path. Prior review warnings (dedup growth, vacuous tests, null/'' equivalence) addressed by 8574eed / b76d9f7 / f1faf08. CI green.
{"body": "## Description\n\nFixes #3369.\n\nWhen a
ConfirmResultaccepts a tool call together with rules to remember, those rules were only registered with the in-memoryPermissionEngine(ReActAgent.applyConfirmResults) and never reachedAgentState.permissionContext. With anAgentStateStoreconfigured, every call reloads the state from the store and rebuilds the engine frompermissionContext, so an accepted rule was lost at the next call boundary: "always allow for this session" did not outlive the call that granted it.\n\n### Fix\n\n-PermissionContextState.withAddedRules(...): returns a copy with the given rules routed by behavior into the allow/deny/ask tables (PASSTHROUGH and null entries ignored; the instance is never mutated)\n-AgentState.updatePermissionContext(...): replaces the persisted context\n-ReActAgent.applyConfirmResults: after registering accepted rules with the engine, merges them intostate.permissionContextso the existingsaveStateToSessionpersists them \u2014 no change to the save path or rule format (they land in the existing rule tables ofpermission_context)\n\nThe design question raised in the issue \u2014 whether runtime-accepted rules should be persisted \u2014 comes down on the side the issue's own "Expected" section describes: a remembered rule applies on the next call. The permission context is already the persistence structure for rules; this change makes runtime acceptance feed it.\n\n\n### Persistence boundary\n\nSessions persisted before this fix never shrink:fromJson\u2192Builder.appendRuledoes not de-duplicate, so duplicates already written to a state store are reloaded as-is and preserved by every laterwithAddedRules. That is a deliberate no-migration choice \u2014 existing stores are left untouched; only new accepts are subject to the dedup.\n## Testing\n\n- newReActAgentHitlTest.confirmedRulesPersistAcrossCallsWithStateStore: withInMemoryAgentStateStoreconfigured \u2014 call 1 pauses withPERMISSION_ASKING; call 2 confirms with an ALLOW rule; the rule is asserted present in the persisted state's permission context; call 3 with the same tool runs without re-asking\n-ReActAgentHitlTest: 20 passed\n"}