Skip to content

fix(harness):declared subagent hook inheritance - #4395

Open
coderzhn wants to merge 16 commits into
agentscope-ai:mainfrom
coderzhn:fix/declared-subagent-hook-inheritance
Open

coderzhn wants to merge 16 commits into
agentscope-ai:mainfrom
coderzhn:fix/declared-subagent-hook-inheritance

Conversation

@coderzhn

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT

Description

Fixes #1578 — declared subagents do not inherit the parent agent's hooks.

buildDeclaredFactory (used for both workspace subagents/*.md and programmatic
SubagentDeclaration subagents) captured and forwarded the parent's middlewares
but never its hooks. The sibling buildGeneralPurposeFactory already propagated
b.hooks, so the two paths were inconsistent: hooks registered on the parent for
tool governance, human-in-the-loop approval, audit, or budget were silently
dropped for declared subagents.

This change captures b.hooks in buildDeclaredFactory and applies them to the
child builder alongside the middlewares, mirroring buildGeneralPurposeFactory.

Changes

  • HarnessAgentBuilderSupport.buildDeclaredFactory: capture b.hooks and forward
    via sub.hooks(capturedHooks) before building the child.
  • ManagedSubagentBoundaryTest: add a regression test asserting a declared
    subagent inherits the parent's hooks.

How to test

  • Targeted: mvn -T1C -pl agentscope-harness -am test -Dtest=ManagedSubagentBoundaryTest
  • Full harness module: mvn -T1C -pl agentscope-harness -am test (1919 tests, 0 failures)

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test)
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (N/A — no public API/doc change)
  • Code is ready for review

coderzhn and others added 4 commits November 13, 2026 18:27
Declared subagents (workspace subagents/*.md and programmatic
SubagentDeclaration) are built through buildDeclaredFactory, which forwarded
the parent's middlewares but not its hooks. The general-purpose subagent
factory already propagates b.hooks, so the two paths were inconsistent: hooks
configured on the parent for tool governance, human-in-the-loop approval,
audit, or budget were silently dropped for declared subagents.

Capture b.hooks in buildDeclaredFactory and apply them to the child builder
alongside the middlewares, mirroring buildGeneralPurposeFactory.

Fixes agentscope-ai#1578
@coderzhn coderzhn changed the title Fix/declared subagent hook inheritance fix(harness):declared subagent hook inheritance Nov 25, 2026

@ningmao-hlyz ningmao-hlyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Inherited hooks re-enable the parent's denied tools in the declared child. Hook tools() are registered after the toolkit is narrowed, so they bypass both the declaration allowlist and the parent's ToolsConfig deny list. Probe on this branch: parent with deny=["execute"] and a hook whose tools() returns an execute tool, declaration allowing only read_file → child toolkit is [execute, read_file]. The same probe on the base commit gives [read_file], so the bypass is introduced here. That is the boundary childCannotReenableParentDeniedTool protects. #2996 filters hook-contributed tools against the declaration allowlist and the effective child workspace policy; the same filter, or skipping tools() for declared children, looks necessary.

[P2] The new test asserts only that the hook object is present in the child's list. One assertion on the tool boundary above would have caught this.

[P2] Hooks are shared by reference (List.copyOf copies the list, not the hooks). One line in the javadoc about reentrancy and agent-scoped state would spare readers the analysis #2996 spells out.

Hook.tools() contributions are installed while the agent is built, after
callers have assembled the toolkit, so there is no way to keep a specific
contribution out before registration.

Add ReActAgent.Builder.hookToolFilter(Predicate<String>). When set, hook
contributions are resolved into a throwaway toolkit first and only the
accepted names are registered on the agent toolkit. A rejected contribution
never registers, so it cannot displace an existing tool with the same name.

HookToolsRegistrationTest covers AgentTool and annotated @tool contributions,
rejected names, and same-name preservation.
Declared subagents inherit the parent's hooks, but their Hook.tools()
contributions were installed after ToolFilter.apply had narrowed the
toolkit, so an inherited hook could re-enable a tool the parent denied or
the declaration excluded.

Set a hook tool filter on declared children that requires both the
declaration allowlist and the effective child ToolsConfig. Add regression
coverage for the denied-tool probe, allowlist boundaries, a parent deny
without a declaration allowlist, a declared-but-denied tool, the no-policy
case, annotated @tool contributions, multiple hooks, and the unchanged
general-purpose path.
- Hook: document that automatically constructed subagents share the same
  instances, the resulting reentrancy and agent-scoped state requirements,
  and that tools() may be resolved more than once.
- harness subagent pages (EN/ZH): note hook inheritance and that
  hook-contributed tools remain bounded by the declaration allowlist and
  the child's effective ToolsConfig.
@mintlify

mintlify Bot commented Nov 29, 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 58f141a.

Approve preview

@coderzhn

Copy link
Copy Markdown
Contributor Author

@ningmao-hlyz

All three points were valid. Follow-up pushed as three commits: 644fbeb9 (core filter),
20498b2d (declared-child wiring + tests), ab91a218 (docs).

P1 — fixed: inherited hooks can no longer re-enable removed tools.

Confirmed the mechanism: ToolFilter.apply runs in HarnessAgent.buildInstance before
inner.build(), while registerToolsFromHooks runs inside inner.build(). Inherited
Hook.tools() contributions therefore landed after the allow/deny narrowing. Your probe
reproduces: parent deny=["execute"], hook contributes an execute tool, declaration allows
only read_file → child toolkit was [execute, read_file]; on the base commit it is
[read_file].

The fix adds ReActAgent.Builder.hookToolFilter(Predicate<String>). At construction time, hook
contributions are resolved into a throwaway toolkit and only names accepted by the predicate are
installed on the agent toolkit. A rejected contribution never registers, so it cannot displace an
existing same-name tool. For declared children, buildDeclaredFactory sets the predicate to:

  (declaration allowlist contains name)                                                                                                                                                                                              
      && ToolFilter.isAllowed(name, effective child ToolsConfig)                                                                                                                                                                     

The two conditions are ANDed, so being declared does not override a parent deny. This is the same
filter contract as #2996, scoped to the hook path and without its workspace/MCP behavior change.

P2 — test coverage.

ManagedSubagentBoundaryTest now has 12 cases: the denied-tool probe, allowlist inside/outside,
parent deny with and without a declaration allowlist, a declared-but-denied tool, the no-policy
case, annotated @Tool resolved names, per-hook filtering, the unchanged general-purpose path,
hook-instance inheritance, and the existing declaration/parent-deny boundaries.

HookToolsRegistrationTest has 5 cases covering the core filter: accepted/rejected names,
annotated names, rejected contributions not displacing an existing same-name tool, and the
default no-filter path.

@ningmao-hlyz ningmao-hlyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at a485a147. The declared path is fixed and both P2s are addressed: the pre-registration filter sits in the right place, and resolving contributions in a throwaway toolkit is the necessary shape — registering first and removing later would throw IllegalStateException on a same-name contribution instead of leaving the existing tool untouched.

Two things remain.

[P2] general-purpose still re-enables a parent-denied hook tool. Same probe as round 1, only the factory changes: parent deny=["hook_extra"] with a hook contributing hook_extra → the gp child toolkit still contains hook_extra; the declared child is now clean. The root cause is that inheritedHookToolAllowlist is a per-call-site opt-in and buildGeneralPurposeFactory never passes it (decl.getTools() is never null, so the null branch is exactly "not a declared child"). This is pre-existing — gp inherited hooks before this PR — but it is the same mechanism and the same code, and #1578 uses gp as the reference behaviour. Please close it here rather than in a follow-up.

[Suggestion] the allowlist condition in the predicate is redundant, and removing it lets the fix cover all three paths. childToolsConfig already builds the child config as strictAllow=true / defaultToolsEnabled=false / allow = decl.tools ∩ parent policy / deny = parent.deny, so ToolFilter.isAllowed(name, childCfg) already means "declared and allowed by the parent". Dropping the extra condition, the builder field, the package-private setter and the factory call leaves all 15 harness cases and 5 core cases green with no test edits, and applying the filter unconditionally in buildInstance fixes declared + general-purpose + the root agent in one place (+4 / −31):

ToolsConfig hookToolPolicy = resolvedToolsConfig;
inner.hookToolFilter(toolName -> ToolFilter.isAllowed(toolName, hookToolPolicy));

Without a tools.json, isAllowed(name, null) is true, so configs with no tool policy are unaffected. I ran the full core + harness suite with that patch: 0 failures, spotless clean. If you would rather keep the blast radius on subagents only, the fallback is one line in buildGeneralPurposeFactory (sub.inheritedHookToolAllowlist(List.of())) plus dropping the redundant &&.

Nits: the new HookToolsRegistrationTest cases use fully-qualified Mockito/Assertions while the file uses static imports; the package-private setter javadoc reads Internal: used by ... where asLeafSubagent() uses the "Package-private because only ... should ..." phrasing; and a debug/warn when a hook contribution is dropped would match ToolFilter.warnUnknown and save someone an afternoon.

@ningmao-hlyz ningmao-hlyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Formalising the review above as a change request, since the general-purpose gap is the same defect this PR is meant to close.

Required

  1. general-purpose must not re-enable a parent-denied hook tool. Probe and root cause are in the comment above; the fix is one line in buildGeneralPurposeFactory (sub.inheritedHookToolAllowlist(List.of())) or, preferably, item 2.
  2. Prefer the unified filter in HarnessAgent.buildInstance — inner.hookToolFilter(toolName -> ToolFilter.isAllowed(toolName, resolvedToolsConfig)) — with inheritedHookToolAllowlist (field, package-private setter, factory call) removed. The declaration allowlist is already encoded in the child's ToolsConfig by childToolsConfig, so the extra && is redundant, and one predicate fixes declared + general-purpose + the root agent: +4 / −31, full core + harness suite green, spotless:check clean, and no behaviour change when no tools.json is present.

The nits from the previous comment (static imports, setter javadoc phrasing, log on dropped contributions) can be handled inline while you are there.

coderzhn and others added 5 commits November 30, 2026 13:37
When hookToolFilter rejects a contribution, the tool is silently absent
from the built agent. Log the dropped name at WARN, matching the
diagnostics ToolFilter.warnUnknown provides for unmatched tools.json
entries.
Match the existing static imports in HookToolsRegistrationTest instead of
fully-qualified Mockito and Assertions references.
Hook.tools() contributions were filtered only for declared children, so
the general-purpose subagent and the root agent could still install a tool
the effective ToolsConfig denied. They register after ToolFilter.apply, so
the deny list never saw them.

childToolsConfig already folds the declaration allowlist into the child's
strict ToolsConfig, so the extra allowlist condition was redundant. Apply
one predicate in HarnessAgent.buildInstance for every build:

    toolName -> ToolFilter.isAllowed(toolName, resolvedToolsConfig)

A null config allows every contribution, preserving configs that define no
tool policy. Remove the per-call-site inheritedHookToolAllowlist field,
setter, and factory call.

Regression coverage: general-purpose and root agents now drop a denied hook
tool; the no-policy general-purpose case still installs it.
Hook-contributed tools are now filtered for the root agent and
general-purpose as well, not only declared children. Describe the behavior
by the effective ToolsConfig and note that declared children also encode
the declaration allowlist in it.
@coderzhn

Copy link
Copy Markdown
Contributor Author

@ningmao-hlyz

Both required items are addressed, along with the nits.

Unified filter. HarnessAgent.buildInstance now installs one predicate for every build:

  ToolsConfig hookToolPolicy = resolvedToolsConfig;                                                                                                                                                                                  
  inner.hookToolFilter(toolName -> ToolFilter.isAllowed(toolName, hookToolPolicy));                                                                                                                                                  

inheritedHookToolAllowlist (field, package-private setter, and the buildDeclaredFactory call)
is removed. You were right that childToolsConfig already folds the declaration allowlist into the
child's strict ToolsConfig, so the extra && was redundant. isAllowed(name, null) stays true,
so configs without a tool policy are unaffected.

general-purpose and root. With the filter applied unconditionally, the gp child and the root
agent both drop a denied hook tool. Added regressions:

  • generalPurposeSubagentDropsDeniedHookTool — your round-2 probe (parent deny=["hook_extra"],
    hook contributes hook_extra).
  • rootAgentDropsDeniedHookTool — the same mechanism on the root build.
    The no-policy gp case still installs the tool (generalPurposeSubagentStillInstallsHookTools), so
    the fix does not over-filter.

Nits.

  • The new HookToolsRegistrationTest cases now use the file's static imports.
  • The package-private setter is gone, so its javadoc phrasing is moot.
  • A rejected contribution now logs at WARN:
    Hook-contributed tool '{}' was rejected by hookToolFilter and will not be installed.

Validation.

  • ManagedSubagentBoundaryTest 17/17, HookToolsRegistrationTest 5/5.
  • Full mvn -T1C -pl agentscope-harness -am test: core 3571, AG-UI 607, harness 2308; 0 failures.
  • spotless:check on core + harness passes.

Docs now describe the behavior by the effective ToolsConfig across root, general-purpose, and
declared children.

@ningmao-hlyz ningmao-hlyz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Follow-up at 58f141a7. Both required items are in, the filter placement is right, and generalPurposeSubagentStillInstallsHookTools is the control I would have asked for. Core 605, harness 2,363 (52 skipped), Spotless clean, CI green.

[P1] A deny list that lives in tools.json never reaches a declared child. childToolsConfig reads toolsConfigOverride, which is null when the parent's policy comes from the workspace file, and the child never loads tools.json itself. Probe: tools.json {"deny":["hook_extra"]}, hook contributing hook_extra, declaration listing it → root rejects, general-purpose rejects, the declared child installs it. With .toolsConfig(cfg) all three reject. A declaration without a tools: list leaks too, and there it is not hook-specific: write_file denied in tools.json still lands in the child.

Pre-existing, those two code paths are untouched here. But the sentence you added to subagent.md states it without qualification.

I tried the small fix first and it does not stay small: hoisting the policy into a builder field fixes the declaration that lists tools:, not the one without a list, because the factories can be created before any build runs (buildSubagentEntries(Path) is public and documented for mounting factories on a session router) and buildStaticSubagentEntries has no workspace manager to load tools.json from. So narrow the sentence here to the declaration allowlist and programmatic config, and take workspace-policy propagation as its own change.

One nit: stray blank line after ToolsConfig toolsConfigOverride;, and the warning says hookToolFilter, an internal name where "tool policy" reads better.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]:声明的子 Agent 不会继承父 Agent hooks

2 participants