Skip to content

fix(permission): make declared rules authoritative on every call - #3361

Merged
jujn merged 9 commits into
agentscope-ai:mainfrom
kyy-logs:fix/permission-rules-authoritative
Nov 4, 2026
Merged

jujn merged 9 commits into
agentscope-ai:mainfrom
kyy-logs:fix/permission-rules-authoritative

Conversation

@kyy-logs

@kyy-logs kyy-logs commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #3291.

A non-null permissionContext now replaces the slot's persisted PermissionContextState the first time this agent activates that slot. Passing null leaves an existing slot untouched.

  • Rebuilding an agent with a tightened context reaches existing sessions on the next call.
  • Within the same agent instance, runtime changes made by replacePermissionContext / setPermissionMode are not overwritten on later calls.
  • No storage schema changes; the replacement is written into the existing AgentState.permissionContext and saved through the normal state-store path.

Preserving runtime state across a rebuild

If you reuse the same state store and want to keep runtime permission state, read the old context first and build the new one from it:

PermissionContextState old =
        agent.getAgentState(userId, sessionId).getPermissionContext();
PermissionContextState next =
        PermissionContextState.builder()
                .mode(old.getMode())
                // carry over working directories and rules you want to keep
                .build();

A non-null PermissionContextState.builder().build() is a valid trivial context, not a no-op: it replaces the old context with the default mode and no rules. Use null when you want to leave the existing context unchanged.

Changed files

  • agentscope-core/.../ReActAgent.java
    • Replace persisted permission context on first slot activation.
    • Remove permissionRulesAuthoritative field, builder setter, and copy logic.
  • agentscope-core/.../ReActAgentPermissionRulesTest.java
    • Rewritten to cover replacement semantics.
  • agentscope-harness/.../HarnessAgent.java
    • Remove the forwarded permissionRulesAuthoritative setter.
  • agentscope-harness/.../HarnessAgentBuilderSupport.java
    • Stop capturing/copying the removed flag to subagents.
  • docs/v2/en/docs/building-blocks/permission-system.md
  • docs/v2/zh/docs/building-blocks/permission-system.md
  • docs/v2/en/docs/building-blocks/agent.md
  • docs/v2/zh/docs/building-blocks/agent.md

Compatibility

This is a behavior change for agents rebuilt with the same non-null permissionContext against a persistent store: existing sessions now pick up the new context instead of keeping the old persisted snapshot. Existing stores remain readable and no migration is needed.

Out of scope

  • ConfirmResult rules accepted at runtime are still written into the live engine only and are not persisted.
  • Parent DENY inheritance for subagents that also declare a static permissionContext is not reconciled with replacement semantics; it needs a separate protected-deny overlay.

Rules passed at init time are copied into a session's AgentState when its slot is first
created, and every later call rebuilds the PermissionEngine from that copy. With a
persistent store a rule changed in code therefore never reaches sessions that already
exist: a tool moved from ALLOW to ASK keeps running without the confirmation, and a new
DENY is not enforced.

`permissionRulesAuthoritative(true)` composes the engine from the declared rules on every
call instead. The declared rules apply for each tool they mention; the session keeps its
own rules only for the tools the declaration says nothing about, which is what stops a
stale persisted ALLOW from relaxing a newer ASK or DENY. The session's mode and working
directories are unchanged, so setPermissionMode still applies, and nothing about what is
persisted changes.

HarnessAgent forwards the option to its inner agent and to the sub-agents it builds.

Co-Authored-By: Claude Code <[email protected]>
@codecov

codecov Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@oss-maintainer oss-maintainer 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.

Summary

Thanks for a careful fix of a genuinely important defect — "a rule tightened in code never reaches a session that already exists" is a security-relevant stale-permission bug (#3291), and the composition approach (session keeps mode + working directories + rules only for undeclared tools, nothing new is persisted) is the right shape. The docs (en + zh) and the four-scenario test class are well above the usual bar for a first contribution.

Two things keep me from calling it complete. First, the composition is invisible to the gate, which still reads the persisted context — so for the very common case of a session written before rules existed, the engine is never engaged and the flag does nothing (inline, with a one-line fix and the missing test). Second, because the "is this tool declared?" check is per behaviour table rather than per tool, the option can tighten rules but cannot loosen or remove one: a stale persisted survives a code change that drops it, and is evaluated first, so it wins. Both are semantic gaps in the new option rather than regressions of old behaviour, so flagging as a review to discuss rather than a blocker.

Findings

  • [Warning] (~L706 / L3399) — consults the persisted context, not , so a session whose persisted context is trivial never reaches the engine and the new flag is a no-op there.
  • [Warning] (~L718) — per-table (not per-tool) replacement keeps a session for a tool the new build declares with only; documented as "applies on every call", so either the code or the doc needs to move.
  • [Info] (~L712) — the no- branch computes and discards it on cache hit; the flag therefore does not apply to in-memory agents, which is not stated.
  • [Info] — mode / working-directory passthrough and the rule-removal case are untested.

Suggestions

  • Gate on (the getter already exists) so the decision follows the context actually in force.
  • Make authoritativeness per tool (union of the three declared tables), or rename/document the option as "declared rules are additive and can only tighten".
  • If you go per tool, note in the docs that a runtime HITL-confirmed for a declared tool will be dropped on the next call once the session context is no longer merged for that tool — worth a sentence, since that is a visible behaviour change for HITL users.

Compatibility

Backward compatible by default (), the flag is forwarded through and both subagent factories, and nothing new is written to state stores — all verified in the diff. is on the per-call path but only composes small maps, so the cost is negligible next to the model round-trip.

CI / CLA: is signed and the checks were still queued at review time — please make sure (and ) is green before merge, since the change above would need a new test anyway.


Automated review by github-manager-bot

.value());
}
PermissionContextState engineContext =
enginePermissionContext(loaded.getPermissionContext());

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.

[Warning] The composed context does not reach the useEngine gate, so the exact scenario the flag targets still slips through.

evaluatePermissions(...) decides whether to engage the engine with boolean useEngine = !state.getPermissionContext().isTrivial(); — that is the session's persisted context, not the engineContext built here. A session persisted before the permission system existed (or by a build that declared no rules) has a trivial context, and freshState(...) only overwrites it when a slot is created, so it stays trivial forever. On such a session the new flag silently falls back to the pre-2.0 lightweight path: the declared DENY/ASK rule tables are never consulted, and evaluateOne passes state.getPermissionContext() (still the trivial one) into ToolBase.checkPermissions. The PR's own repro avoids this only because v1 wrote a non-trivial ALLOW into the session first.

Suggested fix — gate on the context the engine was actually built from (PermissionEngine.getContext() already exists):

boolean useEngine = !permissionEngine.getContext().isTrivial();

and please add a test for it: build/persist a session with no permissionContext, then rebuild with permissionContext(ASK rules) + permissionRulesAuthoritative(true) and assert PERMISSION_ASKING.

}
return new CallExecution(loaded, loadedEngine, slot, loadedVersion);
}

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.

[Warning] Replacement granularity is per behaviour table, not per tool, so loosening a rule still never reaches an existing session.

copyRulesForUndeclaredTools keeps a session table entry whenever declared does not mention the tool in that same table. If the session holds both DENY(deploy) (old build) and ALLOW(deploy), and the new build declares only ALLOW(deploy) — i.e. the maintainer removed the deny — then declared.getDenyRules() has no deploy key, the session's stale DENY is copied, and because PermissionEngine.checkPermission evaluates deny first (L1: deny → ask → tool self-check → allow), the tool stays permanently denied.

That contradicts this method's own javadoc ("a rule the builder now declares replaces the session's") and the docs' "the declared rules apply on every call": the option can tighten, but it cannot loosen or remove.

If "the builder is authoritative for a tool" is the intended unit, key the skip off the tool rather than the table:

Set<String> authoritative = declared.declaredTools(); // union of the three tables
sessionRules.forEach((tool, rules) -> {
    if (authoritative.contains(tool)) {
        return;
    }
    rules.forEach(rule -> adder.accept(tool, rule));
});

and add a "remove a DENY for a tool that is still declared with ALLOW" case to the test class — it documents whichever semantic you choose.

loadedEngine = new PermissionEngine(engineContext);
permissionEngineCache.put(slot, loadedEngine);
} else {
loadedEngine =

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.

[Info] In the no-stateStore branch the composition is computed and then thrown away on every call after the first.

permissionEngineCache.computeIfAbsent(slot, k -> new PermissionEngine(engineContext)) only uses engineContext on a cache miss, so for in-memory agents the flag has no effect after the first call per slot — while enginePermissionContext(...) still rebuilds three maps per call to feed a constructor that is never called. Either rebuild when the flag is on (put instead of computeIfAbsent), or state in the builder javadoc that the option only changes behaviour for persisted sessions. The new tests all use InMemoryAgentStateStore, which is the stateStore != null branch, so this path is currently untested.

* builder declares. A rule the session holds for a tool the builder says nothing about still
* applies — without this, "ignore the persisted context entirely" would look like a fix.
*/
@Test

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.

[Info] Two behaviours the docs promise are not asserted anywhere: the session's mode and its workingDirectories surviving composition. Please add a case that persists a session with e.g. PermissionMode.BYPASS (or an extra working directory), then calls an authoritative agent that declares DEFAULT with rules, and asserts the session's mode/directories still win — that is the guarantee most likely to regress when someone later "simplifies" enginePermissionContext to "just use the declared context".

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Summary (resend — code references were stripped from the review body above)

Apologies for the extra comment: backticked identifiers were eaten by my shell when the review was posted, so the summary above rendered with holes. The four inline comments are intact; this is the corrected summary.

Thanks for a careful fix of a genuinely important defect — "a rule tightened in code never reaches a session that already exists" is a security-relevant stale-permission bug (#3291), and the composition approach (session keeps mode + working directories, plus rules only for undeclared tools, nothing new persisted) is the right shape. The docs (en + zh) and the four-scenario test class are well above the usual bar for a first contribution.

Two things keep me from calling it complete:

  1. The composed context is invisible to the useEngine gate, which still reads the persisted context (evaluatePermissions, ~L3399) — so for the very common case of a session written before rules existed, the engine is never engaged and the flag does nothing.
  2. Because the "is this tool declared?" check is per behaviour table rather than per tool, the option can tighten rules but cannot loosen or remove one: a stale persisted DENY survives a code change that drops it, and PermissionEngine.checkPermission evaluates deny first, so it wins.

Both are semantic gaps in the new option rather than regressions of existing behaviour, so this is a review to discuss, not a blocker.

Findings

  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:706 and :3399 — boolean useEngine = !state.getPermissionContext().isTrivial() consults the persisted context, not engineContext, so a session whose persisted context is trivial never reaches the engine and the new flag is a no-op there. Fix: !permissionEngine.getContext().isTrivial().
  • [Warning] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:718 — per-table (not per-tool) replacement keeps a session DENY for a tool the new build declares with ALLOW only; the docs promise the declared rules "apply on every call", so either the code or the doc needs to move.
  • [Info] agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:712 — the stateStore == null branch computes engineContext and discards it on a cache hit, so the flag does not apply to in-memory agents; not stated anywhere.
  • [Info] ReActAgentPermissionRulesTest — the mode / workingDirectories passthrough and the rule-removal case are untested.

Suggestions

  • Gate on permissionEngine.getContext().isTrivial() (PermissionEngine.getContext() already exists) so the decision follows the context actually in force.
  • Make authoritativeness per tool (union of the three declared tables), or rename/document the option as "declared rules are additive and can only tighten".
  • If you go per tool, add a sentence to the docs: a runtime HITL-confirmed ALLOW for a declared tool will be dropped on the next call once the session context is no longer merged for that tool — a visible behaviour change for HITL users.

Compatibility

Backward compatible by default (permissionRulesAuthoritative = false), the flag is forwarded through HarnessAgent.Builder and both subagent factories in HarnessAgentBuilderSupport, and nothing new is written to state stores — all verified in the diff. enginePermissionContext sits on the per-call path but only composes small maps, so the cost is negligible next to the model round-trip.

CI / CLA: license/cla is success; the checks were still queued when this review was written, so please make sure Java CI with Maven and spotless are green before merge — the useEngine change above needs a new test anyway.


Automated review by github-manager-bot

…e review's cases

Review pointed out that the flag is a no-op on the sessions it most needs to reach: the gate
that decides whether to consult the engine at all read the session's persisted context, and a
session persisted with no rules is trivial, so it stayed on the lightweight path where no rule
is consulted.

`permissionEngine.getContext()` carries the context the engine was actually built from, so the
decision now follows the rules in force. The new test persists a session with no permission
context at all and asserts the declared ASK applies to it.

Also from the review:

- The no-store branch no longer composes a context it then discards; without a store the
  session's context is the declared one on every call, which the builder javadoc now says.
- Tests added for the session's mode surviving composition, and for a dropped DENY not
  surviving while the declaration still mentions the tool. The per-table concern raised in
  review is already handled: the skip is keyed on the union of the three declared tables,
  which is what the suggested declaredTools() would compute.

Co-Authored-By: Claude Code <[email protected]>
@kyy-logs

Copy link
Copy Markdown
Contributor Author

Both warnings are addressed in 2640181 — and thank you for the second one; it is the case my own repro could not see.

The gate (L706). Fixed: useEngine now reads permissionEngine.getContext(), the context the engine was actually built from. You were right about why the repro missed it — v1 writes a non-trivial ALLOW into the session, so the persisted context is never trivial there. declaredRulesReachASessionWhosePersistedContextIsTrivial persists a session with no permissionContext at all and asserts the declared ASK applies; it fails with expected: <PERMISSION_ASKING> but was: <MODEL_STOP> before the gate change and passes after.

The per-table concern (L718). I checked this against the code before changing anything, and I believe it is already per tool: copyRulesForUndeclaredTools skips a tool when declared mentions it in any of the three tables, which is the union your declaredTools() would compute. I added the case you described — the session holds DENY(deploy), the new build declares ALLOW(deploy) only — and it passes: the tool runs, because the stale DENY is dropped. If you have an arrangement in mind where the union is not enough, I would like to know what it is; I would rather fix the semantics than argue about them.

No-store branch (L712). Only the store branch composes now; without a store the cached engine is built from the session's context, which is the declared one on every call. The builder javadoc says the option only changes behaviour with a state store.

Mode and directories (test L246). sessionModeSurvivesComposition added: a session persisted under BYPASS, then an authoritative agent declaring DEFAULT with no rules. With no rule to match, the mode alone decides, so MODEL_STOP shows the session's mode survived. My first version of this used a declared ASK and failed — correctly, since ask rules are evaluated before the BYPASS fallback and would win either way, so it could not distinguish the two modes. Working directories go through the same path but are not asserted: I did not find an assertion for them that tests the composition rather than the engine.

codecov reported one line uncovered on the changed lines: the guard in
`enginePermissionContext` that hands back the session's own context when the builder declares no
permission context at all. That combination is legal — the option is simply a no-op — and without
the guard the composition dereferences null, so it is worth pinning rather than leaving to the
branch that happened to be untested.

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

@oss-maintainer oss-maintainer 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.

Summary

Thanks for the thorough follow-up on 2640181 / bf69013c — both of my previous findings are genuinely resolved, and the second one is exactly the case my own repro could not reach.

  • The gate (FINDING A) — resolved. useEngine now reads permissionEngine.getContext() (ReActAgent.java:3463-3467) rather than the persisted session context, and that engine is the per-call scope's engine built from the composed context in activateSlotForContext (:705-709) — the same object consulted at :3499. getContext() is non-null by construction (PermissionEngine.java:59-64), and the storeless branch (:710-716) is behaviour-preserving. declaredRulesReachASessionWhosePersistedContextIsTrivial is a real regression test: the pre-fix gate would leave the call on the lightweight path and end with MODEL_STOP instead of the asserted PERMISSION_ASKING.
  • Per-tool vs per-table keying (FINDING B) — resolved in code. copyRulesForUndeclaredTools (:753-766) returns early only when the tool appears in none of the three declared tables, so a newly declared ASK/DENY drops every stale session rule for that tool, and a declared ALLOW can now drop a stale DENY. I also checked what is not covered: dropping a tool from the declaration entirely still lets the persisted rule survive, which is the documented contract (:720-728, permission-system.md:237) — worth calling out in the PR body so users do not read permissionRulesAuthoritative(true) as "declarations win unconditionally".

No production defect found in the delta: thread safety is unchanged (one engine per call, put on a ConcurrentHashMap, guarded by callSerializationKey), and enginePermissionContext composes into a new immutable PermissionContextState and never writes back, so persisted-state compatibility is unaffected.

What remains is test quality. Two of the assertions added in this delta cannot fail without the behaviour they claim to pin, because a denied tool call continues the ReAct loop and a plain-text final message defaults to MODEL_STOP (:3055-3060, :3111, :4239-4250, Msg.java:641-657). Since removedDenyDoesNotSurviveWhenTheToolIsStillDeclared is the only evidence offered for the per-tool claim, a future revert to the per-table skip would pass CI silently. Inline comments describe both, with concrete alternatives.

Leaving this as a comment rather than changes-requested: the code is mergeable as-is, and these are coverage gaps rather than defects. But I would not merge until at least the per-tool test discriminates.

Assessment is static reading only — this environment has no JDK 17 or Maven, so nothing was compiled or executed. mvn -T1 -pl agentscope-core -am test -Dtest=ReActAgentPermissionRulesTest against the pre-fix gate would confirm the vacuity claims directly.


Automated review by github-manager-bot

.block();

assertNotNull(afterRemoval);
assertEquals(

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.

This test does not fail without the fix it is meant to pin (the per-tool vs per-table skip in copyRulesForUndeclaredTools, ReActAgent.java:753-766).

If the session's stale DENY survives (the old per-table behaviour), call 2 takes the DENY path: runToolBatch puts a DENIED ToolResultBlock into resultHolder (ReActAgent.java:3237-3242, :3257-3260), the result is not suspended, so the loop continues to the next iteration (ReActAgent.java:3046-3060, :3111) and the second scripted response — a plain text "done" — ends the turn (isFinished, ReActAgent.java:4239-4250). That assistant message carries no reason metadata, and Msg.getGenerateReason() defaults to MODEL_STOP (Msg.java:641-657), so assertEquals(MODEL_STOP, ...) holds for the fixed implementation (declared ALLOW wins, tool runs) and for the broken one (stale DENY wins, tool blocked) alike. It only rules out an explicitly set reason such as PERMISSION_ASKING.

The PR description cites this test as the evidence that "the skip is keyed per tool rather than per rule table", so a future revert to the per-table skip would pass CI silently.

Suggestion: assert something only the fixed behaviour can produce — give DeployTool a counter (AtomicInteger incremented in callAsync) and assert it increased during the second call, or load the session from store and assert its context holds a SUCCESS result for tc-d2 and no DENIED one. A reason-based assertion cannot distinguish "tool ran" from "tool was denied" on this path.

assertNotNull(bypassed);
assertEquals(GenerateReason.MODEL_STOP, bypassed.getGenerateReason());

// A later build declares DEFAULT with an ASK for the tool. If the declared mode replaced

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.

Garbled comment, and the assertion cannot pin the mode behaviour either.

The sentence lost its middle while editing: // If the declared mode replaced / // the / // BYPASS falls through to allow, DEFAULT falls through to ask. A declared ASK could not — it ends mid-clause, and it says "with an ASK for the tool" although the declared context below (:373-379) declares no rules at all.

As written the test cannot fail for the behaviour it claims to pin. If composition had taken the declared mode, the composed context would be DEFAULT + no rules + no working directories — exactly isTrivial() (PermissionContextState.java:107-113) — so ReActAgent.java:3467 would take the lightweight path, DeployTool returns PASSTHROUGH, the tool runs, and the call still ends with the default MODEL_STOP (Msg.java:641-657). (Omitting the declared ASK is presumably why the comment was cut short: an ASK rule is evaluated before the BYPASS fallback — PermissionEngine.java:150-153 precedes :188-196 — so it would ask even with the session's BYPASS preserved.)

To actually pin mode preservation, make the two modes observable instead of asserting on the reason: persist the session under DONT_ASK and declare DEFAULT with no rules, then assert the tool did not run (counter in DeployTool, or a DENIED tool result in the persisted session) — the session's DONT_ASK makes the default a DENY, while a declared-DEFAULT regression falls through to the trivial lightweight path and runs the tool. Please also restore the comment.

Review pointed out that two assertions could not fail without the behaviour they claim to
pin. It is right, and I confirmed it before changing anything: reverting the per-tool skip
to a per-table one left `removedDenyDoesNotSurviveWhenTheToolIsStillDeclared` green.

Neither broken path produces a distinct turn reason. A denied call leaves the ReAct loop
running and the turn still ends with the plain-text reply, and a declared `DEFAULT` with no
rules is exactly a trivial context, so a regression that took the declared mode drops onto
the lightweight path and runs the tool. Both finish at the default `MODEL_STOP`, which is
what both assertions were reading.

Both now assert on the tool instead. `DeployTool` counts its executions, so the DENY case
requires one call during the second turn, and the mode case holds the session under
`DONT_ASK` and requires none. Reverting the skip fails the first with
`expected: <1> but was: <0>`; taking the declared mode fails the second with
`expected: <0> but was: <1>`.

The mode test's comment is restored as well — an earlier edit had left it cut off
mid-sentence and still describing a declared ASK it no longer set.

Co-Authored-By: Claude Code <[email protected]>
@kyy-logs

Copy link
Copy Markdown
Contributor Author

You are right, and I checked it before touching anything: reverting the per-tool skip to a per-table one leaves removedDenyDoesNotSurviveWhenTheToolIsStillDeclared green. Both assertions were reading a reason that neither path can distinguish — a denied call keeps the loop running and the turn still ends with the plain-text reply, and a declared DEFAULT with no rules is exactly a trivial context, so a regression that took the declared mode falls to the lightweight path and runs the tool. Both land on the default MODEL_STOP.

Fixed in 66832a8 by asserting on the tool rather than on the turn: DeployTool counts its executions, so the DENY case requires one call during the second turn, and the mode case holds the session under DONT_ASK and requires none. Reverting the skip now fails the first with expected: <1> but was: <0>; taking the declared mode fails the second with expected: <0> but was: <1>.

The mode test's comment is restored — an earlier edit of mine had left it cut off mid-sentence and describing a declared ASK it no longer set. Thank you for catching that; a comment describing a different test than the one beneath it is worse than no comment at all.

On the point you asked to be called out: the PR body now says that a tool dropped from the declaration entirely keeps whatever the session holds for it, so permissionRulesAuthoritative(true) should not be read as "declarations win unconditionally".

@oss-maintainer oss-maintainer 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.

Summary

Re-review of 66832a8d. All three of my outstanding findings are resolved, and the two test-quality ones are fixed in exactly the way that makes them real. Approving.

  • FINDING A (the gate) — resolved, unchanged since bf69013c. useEngine reads permissionEngine.getContext() (ReActAgent.java:3467), so a session persisted with a trivial context still consults an authoritative engine. I re-read the branch this pass and it is still correct, including the stateStore == null path, which is now documented at :714-715 instead of silently computing a composition it discards — my earlier [Info] on that is answered.
  • FINDING B (per-tool keying) — resolved. copyRulesForUndeclaredTools (:753-766) skips a session tool only when the declaration mentions it in none of the three tables.
  • Vacuous per-tool assertion — resolved. removedDenyDoesNotSurviveWhenTheToolIsStillDeclared now asserts on DeployTool.callCount() == 1 instead of the turn reason. That is the observable difference I asked for: under the old per-table skip the stale DENY wins, the tool never runs, and the reason still read MODEL_STOP. Reverting copyRulesForUndeclaredTools to per-table now fails CI.
  • Mode assertion + garbled comment — resolved. sessionModeSurvivesComposition persists DONT_ASK, declares DEFAULT with no rules, and asserts callCount() == 0. I traced both directions: composition keeping the session mode yields a non-trivial context (isTrivial() requires mode == DEFAULT, PermissionContextState.java:107-113), the engine demotes the default ASK to DENY under DONT_ASK (PermissionEngine.java:198, :319), and the tool does not run; a regression taking the declared mode produces an exactly trivial context, drops to the lightweight path, and runs it. The assertion cuts both ways, and the comment now says what the code does.

The AtomicInteger on DeployTool is written from callAsync and read after .block(), so there is no visibility problem — and incrementing inside callAsync rather than checkPermissions is the right place, since it counts execution and not evaluation.

Two [Info] nits are inline, both optional: the per-tool test does not itself assert that call 1 left a DENY on the session (so its premise is assumed rather than established), and the two new agent(...) overloads duplicate the builder chain. Neither affects correctness or coverage today.

CI: CLA signed, Check License/Check Module Sync/validate/build (ubuntu-latest)/codecov/patch green, build (windows-latest) still in progress at review time. Merge state is BLOCKED — that is branch protection awaiting a maintainer, not a defect; merge authority stays with the maintainers.

Assessment is static reading only — no JDK 17 or Maven in this environment, so I did not compile or run ReActAgentPermissionRulesTest, and I could not execute the pre-fix revert myself to watch the two new assertions go red. The discrimination arguments above are traced through ReActAgent, PermissionEngine and PermissionContextState rather than observed.


Automated review by github-manager-bot

Comment on lines +352 to +355
agent(model("tc-d1"), rules(PermissionBehavior.DENY), store, true)
.call(List.of(userMsg("deploy?")), sessA)
.block();

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.

[Info] Nice — the count makes this discriminate. One thing still keeps it from being airtight: nothing asserts that call 1 actually wrote a stale DENY into the session.

The assertion now fails correctly if copyRulesForUndeclaredTools reverts to per-table keying (stale DENY wins → callCount() == 0), which is exactly what the previous version could not do. Thank you.

But if call 1 ever stopped persisting the DENY — e.g. a future change to freshState, or the authoritative composition starting to drop declared rules at slot-creation time — then call 2's ALLOW would apply against a session that has no DENY to drop, callCount() would still be 1, and the test would pass while pinning nothing. The name promises "a session that already holds it", and that premise is currently assumed rather than established.

Passing a counted tool to call 1 as well makes both halves explicit:

DeployTool denied = new DeployTool();
agent(model("tc-d1"), rules(PermissionBehavior.DENY), store, true, denied)
        .call(List.of(userMsg("deploy?")), sessA)
        .block();
assertEquals(0, denied.callCount(), "call 1 must leave a DENY on the session for call 2 to drop");

DeployTool tool = new DeployTool();
agent(model("tc-d2"), rules(PermissionBehavior.ALLOW), store, true, tool)
        .call(List.of(userMsg("deploy?")), sessA)
        .block();
assertEquals(1, tool.callCount(), "the declared ALLOW replaced the session's stale DENY");

Same shape as the sessionModeSurvivesComposition test below, which already counts on both calls. Non-blocking — happy either way.

Comment on lines +177 to +191
private static ReActAgent agent(
ChatModelBase model,
PermissionContextState rules,
AgentStateStore store,
boolean rulesAuthoritative) {
Toolkit toolkit = new Toolkit();
toolkit.registerAgentTool(new DeployTool());
return ReActAgent.builder()
.name("asst")
.model(model)
.toolkit(toolkit)
.permissionContext(rules)
.permissionRulesAuthoritative(rulesAuthoritative)
.stateStore(store)
.build();

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.

[Info] This overload and the new 5-arg one below (:194-209) differ only by which DeployTool gets registered — worth delegating.

The 4-arg body builds the Toolkit and the whole ReActAgent.builder() chain, and the 5-arg repeats all of it. A one-line delegation keeps them from drifting when someone adds a builder option:

private static ReActAgent agent(
        ChatModelBase model, PermissionContextState rules, AgentStateStore store,
        boolean rulesAuthoritative) {
    return agent(model, rules, store, rulesAuthoritative, new DeployTool());
}

Style only, not a defect — approving regardless.

…e builder chain

The review raised this as style, but the reason it gave is the one that matters: the two
overloads built the ReActAgent chain separately, so a builder option added to one would not
reach the other and the test fixtures would drift apart silently. The four-argument form now
delegates to the five-argument one, which is one line instead of ten.

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

@oss-maintainer oss-maintainer 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.

Summary

Re-reviewed the new head 90284324. The delta since my 66832a8d approval is test-only: the 4-arg agent(...) helper now delegates to the 5-arg overload instead of repeating the builder chain, so DeployTool construction is the single thing that differs between the two helpers and the assertions are unchanged. No production code moved, and the refactor removes a parallel copy of the builder wiring: the 4-arg helper now routes through the same 5-arg overload the other cases use, so there is one place where the toolkit/permissionContext/stateStore wiring is defined.

Behaviour and reasoning I already verified on 66832a8d still hold: enginePermissionContext replaces the session's rules only for tools the declaration mentions, keeps the session's mode and working directories, composes nothing when no store is configured, and the useEngine switch now reads the engine's own context so a session persisted with no rules still consults the declared ASK.

Verdict: APPROVED — CLA signed; license, module-sync, ubuntu + windows builds, validate and codecov all pass.

Notes (non-blocking)

  • The permissionRulesAuthoritative(false) path is a pure no-op by construction (enginePermissionContext returns the persisted context unchanged), which is why the default-behaviour test can pin the defect without the option in the picture. Worth keeping as the compatibility argument if anyone later asks for the composition to run unconditionally.
  • ReActAgent.java:2179 (rules accepted through a ConfirmResult are written to the live engine only) is correctly called out as out of scope: making those survive a call boundary means persisting them, which changes the stored shape. Fine to leave, but it is the natural follow-up to the issue this closes — if it is not already tracked, a separate issue would stop it from being lost.
  • Docs: the EN/ZH permission-system.md and agent.md pairs both changed, so the option is not documented in one language only.

Thanks for the unusually careful test design — asserting on the tool executing rather than on the turn's GenerateReason, because a denied call still ends the turn with a plain-text reply, is exactly the kind of distinction that makes these regression tests able to fail.


Automated review by github-manager-bot

kyy-logs and others added 3 commits October 9, 2026 10:13
Two things are folded here, both integration work.

The conflict, in ReActAgent.activateSlotForContext: main added `|| activeRecorder != null` to
the guard and introduced `resolvedState`; this branch composes the engine context instead of
passing the persisted one through. Both are kept — the condition decides when the engine is
rebuilt, the composition decides what it is built from. That is also the right reading for a
recorder, whose `initial().restore()` state is a session context the option is meant to reach.

The integration fix: main introduced `Builder.copy()`, which `build()` now goes through, and
it copies its fields one by one. This branch's `permissionRulesAuthoritative` was not in that
list, so the option silently reverted to `false` on every build — a clean textual merge that
is wrong at runtime. Eight of the permission tests caught it; three failed. The field is now
copied alongside `permissionContext`.

main's own `agentId` is missing from the same list, so `testAgentIdOverride` fails on main as
well. That is unrelated to this branch and is reported separately rather than fixed here.

Co-Authored-By: Claude Code <[email protected]>
@mintlify

mintlify Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 890a947.

Approve preview

@kyy-logs

Copy link
Copy Markdown
Contributor Author

@jujn thanks for syncing the branch with main.

Heads-up: the merge dropped import java.util.function.BiConsumer; from ReActAgent.java. db0b67e (#3712) removed the last upstream usages of BiConsumer and the import with them, but copyRulesForUndeclaredTools and copyRules on this branch still use the type, so both build jobs fail at ReActAgent.java:842,855 with cannot find symbol: class BiConsumer.

Git reported no conflict here (this branch never touched that import line), so it looks like a silent semantic conflict rather than a bad resolution.

Restored the import in c364745. Locally the module compiles and ReActAgentPermissionRulesTest passes 8/8; validate, Check License and Check Module Sync stayed green, so CI should come back clean.

@jujn
jujn force-pushed the fix/permission-rules-authoritative branch from c364745 to 890a947 Compare November 4, 2026 10:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Builder permission rules are snapshotted into persisted sessions; rule changes never reach existing sessions

3 participants