Skip to content

feat(harness): add disableKnowledgeContext() builder method - #3287

Open
z43460018724 wants to merge 21 commits into
agentscope-ai:mainfrom
z43460018724:pr-disable-knowledge-context
Open

z43460018724 wants to merge 21 commits into
agentscope-ai:mainfrom
z43460018724:pr-disable-knowledge-context

Conversation

@z43460018724

Copy link
Copy Markdown

Fixes #3278

Description

Add a disableKnowledgeContext() Builder method to HarnessAgent that precisely disables knowledge-related system prompt injection without affecting AGENTS.md, MEMORY.md, or memory tools.

Currently the only way to disable knowledge injection is disableWorkspaceContext(), which is a nuclear option — it disables everything including AGENTS.md, MEMORY.md, and session context. This PR adds a granular switch for agents that use a custom enterprise knowledge tool (e.g. Solr + Milvus + Rerank) instead of the framework's local knowledge/ directory.

Changes

HarnessAgent.java

  • Add disableKnowledgeContext boolean flag to Builder (default false)
  • Add disableKnowledgeContext() Builder method with Javadoc
  • Pass flag to WorkspaceContextMiddleware via new 7-arg constructor

WorkspaceContextMiddleware.java

  • Add 2 new WORKSPACE_FILES_NOTICE_NO_KNOWLEDGE_* constants (omit knowledge/KNOWLEDGE.md mention)
  • Add disableKnowledgeContext field
  • Add 7-arg constructor; existing constructors delegate with false (backward compatible)
  • IO short-circuit: skip readKnowledgeMd() entirely when disabled
  • buildGuidance(): skip DOMAIN_KNOWLEDGE_GUIDANCE text when disabled
  • workspaceFilesNotice(): select no-knowledge notice variant when disabled
  • buildKnowledgeBlock(): return empty string immediately when disabled

What is NOT affected when disableKnowledgeContext() is called

  • AGENTS.md injection
  • MEMORY.md injection
  • Memory tools (memory_search, memory_get, etc.)
  • Memory recall guidance
  • Session context (date, OS, workspace path)
  • All existing constructor signatures

Testing

  • All existing WorkspaceContextMiddleware*Test classes pass unchanged (6-arg constructor retained)
  • Suggested new test: WorkspaceContextMiddlewareKnowledgePromptTest mirroring the existing memory-prompt test, asserting ## Domain Knowledge guidance, KNOWLEDGE.md body, Knowledge files: catalog, and notice text are all absent when disabled while AGENTS.md / MEMORY.md / <memory_context> remain present

Backward compatibility

  • No existing API changes
  • Default behavior unchanged (knowledge injection enabled)
  • All 6 existing constructor overloads work as before

@CLAassistant

CLAassistant commented Sep 24, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@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

Adds a granular disableKnowledgeContext() switch on HarnessAgent.Builder that suppresses the ## Domain Knowledge guidance, knowledge/KNOWLEDGE.md and the knowledge file catalog, while leaving AGENTS.md, MEMORY.md and the memory tools intact. The approach is sound and the backward compatibility is handled properly — the 6-arg constructor delegates with false, and the IO short-circuit in buildWorkspaceSection avoids the readKnowledgeMd() read entirely rather than reading and discarding. mergeable is clean and Check License / Check Module Sync are green (build still running at review time).

Three things keep this from an approve:

  1. Subagents don't inherit the switch. HarnessAgentBuilderSupport propagates every sibling disable* flag to both subagent factories; this one is missing from both, so a subagent of an agent that disabled knowledge context still gets the full knowledge injection.
  2. No tests. The diff is production-only; the PR body lists the test as "suggested". WorkspaceContextMiddlewareMemoryPromptTest is a ready-made template for exactly these assertions.
  3. No docs. docs/v2/{en,zh}/docs/harness/workspace.md tabulate every other disable* switch and currently state that knowledge/ can only be switched off via disableWorkspaceContext().

Minor prompt-shape notes (empty <domain_knowledge_context> element, possibly-empty guidance block, constructor arity) are inline.

Findings

  • [Warning] HarnessAgent.java:1253 — disableKnowledgeContext is not captured/propagated in either subagent factory in HarnessAgentBuilderSupport
  • [Warning] HarnessAgent.java:2257 — no test coverage added for the new switch or the two new notice variants
  • [Warning] HarnessAgent.java:2249-2261 — docs/v2/en + docs/v2/zh harness/workspace.md switch tables not updated
  • [Info] WorkspaceContextMiddleware.java:194 — seventh positional param / third adjacent boolean on a public constructor; a setter would match the existing setArtifactDeliveryEnabled pattern
  • [Info] WorkspaceContextMiddleware.java:303 — buildGuidance() can now return a lone "\n", leaving an empty guidance block in the assembled prompt
  • [Info] WorkspaceContextMiddleware.java:624 — an empty <domain_knowledge_context></domain_knowledge_context> element is still emitted; consider skipping it like additionalBlock

Not blocking: none of the above changes behaviour for callers who leave the flag off — default path is byte-identical.


Automated review by github-manager-bot

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@z43460018724

Copy link
Copy Markdown
Author

All 6 review comments addressed in commit f432b189:

# Severity Comment Status
1 Warning Subagent propagation Fixed — disableKnowledgeContext now captured/applied in both HarnessAgentBuilderSupport factories
2 Warning No test coverage Fixed — added WorkspaceContextMiddlewareKnowledgePromptTest (5 cases, all pass)
3 Warning No docs Fixed — updated docs/v2/{en,zh}/docs/harness/workspace.md switch tables + section tables
4 Info Constructor arity (7th param) Acknowledged — kept constructor pattern to match siblings; setter alternative noted for follow-up
5 Info buildGuidance() lone \n Fixed — returns "" when all sections suppressed; assembleSection() skips empty guidance
6 Info Empty <domain_knowledge_context> Fixed — buildLoadedContextSection() checks !knowledgeBlock.isBlank() before appending

CI re-triggered on new commit. Tests: 17/17 pass (5 new + 12 existing).

@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 at f432b189 after the feedback round. All four follow-up items from the previous review are resolved and I verified each against the new commit rather than the replies:

  • Subagent propagation — disableKnowledgeContext is now captured and re-applied in both sibling sites (HarnessAgentBuilderSupport.java:341/398 and :465/570), matching how disableMemoryTools / disableMemoryHooks are handled, so a parent's switch no longer leaks back into spawned children.
  • Tests — WorkspaceContextMiddlewareKnowledgePromptTest adds 5 cases, all green in CI on this head (WorkspaceContextMiddlewareKnowledgePromptTest → Tests run: 5, Failures: 0), covering guidance + content + catalog suppression, both Workspace Files (Injected) notice variants and the default-enabled path. The existing WorkspaceContextMiddlewareMemoryPromptTest assertions on <domain_knowledge_context> still hold, so the two suites do not contradict each other.
  • Docs — both docs/v2/en and docs/v2/zh gained the switch row plus the trimmed guidance/<domain_knowledge_context> rows, in the same table as disableWorkspaceContext().
  • Empty-element and blank-guidance edges — if (!knowledgeBlock.isBlank()) drops the <domain_knowledge_context></domain_knowledge_context> pair, and buildGuidance() now returns "" instead of a lone "\n".

The one item you acknowledged and deliberately kept (the 7th positional boolean on the public constructor) is a fair call for this PR — the telescoping chain is pre-existing and converting it here would widen the blast radius.

Two non-blocking notes below: the wiring paths that actually regressed in the first revision are still only covered indirectly, and the empty-guidance branch adds one blank line to the prompt. Neither is a reason to hold this.

LGTM — approving. Thanks for the fast, complete turnaround on the feedback.


Automated review by github-manager-bot

@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

Adds disableKnowledgeContext() on HarnessAgent.Builder, threads it through WorkspaceContextMiddleware, and — in the commit pushed since my previous review — adds the subagent-propagation tests that were the remaining gap. Re-reviewed at 51c831da; the delta over the commit I approved is test-only (136 added lines, one new test file), and it covers exactly the right surface: both factory branches in HarnessAgentBuilderSupport (general-purpose and declared) plus a default-off control. CLA signed, MERGEABLE, license/validate/module-sync green.

Approved. Two non-blocking nits are inline.

Findings

  • [Info] DisableKnowledgeContextSubagentPropagationTest.java:121 — createChild returns Object, forcing a cast at each call site
  • [Info] DisableKnowledgeContextSubagentPropagationTest.java:65 — assert the rendered child prompt, not just the propagated flag, for an end-to-end guarantee

Verification of the fix itself

HarnessAgentBuilderSupport.java:341,398 (general-purpose) and :465,570 (declared) now capture and re-apply disableKnowledgeContext() alongside the sibling disable* flags, which is what my earlier review asked for. The backward-compatible 6-arg constructor delegation and the IO short-circuit in buildWorkspaceSection are unchanged from the version I approved.


Automated review by github-manager-bot

@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 at f87ba33c. The only change since the commit I approved (2d2166f1) is test-only: DisableKnowledgeContextSubagentPropagationTest now seeds knowledge/KNOWLEDGE.md and asserts on the rendered child system prompt (absence of ## Domain Knowledge when disabled, presence when enabled) instead of only the propagated boolean. That is exactly the end-to-end gap from my previous round, and it is the stronger assertion. No production code moved. Verdict: approve at the new head.

Previous round's findings

  • DisableKnowledgeContextSubagentPropagationTest.java:65 — assert the rendered child prompt, not just the propagated flag — resolved (renderedChildPrompt(child) via WorkspaceContextMiddleware.onSystemPrompt, asserted in all three cases).
  • DisableKnowledgeContextSubagentPropagationTest.java:121 — createChild returns Object, forcing a cast at each call site — still open, non-blocking.

Verification

  • The new assertions exercise the real branch, not a stub: buildGuidance() appends DOMAIN_KNOWLEDGE_GUIDANCE (whose first line is ## Domain Knowledge) only when !disableKnowledgeContext, and seedKnowledgeFile() makes the enabled case produce a non-empty knowledge block, so the positive assertion can genuinely fail.
  • @TempDir workspace + per-test seeding keeps the new file writes isolated; no shared-state risk across the three cases.
  • Diff confirms scope: gh api compare for 2d2166f1...f87ba33c returns a single test file, +26/-0.
  • CI on the new head is green (ubuntu, windows, validate, license, module-sync); CLA signed; MERGEABLE.

Ready to merge

Previously approved, still approved at f87ba33c, CI green, no conflicts. Merging is a maintainer action.


Automated review by github-manager-bot

@z43460018724
z43460018724 force-pushed the pr-disable-knowledge-context branch 2 times, most recently from 320a57d to 6b570d1 Compare October 10, 2026 05:24
- Propagate disableKnowledgeContext to both subagent factories in
  HarnessAgentBuilderSupport (general-purpose and declared)
- buildGuidance(): return empty string when all sections are suppressed
  instead of a lone newline
- assembleSection(): skip empty guidance block
- buildLoadedContextSection(): omit <domain_knowledge_context> element
  when the knowledge block is blank
- Add WorkspaceContextMiddlewareKnowledgePromptTest (5 test cases)
- Update docs/v2/{en,zh}/docs/harness/workspace.md switch tables

(cherry picked from commit e61b256)
…text

Covers both branches of the disableKnowledgeContext flag checks in

(cherry picked from commit 709eb73)
Extract shared parentBuilder()/buildSubagentEntry() helpers, assert entry

(cherry picked from commit 9f7a030)
Addresses review [info]: previously the subagent propagation tests only
asserted the flag reached the child's WorkspaceContextMiddleware. Add
end-to-end assertions that the child's rendered system prompt actually
drops the "## Domain Knowledge" section when disabled and keeps it when
enabled (mirrors WorkspaceContextMiddlewareKnowledgePromptTest). Seeds a
knowledge/KNOWLEDGE.md in the shared temp workspace so the rendered
prompt exercises the real section.

(cherry picked from commit d5724c4)
…ements + escaped HTML)

(cherry picked from commit 0b06a8c)
…disableKnowledgeContext notes

(cherry picked from commit 276d944)
… keep material table unchanged

(cherry picked from commit 6b570d1)
@z43460018724
z43460018724 force-pushed the pr-disable-knowledge-context branch from 6de7d10 to 0008824 Compare October 28, 2026 02:31
@mintlify

mintlify Bot commented Oct 28, 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 8f98562.

Approve preview

@jujn jujn added the P2 重要不紧急 label Nov 4, 2026
@xseruer

xseruer commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Adding another +1 for this capability. We also need an independent opt-out for agents whose domain knowledge is supplied through application-defined tools or skills rather than the harness's local knowledge/ directory.

Why this is valuable and necessary

  • Correct retrieval behavior, not just fewer tokens. Built-in Domain Knowledge guidance advertises a local knowledge source and file-navigation workflow. When an application supplies its own retrieval workflow, these instructions compete with that workflow and can steer the model toward the wrong source. Removing the content alone is insufficient if the prompt still advertises it.
  • A usable opt-out without sacrificing the harness. disableWorkspaceContext() is too broad: applications still need AGENTS.md instructions, memory capabilities, and runtime/workspace context. Disabling memory tools or hooks does not address knowledge injection. Knowledge therefore needs its own switch.
  • Less unnecessary context and I/O. Omitting the knowledge body and file catalog saves prompt budget; skipping knowledge reads and directory enumeration avoids doing work for a capability the application explicitly disabled.

The important contract for us is that disableKnowledgeContext() removes all harness-generated knowledge guidance and reference material: ## Domain Knowledge, <domain_knowledge_context> (including an empty element), KNOWLEDGE.md content, the knowledge file catalog, and related retrieval instructions. Other workspace and memory behavior should remain unchanged, and spawned subagents should inherit the opt-out. This is a prompt-injection opt-out, not a filesystem-access restriction or a filter for caller-authored prompts.

This PR addresses that focused need while keeping the existing default behavior. Its regression coverage, subagent propagation, and EN/ZH documentation are particularly useful for making the switch dependable.

The capability is still absent from the latest upstream main I checked. Given the existing approved reviews and passing Ubuntu/Windows builds, could a maintainer help move this PR toward merge, or clarify whether anything else is needed? The core value is enabling application-controlled knowledge retrieval without disabling unrelated harness capabilities.

# Conflicts:
#	agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java
@z43460018724

Copy link
Copy Markdown
Author

Thanks for the review and the P2 label, @jujn.

Status update — this PR is now fully ready to merge:

  • Merged latest main (a4306d6) into the branch (Nov 14). The only conflict was in HarnessAgent.java, resolved by keeping the disableKnowledgeContext field + builder method and dropping the now-removed disableSessionPersistence field / stale javadoc (main converted it to a no-op).
  • All 6 CI checks green (validate / ubuntu / windows / license / module sync / Mintlify). The earlier ubuntu failure was an upstream flaky A2A test (AgentScopeAgentExecutorInputRequiredTest.streamingConfirmationWithoutStateStoreFails) — main's own ubuntu build (run 43396004630, Nov 13) was red on the same + a durable ProcessRecoveryTest — unrelated to this change.
  • Local harness tests pass 33/33 (WorkspaceContextMiddlewareKnowledgePromptTest, DisableKnowledgeContextSubagentPropagationTest, WorkspaceContextMiddlewareMemoryPromptTest, WorkspaceContextMiddlewareSandboxPromptTest).
  • mergeable_state: clean. All prior review feedback addressed; the oss-maintainer approvals stand.

@xseruer — your Nov 13 follow-up is valid: the opt-out removes all harness-generated knowledge guidance/materials (the ## Domain Knowledge section, KNOWLEDGE.md content, the file catalog, and the retrieval instructions) and propagates to subagents (covered by DisableKnowledgeContextSubagentPropagationTest). Nothing further needed from this side.

Given that multiple consumers are waiting on this and it's ready at any time, would it be possible to bump it to P1 or merge when convenient, @jujn? No blocking work remains on our end.

Thanks!

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

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Add independent switch to disable knowledge context injection

5 participants