RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Go: fix context and warnings (#18097)
Jin Haid7661b676d42
diff --git a/internal/agent/audio/tts_design.md b/internal/agent/audio/tts_design.mdindex 4d5b779ac7..410b71b0b5 100644--- a/internal/agent/audio/tts_design.md+++ b/internal/agent/audio/tts_design.md@@ -16,15 +16,15 @@ and creates an `LLMBundle(tenant, tts_model_config)`. The TTSfactory in `rag/llm/tts_model.py` dispatches to one of several**HTTP-based** providers:-| Provider | Backend | Pure Go? |-|----------|---------|----------|-| FishAudioTTS | HTTP POST to `api.fish.audio/v1/tts` (msgpack body) | feasible |-| QwenTTS | DashScope SDK (over WebSocket) | heavy |-| OpenAITTS | HTTP POST to OpenAI-compatible `/audio/tts` | feasible |-| StepFunTTS | HTTP POST to vendor endpoint | feasible |-| RAGconTTS | LiteLLM proxy (HTTP) | feasible |-| XinferenceTTS | HTTP POST to xinference | feasible |-| TongyiTTS | DashScope SDK | heavy |+| Provider | Backend | Pure Go? |+|---------------|-----------------------------------------------------|----------|+| FishAudioTTS | HTTP POST to `api.fish.audio/v1/tts` (msgpack body) | feasible |+| QwenTTS | DashScope SDK (over WebSocket) | heavy |+| OpenAITTS | HTTP POST to OpenAI-compatible `/audio/tts` | feasible |+| StepFunTTS | HTTP POST to vendor endpoint | feasible |+| RAGconTTS | LiteLLM proxy (HTTP) | feasible |+| XinferenceTTS | HTTP POST to xinference | feasible |+| TongyiTTS | DashScope SDK | heavy |None of the production providers are gtts / edge-tts. The "gtts oredge-tts shell-out" wording in the original plan was a placeholderdiff --git a/internal/agent/canvas/cancel.go b/internal/agent/canvas/cancel.goindex 6afcda9626..20a107d900 100644--- a/internal/agent/canvas/cancel.go+++ b/internal/agent/canvas/cancel.go@@ -14,10 +14,6 @@// limitations under the License.//-// cancel.go implements the cross-process cancel signal for ordinary Agent-// sessions. A canvas run polls Redis for "{sessionID}-cancel"; when the HTTP-// handler sets the key, the watcher cancels the same context used by the-// workflow.package canvasimport (@@ -38,8 +34,8 @@ const cancelKeySuffix = "-cancel"func cancelKey(sessionID string) string { return sessionID + cancelKeySuffix }// cancelPollInterval is the gap between Redis Get polls. 500ms keeps-// cancel latency p99 ≤ 500ms while staying cheap (one GET every half--// second per active run). Tunable later if a tenant needs lower latency.+// cancel latency p99 ≤ 500ms while staying cheap (one GET every half-second per active run).+// Tunable later if a tenant needs lower latency.const cancelPollInterval = 500 * time.Millisecond// RequestCancelTTL is the lifetime of the cancel flag in Redis. Long@@ -62,7 +58,7 @@ var cancelClientFn = func() (*redis.Client, error) {return c, nil}-// WatchCancel blocks until either ctx is cancelled or the Redis+// WatchCancel blocks until either ctx is canceled or the Redis// "{sessionID}-cancel" key contains a non-empty value. When fired, it calls// onCancel exactly once and returns. Polling interval is fixed// at 500ms (see plan §4.9 — revised 2026-06-03 from 1s to 500ms).diff --git a/internal/agent/canvas/canvas.go b/internal/agent/canvas/canvas.goindex f3becc8586..38aa6aedb8 100644--- a/internal/agent/canvas/canvas.go+++ b/internal/agent/canvas/canvas.go@@ -15,7 +15,7 @@ import ()// legacyNoOpNames is the set of component names that the Go port-// recognises for DSL v1 compatibility but does not ship a real+// recognizes for DSL v1 compatibility but does not ship a real// implementation for. Encountering one of these in a DSL is mapped to// the same no-op echo lambda used for placeholder bodies by the// BuildWorkflow in scheduler.go. New DSLs should not use these names —diff --git a/internal/agent/canvas/compile.go b/internal/agent/canvas/compile.goindex 6a29622f17..4bf528740e 100644--- a/internal/agent/canvas/compile.go+++ b/internal/agent/canvas/compile.go@@ -2,7 +2,7 @@//// Compile turns a Canvas (DSL) into a CompiledCanvas: a compiled// compose.Runnable plus the CheckPointID used at this compile. The-// compile-time wiring (state pre/post handlers, checkpoint store,+// compile-time wiring (state pre- / post-handlers, checkpoint store,// serializer) is configured here; the actual run path lives in// runner.go and the HTTP handler / SSE / RunTracker are wired in// internal/service and internal/handler.@@ -88,12 +88,12 @@ type CompileOptions struct {// CompileOption mutates a CompileOptions before the compile runs.type CompileOption func(*CompileOptions)-// WithCheckPointStore attaches a CheckPointStore to the compile.+// WithCheckPointStore attaches a CheckPointStore to compile.func WithCheckPointStore(s CheckPointStore) CompileOption {return func(o *CompileOptions) { o.Store = s }}-// WithStateSerializer attaches a StateSerializer to the compile.+// WithStateSerializer attaches a StateSerializer to compile.func WithStateSerializer(s StateSerializer) CompileOption {return func(o *CompileOptions) { o.Serializer = s }}@@ -130,7 +130,7 @@ func WithInterruptAfterNonTerminalCpn() CompileOption {}// WithOverrideParams attaches a run-level override map (keyed by-// cpnID) to the compile. Each component's params are merged with+// cpnID) to compile. Each component's params are merged with// its own entry at compile time (run-level wins on key collision, see// node_body.go applyOverrideParams). Passing nil is a no-op.func WithOverrideParams(m map[string]any) CompileOption {@@ -138,7 +138,7 @@ func WithOverrideParams(m map[string]any) CompileOption {}// Compile builds the eino Workflow from the Canvas and returns the-// compiled Runnable. State pre/post handlers are wired inside BuildWorkflow+// compiled Runnable. State pre- / post-handlers are wired inside BuildWorkflow// (see scheduler.go). Checkpoint store + serializer are wired here as// compile-time options (compose.GraphCompileOption).//@@ -314,9 +314,8 @@ func dedupeStrings(in []string) []string {}// checkPointAdapter drops the Delete method that compose.CheckPointStore-// does not declare. The RedisCheckPointStore in this package has-// Delete; eino-// doesn't, so the adapter is a thin passthrough.+// does not declare. The RedisCheckPointStore in this package has deleted;+// the adapter is a thin passthrough.type checkPointAdapter struct{ inner CheckPointStore }func (a checkPointAdapter) Get(ctx context.Context, id string) ([]byte, bool, error) {diff --git a/internal/agent/canvas/loop_semantics_test.go b/internal/agent/canvas/loop_semantics_test.goindex 4183598523..94097a9529 100644--- a/internal/agent/canvas/loop_semantics_test.go+++ b/internal/agent/canvas/loop_semantics_test.go@@ -32,7 +32,6 @@package canvasimport (- "context""encoding/json""io""strings"@@ -257,7 +256,7 @@ func TestLoop_MessageEmitsEveryIteration(t *testing.T) {Upstream: []string{"bump"},}- cc, err := Compile(context.Background(), dsl)+ cc, err := Compile(ctx, dsl)if err != nil {t.Fatalf("Compile: %v", err)}diff --git a/internal/agent/canvas/loop_subgraph.go b/internal/agent/canvas/loop_subgraph.goindex bf420eb9b8..c3e40410e6 100644--- a/internal/agent/canvas/loop_subgraph.go+++ b/internal/agent/canvas/loop_subgraph.go@@ -46,7 +46,7 @@ import ("github.com/cloudwego/eino/compose")-// loopExpansion holds the two artefacts produced by buildLoopExpansion+// loopExpansion holds the two artifacts produced by buildLoopExpansion// and consumed by BuildWorkflow to install the loop node.type loopExpansion struct {Sub *compose.Workflow[map[string]any, map[string]any]@@ -124,7 +124,7 @@ func collectLoopMembers(c *Canvas, loopID string) map[string]bool {func collectDescendants(c *Canvas, root string) map[string]bool {visited := make(map[string]bool)- queue := []string{}+ var queue []stringfor _, child := range c.Components[root].Downstream {if child == root {continue@@ -179,8 +179,7 @@ func buildSubWorkflow(// body's mutations accumulate across iterations — otherwise a// VariableAssigner that increments `counter` would be clobbered// back to its initial value at the top of every iteration and- // the loop could never terminate on a condition that watches the- // counter.+ // the loop could never terminate on a condition that watches the counter.//// "First time" is detected by checking whether the loop's state// bucket already holds the variable: a missing bucket entry@@ -535,7 +534,7 @@ func translateLoopCondition(loopID string, params map[string]any) (workflowx.Looreturn false, fmt.Errorf("loop %q: condition eval: no canvas state in context", loopID)}if len(conditions) == 0 {- // No conditions means the loop only stops at max count+ // No conditions mean the loop only stops at max count// — never quit on conditions. Mirrors Python fallback.return false, nil}diff --git a/internal/agent/canvas/node_body_timeout_test.go b/internal/agent/canvas/node_body_timeout_test.goindex 03926e8cc1..fee39df7fc 100644--- a/internal/agent/canvas/node_body_timeout_test.go+++ b/internal/agent/canvas/node_body_timeout_test.go@@ -59,7 +59,7 @@ func TestRealComponentBody_RespectsParentCancellation(t *testing.T) {comp := &blockingComponent{}body := realComponentBody("test-cpn", "TestBlocking", comp)- parentCtx, cancel := context.WithCancel(context.Background())+ parentCtx, cancel := context.WithCancel(t.Context())cancel() // pre-cancel_, err := body(parentCtx, map[string]any{"x": 1})@@ -77,7 +77,7 @@ func TestRealComponentBody_NoTimeoutWhenFast(t *testing.T) {comp := &echoComponent{}body := realComponentBody("test-cpn", "TestEcho", comp)- out, err := body(context.Background(), map[string]any{"x": 1})+ out, err := body(t.Context(), map[string]any{"x": 1})if err != nil {t.Fatalf("unexpected error: %v", err)}diff --git a/internal/agent/canvas/parallel_batch_test.go b/internal/agent/canvas/parallel_batch_test.goindex 6b394b7cd0..1685c0ea05 100644--- a/internal/agent/canvas/parallel_batch_test.go+++ b/internal/agent/canvas/parallel_batch_test.go@@ -50,7 +50,7 @@ func TestBuildWorkflow_ParallelBatchStructure(t *testing.T) {Path: []string{"begin", "a", "b", "final"},}- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)defer cancel()type compileResult struct {diff --git a/internal/agent/canvas/parallel_subgraph_test.go b/internal/agent/canvas/parallel_subgraph_test.goindex 1399e6cf13..3a198162d7 100644--- a/internal/agent/canvas/parallel_subgraph_test.go+++ b/internal/agent/canvas/parallel_subgraph_test.go@@ -1,7 +1,6 @@package canvasimport (- "context""testing")@@ -75,7 +74,7 @@ func TestBuildParallelExpansion_PrefersGroupedMembersOverDescendants(t *testing.},}- exp, err := buildParallelExpansion(context.Background(), c, "Parallel:IterateList")+ exp, err := buildParallelExpansion(t.Context(), c, "Parallel:IterateList")if err != nil {t.Fatalf("buildParallelExpansion: %v", err)}diff --git a/internal/agent/canvas/parallel_timing_test.go b/internal/agent/canvas/parallel_timing_test.goindex d8d9392486..ed8d833db2 100644--- a/internal/agent/canvas/parallel_timing_test.go+++ b/internal/agent/canvas/parallel_timing_test.go@@ -40,7 +40,6 @@package canvasimport (- "context""testing")@@ -73,7 +72,7 @@ func TestCanvas_ParallelExecution_StaticAnalysis(t *testing.T) {Path: []string{"begin", "a", "b", "c", "final"},}- cc, err := Compile(context.Background(), c)+ cc, err := Compile(t.Context(), c)if err != nil {t.Fatalf("Compile: %v", err)}diff --git a/internal/agent/canvas/run_tracker_test.go b/internal/agent/canvas/run_tracker_test.goindex 35ffd7d142..53a51e6134 100644--- a/internal/agent/canvas/run_tracker_test.go+++ b/internal/agent/canvas/run_tracker_test.go@@ -42,7 +42,7 @@ func newTestTracker(t *testing.T, ttl time.Duration) (*RunTracker, *miniredis.Mifunc TestRunTracker_StateTransitions(t *testing.T) {tracker, mr := newTestTracker(t, 30*24*time.Hour)- ctx := context.Background()+ ctx := t.Context()// B1: Startif err := tracker.Start(ctx, "run_1", "canvas_42", "tenant_a", ""); err != nil {@@ -73,7 +73,7 @@ func TestRunTracker_StateTransitions(t *testing.T) {}// AttachCheckpoint- if err := tracker.AttachCheckpoint(ctx, "run_1", "cpn_xyz"); err != nil {+ if err = tracker.AttachCheckpoint(ctx, "run_1", "cpn_xyz"); err != nil {t.Fatalf("AttachCheckpoint: %v", err)}got, _ = tracker.Get(ctx, "run_1")@@ -82,14 +82,14 @@ func TestRunTracker_StateTransitions(t *testing.T) {}// B2: MarkSucceeded- if err := tracker.MarkSucceeded(ctx, "run_1"); err != nil {+ if err = tracker.MarkSucceeded(ctx, "run_1"); err != nil {t.Fatalf("MarkSucceeded: %v", err)}got, _ = tracker.Get(ctx, "run_1")if got["status"] != "1" {t.Fatalf("status = %q, want 1 (succeeded)", got["status"])}- if _, err := strconv.ParseInt(got["finished_at"], 10, 64); err != nil {+ if _, err = strconv.ParseInt(got["finished_at"], 10, 64); err != nil {t.Fatalf("finished_at %q is not an int: %v", got["finished_at"], err)}// All previous fields preserved.@@ -100,7 +100,7 @@ func TestRunTracker_StateTransitions(t *testing.T) {func TestRunTracker_FailedAndCancelled(t *testing.T) {tracker, _ := newTestTracker(t, time.Hour)- ctx := context.Background()+ ctx := t.Context()// B3: MarkFailedif err := tracker.Start(ctx, "run_fail", "c", "t", "run_parent"); err != nil {@@ -138,7 +138,7 @@ func TestRunTracker_FailedAndCancelled(t *testing.T) {func TestRunTracker_TTLRefresh(t *testing.T) {tracker, mr := newTestTracker(t, 2*time.Second)- ctx := context.Background()+ ctx := t.Context()if err := tracker.Start(ctx, "run_ttl", "c", "t", ""); err != nil {t.Fatalf("Start: %v", err)@@ -168,7 +168,7 @@ func TestRunTracker_TTLRefresh(t *testing.T) {// A wait-for-user pause must also keep the run metadata alive for the// full tracker TTL so the next request can resume it.mr.FastForward(500 * time.Millisecond)- if err := tracker.MarkWaiting(ctx, "run_ttl"); err != nil {+ if err = tracker.MarkWaiting(ctx, "run_ttl"); err != nil {t.Fatalf("MarkWaiting: %v", err)}if d := mr.TTL(runKey("run_ttl")); d < 1500*time.Millisecond {@@ -185,7 +185,7 @@ func TestRunTracker_TTLRefresh(t *testing.T) {func TestRunTracker_NilClient(t *testing.T) {tracker := &RunTracker{client: nil, ttl: time.Minute}- ctx := context.Background()+ ctx := t.Context()if err := tracker.Start(ctx, "x", "c", "t", ""); err == nil {t.Fatal("Start with nil client: err = nil, want error")}@@ -211,7 +211,7 @@ func TestRunTracker_NilClient(t *testing.T) {func TestRunTrackerActiveSessionRegistration(t *testing.T) {tracker, mr := newTestTracker(t, time.Hour)- ctx := context.Background()+ ctx := t.Context()if err := tracker.client.Set(ctx, cancelKey("session-1"), "x", time.Hour).Err(); err != nil {t.Fatalf("seed cancel marker: %v", err)}@@ -259,7 +259,7 @@ func TestRunTrackerActiveSessionRegistration(t *testing.T) {func TestRunTrackerActiveSessionTokenProtectsRefreshAndRelease(t *testing.T) {tracker, _ := newTestTracker(t, time.Hour)- ctx := context.Background()+ ctx := t.Context()registered, err := tracker.RegisterActiveSession(ctx, ActiveSession{SessionID: "session-1", Token: "owner-a"})if err != nil || !registered {t.Fatalf("RegisterActiveSession = %v, %v", registered, err)@@ -275,7 +275,7 @@ func TestRunTrackerActiveSessionTokenProtectsRefreshAndRelease(t *testing.T) {if got, _ := tracker.GetActiveSession(ctx, "session-1"); got == nil {t.Fatal("foreign release removed active session")}- if err := tracker.client.Set(ctx, cancelKey("session-1"), "x", time.Hour).Err(); err != nil {+ if err = tracker.client.Set(ctx, cancelKey("session-1"), "x", time.Hour).Err(); err != nil {t.Fatalf("seed cancel marker: %v", err)}released, err = tracker.ReleaseActiveSession(ctx, "session-1", "owner-a")@@ -292,7 +292,7 @@ func TestRunTrackerActiveSessionTokenProtectsRefreshAndRelease(t *testing.T) {func TestRunTrackerActiveSessionTokenProtectsCancel(t *testing.T) {tracker, _ := newTestTracker(t, time.Hour)- ctx := context.Background()+ ctx := t.Context()registered, err := tracker.RegisterActiveSession(ctx, ActiveSession{SessionID: "session-1", Token: "owner-a"})if err != nil || !registered {t.Fatalf("RegisterActiveSession = %v, %v", registered, err)diff --git a/internal/agent/canvas/scheduler_test.go b/internal/agent/canvas/scheduler_test.goindex fe4d86f625..bd1dca9adc 100644--- a/internal/agent/canvas/scheduler_test.go+++ b/internal/agent/canvas/scheduler_test.go@@ -2,7 +2,6 @@package canvasimport (- "context""encoding/json""strings""testing"@@ -32,7 +31,7 @@ func TestBuildWorkflow_3NodeLinear(t *testing.T) {Path: []string{"begin_0", "llm_0", "message_0"},}- wf, err := BuildWorkflow(context.Background(), c)+ wf, err := BuildWorkflow(t.Context(), c)if err != nil {t.Fatalf("BuildWorkflow: %v", err)}@@ -41,7 +40,7 @@ func TestBuildWorkflow_3NodeLinear(t *testing.T) {}// Compile to a Runnable to confirm the topology is internally consistent.- cc, err := Compile(context.Background(), c)+ cc, err := Compile(t.Context(), c)if err != nil {t.Fatalf("Compile: %v", err)}@@ -84,7 +83,7 @@ func TestBuildWorkflow_5NodeDiamond(t *testing.T) {Path: []string{"begin_0", "a_0", "b_0", "c_0", "d_0"},}- cc, err := Compile(context.Background(), c)+ cc, err := Compile(t.Context(), c)if err != nil {t.Fatalf("Compile diamond: %v", err)}@@ -124,7 +123,7 @@ func TestBuildWorkflow_MultiTerminalSucceeds(t *testing.T) {Path: []string{"begin_0", "a_0", "b_0", "c_0"},}- cc, err := Compile(context.Background(), c)+ cc, err := Compile(t.Context(), c)if err != nil {t.Fatalf("Compile multi-terminal canvas: %v", err)}@@ -192,7 +191,7 @@ func TestBuildWorkflow_ParallelGroupWithOuterFollowerSucceeds(t *testing.T) {},}- cc, err := Compile(context.Background(), c)+ cc, err := Compile(t.Context(), c)if err != nil {t.Fatalf("Compile parallel canvas: %v", err)}@@ -218,7 +217,7 @@ func TestBuildWorkflow_ErrorsOnUnknownUpstream(t *testing.T) {},},}- _, err := BuildWorkflow(context.Background(), c)+ _, err := BuildWorkflow(t.Context(), c)if err == nil {t.Fatal("expected error for unknown upstream")}@@ -238,7 +237,7 @@ func TestBuildWorkflow_ErrorsOnSelfEdge(t *testing.T) {},},}- _, err := BuildWorkflow(context.Background(), c)+ _, err := BuildWorkflow(t.Context(), c)if err == nil {t.Fatal("expected error for self-edge")}@@ -249,7 +248,7 @@ func TestBuildWorkflow_ErrorsOnSelfEdge(t *testing.T) {func TestNodeLifecycleEventsSafeMarshalNonSerializableInputs(t *testing.T) {events := make(chan RunEvent, 2)- ctx := WithRunMeta(context.Background(), &RunMeta{+ ctx := WithRunMeta(t.Context(), &RunMeta{Events: events,MessageID: "msg-1",SessionID: "session-1",@@ -280,7 +279,7 @@ func TestNodeLifecycleEventsSafeMarshalNonSerializableInputs(t *testing.T) {if !ok {t.Fatalf("%s inputs = %T %v, want object", wantType, payload["inputs"], payload["inputs"])}- if _, ok := in["callback"]; !ok {+ if _, ok = in["callback"]; !ok {t.Fatalf("%s inputs missing sanitized callback key: %v", wantType, in)}if in["callback"] != nil {@@ -294,7 +293,7 @@ func TestNodeLifecycleEventsSafeMarshalNonSerializableInputs(t *testing.T) {func TestNodeLifecycleEventsFallbackMarshalErrorPreservesIdentity(t *testing.T) {events := make(chan RunEvent, 2)- ctx := WithRunMeta(context.Background(), &RunMeta{+ ctx := WithRunMeta(t.Context(), &RunMeta{Events: events,MessageID: "msg-2",SessionID: "session-2",diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.goindex b36d85d23d..1ac7847dc6 100644--- a/internal/agent/component/agent.go+++ b/internal/agent/component/agent.go@@ -1195,7 +1195,7 @@ func toolMessageTextContent(msg *schema.Message) string {return ""}-// formatArtifactMarkdown renders a slice of artifacts as markdown+// formatArtifactMarkdown renders a slice of artifacts as Markdown// links, omitting URLs already present in the existing text (Python's// `_collect_tool_artifact_markdown` does the same de-duplication).//diff --git a/internal/agent/component/agent_test.go b/internal/agent/component/agent_test.goindex 642ba8c61f..89634f7880 100644--- a/internal/agent/component/agent_test.go+++ b/internal/agent/component/agent_test.go@@ -787,7 +787,7 @@ func TestAgent_Invoke_RespectsParentCancellation(t *testing.T) {})c := NewAgentComponent(AgentParam{ModelID: "echo", MaxRounds: 1})- ctx, cancel := context.WithCancel(context.Background())+ ctx, cancel := context.WithCancel(t.Context())cancel() // pre-cancel_, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "hi"})@@ -1065,15 +1065,16 @@ func TestAgent_CanvasSubAgentToolBuildsDynamicTool(t *testing.T) {if len(agent.param.SubAgents) != 1 {t.Fatalf("sub agents = %d, want 1", len(agent.param.SubAgents))}+ ctx := t.Context()- tools, err := buildAgentTools(t.Context(), agent.param)+ tools, err := buildAgentTools(ctx, agent.param)if err != nil {t.Fatalf("buildAgentTools: %v", err)}if len(tools) != 1 {t.Fatalf("len(tools) = %d, want 1", len(tools))}- info, err := tools[0].Info(context.Background())+ info, err := tools[0].Info(ctx)if err != nil {t.Fatalf("tool.Info: %v", err)}@@ -1125,7 +1126,7 @@ func TestAgent_CanvasSubAgentToolNamesAreUniqueAfterNormalization(t *testing.T)}var names []stringfor _, tool := range tools {- info, err := tool.Info(context.Background())+ info, err := tool.Info(t.Context())if err != nil {t.Fatalf("tool.Info: %v", err)}diff --git a/internal/agent/component/artifact_markdown_test.go b/internal/agent/component/artifact_markdown_test.goindex 6505a54f0a..4e5f88b65b 100644--- a/internal/agent/component/artifact_markdown_test.go+++ b/internal/agent/component/artifact_markdown_test.go@@ -31,7 +31,7 @@ func TestFormatArtifactMarkdown_Empty(t *testing.T) {}}-// TestFormatArtifactMarkdown_ImageLink: image URL → markdown image syntax.+// TestFormatArtifactMarkdown_ImageLink: image URL → Markdown image syntax.func TestFormatArtifactMarkdown_ImageLink(t *testing.T) {arts := []artifactEntry{{Name: "chart", URL: "https://example.com/chart.png"},diff --git a/internal/agent/component/browser_test.go b/internal/agent/component/browser_test.goindex 3e6322b7d6..d6ef4c5afb 100644--- a/internal/agent/component/browser_test.go+++ b/internal/agent/component/browser_test.go@@ -84,7 +84,7 @@ func stateWith(t *testing.T, sys map[string]any) context.Context {t.Helper()state := canvas.NewCanvasState("run-1", "task-1")state.Sys = sys- return canvas.WithState(context.Background(), state)+ return canvas.WithState(t.Context(), state)}// TestBrowser_AcceptsPythonSchema: the v1 fixture's param surface@@ -282,7 +282,7 @@ func TestBrowser_MissingTenant(t *testing.T) {})// state with no tenant_idstate := canvas.NewCanvasState("run-1", "task-1")- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, nil)if err == nil || !strings.Contains(err.Error(), "tenant_id") {diff --git a/internal/agent/component/canvas_var_resolution_test.go b/internal/agent/component/canvas_var_resolution_test.goindex e4747a5c4b..a318e0988d 100644--- a/internal/agent/component/canvas_var_resolution_test.go+++ b/internal/agent/component/canvas_var_resolution_test.go@@ -17,7 +17,6 @@package componentimport (- "context""testing""ragflow/internal/agent/runtime"@@ -38,7 +37,7 @@ func TestLLM_Invoke_ResolvesTemplateRefs(t *testing.T) {SystemPrompt: "Use the following context:",UserPrompt: "What does {{retrieval:0@content}} say?",})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, map[string]any{})if err != nil {t.Fatalf("Invoke: %v", err)@@ -64,7 +63,7 @@ func TestLLM_Invoke_NoState_LeavesPromptsUnchanged(t *testing.T) {ModelID: "echo",UserPrompt: "What does {{retrieval:0@content}} say?",})- _, err := c.Invoke(context.Background(), nil, map[string]any{})+ _, err := c.Invoke(t.Context(), nil, map[string]any{})if err != nil {t.Fatalf("Invoke: %v", err)}@@ -89,7 +88,7 @@ func TestLLM_Invoke_UnresolvedRef_LeavesPromptIntact(t *testing.T) {ModelID: "echo",UserPrompt: "Use {{retrieval:0@content}} please",})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, map[string]any{})if err != nil {t.Fatalf("Invoke should not error on unresolved ref: %v", err)diff --git a/internal/agent/component/chat_template_kwargs_test.go b/internal/agent/component/chat_template_kwargs_test.goindex 74b95e0d4b..147af3c673 100644--- a/internal/agent/component/chat_template_kwargs_test.go+++ b/internal/agent/component/chat_template_kwargs_test.go@@ -17,7 +17,6 @@package componentimport (- "context""testing")@@ -76,7 +75,7 @@ func TestLLM_Invoke_ChatTemplateKwargsDoesNotBreak(t *testing.T) {ModelID: "echo",ChatTemplateKwargs: map[string]any{"seed": 1},})- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "hi"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "hi"})if err != nil {t.Fatalf("Invoke: %v", err)}diff --git a/internal/agent/component/citation_test.go b/internal/agent/component/citation_test.goindex cec92ad073..8a03a6b72a 100644--- a/internal/agent/component/citation_test.go+++ b/internal/agent/component/citation_test.go@@ -17,7 +17,6 @@package componentimport (- "context""strings""testing"@@ -132,7 +131,7 @@ func TestLLM_Invoke_AppendsCitationPrompt(t *testing.T) {withStubInvoker(t, stub)c := NewLLMComponent(LLMParam{ModelID: "echo", SystemPrompt: "You are a bot.", Cite: true})- if _, err := c.Invoke(context.Background(), nil, map[string]any{+ if _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "hi",}); err != nil {t.Fatalf("Invoke: %v", err)@@ -159,7 +158,7 @@ func TestLLM_Invoke_CiteFalseDisablesInjection(t *testing.T) {withStubInvoker(t, stub)c := NewLLMComponent(LLMParam{ModelID: "echo", SystemPrompt: "sys"})- _, _ = c.Invoke(context.Background(), nil, map[string]any{+ _, _ = c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "hi","cite": false,})diff --git a/internal/agent/component/docs_generator.go b/internal/agent/component/docs_generator.goindex ae75bd39bb..ce01f52441 100644--- a/internal/agent/component/docs_generator.go+++ b/internal/agent/component/docs_generator.go@@ -73,7 +73,7 @@ var validOutputFormats = map[string]bool{"txt": true,"markdown": true,"html": true,- "md": true, // alias for markdown+ "md": true, // alias for Markdown}// docsGeneratorParam is the static DSL param surface.@@ -141,7 +141,7 @@ func (p *docsGeneratorParam) Update(conf map[string]any) error {}// Check validates the param. FontSize must be ≥ 12; output_format must-// be one of pdf / docx / txt / markdown / html.+// be one of pdf / docx / txt / Markdown / html.func (p *docsGeneratorParam) Check() error {if !validOutputFormats[strings.ToLower(strings.TrimSpace(p.OutputFormat))] {return &ParamError{@@ -510,7 +510,7 @@ func sanitizeFilename(raw, ext string) string {}// renderTXT / renderMarkdown / renderHTML live in-// internal/agent/component/io/{txt,markdown,html}_writer.go so+// internal/agent/component/io/{txt,Markdown,html}_writer.go so// every per-format writer lives in its own file under io/,// matching the pdf_writer.go / docx_writer.go packaging.diff --git a/internal/agent/component/docs_generator_test.go b/internal/agent/component/docs_generator_test.goindex 6e2443be40..60511ca1c3 100644--- a/internal/agent/component/docs_generator_test.go+++ b/internal/agent/component/docs_generator_test.go@@ -17,7 +17,6 @@package componentimport (- "context""encoding/json""strings""testing"@@ -96,7 +95,7 @@ func TestDocsGenerator_Invoke_HappyPath(t *testing.T) {if err != nil {t.Fatalf("New(DocsGenerator): %v", err)}- _, _ = c.Invoke(context.Background(), nil, map[string]any{})+ _, _ = c.Invoke(t.Context(), nil, map[string]any{})// We do not assert err == nil here because txt output requires// the internal writer (which may not be available in this// checkout). The test pins that the call doesn't panic.@@ -110,7 +109,7 @@ func TestDocsGenerator_Invoke_UsesQueryWhenContentEmpty(t *testing.T) {if err != nil {t.Fatalf("New(DocsGenerator): %v", err)}- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"query": "Hello from begin query",})if err != nil {@@ -134,10 +133,11 @@ func TestDocsGenerator_Invoke_AcceptsDecorationParamNames(t *testing.T) {"footer_text": "Canonical Footer","watermark_text": "Canonical Watermark",})+ ctx := t.Context()if err != nil {t.Fatalf("New(DocsGenerator): %v", err)}- out, err := c.Invoke(context.Background(), nil, map[string]any{})+ out, err := c.Invoke(ctx, nil, map[string]any{})if err != nil {t.Fatalf("Invoke canonical params: %v", err)}@@ -161,7 +161,7 @@ func TestDocsGenerator_Invoke_AcceptsDecorationParamNames(t *testing.T) {if err != nil {t.Fatalf("New(DocsGenerator alias params): %v", err)}- out, err = c.Invoke(context.Background(), nil, map[string]any{})+ out, err = c.Invoke(ctx, nil, map[string]any{})if err != nil {t.Fatalf("Invoke alias params: %v", err)}diff --git a/internal/agent/component/downstream_message_test.go b/internal/agent/component/downstream_message_test.goindex d00e23b609..516964fbd5 100644--- a/internal/agent/component/downstream_message_test.go+++ b/internal/agent/component/downstream_message_test.go@@ -17,7 +17,6 @@package componentimport (- "context""testing""time")@@ -48,7 +47,7 @@ func TestLLM_Stream_ExposesThinkingAndContentForDownstreamMessage(t *testing.T)withStubInvoker(t, stub)c := NewLLMComponent(LLMParam{ModelID: "echo"})- ch, err := c.Stream(context.Background(), nil, map[string]any{"user_prompt": "go"})+ ch, err := c.Stream(t.Context(), nil, map[string]any{"user_prompt": "go"})if err != nil {t.Fatalf("Stream: %v", err)}diff --git a/internal/agent/component/excel_processor_test.go b/internal/agent/component/excel_processor_test.goindex d4f4664815..82980b012a 100644--- a/internal/agent/component/excel_processor_test.go+++ b/internal/agent/component/excel_processor_test.go@@ -32,7 +32,7 @@ import (func excelCtx(t *testing.T) context.Context {t.Helper()state := canvas.NewCanvasState("run-xlsx", "task-xlsx")- return canvas.WithState(context.Background(), state)+ return canvas.WithState(t.Context(), state)}// TestExcelProcessor_WriteThenRead: write a 2x2 grid, then read itdiff --git a/internal/agent/component/fillup_test.go b/internal/agent/component/fillup_test.goindex c6c97c5c7d..0bcd1a39af 100644--- a/internal/agent/component/fillup_test.go+++ b/internal/agent/component/fillup_test.go@@ -17,7 +17,6 @@package componentimport (- "context""testing""ragflow/internal/agent/canvas"@@ -30,7 +29,7 @@ import (func TestFillup_PassesThroughInputs(t *testing.T) {c, _ := New(componentNameFillup, nil)state := canvas.NewCanvasState("run-1", "task-1")- ctx := withStateForTest(context.Background(), state)+ ctx := withStateForTest(t.Context(), state)out, err := c.Invoke(ctx, nil, map[string]any{"inputs": map[string]any{@@ -60,7 +59,7 @@ func TestFillup_NoTipsKey(t *testing.T) {"tips": "should be ignored",})state := canvas.NewCanvasState("run-2", "task-2")- ctx := withStateForTest(context.Background(), state)+ ctx := withStateForTest(t.Context(), state)out, err := c.Invoke(ctx, nil, map[string]any{"inputs": map[string]any{@@ -86,7 +85,7 @@ func TestFillup_NoTipsKey(t *testing.T) {func TestFillup_NonDictInput(t *testing.T) {c, _ := New(componentNameFillup, nil)state := canvas.NewCanvasState("run-3", "task-3")- ctx := withStateForTest(context.Background(), state)+ ctx := withStateForTest(t.Context(), state)out, err := c.Invoke(ctx, nil, map[string]any{"inputs": map[string]any{@@ -117,7 +116,7 @@ func TestFillup_NonDictInput(t *testing.T) {func TestFillup_FileInputStub(t *testing.T) {c, _ := New(componentNameFillup, nil)state := canvas.NewCanvasState("run-4", "task-4")- ctx := withStateForTest(context.Background(), state)+ ctx := withStateForTest(t.Context(), state)out, err := c.Invoke(ctx, nil, map[string]any{"inputs": map[string]any{diff --git a/internal/agent/component/grounding_test.go b/internal/agent/component/grounding_test.goindex 204c3baa73..69194cf667 100644--- a/internal/agent/component/grounding_test.go+++ b/internal/agent/component/grounding_test.go@@ -77,7 +77,7 @@ func TestGrounding_Applied(t *testing.T) {state.SetRetrievalChunks([]map[string]any{{"id": "0", "content": "the source content"},})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)c := NewAgentComponent(AgentParam{ModelID: "stub", Cite: true})out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "q"})@@ -116,7 +116,7 @@ func TestGrounding_NoChunks(t *testing.T) {state := canvas.NewCanvasState("r1", "t1")// No SetRetrievalChunks — state has no chunks recorded.- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)c := NewAgentComponent(AgentParam{ModelID: "stub", Cite: true})out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "q"})@@ -147,7 +147,7 @@ func TestGrounding_CiteFalse(t *testing.T) {})c := NewAgentComponent(AgentParam{ModelID: "stub", Cite: false})- out, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "q"})+ out, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "q"})if err != nil {t.Fatalf("Invoke: %v", err)}@@ -173,7 +173,7 @@ func TestGrounding_LLMError(t *testing.T) {state := canvas.NewCanvasState("r1", "t1")state.SetRetrievalChunks([]map[string]any{{"id": "0", "content": "x"}})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)c := NewAgentComponent(AgentParam{ModelID: "stub", Cite: true})out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "q"})@@ -203,7 +203,7 @@ func TestGrounding_EmptyContent(t *testing.T) {state := canvas.NewCanvasState("r1", "t1")state.SetRetrievalChunks([]map[string]any{{"id": "0", "content": "x"}})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)c := NewAgentComponent(AgentParam{ModelID: "stub", Cite: true})out, err := c.Invoke(ctx, nil, map[string]any{"user_prompt": "q"})diff --git a/internal/agent/component/history_window_test.go b/internal/agent/component/history_window_test.goindex aa4c13e528..803caf5de8 100644--- a/internal/agent/component/history_window_test.go+++ b/internal/agent/component/history_window_test.go@@ -17,7 +17,6 @@package componentimport (- "context""testing""github.com/cloudwego/eino/schema"@@ -130,7 +129,7 @@ func TestLLM_Invoke_HistoryWindow_PrependsFromState(t *testing.T) {UserPrompt: "now",MessageHistoryWindowSize: window,})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, map[string]any{})if err != nil {t.Fatalf("Invoke: %v", err)@@ -166,7 +165,7 @@ func TestLLM_Invoke_HistoryWindow_DoesNotDuplicateCurrentUser(t *testing.T) {UserPrompt: "now",MessageHistoryWindowSize: 5,})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)if _, err := c.Invoke(ctx, nil, map[string]any{}); err != nil {t.Fatalf("Invoke: %v", err)}@@ -200,7 +199,7 @@ func TestLLM_Invoke_HistoryWindow_ZeroIsNoop(t *testing.T) {UserPrompt: "now",// MessageHistoryWindowSize: 0 (default)})- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)_, _ = c.Invoke(ctx, nil, map[string]any{})if len(stub.captured.Messages) != 1 {t.Errorf("expected only 1 message (no history), got %d", len(stub.captured.Messages))@@ -260,7 +259,7 @@ func TestBuildAgentInputMessagesIncludesPriorConversation(t *testing.T) {state.AppendHistory("user", "第 8 章下面的第一个副标题是什么?")state.AppendHistory("assistant", map[string]any{"content": "第一个是解析器工厂。"})state.AppendCurrentUser("第二个呢?")- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)messages := buildAgentInputMessages(ctx, AgentParam{SystemPrompt: "请根据知识库回答。",@@ -291,7 +290,7 @@ func TestBuildAgentInputMessagesUsesConversationTurnWindow(t *testing.T) {state.AppendHistory("user", "recent question")state.AppendHistory("assistant", "recent answer")state.AppendCurrentUser("current question")- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)messages := buildAgentInputMessages(ctx, AgentParam{UserPrompt: "current question",@@ -310,7 +309,7 @@ func TestBuildAgentInputMessagesZeroWindowDisablesHistory(t *testing.T) {state.AppendHistory("user", "ignored question")state.AppendHistory("assistant", "ignored answer")state.AppendCurrentUser("current question")- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)messages := buildAgentInputMessages(ctx, AgentParam{UserPrompt: "current question"})if len(messages) != 1 || messages[0].Content != "current question" {@@ -322,7 +321,7 @@ func TestBuildAgentInputMessagesReplacesTrailingUserLikePython(t *testing.T) {state := runtime.NewCanvasState("run-agent-trailing-user", "task-agent-trailing-user")state.AppendHistory("user", "unanswered previous input")state.AppendCurrentUser("current question")- ctx := runtime.WithState(context.Background(), state)+ ctx := runtime.WithState(t.Context(), state)messages := buildAgentInputMessages(ctx, AgentParam{UserPrompt: "current question",diff --git a/internal/agent/component/invoke_test.go b/internal/agent/component/invoke_test.goindex 13a8c3d956..5c19ee1792 100644--- a/internal/agent/component/invoke_test.go+++ b/internal/agent/component/invoke_test.go@@ -63,7 +63,7 @@ func TestInvoke_GET(t *testing.T) {defer srv.Close()c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": srv.URL,})@@ -101,7 +101,7 @@ func TestInvoke_POST(t *testing.T) {defer srv.Close()c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "POST","url": srv.URL,"body": `{"k":"v"}`,@@ -139,7 +139,7 @@ func TestInvoke_UsesNodeParams(t *testing.T) {if err != nil {t.Fatalf("NewInvokeComponent: %v", err)}- out, err := c.Invoke(context.Background(), nil, map[string]any{})+ out, err := c.Invoke(t.Context(), nil, map[string]any{})if err != nil {t.Fatalf("Invoke: %v", err)}@@ -176,7 +176,7 @@ func TestInvoke_BadMethod(t *testing.T) {setupAllowAnyHost(t, true)c, _ := NewInvokeComponent(nil)- _, err := c.Invoke(context.Background(), nil, map[string]any{+ _, err := c.Invoke(t.Context(), nil, map[string]any{"method": "PATCH","url": "http://localhost:1",})@@ -193,7 +193,7 @@ func TestInvoke_MissingURL(t *testing.T) {setupAllowAnyHost(t, true)c, _ := NewInvokeComponent(nil)- _, err := c.Invoke(context.Background(), nil, map[string]any{+ _, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET",})if err == nil {@@ -222,7 +222,7 @@ func TestInvoke_SSRFGuard_BlocksLoopback(t *testing.T) {defer srv.Close()c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": srv.URL,})@@ -252,7 +252,7 @@ func TestInvoke_SSRFGuard_BlocksMetadataIP(t *testing.T) {defer srv.Close()c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": "http://169.254.169.254/latest/meta-data/",})@@ -288,7 +288,7 @@ func TestInvoke_SSRFGuard_BlocksProxy(t *testing.T) {// (without a side-effect on the local server) is still// caught. PR review round 5 / duplicate fix from the// serverHit-only assertion in the earlier review.- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": "https://example.com/api","proxy": "http://127.0.0.1:8080",@@ -320,7 +320,7 @@ func TestInvoke_NoRedirects_NotFollowed(t *testing.T) {defer srv.Close()c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": srv.URL,})@@ -388,7 +388,7 @@ func TestInvoke_ProxyDNSPin(t *testing.T) {// resolver below). The SSRF guard validates against// the validated public IP, then the dialer is// expected to use that IP — even if the hostname- // "rebinds" to a different answer afterwards.+ // "rebinds" to a different answer afterward.// We achieve "rebinding" by stubbing the DNS lookup// to return a different IP on a second call.originalLookup := utility.LookupHost@@ -401,7 +401,7 @@ func TestInvoke_ProxyDNSPin(t *testing.T) {t.Cleanup(func() { utility.LookupHost = originalLookup })c, _ := NewInvokeComponent(nil)- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)defer cancel()_, err = c.Invoke(ctx, nil, map[string]any{"method": "GET",@@ -429,7 +429,7 @@ func TestInvoke_ProxyRejectsHostnameTarget(t *testing.T) {setupAllowAnyHost(t, false)c, _ := NewInvokeComponent(nil)- out, err := c.Invoke(context.Background(), nil, map[string]any{+ out, err := c.Invoke(t.Context(), nil, map[string]any{"method": "GET","url": "http://example.com/api","proxy": "http://proxy.example.invalid:9999",diff --git a/internal/agent/component/io/markdown_writer.go b/internal/agent/component/io/markdown_writer.goindex cb9ae57077..949c732fd3 100644--- a/internal/agent/component/io/markdown_writer.go+++ b/internal/agent/component/io/markdown_writer.go@@ -16,7 +16,7 @@// Package io — Markdown writer.//-// Round-trips markdown content: header / footer become HTML+// Round-trips Markdown content: header / footer become HTML// comments (so they don't affect rendering), and an optional// front-matter-style timestamp comment goes at the top.diff --git a/internal/agent/component/io/txt_writer.go b/internal/agent/component/io/txt_writer.goindex 7fa2e3b3c0..4c6a808154 100644--- a/internal/agent/component/io/txt_writer.go+++ b/internal/agent/component/io/txt_writer.go@@ -18,9 +18,9 @@//// The TXT writer is the trivial plain-text path: header / footer /// timestamp are wrapped as plain text lines around the body. No-// encoding negotiation (UTF-8 only); no markdown stripping-// (downstream tools that don't understand markdown can consume TXT-// when the source content is markdown-flavoured — the writer does+// encoding negotiation (UTF-8 only); no Markdown stripping+// (downstream tools that don't understand Markdown can consume TXT+// when the source content is Markdown-flavored — the writer does// not rewrite the body).package iodiff --git a/internal/agent/component/list_operations_test.go b/internal/agent/component/list_operations_test.goindex b9c13376bf..1a2e671288 100644--- a/internal/agent/component/list_operations_test.go+++ b/internal/agent/component/list_operations_test.go@@ -17,7 +17,6 @@package componentimport (- "context""reflect""sort""strings"@@ -38,7 +37,7 @@ func TestListOperations_Head(t *testing.T) {}state := canvas.NewCanvasState("run-1", "task-1")state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3, 4, 5}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -71,7 +70,7 @@ func TestListOperations_TopNLegacyAlias(t *testing.T) {}state := canvas.NewCanvasState("run-topn", "task-topn")state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3, 4}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -94,7 +93,7 @@ func TestListOperations_Filter(t *testing.T) {})state := canvas.NewCanvasState("run-2", "task-2")state.Outputs["cpn_0"] = map[string]any{"xs": []any{"foo", "bar", "foobar"}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -119,7 +118,7 @@ func TestListOperations_DropDuplicates(t *testing.T) {map[string]any{"k": 1},map[string]any{"k": 2},}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -146,7 +145,7 @@ func TestListOperations_Tail(t *testing.T) {})state := canvas.NewCanvasState("run-4", "task-4")state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3, 4, 5}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -168,7 +167,7 @@ func TestListOperations_NthPositive(t *testing.T) {})state := canvas.NewCanvasState("run-5", "task-5")state.Outputs["cpn_0"] = map[string]any{"xs": []any{"a", "b", "c", "d"}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -190,7 +189,7 @@ func TestListOperations_SortDesc(t *testing.T) {})state := canvas.NewCanvasState("run-6", "task-6")state.Outputs["cpn_0"] = map[string]any{"xs": []any{3, 1, 4, 1, 5, 9, 2, 6}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -227,7 +226,7 @@ func TestListOperations_SortByFieldList(t *testing.T) {map[string]any{"id": 3, "score": 0.76, "title": "Gamma"},},}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)// sort_by="score", desc → Alpha(0.91), Beta(0.88), Gamma(0.76)cSortDesc, err := NewListOperationsComponent(map[string]any{@@ -312,7 +311,7 @@ func TestListOperations_NotAList(t *testing.T) {})state := canvas.NewCanvasState("run-7", "task-7")state.Outputs["cpn_0"] = map[string]any{"x": "not-a-list"}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, nil)if err == nil {@@ -362,7 +361,7 @@ func TestListOperations_StrictMode_ReturnsError(t *testing.T) {}state := canvas.NewCanvasState("run-strict", "task-strict")state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)_, err = c.Invoke(ctx, nil, nil)if err == nil {@@ -389,7 +388,7 @@ func TestListOperations_StrictStringCoercion(t *testing.T) {}state := canvas.NewCanvasState("run-str-"+v, "task-str-"+v)state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)_, err = c.Invoke(ctx, nil, nil)if err == nil {@@ -414,7 +413,7 @@ func TestListOperations_StrictFalseStringsIgnored(t *testing.T) {}state := canvas.NewCanvasState("run-strf-"+v, "task-strf-"+v)state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -452,7 +451,7 @@ func TestListOperations_FilterEqBool(t *testing.T) {}state := canvas.NewCanvasState("run-feq", "task-feq")state.Outputs["cpn_0"] = map[string]any{"xs": []any{true, false, true, "True"}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)out, err := c.Invoke(ctx, nil, nil)if err != nil {@@ -480,7 +479,7 @@ func TestListOperations_UnknownOp_ReturnsError(t *testing.T) {}state := canvas.NewCanvasState("run-bogus", "task-bogus")state.Outputs["cpn_0"] = map[string]any{"xs": []any{1, 2, 3}}- ctx := canvas.WithState(context.Background(), state)+ ctx := canvas.WithState(t.Context(), state)_, err := c.Invoke(ctx, nil, nil)if err == nil {diff --git a/internal/agent/component/llm_retry_test.go b/internal/agent/component/llm_retry_test.goindex c55298e969..8a263ae804 100644--- a/internal/agent/component/llm_retry_test.go+++ b/internal/agent/component/llm_retry_test.go@@ -61,7 +61,7 @@ func TestRetryInvoker_SucceedsOnSecondAttempt(t *testing.T) {inner := &scriptedInvoker{failTimes: 1, err: errors.New("transient"), resp: want}r := newRetryInvoker(inner, 3, time.Millisecond)- resp, err := r.Invoke(context.Background(), nil, ChatInvokeRequest{ModelName: "m"})+ resp, err := r.Invoke(t.Context(), nil, ChatInvokeRequest{ModelName: "m"})if err != nil {t.Fatalf("Invoke: unexpected err: %v", err)}@@ -81,7 +81,7 @@ func TestRetryInvoker_ExhaustsRetries(t *testing.T) {inner := &alwaysFailInvoker{err: sentinel}r := newRetryInvoker(inner, 3, time.Millisecond)- _, err := r.Invoke(context.Background(), nil, ChatInvokeRequest{ModelName: "m"})+ _, err := r.Invoke(t.Context(), nil, ChatInvokeRequest{ModelName: "m"})if err == nil {t.Fatal("expected error after exhaustion")}@@ -121,7 +121,7 @@ func TestRetryInvoker_HonorsContextCancellation(t *testing.T) {// honored. The cancellation lands within milliseconds.r := newRetryInvoker(inner, 5, 30*time.Second)- ctx, cancel := context.WithCancel(context.Background())+ ctx, cancel := context.WithCancel(t.Context())// Cancel after a short delay, while the retry is sleeping// through the first backoff.go func() {@@ -164,7 +164,7 @@ func TestRetryInvoker_ExponentialBackoff(t *testing.T) {r := newRetryInvoker(inner, 3, initial)start := time.Now()- _, _ = r.Invoke(context.Background(), nil, ChatInvokeRequest{ModelName: "m"})+ _, _ = r.Invoke(t.Context(), nil, ChatInvokeRequest{ModelName: "m"})elapsed := time.Since(start)// 20 + 40 + 80 = 140ms of backoff (3 retries, 4 attempts total).@@ -185,7 +185,7 @@ func TestRetryInvoker_NoRetriesWhenZero(t *testing.T) {inner := &alwaysFailInvoker{err: errors.New("nope")}r := newRetryInvoker(inner, 0, 50*time.Millisecond)- _, err := r.Invoke(context.Background(), nil, ChatInvokeRequest{ModelName: "m"})+ _, err := r.Invoke(t.Context(), nil, ChatInvokeRequest{ModelName: "m"})if err == nil {t.Fatal("expected error")}@@ -198,7 +198,7 @@ func TestRetryInvoker_NoRetriesWhenZero(t *testing.T) {// should not panic when constructed with nil inner.func TestRetryInvoker_NilInner(t *testing.T) {r := newRetryInvoker(nil, 3, time.Millisecond)- _, err := r.Invoke(context.Background(), nil, ChatInvokeRequest{ModelName: "m"})+ _, err := r.Invoke(t.Context(), nil, ChatInvokeRequest{ModelName: "m"})if err == nil {t.Fatal("expected error for nil inner")}@@ -220,7 +220,7 @@ func TestLLMParam_RespectsMaxRetries(t *testing.T) {// zero-value default is 2s, which would make this test slow.c.param.DelayAfterError = time.Millisecond- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "x"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})if err == nil {t.Fatal("expected error from exhausted retries")}@@ -249,7 +249,7 @@ func TestLLMParam_ZeroRetriesMeansOneAttempt(t *testing.T) {// with maxRetries=0.c.param.DelayAfterError = time.Millisecond- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "x"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})if err == nil {t.Fatal("expected error")}@@ -280,7 +280,7 @@ func TestLLMParam_DefaultRetries(t *testing.T) {SetDefaultChatInvoker(newRetryInvoker(fastInner, 2, time.Millisecond))t.Cleanup(func() { SetDefaultChatInvoker(nil) })- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "x"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})if err == nil {t.Fatal("expected error after default retries")}@@ -364,7 +364,7 @@ func TestLLM_ParamOverride_AbsoluteCount_NotStacked(t *testing.T) {// Force a tiny delay so the test runs fast.c.param.DelayAfterError = time.Millisecond- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "x"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})if err == nil {t.Fatal("expected error from exhausted retries")}@@ -394,7 +394,7 @@ func TestLLM_NoParamOverride_StackingPreserved(t *testing.T) {// No param override: MaxRetries=0 AND DelayAfterError=0.c := NewLLMComponent(LLMParam{ModelID: "m"})- _, err := c.Invoke(context.Background(), nil, map[string]any{"user_prompt": "x"})+ _, err := c.Invoke(t.Context(), nil, map[string]any{"user_prompt": "x"})if err == nil {t.Fatal("expected error from exhausted retries")}diff --git a/internal/agent/component/message.go b/internal/agent/component/message.goindex abcf552ac0..578fe762ef 100644--- a/internal/agent/component/message.go+++ b/internal/agent/component/message.go@@ -21,7 +21,7 @@// and (optionally) emits the result as a single SSE chunk.//// Capabilities:-// - output_format rendering (html / markdown / plain) via render.go+// - output_format rendering (html / Markdown / plain) via render.go// - auto_play → TTS engine dispatch via internal/agent/audio// - download extraction from inputs (the {doc_id, filename,// mime_type} walk from Python's _extract_downloads)diff --git a/internal/agent/component/prompts/citation.go b/internal/agent/component/prompts/citation.goindex 96b26279b7..229ab36603 100644--- a/internal/agent/component/prompts/citation.go+++ b/internal/agent/component/prompts/citation.go@@ -27,7 +27,7 @@ import (// citationPromptText is the citation-instruction template, mirrored// from rag/prompts/citation_prompt.md.//-// The full markdown (123 lines) is preserved so the LLM receives the+// The full Markdown (123 lines) is preserved so the LLM receives the// same instruction set as the Python engine. Trim or extend here only// after a corresponding change in citation_prompt.md.//diff --git a/internal/agent/component/render.go b/internal/agent/component/render.goindex bfdd2f6095..e07f2b9b36 100644--- a/internal/agent/component/render.go+++ b/internal/agent/component/render.go@@ -26,7 +26,7 @@// become <a href="..." download="...">filename</a>// - "markdown" — pass through verbatim; downloads become// [filename](url) links. Python also passes-// markdown through with light normalization; we+// Markdown through with light normalization; we// match that for parity.// - "plain" — strip HTML tags (best-effort) and present// downloads as "filename (url)" lines. Default@@ -173,7 +173,7 @@ func joinPlain(body, dlBlock string) string {// plain renderer. It removes paired and unpaired tags without// attempting to keep attribute content. This matches the// pragmatic behaviour in Python's `_stringify_message_value`-// fallback path: "if markdown → use as-is, if plain → strip tags".+// fallback path: "if Markdown → use as-is, if plain → strip tags".var htmlTagRe = regexp.MustCompile(`<[^>]*>`)// StripHTMLTags removes HTML tags from s. Used by callers thatdiff --git a/internal/agent/component/render_test.go b/internal/agent/component/render_test.goindex a93086fb3f..740f939905 100644--- a/internal/agent/component/render_test.go+++ b/internal/agent/component/render_test.go@@ -63,7 +63,7 @@ func TestRender_HTMLEscapesBody(t *testing.T) {}}-// TestRender_Markdown: markdown passthrough + markdown link list+// TestRender_Markdown: Markdown passthrough + Markdown link list// for downloads.func TestRender_Markdown(t *testing.T) {got := Render(RenderRequest{diff --git a/internal/agent/harness/route.go b/internal/agent/harness/route.goindex 9e5ca228c1..dff1219b78 100644--- a/internal/agent/harness/route.go+++ b/internal/agent/harness/route.go@@ -140,7 +140,7 @@ var ()// unmarshalModelJSON mirrors Python's _extract_json: strip thinking preamble and-// markdown fences, then parse JSON.+// Markdown fences, then parse JSON.func unmarshalModelJSON(text string, out interface{}) error {text = reThinkTag.ReplaceAllString(text, "")text = reFence.ReplaceAllString(text, "")diff --git a/internal/agent/tool/code_exec.go b/internal/agent/tool/code_exec.goindex ec883be04a..f2336b4f97 100644--- a/internal/agent/tool/code_exec.go+++ b/internal/agent/tool/code_exec.go@@ -70,7 +70,7 @@ type codeExecArgs struct {// shape mirrors the Python tool's `content` / `_ERROR` / `actual_type`// fields so downstream nodes can pattern-match unchanged. Artifacts and// Attachments are surfaced for the model and downstream component-// consumption (e.g. Message component's artifact markdown formatter).+// consumption (e.g. Message component's artifact Markdown formatter).type codeExecResult struct {Content string `json:"content,omitempty"`ActualType string `json:"actual_type,omitempty"`@@ -184,7 +184,7 @@ func (c *CodeExecTool) InvokableRun(ctx context.Context, argumentsInJSON string,// surface it as `_ARTIFACTS` to match the Python envelope).// - Metadata["attachments"] → Attachments (rendered into// downstream Markdown by Message via the same path the Agent-// tool artifact markdown uses).+// tool artifact Markdown uses).//// Artifacts / Attachments with the wrong element type (anything// other than map[string]any) are silently dropped with a logdiff --git a/internal/agent/tool/code_exec_test.go b/internal/agent/tool/code_exec_test.goindex 369d34378a..c0e308e503 100644--- a/internal/agent/tool/code_exec_test.go+++ b/internal/agent/tool/code_exec_test.go@@ -159,7 +159,7 @@ func TestCodeExec_Info(t *testing.T) {// collection: SandboxResponse.Metadata["artifacts"] must be// surfaced as `_ARTIFACTS` in the tool's JSON envelope so the// Message-// component's artifact markdown formatter can render them.+// component's artifact Markdown formatter can render them.func TestCodeExec_ResultExtractsArtifacts(t *testing.T) {t.Parallel()@@ -222,7 +222,7 @@ func TestCodeExec_ResultDropsBadArtifactShape(t *testing.T) {}// TestCodeExec_ResultExtractsAttachments pins the attachments-// (rendered to downstream Message markdown) path. Distinct from+// (rendered to downstream Message Markdown) path. Distinct from// artifacts so renderers can route them differently.func TestCodeExec_ResultExtractsAttachments(t *testing.T) {t.Parallel()diff --git a/internal/agent/tool/wiki_query.go b/internal/agent/tool/wiki_query.goindex bd02c9a165..7b356ad6cd 100644--- a/internal/agent/tool/wiki_query.go+++ b/internal/agent/tool/wiki_query.go@@ -30,7 +30,7 @@ import (// WikiQueryTool is the wiki_query agent tool (Python harness/tools/exploration.py// wiki_query). It hybrid-searches the compiled wiki/artifact pages of the bound-// datasets and returns each page's rendered markdown as a chunk, narrowed by+// datasets and returns each page's rendered Markdown as a chunk, narrowed by// keywords. Input keeps query + keywords so the LLM's tool schema matches the// other search tools.//diff --git a/internal/cli/filesystem/skill.go b/internal/cli/filesystem/skill.goindex 9710075e98..4388031026 100644--- a/internal/cli/filesystem/skill.go+++ b/internal/cli/filesystem/skill.go@@ -1606,7 +1606,7 @@ func readSkillFiles(skillPath string) ([]*SkillFile, error) {return files, err}-// parseFrontmatter extracts YAML frontmatter from markdown content+// parseFrontmatter extracts YAML frontmatter from Markdown contentfunc parseFrontmatter(content string) (*SkillMetadata, error) {lines := strings.Split(content, "\n")diff --git a/internal/common/kg_query_rewrite.go b/internal/common/kg_query_rewrite.goindex 8bee01e596..a37e04b4e3 100644--- a/internal/common/kg_query_rewrite.go+++ b/internal/common/kg_query_rewrite.go@@ -133,7 +133,7 @@ func ParseQueryRewriteResponse(response string) (*QueryRewriteResult, error) {return result, nil}- // Fallback: try to extract JSON from markdown code blocks+ // Fallback: try to extract JSON from Markdown code blockscleaned := strings.TrimSpace(response)if idx := strings.Index(cleaned, "```"); idx >= 0 {rest := cleaned[idx+3:]diff --git a/internal/deepdoc/parser/pdf/layout/boxes_sections.go b/internal/deepdoc/parser/pdf/layout/boxes_sections.goindex 5b5cc73f35..a3424030c7 100644--- a/internal/deepdoc/parser/pdf/layout/boxes_sections.go+++ b/internal/deepdoc/parser/pdf/layout/boxes_sections.go@@ -101,13 +101,13 @@ func NormalizeSectionPositions(sections []pdf.Section) {}}-// SectionsToMarkdown converts Sections to a markdown string.+// SectionsToMarkdown converts Sections to a Markdown string.//// Title sections get a "## " prefix.// Figure sections produce an "" tag.// Text and all other sections are appended verbatim.//-// This mirrors the Python parser.py:665-671 markdown output path.+// This mirrors the Python parser.py:665-671 Markdown output path.func SectionsToMarkdown(sections []pdf.Section) string {var b strings.Builderfor _, s := range sections {diff --git a/internal/deepdoc/parser/pdf/parse_cgo.go b/internal/deepdoc/parser/pdf/parse_cgo.goindex 7299ddcae2..d48e9e4e9b 100644--- a/internal/deepdoc/parser/pdf/parse_cgo.go+++ b/internal/deepdoc/parser/pdf/parse_cgo.go@@ -15,7 +15,7 @@ import (// transfers ownership of it to the returned *pdf.ParseResult (result.Engine is// populated inside ParseRaw/processPages). The engine is intentionally kept// alive past Parse so the serialization step can still use it — most-// importantly the markdown path (cropMarkdownFigures) renders and crops figure+// importantly the Markdown path (cropMarkdownFigures) renders and crops figure// images on demand. Parse must therefore NOT close the engine itself.//// The caller (the adapter layer: pdfParseResultToJSONWithOptions /diff --git a/internal/deepdoc/parser/type/types.go b/internal/deepdoc/parser/type/types.goindex 486d331424..5c9f79d56f 100644--- a/internal/deepdoc/parser/type/types.go+++ b/internal/deepdoc/parser/type/types.go@@ -38,12 +38,12 @@ type ParseResult struct {DLARegions []DLAPageRegions// Engine is the native PDF backend used to lazily crop section- // images on demand (e.g. for markdown figure embeds or downstream+ // images on demand (e.g. for Markdown figure embeds or downstream// chunk-time cropping). It is populated by ParseRaw and carries// ownership of the engine: Parse does NOT close the engine, so the// caller must release it via Close once the result is fully// serialized. The JSON parse path closes it immediately after- // serialization; the markdown path crops figure images first, then+ // serialization; the Markdown path crops figure images first, then// closes. Close is idempotent and safe to call on a nil result.Engine PDFEngine}diff --git a/internal/engine/elasticsearch/kg_test.go b/internal/engine/elasticsearch/kg_test.goindex 6f83a4fa33..9e062a2c76 100644--- a/internal/engine/elasticsearch/kg_test.go+++ b/internal/engine/elasticsearch/kg_test.go@@ -19,7 +19,6 @@package elasticsearchimport (- "context""testing""ragflow/internal/common"@@ -51,8 +50,9 @@ func TestKGSearchSelectFields(t *testing.T) {SelectFields: []string{"entity_kwd", "entity_type_kwd", "rank_flt"},Limit: 10,}+ ctx := t.Context()- result, err := engine.Search(context.Background(), req)+ result, err := engine.Search(ctx, req)if err != nil {t.Fatalf("search failed: %v", err)}diff --git a/internal/entity/models/mineru_local.go b/internal/entity/models/mineru_local.goindex 18545c303a..da18d8cb59 100644--- a/internal/entity/models/mineru_local.go+++ b/internal/entity/models/mineru_local.go@@ -247,7 +247,7 @@ func (m *MinerULocalModel) ShowTask(ctx context.Context, taskID string, apiConfireturn nil, fmt.Errorf("missing results field")}- // Get markdown+ // Get Markdownfor _, fileObj := range results {fileMap, ok := fileObj.(map[string]interface{})diff --git a/internal/harness/core/middlewares/skill/doc.go b/internal/harness/core/middlewares/skill/doc.goindex ddcf980a43..b026e762e6 100644--- a/internal/harness/core/middlewares/skill/doc.go+++ b/internal/harness/core/middlewares/skill/doc.go@@ -6,6 +6,6 @@// - ForkWithContext: skill tools are loaded with context injection//// Skills can be loaded from:-// - FileSystemBackend: read skill definitions from markdown files+// - FileSystemBackend: read skill definitions from Markdown files// - Embedded content: inline skill definitionspackage skilldiff --git a/internal/ingestion/component/chunker/common.go b/internal/ingestion/component/chunker/common.goindex 69fbfa5b97..da6699e6fc 100644--- a/internal/ingestion/component/chunker/common.go+++ b/internal/ingestion/component/chunker/common.go@@ -90,8 +90,8 @@ func compileDelimPattern(delims []string) *regexp.Regexp {// (token_chunker.py:79-90). The captured delimiter is DISCARDED rather than// glued to a segment: re.split with a captured group keeps delimiters at odd// indices, and only the even-index (text) parts are kept. This is the-// behaviour every delimiter path (primary and children, text/markdown/html-// and json) must reproduce so a split chunk reads "first sentence here"+// behavior every delimiter path (primary and children, text/markdown/html+// and JSON) must reproduce so a split chunk reads "first sentence here"// without the trailing delimiter.func splitDroppingDelim(text string, pattern *regexp.Regexp) []string {if pattern == nil {diff --git a/internal/ingestion/component/chunker/custom_delim_test.go b/internal/ingestion/component/chunker/custom_delim_test.goindex 9ed9701b9a..341a8428e1 100644--- a/internal/ingestion/component/chunker/custom_delim_test.go+++ b/internal/ingestion/component/chunker/custom_delim_test.go@@ -5,15 +5,15 @@ import ("testing")-// custom_delim_test pins the backtick-wrapped newline delimiter behaviour of+// custom_delim_test pins the backtick-wrapped newline delimiter behavior of// TokenChunker against Python's rag/flow/chunker/token_chunker.py.//-// All delimiter paths (primary and children, text/markdown/html and json)+// All delimiter paths (primary and children, text/markdown/html and JSON)// must DROP the captured delimiter from each chunk's text, matching Python's// _split_text_by_pattern (token_chunker.py:79-90, used by both _build_json_chunks// and _split_chunk_docs_by_children). Go's splitDroppingDelim reproduces this.//-// The json primary path is the one most prone to regress: Python's+// The JSON primary path is the one most prone to regress: Python's// _build_json_chunks (token_chunker.py:121) splits each item through// _split_text_by_pattern, which keeps only the even-index (text) parts and// DISCARDS the captured delimiter. So a "first segment line one\n" item yields@@ -119,7 +119,7 @@ func TestCustomDelimMarkdownDropsDelimiter(t *testing.T) {"markdown": "# Title\n\nParagraph one.\n\nParagraph two.",}chunks := invokeTokenChunks(t, params, input)- // The upstream decode normalizes markdown block boundaries into the+ // The upstream decode normalizes Markdown block boundaries into the// backtick-newline delimiter, so the text path must split into exactly// three trimmed chunks with the delimiter dropped (no trailing newline).want := []string{"# Title", "Paragraph one.", "Paragraph two."}diff --git a/internal/ingestion/component/chunker/group.go b/internal/ingestion/component/chunker/group.goindex 51ba9d4691..6c87507300 100644--- a/internal/ingestion/component/chunker/group.go+++ b/internal/ingestion/component/chunker/group.go@@ -378,7 +378,7 @@ func mergePositionMatrix(sources ...json.RawMessage) [][]float64 {// python BaseTitleChunker.extract_line_records uses://// 1. If upstream emitted chunks (output_format == "chunks") OR-// upstream emitted JSON, normalise from the list payload.+// upstream emitted JSON, normalize from the list payload.// 2. Otherwise, treat text/markdown/html as a "one record per line"// stream (preserving indentation for non-text formats, strip-only// for the text format).diff --git a/internal/ingestion/component/chunker/image_upload.go b/internal/ingestion/component/chunker/image_upload.goindex 4c27f3a366..60a5928460 100644--- a/internal/ingestion/component/chunker/image_upload.go+++ b/internal/ingestion/component/chunker/image_upload.go@@ -122,7 +122,7 @@ func uploadOneImage(ctx context.Context, up component.ImageUploader, kbID, chunk// decodeChunkImage strips an optional data-URL prefix and base64-decodes the// payload. Chunker image payloads are "data:image/...;base64,<b64>" (pdfcrop,-// markdown, docx). A bare base64 string is also accepted.+// Markdown, docx). A bare base64 string is also accepted.func decodeChunkImage(s string) ([]byte, error) {if i := strings.Index(s, ";base64,"); i >= 0 {s = s[i+len(";base64,"):]diff --git a/internal/ingestion/component/chunker/title_test.go b/internal/ingestion/component/chunker/title_test.goindex 1ebce286c6..338748fd02 100644--- a/internal/ingestion/component/chunker/title_test.go+++ b/internal/ingestion/component/chunker/title_test.go@@ -106,7 +106,7 @@ func TestTitleChunker_InvokeEmptyInput(t *testing.T) {}// TestTitleChunker_Headings_ASCII is the golden-file parity check-// for the markdown detector: a # heading + body + ## subheading + body+// for the Markdown detector: a # heading + body + ## subheading + body// is recognized at least one chunked partition boundary.//// Note: the title strategy is dispatched to the underlying strategy@@ -149,7 +149,7 @@ func TestTitleChunker_Headings_ASCII(t *testing.T) {}// TestTitleChunker_NoHeadings_FallsBack feeds plain text without any-// markdown heading; the chunker should still produce a chunk+// Markdown heading; the chunker should still produce a chunk// containing the body text (single chunk fallback).func TestTitleChunker_NoHeadings_FallsBack(t *testing.T) {c, err := NewTitleChunker(map[string]any{diff --git a/internal/ingestion/component/chunker/token.go b/internal/ingestion/component/chunker/token.goindex 9b2b925411..de85340dae 100644--- a/internal/ingestion/component/chunker/token.go+++ b/internal/ingestion/component/chunker/token.go@@ -310,7 +310,7 @@ func cropTitleChunks(ctx context.Context, engine deepdoctype.PDFEngine, chunks [}// invokeTextPayload handles plain-text input (output_format in-// {markdown,text,html} on the python side).+// {Markdown,text,html} on the python side).func (c *TokenChunkerComponent) invokeTextPayload(_ context.Context, text string, delimPattern, childrenPattern *regexp.Regexp) map[string]any {if text == "" {return emptyOutputs()diff --git a/internal/ingestion/component/docx_vision_dispatch.go b/internal/ingestion/component/docx_vision_dispatch.goindex 24a71a0297..795ff1bb7e 100644--- a/internal/ingestion/component/docx_vision_dispatch.go+++ b/internal/ingestion/component/docx_vision_dispatch.go@@ -22,8 +22,8 @@// Unlike the PDF vision path (which replaces dispatchParse entirely),// DOCX vision is a post-processing step. It mirrors Python exactly:// vision enrichment happens ONLY on the JSON output path, where each-// item carries a doc_type_kwd and an optional image. The markdown path-// performs no vision enrichment in Python, so it must not here either.+// item carries a doc_type_kwd and an optional image. The Markdown path+// performs no vision enrichment in Python, so it must not be here either.package component@@ -73,8 +73,8 @@ var (// without an image (e.g. DOCX tables) are left untouched, exactly as Python// skips them via `if item.get("image") is None: continue`.//-// The markdown output path receives no vision enrichment — Python's DOCX-// markdown branch only concatenates text and never calls the vision model.+// The Markdown output path receives no vision enrichment — Python's DOCX+// Markdown branch only concatenates text and never calls the vision model.func maybeDispatchDOCXVision(ctx context.Context,db *gorm.DB,@@ -141,7 +141,7 @@ func maybeDispatchDOCXVision(return}// DOCX JSON items have no surrounding context (unlike the- // former markdown path), so use the bare figure prompt —+ // former Markdown path), so use the bare figure prompt —// matching Python's VisionFigureParser(context_size=0).prompt, perr := docxVisionPromptBuilder("", "")if perr != nil {diff --git a/internal/ingestion/component/docx_vision_dispatch_test.go b/internal/ingestion/component/docx_vision_dispatch_test.goindex 11d76ab4f3..4b38f74d7f 100644--- a/internal/ingestion/component/docx_vision_dispatch_test.go+++ b/internal/ingestion/component/docx_vision_dispatch_test.go@@ -135,9 +135,9 @@ func TestMaybeDispatchDOCXVision_EnhancesJSONImages(t *testing.T) {}}-// TestMaybeDispatchDOCXVision_JSONOnly verifies Diff 2.4: the markdown output+// TestMaybeDispatchDOCXVision_JSONOnly verifies Diff 2.4: the Markdown output// path must NOT be enhanced (Python's markdown/docx branch performs no vision-// enrichment). A markdown result with embedded figures is returned untouched.+// enrichment). A Markdown result with embedded figures is returned untouched.func TestMaybeDispatchDOCXVision_JSONOnly(t *testing.T) {origResolver := resolveTenantModelByTypeorigInvoker := visionChatInvokerdiff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.goindex 88f2eb9a89..177b31f8f1 100644--- a/internal/ingestion/component/extractor.go+++ b/internal/ingestion/component/extractor.go@@ -1510,11 +1510,11 @@ func substituteChunkPlaceholders(prompt string, ck map[string]any, chunkText str// tryParseJSONObject tries to parse s as a JSON object. Returns// (parsed, true) on success; (nil, false) on parse error or when-// s is not a JSON object. Trims common markdown code fences+// s is not a JSON object. Trims common Markdown code fences// (```json ... ```) before parsing.func tryParseJSONObject(s string) (map[string]any, bool) {trimmed := strings.TrimSpace(s)- // Strip a surrounding markdown code fence. Models commonly wrap JSON in+ // Strip a surrounding Markdown code fence. Models commonly wrap JSON in// ```json ... ``` (language tag on the opening line) but some emit the tag// on its own line (```\njson\n{...}); Python's json_repair tolerates both,// encoding/json does not, so we drop the fence and any bare leadingdiff --git a/internal/ingestion/component/extractor_test.go b/internal/ingestion/component/extractor_test.goindex 221cab3284..d10236d2b2 100644--- a/internal/ingestion/component/extractor_test.go+++ b/internal/ingestion/component/extractor_test.go@@ -317,7 +317,7 @@ func TestExtractorComponent_Invoke_KeepsJSONAsString(t *testing.T) {}// TestExtractorComponent_Invoke_KeepsJSONStringInFence verifies a JSON-// response wrapped in a markdown code fence is stored as the raw string —+// response wrapped in a Markdown code fence is stored as the raw string —// the code fence is not stripped on the field-extraction path (Python's// _generate_async returns the raw text untouched).func TestExtractorComponent_Invoke_KeepsJSONStringInFence(t *testing.T) {diff --git a/internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go b/internal/ingestion/component/knowledge_compiler/mindmap/mindmap.goindex eea837dd5d..b643f03f53 100644--- a/internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go+++ b/internal/ingestion/component/knowledge_compiler/mindmap/mindmap.go@@ -6,8 +6,8 @@// and shaped into the {"id","children"} mind-map tree. The tree emits as one// product per node with parent links.//-// Per PORT_PLAN.md the markdown source is the LLM's reply, NOT the source-// document markdown, so the Parser component is not reused.+// Per PORT_PLAN.md the Markdown source is the LLM's reply, NOT the source+// document Markdown, so the Parser component is not reused.package mindmapimport (diff --git a/internal/ingestion/component/knowledge_compiler/wiki/page.go b/internal/ingestion/component/knowledge_compiler/wiki/page.goindex d9e9df45bd..28cc60f203 100644--- a/internal/ingestion/component/knowledge_compiler/wiki/page.go+++ b/internal/ingestion/component/knowledge_compiler/wiki/page.go@@ -81,7 +81,7 @@ func refineFromPlan(ctx context.Context, deps common.Deps, llmID, plan string) (return resp.Content, nil}-// Section is one heading block parsed out of a wiki page's markdown body. The+// Section is one heading block parsed out of a wiki page's Markdown body. The// page itself is a separate product; sections live as children linked via// parent_id so the retrieval-side can scope queries to a section (e.g. user// asks "what does the page say about X?" and the SIDE picks the page + the X@@ -92,7 +92,7 @@ type Section struct {Content string // section body until the next heading of equal-or-lower depth}-// ParseOutline splits a wiki page's markdown body into a flat section list.+// ParseOutline splits a wiki page's Markdown body into a flat section list.// Headings are ATX style ("#", "##", ...). The page is treated as a single// implicit "preamble" section when it starts with non-heading text. The page// itself is *not* in the result; buildPageProducts emits it separately so@@ -171,7 +171,7 @@ func buildPageProducts(tenantID, docID, page string, sourceChunkIDs []string) []// buildWikiPageProducts turns multiple wiki page drafts into page + section// products. Each page result becomes one page product and one section product-// per heading in its markdown body.+// per heading in its Markdown body.func buildWikiPageProducts(tenantID, docID string, pages []wikiPageResult) []common.Product {if len(pages) == 0 {appcommon.Info("wiki: buildWikiPageProducts skipped (no refined pages)",@@ -273,7 +273,7 @@ func buildWikiPageProducts(tenantID, docID string, pages []wikiPageResult) []comreturn out}-// firstHeading returns the first markdown "# "-prefixed line, trimmed.+// firstHeading returns the first Markdown "# "-prefixed line, trimmed.func firstHeading(md string) string {for _, line := range strings.Split(md, "\n") {s := strings.TrimSpace(line)diff --git a/internal/ingestion/component/knowledge_compiler/wiki/wiki.go b/internal/ingestion/component/knowledge_compiler/wiki/wiki.goindex eeaa66779b..1a2097ddd6 100644--- a/internal/ingestion/component/knowledge_compiler/wiki/wiki.go+++ b/internal/ingestion/component/knowledge_compiler/wiki/wiki.go@@ -2307,7 +2307,7 @@ func transformWikiLinks(content, kbID string, pageTitles, slugToPageType map[str})// rawLinks counts the model-authored wikilinks in the source content. It// must be counted against content, not out: by this point every [[...]] has- // been rewritten to markdown, so counting on out would always report zero.+ // been rewritten to Markdown, so counting on out would always report zero.rawLinks := wikiWikilinkSimpleRe.FindAllString(content, -1)appcommon.Info("knowledge_compiler: transformWikiLinks resolved outlinks",zap.Int("raw_wikilinks", len(rawLinks)),diff --git a/internal/ingestion/component/knowledge_compiler/wiki/wiki_refine_test.go b/internal/ingestion/component/knowledge_compiler/wiki/wiki_refine_test.goindex a8bf19bedf..67710cf020 100644--- a/internal/ingestion/component/knowledge_compiler/wiki/wiki_refine_test.go+++ b/internal/ingestion/component/knowledge_compiler/wiki/wiki_refine_test.go@@ -11,7 +11,7 @@ import ("ragflow/internal/ingestion/component/knowledge_compiler/common")-// refineChatStub returns per-page markdown keyed by the page title in the+// refineChatStub returns per-page Markdown keyed by the page title in the// writer prompt so each page's result is distinct and deterministic.type refineChatStub struct{}diff --git a/internal/ingestion/component/markdown_vision_dispatch.go b/internal/ingestion/component/markdown_vision_dispatch.goindex 4eff26ec6f..a70a3e846d 100644--- a/internal/ingestion/component/markdown_vision_dispatch.go+++ b/internal/ingestion/component/markdown_vision_dispatch.go@@ -14,13 +14,13 @@// limitations under the License.//-// Markdown vision figure dispatch: enriches parsed markdown JSON+// Markdown vision figure dispatch: enriches parsed Markdown JSON// items with LLM-generated descriptions of embedded images,// mirroring Python's enhance_media_sections_with_vision in// rag/flow/parser/utils.py, called from the _markdown path.//// Unlike the DOCX vision path (which processes a separate figures-// array), markdown vision iterates over the JSON items produced by+// array), Markdown vision iterates over the JSON items produced by// MarkdownParser.ParseWithResult and enhances items whose// doc_type_kwd == "image" and whose "image" field contains a// base64-encoded image.@@ -43,7 +43,7 @@ var (markdownVisionConcurrency uint = 10)-// maybeDispatchMarkdownVision checks whether the markdown parse result+// maybeDispatchMarkdownVision checks whether the Markdown parse result// contains JSON items with embedded images and, when a vision model is// available, enriches those items with AI-generated figure descriptions.//diff --git a/internal/ingestion/component/media_dispatch_test.go b/internal/ingestion/component/media_dispatch_test.goindex 61dfdd4bf2..46213b657d 100644--- a/internal/ingestion/component/media_dispatch_test.go+++ b/internal/ingestion/component/media_dispatch_test.go@@ -357,7 +357,7 @@ func TestMaybeDispatchAudio_DefaultOutputFormatJson(t *testing.T) {}}-// TestMaybeDispatchMarkdownVision_EnhancesTables pins diff 2.5: markdown+// TestMaybeDispatchMarkdownVision_EnhancesTables pins diff 2.5: Markdown// vision enhancement must also process items whose doc_type_kwd is "table"// (Python checks {"image","table"} in parser/utils.py:181), not only "image".// Before the fix the table item was skipped and never sent to the VLM.diff --git a/internal/ingestion/component/parser.go b/internal/ingestion/component/parser.goindex 8155c2f028..18e3e1f73a 100644--- a/internal/ingestion/component/parser.go+++ b/internal/ingestion/component/parser.go@@ -42,7 +42,7 @@// - WHAT IS NOT YET PORTED://// - The Python component dispatches to 13 file-format branches-// (pdf, markdown, text&code, html, spreadsheet, slides, doc,+// (pdf, Markdown, text&code, html, spreadsheet, slides, doc,// docx, image, audio, video, email, epub) — see parser.py// function_map at line ~1273. The Go counterparts in// internal/parser/parser/ are SKELETONS that print to@@ -427,7 +427,7 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st// off the python family identifiers in schema.ParserParam.//// For most families the two forms coincide; the divergence- // exists for markdown ("md" vs "markdown") and slides+ // exists for Markdown ("md" vs "markdown") and slides// ("ppt"/"pptx" vs "slides") and is intentional — the python// ParserParam collapses the slide family into a single key.fileTypeExt := fileTypeFromInputs(inputs)diff --git a/internal/ingestion/component/parser_dispatch.go b/internal/ingestion/component/parser_dispatch.goindex f69ce9637f..50129474f5 100644--- a/internal/ingestion/component/parser_dispatch.go+++ b/internal/ingestion/component/parser_dispatch.go@@ -191,7 +191,7 @@ func dispatchParse(ctx context.Context, fileType utility.FileType, filename stri//// 1. inputs["file_type"] — explicit family hint from the upstream// File component. We accept either the extension ("md", "docx")-// or the python family name ("markdown"); both are normalised+// or the python family name ("markdown"); both are normalized// to the extension form via the pythonFamilyName / familyToExt// lookup tables below.// 2. inputs["file"].name — fall back to the filename so a caller@@ -382,7 +382,7 @@ func pagesFromDispatch(pages []schema.Page) [][]byte {// - output_format string — the dispatch's OutputFormat,// or "text" for the raw-text// fallback-// - json | markdown | text | html — the dispatched payload on+// - json | Markdown | text | html — the dispatched payload on// the matching family key (only// populated on a structured// dispatch)diff --git a/internal/ingestion/component/parser_dispatch_test.go b/internal/ingestion/component/parser_dispatch_test.goindex 3a355682bd..99fd7cb764 100644--- a/internal/ingestion/component/parser_dispatch_test.go+++ b/internal/ingestion/component/parser_dispatch_test.go@@ -61,7 +61,7 @@ func (c *captureSetupConfigurer) ConfigureFromSetup(setup map[string]any) {func TestDispatch_OutputFormatValidation_Allowed(t *testing.T) {param := schema.ParserParam{}.Defaults()setups := defaultSetups()- // Defaults already include markdown → {text, json}.+ // Defaults already include Markdown → {text, json}.c := &ParserComponent{Param: param, Setups: setups}out, err := c.Invoke(t.Context(), nil, map[string]any{@@ -100,14 +100,14 @@ func TestDispatch_OutputFormatValidation_Allowed(t *testing.T) {// TestDispatch_OutputFormatValidation_Rejection pins the// whitelist enforcement: a request for output_format=html on the-// markdown family is rejected because markdown's allowed list is+// Markdown family is rejected because Markdown's allowed list is// {text, json}. The component must surface this as a hard error// before any fallback so a misconfigured template cannot silently// degrade.func TestDispatch_OutputFormatValidation_Rejection(t *testing.T) {param := schema.ParserParam{}.Defaults()setups := defaultSetups()- // Override the markdown setup to ask for an unsupported format.+ // Override the Markdown setup to ask for an unsupported format.// The key is "markdown" (the python-side family identifier),// NOT "md" — utility.FileTypeMarkdown happens to be the string// "md" but the setup key is the family name. resolveOutputFormat@@ -347,7 +347,7 @@ func TestDispatch_PDFMarkdown_UsesConfiguredOutputFormat(t *testing.T) {if !ok || md == "" {t.Fatalf("markdown payload missing or empty: %T", out["markdown"])}- if _, ok := out["json"]; ok {+ if _, ok = out["json"]; ok {t.Fatalf("json payload must be absent for markdown output: %+v", out["json"])}}diff --git a/internal/ingestion/component/schema/chunker.go b/internal/ingestion/component/schema/chunker.goindex 782906b6ca..0e1ee3e629 100644--- a/internal/ingestion/component/schema/chunker.go+++ b/internal/ingestion/component/schema/chunker.go@@ -85,7 +85,7 @@ type ChunkerFromUpstream struct {// Python). Set when OutputFormat == "json".JSONResult []ChunkDoc `json:"json,omitempty"`- // MarkdownResult is the upstream markdown payload (alias "markdown").+ // MarkdownResult is the upstream Markdown payload (alias "markdown").// Set when OutputFormat == "markdown".MarkdownResult *string `json:"markdown,omitempty"`diff --git a/internal/ingestion/component/schema/parser.go b/internal/ingestion/component/schema/parser.goindex b74f59b4b7..d47ed57df9 100644--- a/internal/ingestion/component/schema/parser.go+++ b/internal/ingestion/component/schema/parser.go@@ -116,7 +116,7 @@ type ParserOutputs struct {// JSON holds the list of structured sections when output_format == "json".JSON []map[string]any `json:"json,omitempty"`- // Markdown holds the rendered markdown when output_format == "markdown".+ // Markdown holds the rendered Markdown when output_format == "markdown".Markdown string `json:"markdown,omitempty"`// Text holds the rendered plain text when output_format == "text".diff --git a/internal/ingestion/component/schema/schema_test.go b/internal/ingestion/component/schema/schema_test.goindex d9559b0e66..f3f7509e65 100644--- a/internal/ingestion/component/schema/schema_test.go+++ b/internal/ingestion/component/schema/schema_test.go@@ -150,7 +150,7 @@ func TestParserParamJSONRoundTrip(t *testing.T) {t.Errorf("expected allowed_output_format in JSON, got %s", data)}var decoded ParserParam- if err := json.Unmarshal(data, &decoded); err != nil {+ if err = json.Unmarshal(data, &decoded); err != nil {t.Fatalf("unmarshal: %v", err)}if got := decoded.AllowedOutputFormat["pdf"]; len(got) != 2 || got[0] != "json" || got[1] != "markdown" {@@ -364,11 +364,11 @@ func TestTokenizerFromUpstreamValidate(t *testing.T) {if err := (&TokenizerFromUpstream{OutputFormat: PayloadFormatChunks}).Validate(); err != nil {t.Fatalf("output_format=chunks should be valid, got %v", err)}- // output_format=markdown with no MarkdownResult -> error.+ // output_format=Markdown with no MarkdownResult -> error.if err := (&TokenizerFromUpstream{OutputFormat: PayloadFormatMarkdown}).Validate(); err == nil {t.Fatal("expected error for markdown without payload")}- // output_format=markdown with payload -> OK.+ // output_format=Markdown with payload -> OK.md := "# title"if err := (&TokenizerFromUpstream{OutputFormat: PayloadFormatMarkdown, MarkdownResult: &md}).Validate(); err != nil {t.Fatalf("markdown with payload should be valid, got %v", err)@@ -434,7 +434,7 @@ func TestTokenizerFromUpstreamJSONRoundTrip(t *testing.T) {if decoded.MarkdownResult == nil || *decoded.MarkdownResult != "# title" {t.Errorf("markdown round-trip mismatch: got %v", decoded.MarkdownResult)}- // Re-marshal the decoded and confirm we can read markdown back.+ // Re-marshal the decoded and confirm we can read Markdown back.data2, err := json.Marshal(decoded)if err != nil {t.Fatalf("re-marshal: %v", err)diff --git a/internal/ingestion/component/schema/tokenizer.go b/internal/ingestion/component/schema/tokenizer.goindex 429189c7f6..7f4e9de562 100644--- a/internal/ingestion/component/schema/tokenizer.go+++ b/internal/ingestion/component/schema/tokenizer.go@@ -60,7 +60,7 @@ type TokenizerFromUpstream struct {// JSONResult is the upstream structured JSON list (alias "json").JSONResult []ChunkDoc `json:"json,omitempty"`- // MarkdownResult is the upstream markdown payload (alias "markdown").+ // MarkdownResult is the upstream Markdown payload (alias "markdown").MarkdownResult *string `json:"markdown,omitempty"`// TextResult is the upstream plain-text payload (alias "text").diff --git a/internal/ingestion/task/debug_result_dsl_test.go b/internal/ingestion/task/debug_result_dsl_test.goindex 15ea52cd6e..90b812af5f 100644--- a/internal/ingestion/task/debug_result_dsl_test.go+++ b/internal/ingestion/task/debug_result_dsl_test.go@@ -401,7 +401,7 @@ func TestDeepCopy_MapSliceIsDeep(t *testing.T) {}// TestDetectFormat_Priority locks the format selection order-// (chunks > json > text > html > markdown) used to pick a component's payload+// (chunks > json > text > html > Markdown) used to pick a component's payload// key. A component that emits multiple recognized keys must surface the// highest-priority one, matching NormalizeChunks and the front-end tab render.func TestDetectFormat_Priority(t *testing.T) {diff --git a/internal/parser/parser/align_test.go b/internal/parser/parser/align_test.goindex d031f4f738..ac4f991c07 100644--- a/internal/parser/parser/align_test.go+++ b/internal/parser/parser/align_test.go@@ -60,7 +60,7 @@ func CollapseWhitespace() Normalizer {}// htmlTagRE matches an HTML tag so table/HTML markup can be ignored when-// comparing content across the two markdown libraries (goldmark vs+// comparing content across the two Markdown libraries (goldmark vs// Python-Markdown serialize tables differently but the cell text is the same).var htmlTagRE = regexp.MustCompile(`(?is)<[^>]+>`)@@ -68,7 +68,7 @@ var htmlTagRE = regexp.MustCompile(`(?is)<[^>]+>`)// visible text. Tags are replaced with a single space (not deleted) so// adjacent cell text does not fuse — e.g. "<td>A</td><td>B</td>" becomes// "A B" rather than "AB". CollapseWhitespace then folds the extra space.-// Used so table-markup differences between markdown libraries don't mask the+// Used so table-markup differences between Markdown libraries don't mask the// underlying content equivalence.func StripHTMLTags() Normalizer {return func(s string) string {@@ -77,17 +77,17 @@ func StripHTMLTags() Normalizer {}// Markdown-syntax regexes removed by StripMarkdownSyntax. The Python flow-// parser keeps raw markdown in its section text ("# Title", "- item",+// parser keeps raw Markdown in its section text ("# Title", "- item",// ``` fenced ```); the Go parser emits clean per-block text. These are// representation differences (PARSER_ALIGNMENT_HANDOFF.md §3.1), not content-// divergences, so the markdown alignment strips them before comparing.+// divergences, so the Markdown alignment strips them before comparing.var (mdHeaderRE = regexp.MustCompile(`(?m)^#{1,6}\s+`)mdListRE = regexp.MustCompile(`(?m)^\s*[-*+]\s+`)mdFenceRE = regexp.MustCompile("(?s)```[^\n]*\n(.*?)```"))-// StripMarkdownSyntax returns a Normalizer that removes markdown presentation+// StripMarkdownSyntax returns a Normalizer that removes Markdown presentation// characters (ATX headings, list bullets, fenced-code fences) from a section,// leaving the bare text. It must run before CollapseWhitespace because the// fence regex relies on the surrounding newlines.@@ -203,7 +203,7 @@ func LoadGolden(t *testing.T, path string) []map[string]any {return items}-// MarkdownAlignOptions returns the normalizer preset for markdown. The order+// MarkdownAlignOptions returns the normalizer preset for Markdown. The order// matters:// - StripMarkdownSyntax first: drops "#"/"-"/fenced-code markup that Python// keeps inline but Go parses out (relies on the surrounding newlines, so it@@ -218,7 +218,7 @@ func LoadGolden(t *testing.T, path string) []map[string]any {// inter-tag gaps of an HTML table, the space from delimiter replacement,// the newlines inside a fenced code block) into single spaces.//-// Reused by every markdown alignment test; other formats define their own+// Reused by every Markdown alignment test; other formats define their own// preset and share CompareAlignment.func MarkdownAlignOptions(delimiter string) AlignOptions {return AlignOptions{@@ -232,6 +232,6 @@ func MarkdownAlignOptions(delimiter string) AlignOptions {}}-// DefaultMarkdownDelimiter is the flow parser's default markdown delimiter+// DefaultMarkdownDelimiter is the flow parser's default Markdown delimiter// set, used when generating/loading the golden baseline.const DefaultMarkdownDelimiter = "\n!?;。;!?"diff --git a/internal/parser/parser/docx_ir.go b/internal/parser/parser/docx_ir.goindex 36fae673a8..5e28829f8d 100644--- a/internal/parser/parser/docx_ir.go+++ b/internal/parser/parser/docx_ir.go@@ -36,7 +36,7 @@ type DOCXFigure struct {Image string `json:"image"` // base64-encoded image bytesContextAbove string `json:"context_above"` // text before the image blockContextBelow string `json:"context_below"` // text after the image block- Marker string `json:"marker"` // substring to locate image position in markdown+ Marker string `json:"marker"` // substring to locate image position in Markdown}// --- office_oxide IR types (local copy, independent of deepdoc) ---@@ -349,7 +349,7 @@ func extractDOCXFiguresFromIR(irJSON string) []DOCXFigure {// Marker: text of the immediately preceding flat block,// used by the vision dispatcher to locate the image position- // in the rendered markdown for inline insertion.+ // in the rendered Markdown for inline insertion.for j := i - 1; j >= 0; j-- {if flat[j].text != "" {fig.Marker = flat[j].textdiff --git a/internal/parser/parser/docx_parser.go b/internal/parser/parser/docx_parser.goindex 4405b17096..e6c0972c53 100644--- a/internal/parser/parser/docx_parser.go+++ b/internal/parser/parser/docx_parser.go@@ -44,7 +44,7 @@ func NewDOCXParser() *DOCXParser {// ConfigureFromSetup implements parserSetupConfigurer, receiving the// DSL "docx" family setup map. The output_format key drives whether-// ParseWithResult produces JSON items (structured) or markdown.+// ParseWithResult produces JSON items (structured) or Markdown.func (p *DOCXParser) ConfigureFromSetup(setup map[string]any) {if p == nil || setup == nil {return@@ -120,12 +120,12 @@ func (p *DOCXParser) ParseWithResult(ctx context.Context, filename string, data}}- // Default / markdown path.+ // Default / Markdown path.md, err := doc.ToMarkdown()if err != nil {return ParseResult{Err: fmt.Errorf("docx to-markdown: %w", err)}}- // remove_header_footer on markdown: filter lines by exact match+ // remove_header_footer on Markdown: filter lines by exact match// (mirrors Python parser.py:923-926 split lines → filter → rejoin).if p.RemoveHeaderFooter {hfTexts := extractDOCXHeaderFooterTexts(data)@@ -141,8 +141,8 @@ func (p *DOCXParser) ParseWithResult(ctx context.Context, filename string, data}md = strings.Join(rebuilt, "\n")}- // remove_toc on markdown: split lines, filter, rejoin- // (mirrors Python parser.py:927-928 remove_toc_word on markdown).+ // remove_toc on Markdown: split lines, filter, rejoin+ // (mirrors Python parser.py:927-928 remove_toc_word on Markdown).if p.RemoveTOC && irErr == nil {outlines := extractDOCXOutlines(irJSON)lines := strings.Split(md, "\n")diff --git a/internal/parser/parser/markdown_parser.go b/internal/parser/parser/markdown_parser.goindex e41897d152..54175449f6 100644--- a/internal/parser/parser/markdown_parser.go+++ b/internal/parser/parser/markdown_parser.go@@ -37,7 +37,7 @@ import (// dataURIPrefix is the MIME prefix for data URI images.const dataURIPrefix = "data:image/"-// GoMarkdown is the lib_type identifier for the pure-Go markdown backend.+// GoMarkdown is the lib_type identifier for the pure-Go Markdown backend.const GoMarkdown = "go_markdown"// ssrfAllowLoopback lets tests exercise the HTTP image fetch path against a@@ -83,10 +83,10 @@ func (p *MarkdownParser) ConfigureFromSetup(setup map[string]any) {}// ParseWithResult implements ParseResultProducer (plan §6.5) and-// returns a structured markdown payload that mirrors the Python+// returns a structured Markdown payload that mirrors the Python// parser's `output_format == "json"` shape. Each top-level block// emits one item with `text` + `doc_type_kwd: "text"`. When the-// block contains a markdown image reference (), the image+// block contains a Markdown image reference (), the image// data is resolved and the item carries `doc_type_kwd: "image"` with// the base64-encoded image payload. The legacy debug-print path has// been removed; callers consume ParseResult directly.@@ -162,7 +162,7 @@ func renderMarkdownTablesInline(text string) (string, bool) {// Wrap the inlined <table> HTML in blank lines so gomarkdown// keeps it as a single HTML block (one item) instead of// re-parsing it into scattered cell text. See- // PARSER_ALIGNMENT_HANDOFF.md §3.1 (markdown session A, 方案 Y).+ // PARSER_ALIGNMENT_HANDOFF.md §3.1 (Markdown session A, 方案 Y).ensureTrailingBlankLine(&buf)buf.WriteString(strings.TrimRight(string(tableHTML), "\r\n"))buf.WriteString("\n\n")@@ -259,7 +259,7 @@ func markdownTableCells(line string) []string {// walkMarkdownBlocksWithImages emits one normalized item per// top-level block. Headings, paragraphs, lists, and code blocks are-// emitted with their text. When a block contains a markdown image+// emitted with their text. When a block contains a Markdown image// reference (), the image data is resolved via// findBlockImage (per-block AST walk) and the item carries// `doc_type_kwd: "image"` together with the base64-encoded image@@ -345,7 +345,7 @@ func walkMarkdownBlocksWithImages(doc ast.Node, out *[]map[string]any, flatten bitem["ck_type"] = ckType}- // Resolve markdown images from the AST node of THIS block only, so+ // Resolve Markdown images from the AST node of THIS block only, so// the image payload (and doc_type_kwd:"image") is attached to the// single block that actually contains the  reference.// Scanning the whole document (the old approach) wrongly tagged@@ -399,7 +399,7 @@ func findBlockImage(n ast.Node) (string, bool) {return url, found}-// resolveImageURL resolves a markdown image URL to its base64-encoded data.+// resolveImageURL resolves a Markdown image URL to its base64-encoded data.// Supports:// - data:image/... URIs → decoded directly// - http:// / https:// URLs → fetched (with basic SSRF filtering)@@ -536,7 +536,7 @@ func resolveAndValidateHost(host string) (net.IP, error) {return nil, fmt.Errorf("markdown: cannot resolve image host: %s", hostname)}for _, addr := range addrs {- ip := addr.IP+ ip = addr.IPif (ip.IsLoopback() && !ssrfAllowLoopback) || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||ip.IsPrivate() || ip.IsUnspecified() {return nil, fmt.Errorf("markdown: rejected image URL resolving to internal address: %s (%s)", host, ip)diff --git a/internal/parser/parser/markdown_parser_test.go b/internal/parser/parser/markdown_parser_test.goindex 34ab5693a3..82891932dd 100644--- a/internal/parser/parser/markdown_parser_test.go+++ b/internal/parser/parser/markdown_parser_test.go@@ -297,7 +297,7 @@ func TestFetchImageAsBase64_InvalidURL(t *testing.T) {}// TestMarkdownParser_TableNotCollapsed is the core regression guard for the-// markdown table fix (方案 Y): a document containing a GFM table must keep one+// Markdown table fix (方案 Y): a document containing a GFM table must keep one// item per top-level block instead of collapsing into one giant item, AND the// table must be emitted as a single raw <table>…</table> HTML block (not// scattered cell text), appearing both as an inlined text copy and as a@@ -526,8 +526,8 @@ func TestMarkdownParser_MultipleTablesOrdering(t *testing.T) {// TestMarkdownParser_AlignmentGolden verifies Go's ParseWithResult output is// content-equivalent to Python's _markdown on the shared sample, using the// shared concatenation-normalization alignment tool (align_test.go). Python-// keeps raw markdown and splits on the delimiter set; Go emits clean per-block-// text. The comparison normalizes both (markdown syntax, html tags, delimiters+// keeps raw Markdown and splits on the delimiter set; Go emits clean per-block+// text. The comparison normalizes both (Markdown syntax, html tags, delimiters// stripped; whitespace collapsed) and ignores "table"/"image" items, which are// accepted representation differences (PARSER_ALIGNMENT_HANDOFF.md §3.1).//diff --git a/internal/parser/parser/paddleocr.go b/internal/parser/parser/paddleocr.goindex 7ec242a231..633019a225 100644--- a/internal/parser/parser/paddleocr.go+++ b/internal/parser/parser/paddleocr.go@@ -358,7 +358,7 @@ func (c *PaddleOCRClient) extractImageText(resultLines []map[string]any) string}content, _ := blockMap["block_content"].(string)content = strings.TrimSpace(content)- // Remove markdown image blocks+ // Remove Markdown image blockscontent = removeMarkdownImages(content)if content != "" {texts = append(texts, content)diff --git a/internal/parser/parser/parse_result.go b/internal/parser/parser/parse_result.goindex 6dc642cdf8..a8b9cedd2a 100644--- a/internal/parser/parser/parse_result.go+++ b/internal/parser/parser/parse_result.go@@ -61,7 +61,7 @@ type ParseResult struct {// Shape depends on the parser family: PDF emits// `[]map[string]any` with `text` + `doc_type_kwd` keys (and// optional `image` / `layout` / `positions` fields);- // markdown / html / text emit normalized+ // Markdown / HTML / text emit normalized// `{text, doc_type_kwd}` items; image emits OCR/VLM result// items. Exactly one payload family is populated on success.JSON []map[string]anydiff --git a/internal/parser/parser/pdf_parser_common.go b/internal/parser/parser/pdf_parser_common.goindex 7de46ede7b..05b08d352f 100644--- a/internal/parser/parser/pdf_parser_common.go+++ b/internal/parser/parser/pdf_parser_common.go@@ -473,8 +473,8 @@ func sectionsToMarkdown(sections []deepdoctype.Section) string {}// cropMarkdownFigures crops inline images for figure sections so the-// markdown output can embed them. It mirrors the figure branch of the-// former Parse.fillSectionImages, but runs only for the markdown path+// Markdown output can embed them. It mirrors the figure branch of the+// former Parse.fillSectionImages, but runs only for the Markdown path// (the JSON path defers cropping to the chunker). The engine is read// from result.Engine; callers must Close the result afterwards.func cropMarkdownFigures(result *deepdoctype.ParseResult) {diff --git a/internal/parser/parser/pdf_postprocess.go b/internal/parser/parser/pdf_postprocess.goindex 969324d21b..7a0ff99b2f 100644--- a/internal/parser/parser/pdf_postprocess.go+++ b/internal/parser/parser/pdf_postprocess.go@@ -76,7 +76,7 @@ func assignPDFDocTypeKeywords(result *deepdoctype.ParseResult, flatten bool) {default:// doc_type_kwd is derived from layout, not from whether a// section image was cropped. Cropping happens lazily at- // markdown serialization / chunk time, so it must not+ // Markdown serialization / chunk time, so it must not// influence classification here (otherwise every positioned// text box would be mislabeled "image").section.DocTypeKwd = "text"diff --git a/internal/parser/parser/pdf_postprocess_test.go b/internal/parser/parser/pdf_postprocess_test.goindex f95bbd2128..dbb62bb12c 100644--- a/internal/parser/parser/pdf_postprocess_test.go+++ b/internal/parser/parser/pdf_postprocess_test.go@@ -50,7 +50,7 @@ func TestApplyPDFPostProcess_AssignsDocTypeKeywords(t *testing.T) {applyPDFPostProcess(result, pdfPostProcessOptions{})// doc_type_kwd is derived from layout type only. A pre-set Image no// longer reclassifies a section as "image" — cropping happens lazily- // at markdown serialization / chunk time (see pdf_parser_common.go).+ // at Markdown serialization / chunk time (see pdf_parser_common.go).want := []string{"table", "image", "text", "text"}for i, s := range result.Sections {if s.DocTypeKwd != want[i] {diff --git a/internal/service/chat_pipeline.go b/internal/service/chat_pipeline.goindex de24f100ec..29d46142e9 100644--- a/internal/service/chat_pipeline.go+++ b/internal/service/chat_pipeline.go@@ -2895,10 +2895,10 @@ func (s *ChatPipelineService) decorateAnswer(Answer: think + ans,Reference: refs,AudioBinary: audioBinary,- // Fix 7: Apply the markdown line-break substitution+ // Fix 7: Apply the Markdown line-break substitution// re.sub(r"\n", " \n", prompt) at the very end, matching// dialog_service.py:865. This converts single \n to " \n"- // so multi-line prompt text renders as a single markdown+ // so multi-line prompt text renders as a single Markdown// paragraph instead of being broken into separate lines.Prompt: strings.ReplaceAll(timeStats, "\n", " \n"),CreatedAt: float64(finishChatTs.Unix()),diff --git a/internal/service/chat_pipeline_test.go b/internal/service/chat_pipeline_test.goindex b47f974e26..e7c940babc 100644--- a/internal/service/chat_pipeline_test.go+++ b/internal/service/chat_pipeline_test.go@@ -830,7 +830,7 @@ func TestStripISOTimestamps(t *testing.T) {{"multiple", "x T01:02:03|y T04:05:06|z", "x |y |z"},{"no space before T", "abcT13:24:55|def", "abc|def"},{"empty", "", ""},- // Realistic markdown cell: |2024-01-15T13:24:55| → |2024-01-15|+ // Realistic Markdown cell: |2024-01-15T13:24:55| → |2024-01-15|{"realistic cell", "|2024-01-15T13:24:55|", "|2024-01-15|"},}for _, tc := range cases {diff --git a/internal/service/deep_researcher.go b/internal/service/deep_researcher.goindex 4593bd793c..6a8ae3f9e7 100644--- a/internal/service/deep_researcher.go+++ b/internal/service/deep_researcher.go@@ -682,14 +682,14 @@ func (dr *DeepResearcher) chatOnce(return *resp.Answer, nil}-// cleanLLMResponse strips think tags, markdown fences, and trailing backticks.+// cleanLLMResponse strips think tags, Markdown fences, and trailing backticks.var thinkTagRe = regexp.MustCompile(`(?s)^.*?</think>`)var trailingCommaRe = regexp.MustCompile(`,\s*([}\]])`)var cleanResponseRe = regexp.MustCompile(`(?s)(^.*?</think>|` + "```json\\n" + `|` + "```\\n*$" + `)`)var trailingBacktickRe = regexp.MustCompile("```\\n*$")func cleanLLMResponse(raw string) string {- // Strip think tags, markdown fences+ // Strip think tags, Markdown fencesraw = cleanResponseRe.ReplaceAllString(raw, "")// Also handle trailing ```` in case any remain after the regex passdiff --git a/internal/service/load_prompt.go b/internal/service/load_prompt.goindex 9da2e0e3c0..13df5570dd 100644--- a/internal/service/load_prompt.go+++ b/internal/service/load_prompt.go@@ -49,7 +49,7 @@ var (// rest of the response invisible to the caller.var thinkBlockRE = regexp.MustCompile(`^[\s\S]*</think>`)-// jsonFenceRE matches markdown code fences around JSON responses.+// jsonFenceRE matches Markdown code fences around JSON responses.// Mirrors Python's re.sub(r"(`{3}json\n|`{3}\n*$)", ..., flags=re.DOTALL).// Note: `\n*` is intentionally narrower than Go's `\s*` — Python only// matches newlines, not other whitespace, so a closing fence followeddiff --git a/internal/syncer/connector/github.go b/internal/syncer/connector/github.goindex ae48aebd24..7984c192c3 100644--- a/internal/syncer/connector/github.go+++ b/internal/syncer/connector/github.go@@ -723,7 +723,7 @@ func configBoolDefault(value any, fallback bool) bool {return fallback}-// sanitizeGitHubName mirrors Python's sanitized markdown filename intent.+// sanitizeGitHubName mirrors Python's sanitized Markdown filename intent.func sanitizeGitHubName(name, extension string) string {name = strings.TrimSpace(name)if name == "" {diff --git a/internal/utility/markdown_to_json.go b/internal/utility/markdown_to_json.goindex 7ea56c7ed0..73cccdfe06 100644--- a/internal/utility/markdown_to_json.go+++ b/internal/utility/markdown_to_json.go@@ -104,7 +104,7 @@ const (otherBlock)-// mdBlock is one markdown block in dictify terms: heading (level+text), list+// mdBlock is one Markdown block in dictify terms: heading (level+text), list// (flattened items), paragraph/fenced/other (text).type mdBlock struct {typ blockType@@ -117,7 +117,7 @@ type mdBlock struct {// lines (``` or ```lang) are removed before parsing.var fenceStripRE = regexp.MustCompile("```[^\\n]*")-// StripFences removes markdown code-fence marker lines from an LLM reply.+// StripFences removes Markdown code-fence marker lines from an LLM reply.func StripFences(s string) string {return fenceStripRE.ReplaceAllString(s, "")}@@ -422,7 +422,7 @@ func toBlock(n ast.Node, src []byte) mdBlock {}// headingRawText renders the heading's raw source line without the ATX-// markers, keeping inline markdown (e.g. asterisks) intact like CommonMark's+// markers, keeping inline Markdown (e.g. asterisks) intact like CommonMark's// block.strings (goldmark's inline text would strip emphasis). Both leading// and trailing '#' runs are removed (deviation #1 fixed: Python's CommonMark// strips the closing '#' sequence too).diff --git a/internal/utility/upload.go b/internal/utility/upload.goindex 585dc668b9..ea72cd1473 100644--- a/internal/utility/upload.go+++ b/internal/utility/upload.go@@ -110,7 +110,7 @@ func FetchRemoteFileSafelyWithTimeout(ctx context.Context, rawURL string, maxSiz// NormalizeUploadInfoContent normalizes an uploaded file's filename, content// type, and content bytes: detects PDF by magic bytes, converts HTML to-// readable markdown, and fixes the filename extension.+// readable Markdown, and fixes the filename extension.func NormalizeUploadInfoContent(filename, contentType string, data []byte) (string, string, []byte) {lowerCT := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))if lowerCT == "" {diff --git a/tools/gen-component-parity/main.go b/tools/gen-component-parity/main.goindex 8c644f283d..8f897a26ab 100644--- a/tools/gen-component-parity/main.go+++ b/tools/gen-component-parity/main.go@@ -9,7 +9,7 @@//// gen-component-parity is a small developer tool that walks the live Go-// component and tool registries and emits a markdown parity matrix for+// component and tool registries and emits a Markdown parity matrix for// docs/component-parity.md. It supersedes the manually-curated table// previously maintained in that file.//@@ -21,7 +21,7 @@// The tool imports the production packages (which trigger init()// registration of every component / tool factory) and reflects on each// registered entry's Name() / Inputs() / Outputs() (for components) or-// Info() (for tools). It then writes a markdown table to stdout.+// Info() (for tools). It then writes a Markdown table to stdout.//// Limitations://@@ -31,7 +31,7 @@// the structural inventory.// - Component factories that require non-empty params to construct// (e.g. Retrieval, ExeSQL) are skipped with a "⏭" annotation; their-// parity is captured in the hand-written matrix.+// parity is captured in the handwritten matrix.// - The script does not import cmd/server_main.go to avoid pulling// in the full boot path (Redis, MySQL, etc.).package maindiff --git a/tools/gen-component-parity/main_test.go b/tools/gen-component-parity/main_test.goindex 7f86f61698..b5ce06a9f4 100644--- a/tools/gen-component-parity/main_test.go+++ b/tools/gen-component-parity/main_test.go@@ -17,7 +17,7 @@ import ("testing")-// TestWriteMarkdown_SpotCheck pins the markdown output contract: it+// TestWriteMarkdown_SpotCheck pins the Markdown output contract: it// must enumerate both universes and surface at least one entry per// universe. The exhaustive list is owned by RegisteredNames() and// tool/registry.go — this test just guards against the structural