Skip to content

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

Open

Description

@z43460018724

Problem

Currently, the only way to disable knowledge-related system prompt injection is disableWorkspaceContext(), which is a nuclear option — it disables everything: AGENTS.md, MEMORY.md, knowledge/KNOWLEDGE.md, knowledge file catalog, guidance text, and session context.

There is no independent switch to disable only the knowledge context while keeping AGENTS.md, MEMORY.md, and memory tools intact.

Use Case

We build an enterprise Q&A agent with a custom searchKnowledge tool (backed by Solr full-text search + Milvus vector search + Rerank, indexing 120K enterprise documents). The LLM is expected to call searchKnowledge when it needs domain knowledge.

However, the framework's WorkspaceContextMiddleware injects into every system prompt:

  1. DOMAIN_KNOWLEDGE_GUIDANCE text ("The knowledge/ directory is the source of truth...")
  2. knowledge/KNOWLEDGE.md full content
  3. All file paths under knowledge/ directory
  4. Workspace Files notice mentioning knowledge/KNOWLEDGE.md

This causes the LLM to prefer list_files on the knowledge/ directory or memory_search over calling our searchKnowledge tool. For example, when asked about a contact person, the LLM tries to browse local files instead of querying the enterprise knowledge base.

We need a way to disable only the knowledge injection so the LLM relies on our custom tool, while keeping AGENTS.md, MEMORY.md, and memory tools working normally.

Proposed Solution

Add a disableKnowledgeContext() Builder method that precisely disables knowledge-related injection without affecting other workspace context:

HarnessAgent.builder()
    .disableKnowledgeContext()  // NEW: disable knowledge/ injection only
    // AGENTS.md — still injected
    // MEMORY.md — still injected
    // memory tools (memory_search, memory_get, etc.) — still available
    // session context (date, OS, workspace path) — still injected

When disableKnowledgeContext() is called:

  1. Skip DOMAIN_KNOWLEDGE_GUIDANCE text
  2. Skip knowledge/KNOWLEDGE.md content injection (including file IO)
  3. Skip knowledge file path catalog
  4. Use Workspace Files notice text without knowledge/ mention

Relationship to existing switches

Method What it disables
disableWorkspaceContext() Everything (nuclear option)
disableMemoryTools() memory_search / memory_get / memory_save tools
disableMemoryHooks() memory flush + background maintenance + MEMORY.md injection
disableKnowledgeContext() Only knowledge-related injection (guidance + KNOWLEDGE.md + file catalog + notice text)

Affected Code

  • WorkspaceContextMiddleware.java: buildGuidance(), workspaceFilesNotice(), buildKnowledgeBlock(), buildWorkspaceSection()
  • HarnessAgent.java: Builder method + flag + constructor pass-through

We have a working prototype and are happy to review a PR once implemented.

Activity

  1. changed the title [-]Feature: Add independent switch to disable knowledge context injection[/-] [+][Feature]: Add independent switch to disable knowledge context injection[/+] on Sep 24, 2026
  2. z43460018724 commented on Sep 24, 2026

    @z43460018724
    Author

    Here is a working prototype diff for reference. It touches 2 files, ~60 lines:

    diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java
    index e7afb9b5..a5dfc3f1 100644
    --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java
    +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/HarnessAgent.java
    @@ -1252,6 +1252,7 @@ public class HarnessAgent implements Agent, AutoCloseable {
     
             boolean disableMemoryTools = false;
             boolean disableMemoryHooks = false;
    +        boolean disableKnowledgeContext = false;
             boolean disableTranscript = false;
             TranscriptStore transcriptStore;
             String transcriptTenant;
    @@ -2247,6 +2248,18 @@ public class HarnessAgent implements Agent, AutoCloseable {
                 return this;
             }
     
    +        /**
    +         * Disables the framework-local knowledge context: skips injection of
    +         * {@code knowledge/KNOWLEDGE.md} content, the knowledge file list, and the
    +         * {@code DOMAIN_KNOWLEDGE_GUIDANCE} text into the workspace system prompt.
    +         * Use this when the agent relies on a custom enterprise knowledge tool
    +         * (e.g. searchKnowledge backed by Solr + Milvus) instead of local files.
    +         */
    +        public Builder disableKnowledgeContext() {
    +            this.disableKnowledgeContext = true;
    +            return this;
    +        }
    +
             /**
              * Disables the independent session-transcript middleware. Prefer leaving transcript on;
              * memory hooks can be disabled separately via {@link #disableMemoryHooks()}.
    @@ -2534,7 +2547,8 @@ public class HarnessAgent implements Agent, AutoCloseable {
                                     environmentMemory,
                                     maxContextTokens,
                                     disableMemoryTools,
    -                                disableMemoryHooks);
    +                                disableMemoryHooks,
    +                                disableKnowledgeContext);
                     markdownMw.setAdditionalContextFiles(additionalContextFiles);
                     markdownMw.setArtifactDeliveryEnabled(artifactDeliveryEnabled);
                     inner.middleware(markdownMw);
    diff --git a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddleware.java b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddleware.java
    index 885eb2a6..4f7c5e50 100644
    --- a/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddleware.java
    +++ b/agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/WorkspaceContextMiddleware.java
    @@ -117,7 +117,21 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
                 """
                 ## Workspace Files (Injected)
                 The following <loaded_context> was loaded in from files in your workspace.
    -            These files (for example, `AGENTS.md` and `knowledge/KNOWLEDGE.md`) contain guidelines and domain context for this agent.
    +            These files (for example, `AGENTS.md`) contain guidelines and domain context for this agent.
    +            """;
    +
    +    private static final String WORKSPACE_FILES_NOTICE_NO_KNOWLEDGE_WITH_MEMORY =
    +            """
    +            ## Workspace Files (Injected)
    +            The following <loaded_context> was loaded in from files in your workspace.
    +            These files (for example, `AGENTS.md`, `MEMORY.md`) contain memory, facts, preferences, guidelines, and user-specific details learned from prior interactions with user.
    +            """;
    +
    +    private static final String WORKSPACE_FILES_NOTICE_NO_KNOWLEDGE_WITHOUT_MEMORY =
    +            """
    +            ## Workspace Files (Injected)
    +            The following <loaded_context> was loaded in from files in your workspace.
    +            These files (for example, `AGENTS.md`) contain guidelines and domain context for this agent.
                 """;
     
         private static final String TRUNCATION_NOTICE_WITH_SEARCH =
    @@ -133,15 +147,16 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
         private final int maxContextTokens;
         private final boolean disableMemoryTools;
         private final boolean disableMemoryHooks;
    +    private final boolean disableKnowledgeContext;
         private List<String> additionalContextFiles = List.of();
         private boolean artifactDeliveryEnabled = false;
     
         public WorkspaceContextMiddleware(WorkspaceManager workspaceManager) {
    -        this(workspaceManager, "HarnessAgent", null, DEFAULT_MAX_CONTEXT_TOKENS, false, false);
    +        this(workspaceManager, "HarnessAgent", null, DEFAULT_MAX_CONTEXT_TOKENS, false, false, false);
         }
     
         public WorkspaceContextMiddleware(WorkspaceManager workspaceManager, int maxContextTokens) {
    -        this(workspaceManager, "HarnessAgent", null, maxContextTokens, false, false);
    +        this(workspaceManager, "HarnessAgent", null, maxContextTokens, false, false, false);
         }
     
         public WorkspaceContextMiddleware(
    @@ -149,7 +164,7 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
                 String agentName,
                 String environmentMemory,
                 int maxContextTokens) {
    -        this(workspaceManager, agentName, environmentMemory, maxContextTokens, false, false);
    +        this(workspaceManager, agentName, environmentMemory, maxContextTokens, false, false, false);
         }
     
         public WorkspaceContextMiddleware(
    @@ -159,12 +174,24 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
                 int maxContextTokens,
                 boolean disableMemoryTools,
                 boolean disableMemoryHooks) {
    +        this(workspaceManager, agentName, environmentMemory, maxContextTokens, disableMemoryTools, disableMemoryHooks, false);
    +    }
    +
    +    public WorkspaceContextMiddleware(
    +            WorkspaceManager workspaceManager,
    +            String agentName,
    +            String environmentMemory,
    +            int maxContextTokens,
    +            boolean disableMemoryTools,
    +            boolean disableMemoryHooks,
    +            boolean disableKnowledgeContext) {
             this.workspaceManager = workspaceManager;
             this.agentName = agentName != null && !agentName.isBlank() ? agentName : "HarnessAgent";
             this.environmentMemory = environmentMemory;
             this.maxContextTokens = maxContextTokens;
             this.disableMemoryTools = disableMemoryTools;
             this.disableMemoryHooks = disableMemoryHooks;
    +        this.disableKnowledgeContext = disableKnowledgeContext;
         }
     
         public void setAdditionalContextFiles(List<String> files) {
    @@ -213,7 +240,8 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
             boolean includeMemoryContext = includeMemoryContext();
             String memoryContent =
                     includeMemoryContext ? workspaceManager.readMemoryMd(rc).strip() : "";
    -        String knowledgeContent = workspaceManager.readKnowledgeMd(rc).strip();
    +        String knowledgeContent =
    +                disableKnowledgeContext ? "" : workspaceManager.readKnowledgeMd(rc).strip();
             Path workspace = workspaceManager.getWorkspace();
             AbstractFilesystem filesystem = workspaceManager.getFilesystem();
             Path effectiveWorkspace =
    @@ -257,7 +285,9 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
     
         private String buildGuidance() {
             StringBuilder sb = new StringBuilder();
    -        sb.append(DOMAIN_KNOWLEDGE_GUIDANCE.strip()).append("\n\n");
    +        if (!disableKnowledgeContext) {
    +            sb.append(DOMAIN_KNOWLEDGE_GUIDANCE.strip()).append("\n\n");
    +        }
             if (!disableMemoryTools) {
                 sb.append(MEMORY_RECALL_GUIDANCE.strip()).append("\n\n");
             }
    @@ -523,6 +553,11 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
         }
     
         private String workspaceFilesNotice() {
    +        if (disableKnowledgeContext) {
    +            return includeMemoryContext()
    +                    ? WORKSPACE_FILES_NOTICE_NO_KNOWLEDGE_WITH_MEMORY
    +                    : WORKSPACE_FILES_NOTICE_NO_KNOWLEDGE_WITHOUT_MEMORY;
    +        }
             return includeMemoryContext()
                     ? WORKSPACE_FILES_NOTICE_WITH_MEMORY
                     : WORKSPACE_FILES_NOTICE_WITHOUT_MEMORY;
    @@ -571,6 +606,9 @@ public class WorkspaceContextMiddleware implements HarnessRuntimeMiddleware {
         }
     
         private String buildKnowledgeBlock(RuntimeContext rc, String knowledgeContent, Path workspace) {
    +        if (disableKnowledgeContext) {
    +            return "";
    +        }
             List<Path> knowledgeFiles = workspaceManager.listKnowledgeFiles(rc);
             StringBuilder sb = new StringBuilder();

    Key design points to avoid missing:

    1. IO short-circuit: when disabled, do NOT call readKnowledgeMd() at all — skip the file read entirely, not just discard the result.
    2. Guidance text: DOMAIN_KNOWLEDGE_GUIDANCE says "The knowledge/ directory is the source of truth" — if this text remains in the prompt, the LLM will still try to browse knowledge/ via list_files or memory_search. Must be skipped.
    3. Workspace Files notice: the default notice mentions knowledge/KNOWLEDGE.md by name. Need two variants (with/without MEMORY.md) that omit the knowledge mention.
    4. Knowledge file catalog: buildKnowledgeBlock() lists all files under knowledge/. Return empty string immediately when disabled.
    5. Constructor backward compatibility: keep all existing constructors working by delegating to the new 7-arg version with disableKnowledgeContext=false.
  3. oss-maintainer commented on Sep 24, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: enhancement (area/harness) | Status: Evaluated — feasible, but blocked on an in-flight refactor | Severity: low-medium (ergonomics / prompt-budget control)

    Claim-by-claim check (verified against main @ fefc196f4, engine-assisted read of agentscope-harness)

    Claim Result Evidence
    disableWorkspaceContext() is the only switch today, and it is all-or-nothing TRUE HarnessAgent.java:1259 (single boolean) → the whole WorkspaceContextMiddleware is skipped at HarnessAgent.java:2529-2541
    No narrower switch disables only knowledge TRUE The Builder declares 16 disable* flags at HarnessAgent.java:1232-1265 (compaction, toolResultEviction, filesystemTools, shellTool, webTools, memoryTools, memoryHooks, transcript, sessionPersistence, workspaceContext, atPathExpansion, subagents, dynamicSkills, defaultWorkspaceSkills, dynamicSubagents, toolsConfig); none gates knowledge. disableMemoryTools() / disableMemoryHooks() leave knowledge injection intact — WorkspaceContextMiddlewareMemoryPromptTest:158-167 asserts ## Domain Knowledge and <domain_knowledge_context> still appear when both are set
    All four injection points are unconditional TRUE (a) DOMAIN_KNOWLEDGE_GUIDANCE appended unconditionally in buildGuidance() — WorkspaceContextMiddleware.java:260; (b) readKnowledgeMd(rc) called unconditionally — :216; (c) listKnowledgeFiles(rc) catalog — :574; (d) both WORKSPACE_FILES_NOTICE_* templates name knowledge/KNOWLEDGE.md — :113, :120, selected at :525-529
    Affected files are WorkspaceContextMiddleware + HarnessAgent TRUE exactly the four methods named in the report, plus the 6-arg middleware construction at HarnessAgent.java:2531

    There is also no alternative escape hatch today (no system property, env var, spec option or middleware flag). The only non-API workaround is to not ship a knowledge/ directory, which is not viable for the reporter's setup. So the gap is real and the motivation (a custom retrieval tool competing with framework-injected "knowledge/ is the source of truth" guidance) is legitimate.

    Why no automated PR this tick — the proposed patch would collide with #3275.

    PR #3275 (OPEN, +8148/-562, by a project collaborator, opened ~1h50m before this issue; currently REVIEW_REQUIRED) rewrites the context pipeline these very methods live in:

    • buildWorkspaceSection() stops emitting <domain_knowledge_context> via buildXmlContext(...) and instead emits new ContextItem("knowledge", "workspace:knowledge", knowledgeBlock) into a new HARNESS_CONTEXT model, with ContextSelectionPolicy.defaults() ranking knowledge second in the budget-omission order (after memory).
    • DOMAIN_KNOWLEDGE_GUIDANCE is reworded, and both WORKSPACE_FILES_NOTICE_WITH_MEMORY / ..._WITHOUT_MEMORY constants (the exact strings the prototype patch edits) are deleted.
    • HarnessAgent.java, HarnessAgentBuilderSupport.java and all three WorkspaceContextMiddleware*Test classes are modified in the same PR.

    So the diff attached to this issue cannot be applied as-is after #3275 lands, and if written now against main it conflicts on every touched hunk.

    Recommended direction (maintainer call, since #3275 changes what "a switch" means):

    1. If feat(harness): unify context construction and add optional task verification #3275 lands: express "no knowledge" as a per-source selection on the new context API (e.g. mark the workspace:knowledge source non-required / excluded, or a ContextSelectionPolicy that omits it unconditionally) rather than a new boolean threaded through the middleware constructor. This keeps one configuration model for the new pipeline instead of reintroducing the old flag pattern.
    2. If a fix is wanted before feat(harness): unify context construction and add optional task verification #3275 settles: keep the flag on HarnessAgent.Builder, but add a WorkspaceContextMiddleware overload instead of changing the 6-arg constructor — WorkspaceContextMiddlewareMemoryPromptTest:119, :139, :154 call that constructor directly, so a signature change breaks the build.
    3. Either way, gating the IO (skip readKnowledgeMd / listKnowledgeFiles calls, not just discard their output) is worth keeping from the prototype — it is the part that avoids reading a 120K-document tree every turn.
    4. docs/v2/{en,zh}/docs/harness/*.md has a switch table listing disableWorkspaceContext(); a new switch needs a row in both languages.

    Testability: yes, no external services needed — a WorkspaceContextMiddlewareKnowledgePromptTest mirroring the existing memory-prompt test, asserting ## Domain Knowledge guidance, the KNOWLEDGE.md body, the Knowledge files: catalog and the notice text are all absent when disabled while AGENTS.md / MEMORY.md / <memory_context> remain present.

    @z43460018724 the requirement itself checks out — this is a genuine gap, not a misreading of the existing switches. The blocker is purely sequencing against #3275. If a harness owner confirms which of (1) or (2) they want, reply /approve or /revise <direction> and a patch will be generated against the agreed shape.


    Automated evaluation by github-manager-bot

  4. added
    enhancement
    area/harness
    on Sep 24, 2026
  5. z43460018724 commented on Sep 24, 2026

    @z43460018724
    Author

    Update: PR #3275 (the in-flight context pipeline refactor that was blocking this issue) has been closed without merging on Sep 24 due to merge conflicts with main. The blocker no longer applies.

    We have submitted PR #3287 implementing the disableKnowledgeContext() approach (direction 2 — overload instead of changing the 6-arg constructor, per the evaluation's note about WorkspaceContextMiddlewareMemoryPromptTest).

    PR #3287 is ready for review.

  6. oss-maintainer commented on Sep 27, 2026

    @oss-maintainer
    Collaborator

    Proposal window closed — no competing PR will be filed from this proposal window

    The 72 h feedback window opened by the evaluation above (2026-09-24T10:14:40Z) reached its bound with
    no approve / revise / reject directive from a harness owner.

    The thread answered the question in another way: @z43460018724 reported on 2026-09-24T21:59:10Z that
    the sequencing blocker (PR #3275) had been closed without merging, and opened PR #3287 —
    Fixes #3278, direction 2 from the evaluation (a WorkspaceContextMiddleware overload rather than a
    signature change on the 6-arg constructor). As of this read #3287 is OPEN, not a draft, review
    decision APPROVED, 7/7 checks passing, +398/-9 across 7 files, head f87ba33cab.

    So the implementation path for this request is owned by a community PR that already exists and is
    awaiting maintainer merge. Filing a second PR against the same issue is exactly the collision this
    window policy exists to prevent, so the proposal is stood down and no automated PR will be generated
    from it.

    Nothing here disputes the evaluation: the gap is real and the recommended shape is the one #3287
    implements. Merge, close, or request changes on #3287 — that is the productive thread now. If #3287 is
    closed unmerged and this remains wanted, reopen the question on #3278 and it will be re-evaluated
    against whatever main looks like at that point.

    Automated feedback-window maintenance by github-manager-bot

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/harnessenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions