An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Resolve Go static-analysis diagnostics in the kernel
Jeffrey Chen92a7134682eb
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 9b927c7afe..d9782733a1 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -175,14 +175,19 @@ var toolSignatureKeys = map[string][]string{// buildDoomSignature 用 toolName + action + 关键参数构造死循环签名。func buildDoomSignature(name, action string, args map[string]any) string {var sig strings.Builder- sig.WriteString(name + "::action=" + action)+ sig.WriteString(name)+ sig.WriteString("::action=")+ sig.WriteString(action)for _, k := range toolSignatureKeys[name] {if v, ok := args[k]; ok {s := fmt.Sprint(v)if len(s) > 64 {s = s[:64] + "..."}- sig.WriteString("::" + k + "=" + s)+ sig.WriteString("::")+ sig.WriteString(k)+ sig.WriteString("=")+ sig.WriteString(s)}}return sig.String()@@ -553,7 +558,6 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagsendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: capabilityErr.Error()})return}- tools := capabilities.definitionsvar messages []openai.ChatCompletionMessagevar checkpointMsgs []AgentMessagevar contextMsgs []AgentMessage@@ -944,7 +948,6 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagroundCapabilities = &capabilitySet{registrations: map[string]*capabilityRegistration{}}}capabilities = roundCapabilities- tools = requestToolscontextMsgs = projectCompactionContext(checkpointMsgs, coveredMessages)messages = checkpointMessagesToOpenAIWithSummary(contextMsgs, language, capabilities, compaction, instructions.Content)if len(messages) > 0 && messages[0].Role == openai.ChatMessageRoleSystem {@@ -1603,13 +1606,6 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagsendCriticalEvent(ctx, ch, AgentEvent{Type: "done", TurnID: turn.TurnID})return}-- turn.TokenBreakdown = computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens)- if !saveTurn("finished") {- return- }- sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: turn.TokenBreakdown, CachedTokens: lastCachedTokens, ContextLimit: contextLimit})- sendCriticalEvent(ctx, ch, AgentEvent{Type: "done", TurnID: turn.TurnID})}()return ch@@ -2125,7 +2121,13 @@ func buildSystemPrompt(language string, capabilities *capabilitySet, instruction"Yes requires loading skill with source=builtin and name=siyuan-plugin-development BEFORE asking only materially missing details; No skips that skill and continues the user's custom approach. " +"Do not turn ordinary templates or existing capabilities into plugin work. Confirm a short proposal with workflow.action=plan before implementation; neither choice nor proposal authorizes installation or enabling. " +"Reuse the taskId for adjustments; use newTask only for a separate requested plugin and reconsider only when the user changes the choice.\n")- sb.WriteString("Official skill: " + html.EscapeString(builtin.ID) + " · " + html.EscapeString(builtin.Version) + " · " + html.EscapeString(builtin.Digest) + ". This entry requires the workflow question; generic skill matching does not activate it.")+ sb.WriteString("Official skill: ")+ sb.WriteString(html.EscapeString(builtin.ID))+ sb.WriteString(" · ")+ sb.WriteString(html.EscapeString(builtin.Version))+ sb.WriteString(" · ")+ sb.WriteString(html.EscapeString(builtin.Digest))+ sb.WriteString(". This entry requires the workflow question; generic skill matching does not activate it.")}}@@ -2213,9 +2215,9 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCtotalVisible := len(editorCtx.VisibleBlockIDs)if totalVisible > maxVisibleBlockIDs {sb.WriteString("Visible block ids (showing first ")- sb.WriteString(fmt.Sprintf("%d", maxVisibleBlockIDs))+ fmt.Fprintf(&sb, "%d", maxVisibleBlockIDs)sb.WriteString(" of ")- sb.WriteString(fmt.Sprintf("%d", totalVisible))+ fmt.Fprintf(&sb, "%d", totalVisible)sb.WriteString("):\n")} else {sb.WriteString("Visible block ids:\n")@@ -2448,7 +2450,7 @@ func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, languareturn msgs}-func checkpointMessagesToOpenAIResponseInput(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet,+func checkpointMessagesToOpenAIResponseInput(checkpointMsgs []AgentMessage, _ string, capabilities *capabilitySet,compaction *runtimeCompaction, downgradeImages bool) []any {var input []anyif compaction != nil {diff --git a/kernel/agent/compaction_context.go b/kernel/agent/compaction_context.goindex 192e737775..51a4c988ab 100644--- a/kernel/agent/compaction_context.go+++ b/kernel/agent/compaction_context.go@@ -132,9 +132,10 @@ func projectCompactionContext(messages []AgentMessage, covered int) []AgentMessa}index := 0for _, message := range messages {- if message.Role == "system" {+ switch message.Role {+ case "system":projected = append(projected, message)- } else if message.Role == "user" || message.Role == "assistant" {+ case "user", "assistant":if index >= covered {projected = append(projected, message)}diff --git a/kernel/agent/compaction_context_test.go b/kernel/agent/compaction_context_test.goindex b86c64ebe1..ca367c8ef9 100644--- a/kernel/agent/compaction_context_test.go+++ b/kernel/agent/compaction_context_test.go@@ -415,9 +415,10 @@ func TestAgentChatReusesOnlyCompatibleCompaction(t *testing.T) {t.Fatal(err)}model, provider := "test-model", "provider"- if name == "other-model" {+ switch name {+ case "other-model":model = "other-model"- } else if name == "other-provider" {+ case "other-provider":provider = "other-provider"}var summaries atomic.Int32diff --git a/kernel/agent/plugin_workflow.go b/kernel/agent/plugin_workflow.goindex 863e34a605..0996879874 100644--- a/kernel/agent/plugin_workflow.go+++ b/kernel/agent/plugin_workflow.go@@ -410,9 +410,10 @@ func handlePluginWorkflowQuestion(ctx context.Context, args map[string]any, sess}}questionKey, yesKey, noKey := "agentPluginFlowQuestion", "agentPluginFlowYes", "agentPluginFlowNo"- if action == "plan" {+ switch action {+ case "plan":questionKey, yesKey, noKey = "agentPluginPlanQuestion", "confirm", "cancel"- } else if action == "recover" {+ case "recover":questionKey, yesKey, noKey = "agentPluginRecoveryQuestion", "confirm", "cancel"}question, err := pluginWorkflowTerm(language, questionKey)@@ -438,7 +439,8 @@ func handlePluginWorkflowQuestion(ctx context.Context, args map[string]any, sessreturn errors.New("the official plugin development skill is disabled")}state := runtime.PluginWorkflow- if action == "choose" {+ switch action {+ case "choose":newTask, _ := workflow["newTask"].(bool)reconsider, _ := workflow["reconsider"].(bool)if state != nil && !newTask && !reconsider && state.Choice != "" &&@@ -455,7 +457,7 @@ func handlePluginWorkflowQuestion(ctx context.Context, args map[string]any, sessstate.Choice, state.Loaded, state.Approved, state.Paused = "", false, false, falsestate.RecoveryApproved = falsestate.SkillVersion, state.SkillDigest = info.Version, info.Digest- } else if action == "recover" {+ case "recover":if state == nil || state.TaskID != taskID || state.Choice != "yes" || !state.Loaded || state.Plan == nil ||state.SkillVersion != info.Version || state.SkillDigest != info.Digest {return errors.New("recovery requires the same loaded skill and a previously approved plugin proposal")@@ -463,7 +465,7 @@ func handlePluginWorkflowQuestion(ctx context.Context, args map[string]any, sessstate.Approved, state.Paused, state.RecoveryApproved = false, true, falsestate.RecoveryPlanHash = state.Plan.Hashquestion += "\n\n" + state.Plan.Display + "\n\n" + state.Plan.Hash- } else {+ default:if state == nil || state.TaskID != taskID || state.Choice != "yes" || !state.Loaded ||state.SkillVersion != info.Version || state.SkillDigest != info.Digest {return errors.New("choose the official workflow and load its current skill before proposing a plan")@@ -526,17 +528,18 @@ func handlePluginWorkflowQuestion(ctx context.Context, args map[string]any, sessreturn nil}accepted := answer.Answers[0] == yes- if action == "choose" {+ switch action {+ case "choose":state.Choice, state.ChoiceQuestionID = "no", questionIDif accepted {state.Choice = "yes"}- } else if action == "recover" {+ case "recover":if state.Plan == nil || state.Plan.Hash != state.RecoveryPlanHash {return errors.New("recovery proposal changed while awaiting confirmation")}state.RecoveryApproved, state.RecoveryQuestionID = accepted, questionID- } else {+ default:if state.PendingPlan == nil {return errors.New("plugin proposal snapshot is unavailable")}diff --git a/kernel/agent/session.go b/kernel/agent/session.goindex 35d8b57366..2c78314b11 100644--- a/kernel/agent/session.go+++ b/kernel/agent/session.go@@ -175,7 +175,7 @@ func ListSessions(page, pageSize int, keyword string) *SessionListResult {indexMu.Lock()index := loadSessionIndex()- if index == nil || len(index) == 0 {+ if len(index) == 0 {index = rebuildSessionIndex()}if index == nil {diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex d45bd6c083..e8596e8791 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -105,9 +105,10 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {}}id := docID- if name == "child" {+ switch name {+ case "child":id = tree.Root.FirstChild.ID- } else if name == "missing" {+ case "missing":id = ast.NewNodeID()}if name == "indexing" {diff --git a/kernel/api/contract_bazaar_reference_test.go b/kernel/api/contract_bazaar_reference_test.goindex ccd1e76021..71b390dbc2 100644--- a/kernel/api/contract_bazaar_reference_test.go+++ b/kernel/api/contract_bazaar_reference_test.go@@ -2,6 +2,7 @@ package apiimport ("errors"+"github.com/88250/gulu""github.com/siyuan-note/siyuan/kernel/bazaar""github.com/siyuan-note/siyuan/kernel/model"@@ -14,12 +15,6 @@ func bazaarPackageRatingsResponseData(ratings map[string]*bazaar.PackageRating,"eligiblePackageNames": eligiblePackageNames,}}-func bazaarPackageUserRatingsResponseData(userRatings map[string]int, eligiblePackageNames []string) map[string]any {- return map[string]any{- "userRatings": userRatings,- "eligiblePackageNames": eligiblePackageNames,- }-}func bazaarPackageRatingResponseData(rating *bazaar.PackageRating, ratingAvailable bool, userRating int) map[string]any {ret := map[string]any{"ratingAvailable": ratingAvailable,diff --git a/kernel/api/contract_block_remaining_test.go b/kernel/api/contract_block_remaining_test.goindex d877509442..0ed6a6eec4 100644--- a/kernel/api/contract_block_remaining_test.go+++ b/kernel/api/contract_block_remaining_test.go@@ -83,7 +83,7 @@ func testAPIContractRemainingBlockQueries(t *testing.T, engine *gin.Engine, boxIt.Fatal(err)}got.Timestamp = want.Timestamp- actualJSON, _ := json.Marshal(got)+ actualJSON, _ := json.Marshal(&got)wantJSON, _ := json.Marshal(want)if string(actualJSON) != string(wantJSON) {t.Fatalf("heading JSON changed: %s != %s", actualJSON, wantJSON)diff --git a/kernel/api/icon.go b/kernel/api/icon.goindex c1ab3fc997..4bb920a48a 100644--- a/kernel/api/icon.go+++ b/kernel/api/icon.go@@ -624,19 +624,19 @@ func generateTypeEightSVG(color, content string) string {isChinese := iconHanPattern.MatchString(content)var fontSize float64if isChinese {- switch {- case contentLen == 1:+ switch contentLen {+ case 1:fontSize = 320default:fontSize = 480 / float64(contentLen)}} else {- switch {- case contentLen == 1:+ switch contentLen {+ case 1:fontSize = 480- case contentLen == 2:+ case 2:fontSize = 300- case contentLen == 3:+ case 3:fontSize = 240default:fontSize = 750 / float64(contentLen)diff --git a/kernel/api/lute_clipboard_math.go b/kernel/api/lute_clipboard_math.goindex 3e41856599..9c56c6452e 100644--- a/kernel/api/lute_clipboard_math.go+++ b/kernel/api/lute_clipboard_math.go@@ -240,12 +240,22 @@ func normalizeOfficeHTMLOMML(fragment string) (normalized string, ok bool) {builder.WriteString("<w:p>")}mathStack = append(mathStack, value.Name.Local)- builder.WriteString("<m:" + value.Name.Local)+ builder.WriteString("<m:")+ builder.WriteString(value.Name.Local)for _, attr := range value.Attr {- if attr.Name.Space == officeHTMLOMMLNamespace || attr.Name.Space == docxOMMLNamespace {- builder.WriteString(` m:` + attr.Name.Local + `="` + html.EscapeString(attr.Value) + `"`)- } else if attr.Name.Space == "http://www.w3.org/XML/1998/namespace" {- builder.WriteString(` xml:` + attr.Name.Local + `="` + html.EscapeString(attr.Value) + `"`)+ switch attr.Name.Space {+ case officeHTMLOMMLNamespace, docxOMMLNamespace:+ builder.WriteString(` m:`)+ builder.WriteString(attr.Name.Local)+ builder.WriteString(`="`)+ builder.WriteString(html.EscapeString(attr.Value))+ builder.WriteString(`"`)+ case "http://www.w3.org/XML/1998/namespace":+ builder.WriteString(` xml:`)+ builder.WriteString(attr.Name.Local)+ builder.WriteString(`="`)+ builder.WriteString(html.EscapeString(attr.Value))+ builder.WriteString(`"`)}}builder.WriteByte('>')@@ -257,7 +267,9 @@ func normalizeOfficeHTMLOMML(fragment string) (normalized string, ok bool) {if localName != value.Name.Local {return "", false}- builder.WriteString("</m:" + localName + ">")+ builder.WriteString("</m:")+ builder.WriteString(localName)+ builder.WriteString(">")mathStack = mathStack[:len(mathStack)-1]if len(mathStack) == 0 {builder.WriteString("</w:p>")@@ -270,7 +282,9 @@ func normalizeOfficeHTMLOMML(fragment string) (normalized string, ok bool) {if mathStack[len(mathStack)-1] == "t" {builder.WriteString(html.EscapeString(content))} else if mathStack[len(mathStack)-1] == "r" && strings.TrimSpace(content) != "" {- builder.WriteString(`<m:t xml:space="preserve">` + html.EscapeString(content) + `</m:t>`)+ builder.WriteString(`<m:t xml:space="preserve">`)+ builder.WriteString(html.EscapeString(content))+ builder.WriteString(`</m:t>`)}}}diff --git a/kernel/api/lute_clipboard_style.go b/kernel/api/lute_clipboard_style.goindex 91413af67d..61a4d3e87f 100644--- a/kernel/api/lute_clipboard_style.go+++ b/kernel/api/lute_clipboard_style.go@@ -206,9 +206,10 @@ func filterClipboardStyle(style string, remove map[string]bool) string {quote = ccontinue}- if c == '(' {+ switch c {+ case '(':depth++- } else if c == ')' {+ case ')':depth--}if c != ';' || depth != 0 {diff --git a/kernel/apicontract/plugin_service_protocol.go b/kernel/apicontract/plugin_service_protocol.goindex ad9c05c9d0..cd6ee8929f 100644--- a/kernel/apicontract/plugin_service_protocol.go+++ b/kernel/apicontract/plugin_service_protocol.go@@ -167,7 +167,7 @@ func validatePluginServiceStatus(mode PluginServiceMode, status int) error {return nil}-func (b *Bundle) validatePluginServiceHTTPResponse(endpoint EndpointSchema, status int, contentType string, payload []byte) error {+func (b *Bundle) validatePluginServiceHTTPResponse(endpoint EndpointSchema, status int, _ string, payload []byte) error {if status < 100 || status > 999 {return fmt.Errorf("invalid plugin service HTTP status")}diff --git a/kernel/av/filter.go b/kernel/av/filter.goindex 55df38e13b..c63e870706 100644--- a/kernel/av/filter.go+++ b/kernel/av/filter.go@@ -1338,8 +1338,7 @@ func (value *Value) filter(other *Value, relativeDate, relativeDate2 *RelativeDacase KeyTypeRelation: // 过滤汇总字段,并且汇总目标是关联字段时才会进入该分支if nil != value.Relation && 0 < len(value.Relation.Contents) && nil != value.Relation.Contents[0].Block &&nil != other && nil != other.Relation && 0 < len(other.Relation.BlockIDs) {- filterValue := &Value{Type: KeyTypeBlock, Block: &ValueBlock{Content: other.Relation.BlockIDs[0]}}- return filterTextContent(operator, value.Relation.Contents[0].Block.Content, filterValue.Block.Content)+ return filterTextContent(operator, value.Relation.Contents[0].Block.Content, other.Relation.BlockIDs[0])}}return falsediff --git a/kernel/av/number_calc_test.go b/kernel/av/number_calc_test.goindex af8a0b897d..0b5cea29b9 100644--- a/kernel/av/number_calc_test.go+++ b/kernel/av/number_calc_test.go@@ -185,7 +185,7 @@ func TestDecimalSumNonFinite(t *testing.T) {}func BenchmarkDecimalSum(b *testing.B) {- for i := 0; i < b.N; i++ {+ for b.Loop() {var sum decimalSumfor range 10000 {sum.add(0.1)diff --git a/kernel/av/sort.go b/kernel/av/sort.goindex 00f59e008b..ba1d57c6bb 100644--- a/kernel/av/sort.go+++ b/kernel/av/sort.go@@ -191,12 +191,13 @@ func (value *Value) compare(other *Value, optionSort map[string]int, dateEndpoin}case KeyTypeText:if nil != value.Text && nil != other.Text {- if "" == value.Text.Content {+ switch "" {+ case value.Text.Content:if "" == other.Text.Content {return 0}return 1- } else if "" == other.Text.Content {+ case other.Text.Content:return -1}@@ -324,24 +325,26 @@ func (value *Value) compare(other *Value, optionSort map[string]int, dateEndpoin}case KeyTypeURL:if nil != value.URL && nil != other.URL {- if "" == value.URL.Content {+ switch "" {+ case value.URL.Content:if "" == other.URL.Content {return 0}return 1- } else if "" == other.URL.Content {+ case other.URL.Content:return -1}return strings.Compare(value.URL.Content, other.URL.Content)}case KeyTypeEmail:if nil != value.Email && nil != other.Email {- if "" == value.Email.Content {+ switch "" {+ case value.Email.Content:if "" == other.Email.Content {return 0}return 1- } else if "" == other.Email.Content {+ case other.Email.Content:return -1}return strings.Compare(value.Email.Content, other.Email.Content)@@ -360,12 +363,13 @@ func (value *Value) compare(other *Value, optionSort map[string]int, dateEndpoinreturn strings.Compare(left, right)case KeyTypePhone:if nil != value.Phone && nil != other.Phone {- if "" == value.Phone.Content {+ switch "" {+ case value.Phone.Content:if "" == other.Phone.Content {return 0}return 1- } else if "" == other.Phone.Content {+ case other.Phone.Content:return -1}return strings.Compare(value.Phone.Content, other.Phone.Content)diff --git a/kernel/av/value_location_test.go b/kernel/av/value_location_test.goindex 2c5ac84466..a0a106eaf7 100644--- a/kernel/av/value_location_test.go+++ b/kernel/av/value_location_test.go@@ -7,9 +7,6 @@ import ("testing")-//go:fix inline-func locationCoordinate(value float64) *float64 { return new(value) }-func TestLocationValueValidationAndDisplay(t *testing.T) {for _, test := range []struct {name stringdiff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.goindex 1ee8436143..90eb2ba036 100644--- a/kernel/av/value_text_test.go+++ b/kernel/av/value_text_test.go@@ -35,7 +35,11 @@ func TestValueTextRichEmptyParagraphs(t *testing.T) {for _, paragraphs := range [][]string{{"", ""}, {"", "first", "", "", "last", ""}} {var dom strings.Builderfor _, content := range paragraphs {- dom.WriteString(`<div data-node-id="` + ast.NewNodeID() + `" data-type="NodeParagraph"><div contenteditable="true">` + content + `</div></div>`)+ dom.WriteString(`<div data-node-id="`)+ dom.WriteString(ast.NewNodeID())+ dom.WriteString(`" data-type="NodeParagraph"><div contenteditable="true">`)+ dom.WriteString(content)+ dom.WriteString(`</div></div>`)}rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown,Content: valueTextRichBlockDOM2Kramdown(newValueTextRichLute(), dom.String())}diff --git a/kernel/cli/cmd/block.go b/kernel/cli/cmd/block.goindex ddf24285f2..4321382d97 100644--- a/kernel/cli/cmd/block.go+++ b/kernel/cli/cmd/block.go@@ -534,9 +534,9 @@ var blockBatchKramdownCmd = &cobra.Command{var sb strings.Builderfor _, id := range ids {if kd, ok := kramdowns[id]; ok {- sb.WriteString(fmt.Sprintf("--- %s ---\n%s\n\n", id, kd))+ fmt.Fprintf(&sb, "--- %s ---\n%s\n\n", id, kd)} else {- sb.WriteString(fmt.Sprintf("--- %s ---\n(not found)\n\n", id))+ fmt.Fprintf(&sb, "--- %s ---\n(not found)\n\n", id)}}fmt.Print(sb.String())diff --git a/kernel/cli/cmd/outline.go b/kernel/cli/cmd/outline.goindex 63f3390103..71873c34d1 100644--- a/kernel/cli/cmd/outline.go+++ b/kernel/cli/cmd/outline.go@@ -52,7 +52,7 @@ var outlineGetCmd = &cobra.Command{fmt.Println(string(data))default:var sb strings.Builder- sb.WriteString(fmt.Sprintf("Document outline (%d headings):\n\n", countOutlineHeadings(paths)))+ fmt.Fprintf(&sb, "Document outline (%d headings):\n\n", countOutlineHeadings(paths))for _, p := range paths {writeOutlinePath(&sb, p, 0)}@@ -86,7 +86,7 @@ func countOutlineBlockChildren(b *model.Block) int {func writeOutlinePath(sb *strings.Builder, p *model.Path, depth int) {prefix := strings.Repeat(" ", depth)- sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, p.Name, p.ID, p.Depth))+ fmt.Fprintf(sb, "%s- [%s] (id: %s, depth: %d)\n", prefix, p.Name, p.ID, p.Depth)for _, b := range p.Blocks {writeOutlineBlock(sb, b, depth+1)}@@ -97,7 +97,7 @@ func writeOutlinePath(sb *strings.Builder, p *model.Path, depth int) {func writeOutlineBlock(sb *strings.Builder, b *model.Block, depth int) {prefix := strings.Repeat(" ", depth)- sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, b.Content, b.ID, b.Depth))+ fmt.Fprintf(sb, "%s- [%s] (id: %s, depth: %d)\n", prefix, b.Content, b.ID, b.Depth)for _, c := range b.Children {writeOutlineBlock(sb, c, depth+1)}diff --git a/kernel/cli/cmd/search.go b/kernel/cli/cmd/search.goindex 26088b5d34..639bee022d 100644--- a/kernel/cli/cmd/search.go+++ b/kernel/cli/cmd/search.go@@ -169,7 +169,7 @@ func printAssetSearchResult(assetContents []*model.AssetContent, matchedAssetCou(page-1)*pageSize+1, (page-1)*pageSize+len(assetContents), matchedAssetCount, pageCount)}-func printSearchResult(blocks []*model.Block, matchedBlockCount, matchedRootCount, pageCount int, docMode bool, page, pageSize, groupBy int) {+func printSearchResult(blocks []*model.Block, matchedBlockCount, matchedRootCount, pageCount int, _ bool, page, pageSize, groupBy int) {if len(blocks) == 0 {fmt.Println("No results found.")returndiff --git a/kernel/conf/flashcard.go b/kernel/conf/flashcard.goindex 84579427e2..dcf706ea79 100644--- a/kernel/conf/flashcard.go+++ b/kernel/conf/flashcard.go@@ -64,7 +64,7 @@ func DefaultFSRSWeights() string {buf := bytes.Buffer{}defaultWs := fsrs.DefaultWeights()for i, w := range defaultWs {- buf.WriteString(fmt.Sprintf("%v", w))+ fmt.Fprintf(&buf, "%v", w)if i < len(defaultWs)-1 {buf.WriteString(", ")}diff --git a/kernel/conf/search.go b/kernel/conf/search.goindex b0c24ffd62..7b57a179bb 100644--- a/kernel/conf/search.go+++ b/kernel/conf/search.go@@ -148,13 +148,16 @@ func (s *Search) NAMFilter(keyword string) string {pattern := SearchLikePattern(strings.TrimSpace(keyword))buf := bytes.Buffer{}if s.Name {- buf.WriteString(" OR name LIKE " + pattern)+ buf.WriteString(" OR name LIKE ")+ buf.WriteString(pattern)}if s.Alias {- buf.WriteString(" OR alias LIKE " + pattern)+ buf.WriteString(" OR alias LIKE ")+ buf.WriteString(pattern)}if s.Memo {- buf.WriteString(" OR memo LIKE " + pattern)+ buf.WriteString(" OR memo LIKE ")+ buf.WriteString(pattern)}return buf.String()}diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.goindex ea99e72ced..1fb8f3eaf5 100644--- a/kernel/filesys/crypto_hook.go+++ b/kernel/filesys/crypto_hook.go@@ -128,20 +128,6 @@ func SyAAD(boxID, relativePath string) (string, error) {return "siyuan:file:" + boxID + ":" + base, nil}-// encryptedBox 判断 boxID 是否为已解锁的加密 box,供 filesys 内部分流(如静默修正禁用)。-// 通过 DEKProvider 探测:返回非 nil dek 即加密且已解锁。-func encryptedBox(boxID string) bool {- if DEKProvider == nil {- return false- }- if DEKLockAcquire != nil {- DEKLockAcquire(boxID)- defer DEKLockRelease(boxID)- }- dek, err := DEKProvider(boxID)- return err == nil && dek != nil-}-// docIALBoxID 从 .sy 绝对路径反推 boxID,供 DocIAL 判断是否需整体解密。// 路径形如 <DataDir>/<boxID>/...;若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。func docIALBoxID(absPath string) string {diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.goindex 9de96b98f4..db11c9144d 100644--- a/kernel/harmony/kernel.go+++ b/kernel/harmony/kernel.go@@ -252,8 +252,7 @@ func Unzip(zipFilePath, destination *C.char) {func GetExportFilePath(exportPath *C.char) *C.char {pathStr := C.GoString(exportPath)var absPath string- if strings.HasPrefix(pathStr, "/export/") {- fileName := strings.TrimPrefix(pathStr, "/export/")+ if fileName, ok := strings.CutPrefix(pathStr, "/export/"); ok {if decoded, err := url.PathUnescape(fileName); err == nil {fileName = decoded}diff --git a/kernel/heif/internal/h265heic/grid.go b/kernel/heif/internal/h265heic/grid.goindex 8cc7fc0828..67bd5feb1f 100644--- a/kernel/heif/internal/h265heic/grid.go+++ b/kernel/heif/internal/h265heic/grid.go@@ -371,27 +371,6 @@ func planes16(src, dst *hevc.Picture, pl int) ([]uint16, []uint16) {}}-// gridAlpha assembles a grid's alpha from the auxiliary items on its tiles.-func (f *file) gridAlpha(it *item) (*hevc.Picture, error) {- g, tiles, err := f.gridOf(it)- if err != nil {- return nil, err- }-- alpha := make([]uint32, len(tiles))-- for i, id := range tiles {- a := f.alphaOf(id)- if a == nil {- return nil, nil- }-- alpha[i] = a.id- }-- return f.decodeTiles(g, alpha)-}-func (f *file) hasAlpha(it *item) (bool, error) {if it.typ != "grid" {return f.alphaOf(it.id) != nil, nildiff --git a/kernel/heif/internal/h265heic/heic.go b/kernel/heif/internal/h265heic/heic.goindex c1506a8e57..adb8e7d042 100644--- a/kernel/heif/internal/h265heic/heic.go+++ b/kernel/heif/internal/h265heic/heic.go@@ -223,65 +223,6 @@ func srcFor(r io.Reader) (*source, error) {return memSource(data), nil}-// parseHeader reads only the boxes a configuration needs and stops as soon as-// one can be derived, so a stream that cannot be addressed by range still-// costs no more than its header.-func parseHeader(r io.Reader) (*file, error) {- f := &file{}-- seen := false-- err := eachBoxReader(r, func(typ string, n int64, body io.Reader) error {- switch typ {- case "ftyp":- seen = true-- case "meta":- if f.meta != nil {- return nil- }-- b, err := boxBytes(body, n)- if err != nil {- return err- }-- m, err := parseMeta(b)- if err != nil {- return err- }-- f.meta = m-- case "moov":- return ErrUnsupported-- default:- return nil- }-- // Only a configuration from the primary item ends the walk. A picture- // track is the fallback for a file that has no usable image item, and- // a meta box after moov would still outrank it.- if seen {- if _, err := f.config(); err == nil {- return errStop- }- }-- return nil- })- if err != nil && !errors.Is(err, errStop) {- return nil, err- }-- if !seen || f.meta == nil {- return nil, ErrInvalid- }-- return f, nil-}-// config is the image configuration of the primary item, or of the picture// track when a file carries no image item.func (f *file) config() (image.Config, error) {diff --git a/kernel/heif/internal/h265heic/image.go b/kernel/heif/internal/h265heic/image.goindex 11f2736635..a6fa560504 100644--- a/kernel/heif/internal/h265heic/image.go+++ b/kernel/heif/internal/h265heic/image.go@@ -7,11 +7,11 @@ import ("github.com/gen2brain/h265/hevc")-func colorModelFor(f *file, it *item) color.Model {+func colorModelFor(_ *file, _ *item) color.Model {return color.NRGBAModel}-func (f *file) colorInfo(it *item, pic *hevc.Picture) ColorInfo {+func (f *file) colorInfo(it *item, _ *hevc.Picture) ColorInfo {ci := ColorInfo{Matrix: mcUnspec, Primaries: 2, Transfer: 2}p := f.meta.prop(it, "colr")diff --git a/kernel/heif/internal/h265heic/isobmff.go b/kernel/heif/internal/h265heic/isobmff.goindex 87e1a899b3..a8ddccbdeb 100644--- a/kernel/heif/internal/h265heic/isobmff.go+++ b/kernel/heif/internal/h265heic/isobmff.go@@ -347,102 +347,6 @@ func (s *source) eachBox(fn func(typ string, off, n uint64) error) error {return nil}-// maxHeaderBox bounds a box eachBoxReader buffers, since its size comes from-// the file being read.-const maxHeaderBox = maxMetadataBytes--// errStop ends a walk from inside the callback.-var errStop = errors.New("heic: stop")--// eachBoxReader walks the top-level boxes of a stream. fn reads as much of a-// box as it wants from body, whose length is n, or -1 when the box runs to the-// end of the file; the rest is discarded before the next box. Boxes fn does-// not read are never buffered, so a caller after the header alone does not pay-// for the media data behind it.-func eachBoxReader(r io.Reader, fn func(typ string, n int64, body io.Reader) error) error {- var hdr [16]byte- count := 0-- for {- count++- if count > maxTopLevelBoxes {- return ErrUnsupported- }- // A short read at a box boundary is the end of the walk, which is- // what the in-memory form does with a trailing partial header.- if _, err := io.ReadFull(r, hdr[:8]); err != nil {- if err == io.EOF || err == io.ErrUnexpectedEOF {- return nil- }-- return ErrInvalid- }-- size := uint64(hdr[0])<<24 | uint64(hdr[1])<<16 | uint64(hdr[2])<<8 | uint64(hdr[3])- typ := string(hdr[4:8])- head := uint64(8)-- if size == 1 {- if _, err := io.ReadFull(r, hdr[8:16]); err != nil {- return ErrInvalid- }-- size = 0- for _, b := range hdr[8:16] {- size = size<<8 | uint64(b)- }-- head = 16- }-- n := int64(-1)- if size != 0 {- if size < head {- return ErrInvalid- }-- n = int64(size - head)- }-- body := &io.LimitedReader{R: r, N: maxHeaderBox}- if n >= 0 {- body.N = n- }-- err := fn(typ, n, body)-- if _, derr := io.Copy(io.Discard, body); derr != nil {- return ErrInvalid- }-- if err != nil {- return err- }-- if n < 0 {- return nil- }- }-}--// boxBytes reads a whole box payload, refusing one too large to be a header.-func boxBytes(body io.Reader, n int64) ([]byte, error) {- if n < 0 {- return io.ReadAll(body)- }-- if n > maxHeaderBox {- return nil, ErrInvalid- }-- b := make([]byte, n)- if _, err := io.ReadFull(body, b); err != nil {- return nil, ErrInvalid- }-- return b, nil-}-func parseMeta(payload []byte) (*metaBox, error) {r := &reader{b: payload}r.fullBox()diff --git a/kernel/heif/internal/h265heic/transform.go b/kernel/heif/internal/h265heic/transform.goindex 8ced951d1d..d02107d19e 100644--- a/kernel/heif/internal/h265heic/transform.go+++ b/kernel/heif/internal/h265heic/transform.go@@ -39,44 +39,6 @@ func (r *raw) at(x, y int) []byte {return r.pix[o : o+r.psize]}-func (r *raw) crop(x, y, w, h int) *raw {- out := r.alloc(w, h)- for j := range h {- copy(out.pix[j*out.stride:][:w*r.psize], r.at(x, y+j)[:w*r.psize])- }-- return out-}--// rotate turns the image anti-clockwise by angle quarter turns.-func (r *raw) rotate(angle int) *raw {- if angle == 0 {- return r- }- w, h := r.w, r.h- if angle&1 != 0 {- w, h = h, w- }- out := r.alloc(w, h)-- for j := range r.h {- for i := range r.w {- var dx, dy int- switch angle {- case 1:- dx, dy = j, r.w-1-i- case 2:- dx, dy = r.w-1-i, r.h-1-j- default:- dx, dy = r.h-1-j, i- }- copy(out.at(dx, dy), r.at(i, j))- }- }-- return out-}-func (r *raw) mirror(axis int) *raw {if axis == 0 {for y := range r.h / 2 {diff --git a/kernel/mcp/client/http_protocol_test.go b/kernel/mcp/client/http_protocol_test.goindex eacf0e8b15..27c10140e2 100644--- a/kernel/mcp/client/http_protocol_test.go+++ b/kernel/mcp/client/http_protocol_test.go@@ -107,16 +107,17 @@ func TestMCPHTTPModernProtocol(t *testing.T) {case "server/discover":result = map[string]any{"supportedVersions": []string{version}, "capabilities": test.capabilities}case "tools/list":- if request.Params.Cursor == "" {+ switch request.Params.Cursor {+ case "":result = map[string]any{"tools": []any{}, "nextCursor": "page-2"}- } else if request.Params.Cursor == "page-2" {+ case "page-2":result = map[string]any{"tools": []any{map[string]any{"name": toolName,"inputSchema": map[string]any{"type": "object", "properties": map[string]any{"query": map[string]any{"type": "string", "x-mcp-header": "Query"},}},}}}- } else {+ default:t.Errorf("unexpected cursor: %q", request.Params.Cursor)}case "tools/call":diff --git a/kernel/mcp/tools/asset.go b/kernel/mcp/tools/asset.goindex e12bc0158a..4403662eef 100644--- a/kernel/mcp/tools/asset.go+++ b/kernel/mcp/tools/asset.go@@ -194,14 +194,14 @@ func htmlAssetIFrameBlockDOM(assetPath string) (dom, blockID string, err error)func newAssetUploadToolResult(succeeded []model.AssetUploadSuccess, failed []model.AssetUploadFailure) CallToolResult {var sb strings.Builder- sb.WriteString(fmt.Sprintf("Uploaded %d file(s):\n", len(succeeded)))+ fmt.Fprintf(&sb, "Uploaded %d file(s):\n", len(succeeded))for _, result := range succeeded {- sb.WriteString(fmt.Sprintf("- %s -> %s\n", result.Name, result.Path))+ fmt.Fprintf(&sb, "- %s -> %s\n", result.Name, result.Path)}if 0 < len(failed) {- sb.WriteString(fmt.Sprintf("\nFailed %d file(s):\n", len(failed)))+ fmt.Fprintf(&sb, "\nFailed %d file(s):\n", len(failed))for _, result := range failed {- sb.WriteString(fmt.Sprintf("- %s: %s\n", result.Name, result.Error))+ fmt.Fprintf(&sb, "- %s: %s\n", result.Name, result.Error)}}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}, IsError: 0 < len(failed)}@@ -246,7 +246,7 @@ func validateAssetUploadPaths(fileList []string) ([]string, error) {return fileList, nil}-func assetUnused(args map[string]any) (CallToolResult, error) {+func assetUnused(_ map[string]any) (CallToolResult, error) {items, err := model.UnusedAssets(true)if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nil@@ -255,9 +255,9 @@ func assetUnused(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no unused assets found"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Unused assets (%d):\n\n", len(items)))+ fmt.Fprintf(&sb, "Unused assets (%d):\n\n", len(items))for _, item := range items {- sb.WriteString(fmt.Sprintf("- %s (%s)\n", item.Item, item.Name))+ fmt.Fprintf(&sb, "- %s (%s)\n", item.Item, item.Name)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -283,9 +283,9 @@ func assetClean(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no unused assets to clean"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Removed %d asset(s):\n\n", len(removed)))+ fmt.Fprintf(&sb, "Removed %d asset(s):\n\n", len(removed))for _, p := range removed {- sb.WriteString(fmt.Sprintf("- %s\n", p))+ fmt.Fprintf(&sb, "- %s\n", p)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/mcp/tools/attr.go b/kernel/mcp/tools/attr.goindex 38ff2eeac4..7ad3a7ce7c 100644--- a/kernel/mcp/tools/attr.go+++ b/kernel/mcp/tools/attr.go@@ -73,9 +73,9 @@ func attrGet(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Attributes for %s:\n\n", id))+ fmt.Fprintf(&sb, "Attributes for %s:\n\n", id)for k, v := range attrs {- sb.WriteString(fmt.Sprintf("- %s: %s\n", k, v))+ fmt.Fprintf(&sb, "- %s: %s\n", k, v)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -135,11 +135,11 @@ func attrBatchGet(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Batch attributes (%d blocks):\n\n", len(attrs)))+ fmt.Fprintf(&sb, "Batch attributes (%d blocks):\n\n", len(attrs))for id, kv := range attrs {- sb.WriteString(fmt.Sprintf("--- %s ---\n", id))+ fmt.Fprintf(&sb, "--- %s ---\n", id)for k, v := range kv {- sb.WriteString(fmt.Sprintf("- %s: %s\n", k, v))+ fmt.Fprintf(&sb, "- %s: %s\n", k, v)}}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nildiff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.goindex b5050533a2..103a28f3b3 100644--- a/kernel/mcp/tools/block.go+++ b/kernel/mcp/tools/block.go@@ -210,7 +210,7 @@ func blockGetChildren(args map[string]any) (CallToolResult, error) {content = c.Content}content = truncateText(content, 200)- sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", c.Type, content, c.ID))+ fmt.Fprintf(&sb, "- [%s] %s (%s)\n", c.Type, content, c.ID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -601,7 +601,7 @@ func blockBreadcrumb(args map[string]any) (CallToolResult, error) {var sb strings.Builderfor _, p := range paths {- sb.WriteString(fmt.Sprintf("%s/%s (%s)\n", p.Type, p.Name, p.ID))+ fmt.Fprintf(&sb, "%s/%s (%s)\n", p.Type, p.Name, p.ID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -678,9 +678,9 @@ func blockBatchGet(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Batch get %d blocks (found %d):\n\n", len(ids), len(infos)))+ fmt.Fprintf(&sb, "Batch get %d blocks (found %d):\n\n", len(ids), len(infos))for _, info := range infos {- sb.WriteString(fmt.Sprintf("- %s: %s (rootID: %s, refCount: %d)\n", info.ID, info.Name, info.RootID, info.RefCount))+ fmt.Fprintf(&sb, "- %s: %s (rootID: %s, refCount: %d)\n", info.ID, info.Name, info.RootID, info.RefCount)}for _, id := range ids {found := false@@ -691,7 +691,7 @@ func blockBatchGet(args map[string]any) (CallToolResult, error) {}}if !found {- sb.WriteString(fmt.Sprintf("- %s: not found\n", id))+ fmt.Fprintf(&sb, "- %s: not found\n", id)}}@@ -722,12 +722,12 @@ func blockBatchKramdown(args map[string]any) (CallToolResult, error) {kramdowns := model.GetBlockKramdownsInBox(ids, "md", boxID)var sb strings.Builder- sb.WriteString(fmt.Sprintf("Batch kramdown %d blocks (found %d):\n\n", len(ids), len(kramdowns)))+ fmt.Fprintf(&sb, "Batch kramdown %d blocks (found %d):\n\n", len(ids), len(kramdowns))for _, id := range ids {if kd, ok := kramdowns[id]; ok {- sb.WriteString(fmt.Sprintf("--- %s ---\n%s\n\n", id, kd))+ fmt.Fprintf(&sb, "--- %s ---\n%s\n\n", id, kd)} else {- sb.WriteString(fmt.Sprintf("--- %s ---\n(not found)\n\n", id))+ fmt.Fprintf(&sb, "--- %s ---\n(not found)\n\n", id)}}diff --git a/kernel/mcp/tools/block_test.go b/kernel/mcp/tools/block_test.goindex 7e8a073420..43af85e690 100644--- a/kernel/mcp/tools/block_test.go+++ b/kernel/mcp/tools/block_test.go@@ -169,7 +169,7 @@ func TestBlockToolPreservesNativeDOMIdentity(t *testing.T) {if _, err = prepareBlockWriteData(strings.Replace(dom, id, "invalid", 1), "dom"); err == nil {t.Fatal("invalid explicit block ID was accepted")}- duplicate := strings.Replace(nativeMindmapTestDOM, `data-type="NodeParagraph"`, `data-node-id="`+id+`" data-type="NodeParagraph"`, -1)+ duplicate := strings.ReplaceAll(nativeMindmapTestDOM, `data-type="NodeParagraph"`, `data-node-id="`+id+`" data-type="NodeParagraph"`)if _, err = prepareBlockWriteData(duplicate, "dom"); err == nil {t.Fatal("duplicate explicit block IDs were accepted")}diff --git a/kernel/mcp/tools/bookmark.go b/kernel/mcp/tools/bookmark.goindex 380d5b7ceb..817a5e026e 100644--- a/kernel/mcp/tools/bookmark.go+++ b/kernel/mcp/tools/bookmark.go@@ -61,25 +61,25 @@ func bookmarkHandler(args map[string]any) (CallToolResult, error) {}, nil}-func bookmarkList(args map[string]any) (CallToolResult, error) {+func bookmarkList(_ map[string]any) (CallToolResult, error) {bookmarks := model.BuildBookmark()var sb strings.Builder- sb.WriteString(fmt.Sprintf("Bookmarks (%d):\n\n", len(*bookmarks)))+ fmt.Fprintf(&sb, "Bookmarks (%d):\n\n", len(*bookmarks))for _, b := range *bookmarks {- sb.WriteString(fmt.Sprintf("- %s: %d blocks\n", b.Name, b.Count))+ fmt.Fprintf(&sb, "- %s: %d blocks\n", b.Name, b.Count)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}-func bookmarkLabels(args map[string]any) (CallToolResult, error) {+func bookmarkLabels(_ map[string]any) (CallToolResult, error) {labels := model.BookmarkLabels()if len(labels) == 0 {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no bookmark labels found"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Bookmark labels (%d):\n\n", len(labels)))+ fmt.Fprintf(&sb, "Bookmark labels (%d):\n\n", len(labels))for _, l := range labels {- sb.WriteString(fmt.Sprintf("- %s\n", l))+ fmt.Fprintf(&sb, "- %s\n", l)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/mcp/tools/database.go b/kernel/mcp/tools/database.goindex 4d79c1f044..e928010d1a 100644--- a/kernel/mcp/tools/database.go+++ b/kernel/mcp/tools/database.go@@ -524,7 +524,7 @@ func databaseItemUpdate(args map[string]any) (CallToolResult, error) {})}-func databaseUnused(args map[string]any) (CallToolResult, error) {+func databaseUnused(_ map[string]any) (CallToolResult, error) {items, err := model.UnusedAttributeViews(true)if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}, nildiff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.goindex 8706e7221b..af0ed0b874 100644--- a/kernel/mcp/tools/document.go+++ b/kernel/mcp/tools/document.go@@ -172,9 +172,9 @@ func documentList(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Documents in %s (hPath: %s):\n\n", notebook, hPath))+ fmt.Fprintf(&sb, "Documents in %s (hPath: %s):\n\n", notebook, hPath)for _, f := range files {- sb.WriteString(fmt.Sprintf("- %s (id: %s, hPath: %s)\n", f.Name, f.ID, strings.TrimRight(hPath, "/")+"/"+f.Name))+ fmt.Fprintf(&sb, "- %s (id: %s, hPath: %s)\n", f.Name, f.ID, strings.TrimRight(hPath, "/")+"/"+f.Name)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -272,13 +272,13 @@ func documentSearchDocs(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Search results matching '%s' (%d):\n\n", keyword, len(docs)))+ fmt.Fprintf(&sb, "Search results matching '%s' (%d):\n\n", keyword, len(docs))for _, d := range docs {typ, id, name := documentSearchDisplayFields(d)if typ == "NOTEBOOK" {- sb.WriteString(fmt.Sprintf("- [%s] %s (id: %s, hPath: %s)\n", typ, name, id, d["hPath"]))+ fmt.Fprintf(&sb, "- [%s] %s (id: %s, hPath: %s)\n", typ, name, id, d["hPath"])} else {- sb.WriteString(fmt.Sprintf("- [%s] %s (id: %s, notebook: %s, hPath: %s)\n", typ, name, id, d["box"], d["hPath"]))+ fmt.Fprintf(&sb, "- [%s] %s (id: %s, notebook: %s, hPath: %s)\n", typ, name, id, d["box"], d["hPath"])}}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil@@ -304,24 +304,22 @@ func documentInfo(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf(- "ID: %s\nRootID: %s\nName: %s\nRefCount: %d\nSubFileCount: %d\nIcon: %s",- info.ID, info.RootID, info.Name, info.RefCount, info.SubFileCount, info.Icon,- ))+ fmt.Fprintf(&sb, "ID: %s\nRootID: %s\nName: %s\nRefCount: %d\nSubFileCount: %d\nIcon: %s",+ info.ID, info.RootID, info.Name, info.RefCount, info.SubFileCount, info.Icon)if len(info.RefIDs) > 0 {- sb.WriteString(fmt.Sprintf("\nRefIDs: %s", strings.Join(info.RefIDs, ", ")))+ fmt.Fprintf(&sb, "\nRefIDs: %s", strings.Join(info.RefIDs, ", "))}if len(info.AttrViews) > 0 {sb.WriteString("\nAttrViews:")for _, av := range info.AttrViews {- sb.WriteString(fmt.Sprintf("\n - %s: %s", av.ID, av.Name))+ fmt.Fprintf(&sb, "\n - %s: %s", av.ID, av.Name)}}if len(info.IAL) > 0 {sb.WriteString("\nIAL:")for k, v := range info.IAL {v = truncateText(v, 100)- sb.WriteString(fmt.Sprintf("\n %s: %s", k, v))+ fmt.Fprintf(&sb, "\n %s: %s", k, v)}}diff --git a/kernel/mcp/tools/export.go b/kernel/mcp/tools/export.goindex e3af9ee45e..caee6f9906 100644--- a/kernel/mcp/tools/export.go+++ b/kernel/mcp/tools/export.go@@ -153,7 +153,7 @@ func exportMdZip(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("exported md zip to: %s", zipPath)}}}, nil}-func exportData(args map[string]any) (CallToolResult, error) {+func exportData(_ map[string]any) (CallToolResult, error) {zipPath, err := model.ExportData()if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "export data failed: " + err.Error()}}, IsError: true}, nildiff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.goindex 37e8a10999..5ad1561a0b 100644--- a/kernel/mcp/tools/file.go+++ b/kernel/mcp/tools/file.go@@ -35,6 +35,7 @@ import ("github.com/siyuan-note/siyuan/kernel/util""github.com/88250/gulu"+ "github.com/siyuan-note/logging")var FileTool = &Tool{@@ -267,18 +268,18 @@ func fileList(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Directory: %s (%d entries)\n\n", p, total))+ fmt.Fprintf(&sb, "Directory: %s (%d entries)\n\n", p, total)for _, e := range entries {info, _ := e.Info()size := ""if info != nil {size = fmt.Sprintf("%d", info.Size())}- sb.WriteString(fmt.Sprintf("- %s [%s] %s\n", e.Name(), typeLabel(e.IsDir()), size))+ fmt.Fprintf(&sb, "- %s [%s] %s\n", e.Name(), typeLabel(e.IsDir()), size)}if max > 0 && max < total {- sb.WriteString(fmt.Sprintf("\n...output limited to %d of %d entries. Use limit parameter to adjust.", max, total))+ fmt.Fprintf(&sb, "\n...output limited to %d of %d entries. Use limit parameter to adjust.", max, total)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil@@ -591,7 +592,8 @@ func fileMutationRequest(args map[string]any) (util.TextFileMutation, error) {request.IfAbsent, _ = args["ifAbsent"].(bool)request.DryRun, _ = args["dryRun"].(bool)action, _ := args["action"].(string)- if action == "edit" {+ switch action {+ case "edit":raw, ok := args["edits"].([]any)if !ok || len(raw) == 0 || len(raw) > 128 {return request, fileInvalid("invalid_edit", "edits must contain 1 to 128 replacements")@@ -609,7 +611,7 @@ func fileMutationRequest(args map[string]any) (util.TextFileMutation, error) {}request.Edits[i] = util.TextEdit{OldText: oldText, NewText: newText}}- } else if action == "write" || action == "" {+ case "write", "":var ok boolrequest.Content, ok = args["data"].(string)if !ok {@@ -948,7 +950,7 @@ func fileGrep(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Found %d lines:\n\n", len(results)))+ fmt.Fprintf(&sb, "Found %d lines:\n\n", len(results))for _, r := range results {rel, relErr := filepath.Rel(util.WorkspaceDir, r.File)if relErr != nil {@@ -958,7 +960,7 @@ func fileGrep(args map[string]any) (CallToolResult, error) {if r.Context {sep = "-:"}- sb.WriteString(fmt.Sprintf("%s:%d%s %s\n", rel, r.Line, sep, r.Text))+ fmt.Fprintf(&sb, "%s:%d%s %s\n", rel, r.Line, sep, r.Text)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil@@ -1079,6 +1081,9 @@ func grepGuardedFile(path string, re *regexp.Regexp, context int, results *[]*gu}}}+ if scanErr := scanner.Err(); scanErr != nil {+ logging.LogErrorf("scan file [%s] failed: %s", path, scanErr)+ }}// skipTraversalDir 判断遍历时是否跳过该目录,与 Gulu 的隐藏目录跳过规则保持一致。@@ -1143,15 +1148,16 @@ func fileFind(args map[string]any) (CallToolResult, error) {var sb strings.Builderif max > 0 && max < total {- sb.WriteString(fmt.Sprintf("Found %d files (showing first %d):\n\n", total, max))+ fmt.Fprintf(&sb, "Found %d files (showing first %d):\n\n", total, max)} else {- sb.WriteString(fmt.Sprintf("Found %d files:\n\n", len(results)))+ fmt.Fprintf(&sb, "Found %d files:\n\n", len(results))}for _, r := range results {- sb.WriteString(r + "\n")+ sb.WriteString(r)+ sb.WriteString("\n")}if max > 0 && max < total {- sb.WriteString(fmt.Sprintf("\n...output limited to %d of %d files. Use limit parameter to adjust.", max, total))+ fmt.Fprintf(&sb, "\n...output limited to %d of %d files. Use limit parameter to adjust.", max, total)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nildiff --git a/kernel/mcp/tools/history.go b/kernel/mcp/tools/history.goindex 98db381615..cf47484b63 100644--- a/kernel/mcp/tools/history.go+++ b/kernel/mcp/tools/history.go@@ -87,12 +87,12 @@ func historyList(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("History (%d total, page %d/%d):\n\n", totalCount, page, pageCount))+ fmt.Fprintf(&sb, "History (%d total, page %d/%d):\n\n", totalCount, page, pageCount)for _, ts := range results {items := model.FullTextSearchHistoryItems(ts, query, notebook, op, typ)- sb.WriteString(fmt.Sprintf("--- %s (%d items) ---\n", ts, len(items)))+ fmt.Fprintf(&sb, "--- %s (%d items) ---\n", ts, len(items))for _, item := range items {- sb.WriteString(fmt.Sprintf(" - [%s] %s (path: %s)\n", item.Op, item.Title, item.Path))+ fmt.Fprintf(&sb, " - [%s] %s (path: %s)\n", item.Op, item.Title, item.Path)}}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil@@ -137,12 +137,12 @@ func historySearch(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Search '%s' (%d total, page %d/%d):\n\n", query, totalCount, page, pageCount))+ fmt.Fprintf(&sb, "Search '%s' (%d total, page %d/%d):\n\n", query, totalCount, page, pageCount)for _, ts := range timestamps {items := model.FullTextSearchHistoryItems(ts, query, box, op, typ)- sb.WriteString(fmt.Sprintf("--- %s (%d items) ---\n", ts, len(items)))+ fmt.Fprintf(&sb, "--- %s (%d items) ---\n", ts, len(items))for _, item := range items {- sb.WriteString(fmt.Sprintf(" - [%s] %s (path: %s)\n", item.Op, item.Title, item.Path))+ fmt.Fprintf(&sb, " - [%s] %s (path: %s)\n", item.Op, item.Title, item.Path)}}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil@@ -164,7 +164,7 @@ func historyRollback(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "history rolled back: " + path}}}, nil}-func historyClear(args map[string]any) (CallToolResult, error) {+func historyClear(_ map[string]any) (CallToolResult, error) {if err := model.ClearWorkspaceHistory(); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "clear history failed: " + err.Error()}}, IsError: true}, nil}diff --git a/kernel/mcp/tools/inbox.go b/kernel/mcp/tools/inbox.goindex 5d76dc9cf8..81139b12b5 100644--- a/kernel/mcp/tools/inbox.go+++ b/kernel/mcp/tools/inbox.go@@ -88,7 +88,7 @@ func inboxList(args map[string]any) (CallToolResult, error) {data, _ := result["data"].(map[string]any)shorthands, _ := data["shorthands"].([]any)var sb strings.Builder- sb.WriteString(fmt.Sprintf("Inbox (page %d, %d item(s)):\n\n", page, len(shorthands)))+ fmt.Fprintf(&sb, "Inbox (page %d, %d item(s)):\n\n", page, len(shorthands))for _, item := range shorthands {sh, _ := item.(map[string]any)if sh == nil {@@ -99,12 +99,14 @@ func inboxList(args map[string]any) (CallToolResult, error) {desc, _ := sh["shorthandDesc"].(string)url, _ := sh["shorthandURL"].(string)hCreated, _ := sh["hCreated"].(string)- sb.WriteString(fmt.Sprintf("- id: %s\n title: %s\n created: %s", id, title, hCreated))+ fmt.Fprintf(&sb, "- id: %s\n title: %s\n created: %s", id, title, hCreated)if url != "" {- sb.WriteString("\n url: " + url)+ sb.WriteString("\n url: ")+ sb.WriteString(url)}if desc != "" {- sb.WriteString("\n summary: " + desc)+ sb.WriteString("\n summary: ")+ sb.WriteString(desc)}sb.WriteString("\n\n")}@@ -133,11 +135,14 @@ func inboxGet(args map[string]any) (CallToolResult, error) {hCreated, _ := sh["hCreated"].(string)md, _ := sh["shorthandMd"].(string)var sb strings.Builder- sb.WriteString(fmt.Sprintf("id: %s\ntitle: %s\ncreated: %s\n", id, title, hCreated))+ fmt.Fprintf(&sb, "id: %s\ntitle: %s\ncreated: %s\n", id, title, hCreated)if url != "" {- sb.WriteString("url: " + url + "\n")+ sb.WriteString("url: ")+ sb.WriteString(url)+ sb.WriteString("\n")}- sb.WriteString("\nmarkdown:\n" + md)+ sb.WriteString("\nmarkdown:\n")+ sb.WriteString(md)return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -180,14 +185,14 @@ func inboxConvert(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Converting %d shorthand(s) -> notebook %s (hPath: %s):\n\n", len(ids), notebook, hPath))+ fmt.Fprintf(&sb, "Converting %d shorthand(s) -> notebook %s (hPath: %s):\n\n", len(ids), notebook, hPath)successIDs := make([]string, 0, len(ids))failed := 0for _, id := range ids {sh, err := model.GetCloudShorthand(id)if err != nil {- sb.WriteString(fmt.Sprintf("- [%s] FAILED: %s\n", id, err.Error()))+ fmt.Fprintf(&sb, "- [%s] FAILED: %s\n", id, err.Error())failed++continue}@@ -210,23 +215,24 @@ func inboxConvert(args map[string]any) (CallToolResult, error) {docPath := strings.TrimRight(parentPath, "/") + "/" + docID + ".sy"tree, err := model.CreateDocByMdSync(notebook, docPath, title, md, nil, nil)if err != nil {- sb.WriteString(fmt.Sprintf("- [%s] %s -> FAILED: %s\n", id, title, err.Error()))+ fmt.Fprintf(&sb, "- [%s] %s -> FAILED: %s\n", id, title, err.Error())failed++continue}successIDs = append(successIDs, id)- sb.WriteString(fmt.Sprintf("- [%s] %s -> created %s\n", id, title, tree.Root.ID))+ fmt.Fprintf(&sb, "- [%s] %s -> created %s\n", id, title, tree.Root.ID)}// 仅在全部转换成功的条目上清理云端原件;失败条目保留以便重试。if removeAfter && len(successIDs) > 0 {if err := model.RemoveCloudShorthands(successIDs); err != nil {- sb.WriteString("\nWARNING: failed to remove cloud originals: " + err.Error())+ sb.WriteString("\nWARNING: failed to remove cloud originals: ")+ sb.WriteString(err.Error())}}util.PushReloadFiletree()- sb.WriteString(fmt.Sprintf("\nDone: %d succeeded, %d failed.", len(successIDs), failed))+ fmt.Fprintf(&sb, "\nDone: %d succeeded, %d failed.", len(successIDs), failed)return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/mcp/tools/log.go b/kernel/mcp/tools/log.goindex f94d21f520..96b8e22b2f 100644--- a/kernel/mcp/tools/log.go+++ b/kernel/mcp/tools/log.go@@ -320,7 +320,7 @@ func collectAgentLogSecrets(value reflect.Value, ownerType string, secrets map[sreturn}if value.CanInterface() {- if section, ok := value.Interface().(interface{ SnapshotValue() any }); ok {+ if section, ok := reflect.TypeAssert[interface{ SnapshotValue() any }](value); ok {collectAgentLogSecrets(reflect.ValueOf(section.SnapshotValue()), ownerType, secrets)return}diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.goindex 10829d6e72..f274610186 100644--- a/kernel/mcp/tools/notebook.go+++ b/kernel/mcp/tools/notebook.go@@ -72,16 +72,16 @@ func notebookHandler(args map[string]any) (CallToolResult, error) {}, nil}-func notebookList(args map[string]any) (CallToolResult, error) {+func notebookList(_ map[string]any) (CallToolResult, error) {notebooks, err := model.ListNotebooks()if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "list notebooks failed: " + err.Error()}}, IsError: true}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Notebooks (%d):\n\n", len(notebooks)))+ fmt.Fprintf(&sb, "Notebooks (%d):\n\n", len(notebooks))for _, nb := range notebooks {- sb.WriteString(fmt.Sprintf("- %s (id: %s, icon: %s, closed: %v)\n", nb.Name, nb.ID, nb.Icon, nb.Closed))+ fmt.Fprintf(&sb, "- %s (id: %s, icon: %s, closed: %v)\n", nb.Name, nb.ID, nb.Icon, nb.Closed)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -245,12 +245,12 @@ func notebookRandomIcon(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Randomized icons for %d notebook(s):\n", len(targets)))+ fmt.Fprintf(&sb, "Randomized icons for %d notebook(s):\n", len(targets))for _, nb := range targets {oldIcon := nb.IconnewIcon := randomEmoji()model.SetBoxIcon(nb.ID, newIcon)- sb.WriteString(fmt.Sprintf("- %s (id: %s): %s -> %s\n", nb.Name, nb.ID, oldIcon, newIcon))+ fmt.Fprintf(&sb, "- %s (id: %s): %s -> %s\n", nb.Name, nb.ID, oldIcon, newIcon)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nildiff --git a/kernel/mcp/tools/outline.go b/kernel/mcp/tools/outline.goindex ccef8619a5..c3d3ff8314 100644--- a/kernel/mcp/tools/outline.go+++ b/kernel/mcp/tools/outline.go@@ -69,7 +69,7 @@ func outlineGet(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Document outline (%d headings):\n\n", countHeadings(paths)))+ fmt.Fprintf(&sb, "Document outline (%d headings):\n\n", countHeadings(paths))for _, p := range paths {writePaths(&sb, p, 0)}@@ -101,7 +101,7 @@ func countBlockChildren(b *model.Block) int {func writePaths(sb *strings.Builder, p *model.Path, depth int) {prefix := strings.Repeat(" ", depth)- sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, p.Name, p.ID, p.Depth))+ fmt.Fprintf(sb, "%s- [%s] (id: %s, depth: %d)\n", prefix, p.Name, p.ID, p.Depth)for _, b := range p.Blocks {writeBlock(sb, b, depth+1)}@@ -112,7 +112,7 @@ func writePaths(sb *strings.Builder, p *model.Path, depth int) {func writeBlock(sb *strings.Builder, b *model.Block, depth int) {prefix := strings.Repeat(" ", depth)- sb.WriteString(fmt.Sprintf("%s- [%s] (id: %s, depth: %d)\n", prefix, b.Content, b.ID, b.Depth))+ fmt.Fprintf(sb, "%s- [%s] (id: %s, depth: %d)\n", prefix, b.Content, b.ID, b.Depth)for _, c := range b.Children {writeBlock(sb, c, depth+1)}diff --git a/kernel/mcp/tools/ref.go b/kernel/mcp/tools/ref.goindex 5cf876551b..ba8d24c222 100644--- a/kernel/mcp/tools/ref.go+++ b/kernel/mcp/tools/ref.go@@ -73,9 +73,9 @@ func refBacklinks(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Backlinks (%d):\n\n", len(backlinks)))+ fmt.Fprintf(&sb, "Backlinks (%d):\n\n", len(backlinks))for _, p := range backlinks {- sb.WriteString(fmt.Sprintf("- [%s] %s (id: %s)\n", p.NodeType, p.HPath, p.ID))+ fmt.Fprintf(&sb, "- [%s] %s (id: %s)\n", p.NodeType, p.HPath, p.ID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -94,9 +94,9 @@ func refMentions(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Mentions (%d):\n\n", len(mentions)))+ fmt.Fprintf(&sb, "Mentions (%d):\n\n", len(mentions))for _, p := range mentions {- sb.WriteString(fmt.Sprintf("- [%s] %s (id: %s)\n", p.NodeType, p.HPath, p.ID))+ fmt.Fprintf(&sb, "- [%s] %s (id: %s)\n", p.NodeType, p.HPath, p.ID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/mcp/tools/repo.go b/kernel/mcp/tools/repo.goindex 7af852882d..951a1c9286 100644--- a/kernel/mcp/tools/repo.go+++ b/kernel/mcp/tools/repo.go@@ -106,9 +106,9 @@ func repoList(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no tagged snapshots found"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Tagged snapshots (%d):\n\n", len(snapshots)))+ fmt.Fprintf(&sb, "Tagged snapshots (%d):\n\n", len(snapshots))for _, s := range snapshots {- sb.WriteString(fmt.Sprintf("- %s (memo: %s)\n", s.ID, s.Memo))+ fmt.Fprintf(&sb, "- %s (memo: %s)\n", s.ID, s.Memo)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -121,9 +121,9 @@ func repoList(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no snapshots found"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Snapshots (page %d/%d, %d total):\n\n", page, pageCount, totalCount))+ fmt.Fprintf(&sb, "Snapshots (page %d/%d, %d total):\n\n", page, pageCount, totalCount)for _, s := range snapshots {- sb.WriteString(fmt.Sprintf("- %s (memo: %s)\n", s.ID, s.Memo))+ fmt.Fprintf(&sb, "- %s (memo: %s)\n", s.ID, s.Memo)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}@@ -188,23 +188,23 @@ func repoDiff(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "diff failed: " + err.Error()}}, IsError: true}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Diff between %s and %s:\n\n", left, right))+ fmt.Fprintf(&sb, "Diff between %s and %s:\n\n", left, right)if len(diff.AddsLeft) > 0 {- sb.WriteString(fmt.Sprintf("Adds (%d):\n", len(diff.AddsLeft)))+ fmt.Fprintf(&sb, "Adds (%d):\n", len(diff.AddsLeft))for _, f := range diff.AddsLeft {- sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", f.FileID, f.Title, f.Path))+ fmt.Fprintf(&sb, "- [%s] %s (%s)\n", f.FileID, f.Title, f.Path)}}if len(diff.UpdatesLeft) > 0 {- sb.WriteString(fmt.Sprintf("\nUpdates (%d):\n", len(diff.UpdatesLeft)))+ fmt.Fprintf(&sb, "\nUpdates (%d):\n", len(diff.UpdatesLeft))for _, f := range diff.UpdatesLeft {- sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", f.FileID, f.Title, f.Path))+ fmt.Fprintf(&sb, "- [%s] %s (%s)\n", f.FileID, f.Title, f.Path)}}if len(diff.RemovesRight) > 0 {- sb.WriteString(fmt.Sprintf("\nRemoves (%d):\n", len(diff.RemovesRight)))+ fmt.Fprintf(&sb, "\nRemoves (%d):\n", len(diff.RemovesRight))for _, f := range diff.RemovesRight {- sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", f.FileID, f.Title, f.Path))+ fmt.Fprintf(&sb, "- [%s] %s (%s)\n", f.FileID, f.Title, f.Path)}}if len(diff.AddsLeft) == 0 && len(diff.UpdatesLeft) == 0 && len(diff.RemovesRight) == 0 {@@ -233,14 +233,14 @@ func repoSearch(args map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no files found"}}}, nil}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Files matching '%s' (page %d/%d, %d total):\n\n", keyword, page, pageCount, totalCount))+ fmt.Fprintf(&sb, "Files matching '%s' (page %d/%d, %d total):\n\n", keyword, page, pageCount, totalCount)for _, f := range files {- sb.WriteString(fmt.Sprintf("- [%s] %s (%s)\n", f.FileID, f.Title, f.Path))+ fmt.Fprintf(&sb, "- [%s] %s (%s)\n", f.FileID, f.Title, f.Path)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}-func repoPurge(args map[string]any) (CallToolResult, error) {+func repoPurge(_ map[string]any) (CallToolResult, error) {if err := model.PurgeRepo(); err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "purge failed: " + err.Error()}}, IsError: true}, nil}diff --git a/kernel/mcp/tools/search.go b/kernel/mcp/tools/search.goindex 3cfadf2d94..1b158289c7 100644--- a/kernel/mcp/tools/search.go+++ b/kernel/mcp/tools/search.go@@ -168,17 +168,17 @@ func fulltextSearch(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Found %d results (page %d/%d):\n\n", matchedCount, page, pageCount))+ fmt.Fprintf(&sb, "Found %d results (page %d/%d):\n\n", matchedCount, page, pageCount)for _, b := range blocks {content := b.Markdownif content == "" {content = b.Content}content = truncateText(content, 200)- sb.WriteString(fmt.Sprintf("- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID))+ fmt.Fprintf(&sb, "- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID)}if docMode {- sb.WriteString(fmt.Sprintf("(grouped by document, %d documents matched)\n", matchedRootCount))+ fmt.Fprintf(&sb, "(grouped by document, %d documents matched)\n", matchedRootCount)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}},@@ -222,17 +222,17 @@ func semanticSearch(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Found %d semantic results (page %d/%d):\n\n", matchedCount, page, pageCount))+ fmt.Fprintf(&sb, "Found %d semantic results (page %d/%d):\n\n", matchedCount, page, pageCount)for _, b := range blocks {content := b.Markdownif content == "" {content = b.Content}content = truncateText(content, 200)- sb.WriteString(fmt.Sprintf("- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID))+ fmt.Fprintf(&sb, "- [%s] %s\n %s\n id: %s\n\n", b.HPath, b.Type, content, b.ID)}if matchedRootCount > 0 {- sb.WriteString(fmt.Sprintf("(%d documents matched)\n", matchedRootCount))+ fmt.Fprintf(&sb, "(%d documents matched)\n", matchedRootCount)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}},@@ -282,15 +282,15 @@ func assetSearch(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Found %d asset matches (page %d/%d):\n\n", matchedAssetCount, page, pageCount))+ fmt.Fprintf(&sb, "Found %d asset matches (page %d/%d):\n\n", matchedAssetCount, page, pageCount)for _, a := range assetContents {content := a.Contentcontent = truncateText(content, 200)- sb.WriteString(fmt.Sprintf("- [%s] %s\n", a.Ext, a.Name))- sb.WriteString(fmt.Sprintf(" path: %s\n", a.Path))- sb.WriteString(fmt.Sprintf(" size: %s\n", a.HSize))- sb.WriteString(fmt.Sprintf(" content: %s\n", content))- sb.WriteString(fmt.Sprintf(" id: %s\n\n", a.ID))+ fmt.Fprintf(&sb, "- [%s] %s\n", a.Ext, a.Name)+ fmt.Fprintf(&sb, " path: %s\n", a.Path)+ fmt.Fprintf(&sb, " size: %s\n", a.HSize)+ fmt.Fprintf(&sb, " content: %s\n", content)+ fmt.Fprintf(&sb, " id: %s\n\n", a.ID)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}},@@ -312,11 +312,11 @@ func getAssetHandler(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Asset: %s\n", a.Name))- sb.WriteString(fmt.Sprintf("Ext: %s\n", a.Ext))- sb.WriteString(fmt.Sprintf("Path: %s\n", a.Path))- sb.WriteString(fmt.Sprintf("Size: %s\n", a.HSize))- sb.WriteString(fmt.Sprintf("ID: %s\n", a.ID))+ fmt.Fprintf(&sb, "Asset: %s\n", a.Name)+ fmt.Fprintf(&sb, "Ext: %s\n", a.Ext)+ fmt.Fprintf(&sb, "Path: %s\n", a.Path)+ fmt.Fprintf(&sb, "Size: %s\n", a.HSize)+ fmt.Fprintf(&sb, "ID: %s\n", a.ID)sb.WriteString("\nContent:\n")sb.WriteString(a.Content)return CallToolResult{diff --git a/kernel/mcp/tools/skill.go b/kernel/mcp/tools/skill.goindex b5361bacbd..d4d5413acf 100644--- a/kernel/mcp/tools/skill.go+++ b/kernel/mcp/tools/skill.go@@ -290,13 +290,17 @@ func skillInstall(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("installed %d skill(s):\n", len(result.Names)))+ fmt.Fprintf(&sb, "installed %d skill(s):\n", len(result.Names))for i, name := range result.Names {desc := ""if i < len(result.Descriptions) {desc = result.Descriptions[i]}- sb.WriteString("- **" + name + "**: " + desc + "\n")+ sb.WriteString("- **")+ sb.WriteString(name)+ sb.WriteString("**: ")+ sb.WriteString(desc)+ sb.WriteString("\n")}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}},@@ -352,7 +356,7 @@ func skillRename(args map[string]any) (CallToolResult, error) {}, nil}-func skillList(args map[string]any) (CallToolResult, error) {+func skillList(_ map[string]any) (CallToolResult, error) {skills := util.DiscoverSkills(model.EnabledUserSkills())if len(skills) == 0 {return CallToolResult{@@ -363,7 +367,11 @@ func skillList(args map[string]any) (CallToolResult, error) {var sb strings.Buildersb.WriteString("available skills:\n")for _, s := range skills {- sb.WriteString("- **" + s.Name + "**: " + s.Description + "\n")+ sb.WriteString("- **")+ sb.WriteString(s.Name)+ sb.WriteString("**: ")+ sb.WriteString(s.Description)+ sb.WriteString("\n")}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}},@@ -378,7 +386,11 @@ func skillListDesc() string {var sb strings.Buildersb.WriteString("Available skills:\n")for _, s := range skills {- sb.WriteString("- **" + s.Name + "**: " + s.Description + "\n")+ sb.WriteString("- **")+ sb.WriteString(s.Name)+ sb.WriteString("**: ")+ sb.WriteString(s.Description)+ sb.WriteString("\n")}return sb.String()}diff --git a/kernel/mcp/tools/sql.go b/kernel/mcp/tools/sql.goindex 5f2b63d332..d155b6f5b7 100644--- a/kernel/mcp/tools/sql.go+++ b/kernel/mcp/tools/sql.go@@ -173,12 +173,16 @@ func formatSQLRows(rows []map[string]any, possiblyTruncated bool) string {var sb strings.Builderif possiblyTruncated {- sb.WriteString(fmt.Sprintf("Query results (%d rows; the %d-row limit may have truncated the result. Use an explicit LIMIT with OFFSET to paginate):\n\n", len(rows), sqlQueryDefaultLimit))+ fmt.Fprintf(&sb, "Query results (%d rows; the %d-row limit may have truncated the result. Use an explicit LIMIT with OFFSET to paginate):\n\n", len(rows), sqlQueryDefaultLimit)} else {- sb.WriteString(fmt.Sprintf("Query results (%d rows):\n\n", len(rows)))- }- sb.WriteString("| " + strings.Join(columns, " | ") + " |\n")- sb.WriteString("|" + strings.Repeat("---|", len(columns)) + "\n")+ fmt.Fprintf(&sb, "Query results (%d rows):\n\n", len(rows))+ }+ sb.WriteString("| ")+ sb.WriteString(strings.Join(columns, " | "))+ sb.WriteString(" |\n")+ sb.WriteString("|")+ sb.WriteString(strings.Repeat("---|", len(columns)))+ sb.WriteString("\n")for _, row := range rows {vals := make([]string, 0, len(columns))for _, k := range columns {@@ -187,7 +191,9 @@ func formatSQLRows(rows []map[string]any, possiblyTruncated bool) string {value = strings.ReplaceAll(strings.ReplaceAll(value, "\r\n", "\n"), "\n", "<br>")vals = append(vals, value)}- sb.WriteString("| " + strings.Join(vals, " | ") + " |\n")+ sb.WriteString("| ")+ sb.WriteString(strings.Join(vals, " | "))+ sb.WriteString(" |\n")}return sb.String()}diff --git a/kernel/mcp/tools/sync.go b/kernel/mcp/tools/sync.goindex bf19cc93bc..70f3b87730 100644--- a/kernel/mcp/tools/sync.go+++ b/kernel/mcp/tools/sync.go@@ -57,22 +57,22 @@ func syncHandler(args map[string]any) (CallToolResult, error) {}, nil}-func syncPerform(args map[string]any) (CallToolResult, error) {+func syncPerform(_ map[string]any) (CallToolResult, error) {model.SyncData(true)return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync done: " + model.Conf.Sync.Load().Stat}}}, nil}-func syncUpload(args map[string]any) (CallToolResult, error) {+func syncUpload(_ map[string]any) (CallToolResult, error) {model.SyncDataUpload()return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync upload done: " + model.Conf.Sync.Load().Stat}}}, nil}-func syncDownload(args map[string]any) (CallToolResult, error) {+func syncDownload(_ map[string]any) (CallToolResult, error) {model.SyncDataDownload()return CallToolResult{Content: []ContentItem{{Type: "text", Text: "sync download done: " + model.Conf.Sync.Load().Stat}}}, nil}-func syncStatus(args map[string]any) (CallToolResult, error) {+func syncStatus(_ map[string]any) (CallToolResult, error) {s := model.Conf.Sync.Load()return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("Sync Status:\n Enabled: %v\n Mode: %d (0/1=auto, 2=manual, 3=full-manual)\n Provider: %d\n Cloud: %s\n Perception: %v\n Interval: %ds\n Synced: %d\n Stat: %s",diff --git a/kernel/mcp/tools/system.go b/kernel/mcp/tools/system.goindex c049c5770d..ea2fd53acd 100644--- a/kernel/mcp/tools/system.go+++ b/kernel/mcp/tools/system.go@@ -56,16 +56,16 @@ func systemHandler(args map[string]any) (CallToolResult, error) {}, nil}-func systemVersion(args map[string]any) (CallToolResult, error) {+func systemVersion(_ map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: util.Ver}}}, nil}-func systemCurrentTime(args map[string]any) (CallToolResult, error) {+func systemCurrentTime(_ map[string]any) (CallToolResult, error) {ms := util.CurrentTimeMillis()t := time.UnixMilli(ms)return CallToolResult{Content: []ContentItem{{Type: "text", Text: t.Format(time.RFC3339)}}}, nil}-func systemWorkspace(args map[string]any) (CallToolResult, error) {+func systemWorkspace(_ map[string]any) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: fmt.Sprintf("Workspace: %s\nVersion: %s\nContainer: %s", util.WorkspaceDir, util.Ver, util.Container)}}}, nil}diff --git a/kernel/mcp/tools/tag.go b/kernel/mcp/tools/tag.goindex aa885c9182..ac294e616c 100644--- a/kernel/mcp/tools/tag.go+++ b/kernel/mcp/tools/tag.go@@ -70,7 +70,7 @@ func tagList(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Tags (%d):\n\n", len(tags)))+ fmt.Fprintf(&sb, "Tags (%d):\n\n", len(tags))for _, t := range tags {sb.WriteString("- ")sb.WriteString(formatTagTextMark(t))diff --git a/kernel/mcp/tools/template.go b/kernel/mcp/tools/template.goindex 804ca23be0..83425a354e 100644--- a/kernel/mcp/tools/template.go+++ b/kernel/mcp/tools/template.go@@ -76,10 +76,10 @@ func templateSearch(args map[string]any) (CallToolResult, error) {}var sb strings.Builder- sb.WriteString(fmt.Sprintf("Templates (%d):\n\n", len(results)))+ fmt.Fprintf(&sb, "Templates (%d):\n\n", len(results))for _, r := range results {- sb.WriteString(fmt.Sprintf("- %s\n", r.Content))- sb.WriteString(fmt.Sprintf(" path: %s\n", r.Path))+ fmt.Fprintf(&sb, "- %s\n", r.Content)+ fmt.Fprintf(&sb, " path: %s\n", r.Path)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/mcp/tools/todo.go b/kernel/mcp/tools/todo.goindex 9a2628159a..7a5a8c3649 100644--- a/kernel/mcp/tools/todo.go+++ b/kernel/mcp/tools/todo.go@@ -121,13 +121,13 @@ func formatTodoResult(todos []agentTodoItem) string {for _, t := range todos {switch t.Status {case "completed":- sb.WriteString(fmt.Sprintf("- [x] %s\n", t.Content))+ fmt.Fprintf(&sb, "- [x] %s\n", t.Content)case "in_progress":- sb.WriteString(fmt.Sprintf("- [/] %s\n", t.Content))+ fmt.Fprintf(&sb, "- [/] %s\n", t.Content)case "cancelled":- sb.WriteString(fmt.Sprintf("- [-] %s\n", t.Content))+ fmt.Fprintf(&sb, "- [-] %s\n", t.Content)default:- sb.WriteString(fmt.Sprintf("- [ ] %s\n", t.Content))+ fmt.Fprintf(&sb, "- [ ] %s\n", t.Content)}}return sb.String()diff --git a/kernel/mcp/tools/workspace.go b/kernel/mcp/tools/workspace.goindex 8c4b5d9c43..f2aa3ba5ea 100644--- a/kernel/mcp/tools/workspace.go+++ b/kernel/mcp/tools/workspace.go@@ -54,7 +54,7 @@ func workspaceHandler(args map[string]any) (CallToolResult, error) {}, nil}-func workspaceList(args map[string]any) (CallToolResult, error) {+func workspaceList(_ map[string]any) (CallToolResult, error) {paths, err := util.ReadWorkspacePaths()if err != nil {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "list workspaces failed: " + err.Error()}}, IsError: true}, nil@@ -62,23 +62,23 @@ func workspaceList(args map[string]any) (CallToolResult, error) {var sb strings.Builderseen := map[string]bool{}- sb.WriteString(fmt.Sprintf("Registered workspaces (%d):\n\n", len(paths)))+ fmt.Fprintf(&sb, "Registered workspaces (%d):\n\n", len(paths))for _, p := range paths {key := strings.ToLower(p)if seen[key] {continue}seen[key] = true- sb.WriteString(fmt.Sprintf("- %s\n", p))+ fmt.Fprintf(&sb, "- %s\n", p)}return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}-func workspaceInfo(args map[string]any) (CallToolResult, error) {+func workspaceInfo(_ map[string]any) (CallToolResult, error) {dir := util.WorkspaceDirsb := strings.Builder{}- sb.WriteString(fmt.Sprintf("Path: %s\n", dir))- sb.WriteString(fmt.Sprintf("Version: %s\n", util.Ver))- sb.WriteString(fmt.Sprintf("Valid: %v\n", util.IsWorkspaceDir(dir)))+ fmt.Fprintf(&sb, "Path: %s\n", dir)+ fmt.Fprintf(&sb, "Version: %s\n", util.Ver)+ fmt.Fprintf(&sb, "Valid: %v\n", util.IsWorkspaceDir(dir))return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil}diff --git a/kernel/model/asset_content.go b/kernel/model/asset_content.goindex 1cff98fb9a..3bcb32c9b3 100644--- a/kernel/model/asset_content.go+++ b/kernel/model/asset_content.go@@ -376,7 +376,6 @@ func indexAssetContent(absPath string) {func ReindexAssetContent() {task.AppendTask(task.AssetContentDatabaseIndexFull, fullReindexAssetContent)- return}func fullReindexAssetContent() {@@ -384,7 +383,6 @@ func fullReindexAssetContent() {sql.InitAssetContentDatabase(true)assetContentSearcher.FullIndex()- return}func init() {@@ -748,7 +746,8 @@ func (parser *XlsxAssetParser) Parse(absPath string) (ret *AssetParseResult) {}for _, row := range rows {for _, colCell := range row {- buf.WriteString(colCell + " ")+ buf.WriteString(colCell)+ buf.WriteString(" ")}}}@@ -967,7 +966,8 @@ func (parser *PdfAssetParser) Parse(absPath string) (ret *AssetParseResult) {// loop through ordered PDF text pages and join content for asset parse DB resultcontentBuilder := bytes.Buffer{}for _, pt := range pageText {- contentBuilder.WriteString(" " + normalizeNonTxtAssetContent(pt))+ contentBuilder.WriteString(" ")+ contentBuilder.WriteString(normalizeNonTxtAssetContent(pt))}ret = &AssetParseResult{Content: contentBuilder.String(),diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex f71a681fee..5ab01c4406 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -758,9 +758,7 @@ func netAssets2LocalAssets0(tree *parse.Tree, onlyImg bool, originalURL string,u := destif strings.Contains(u, "qpic.cn") {// 改进 `网络图片转换为本地图片` 微信图片拉取 https://github.com/siyuan-note/siyuan/issues/5052- if strings.Contains(u, "http://") {- u = strings.Replace(u, "http://", "https://", 1)- }+ u = strings.Replace(u, "http://", "https://", 1)// 改进 `网络图片转换为本地图片` 微信图片拉取 https://github.com/siyuan-note/siyuan/issues/6431// 下面这部分需要注释掉,否则会导致响应 400diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex d5c58f48ee..cae64673d6 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -4831,7 +4831,7 @@ func (tx *Transaction) doSortAttrViewView(operation *Operation) (ret *TxErr) {view := attrView.GetView(operation.ID)if nil == view {logging.LogErrorf("get view failed: %s", operation.BlockID)- return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: av.ErrViewNotFound.Error()}}viewID := view.IDpreviousViewID := operation.PreviousID@@ -5655,7 +5655,7 @@ func (tx *Transaction) doSetAttrViewContextFilter(operation *Operation) (ret *Tx}// resolveAttributeViewFilterContext 将数据库块所在根文档映射为关联目标数据库的条目 ID。-func resolveAttributeViewFilterContext(attrView *av.AttributeView, view *av.View,+func resolveAttributeViewFilterContext(attrView *av.AttributeView, _ *av.View,blockID string) (*av.FilterContext, error) {if nil == attrView || "" == blockID {return nil, nil@@ -6100,7 +6100,7 @@ func setAttributeViewColumnCalc(operation *Operation) (err error) {return}- operationData := operation.Data.(any)+ operationData := operation.Datadata, err := gulu.JSON.MarshalJSON(operationData)if err != nil {return@@ -8477,12 +8477,10 @@ func updateAttributeViewValue0(tx *Transaction, attrView *av.AttributeView, keyI}}- if nil != blockVal {- blockVal.Block.Updated = now- blockVal.SetUpdatedAt(now)- if isUpdatingBlockKey {- blockVal.IsDetached = val.IsDetached- }+ blockVal.Block.Updated = now+ blockVal.SetUpdatedAt(now)+ if isUpdatingBlockKey {+ blockVal.IsDetached = val.IsDetached}val.SetUpdatedAt(now)@@ -8672,7 +8670,6 @@ func unbindBlockAv(tx *Transaction, avID, nodeID string) {logging.LogWarnf("set node [%s] attrs failed: %s", nodeID, err)return}- return}func (tx *Transaction) doSortAttrViewBinding(operation *Operation) (ret *TxErr) {@@ -8747,7 +8744,6 @@ func bindBlockAv(tx *Transaction, avID, blockID string) {}bindBlockAv0(tx, avID, node, tree)- return}func bindBlockAv0(tx *Transaction, avID string, node *ast.Node, tree *parse.Tree) {@@ -8779,7 +8775,6 @@ func bindBlockAv0(tx *Transaction, avID string, node *ast.Node, tree *parse.Treelogging.LogWarnf("set node [%s] attrs failed: %s", node.ID, err)return}- return}func updateBlockValueStaticText(tx *Transaction, node *ast.Node, tree *parse.Tree, avID, text string) {diff --git a/kernel/model/attribute_view_automation.go b/kernel/model/attribute_view_automation.goindex f1268b7a2d..be85307676 100644--- a/kernel/model/attribute_view_automation.go+++ b/kernel/model/attribute_view_automation.go@@ -402,9 +402,10 @@ func equalAutomationValues(left, right *av.Value) bool {func (tx *Transaction) automationTarget(source *av.AttributeView, action *av.AutomationAction, boxID string) (*av.AttributeView, error) {id := action.AvID- if action.Target == "current" {+ switch action.Target {+ case "current":id = source.ID- } else if action.Target == "related" {+ case "related":key, err := source.GetKey(action.RelationKeyID)if err != nil || key.Relation == nil || key.Relation.AvID == "" {return nil, unavailableAutomationReference("fields", action.RelationKeyID,diff --git a/kernel/model/attribute_view_block_undo_fts5_test.go b/kernel/model/attribute_view_block_undo_fts5_test.goindex 49d5284cfd..7730616006 100644--- a/kernel/model/attribute_view_block_undo_fts5_test.go+++ b/kernel/model/attribute_view_block_undo_fts5_test.go@@ -315,9 +315,10 @@ func setupAttributeViewDeletedBlockTest(t *testing.T, mode string) (*fileOperati}var nodes []*ast.Nodecount := 1- if mode == "container" {+ switch mode {+ case "container":count = 2- } else if mode == "batch" {+ case "batch":count = 32}for i := 0; i < count; i++ {diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 57dcb31bdd..89b16c6eae 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -445,7 +445,7 @@ func (tx *Transaction) addCollectedItem(view *av.AttributeView, rule *av.Automat&av.AutomationAction{Type: "edit", Target: "current", Fields: rule.Actions[0].Fields}, rule.TimeZone)}-func (tx *Transaction) removeCollectedItem(view *av.AttributeView, row *av.Value, boxID string) error {+func (tx *Transaction) removeCollectedItem(view *av.AttributeView, row *av.Value, _ string) error {if err := tx.rememberAutomationView(view, ""); err != nil {return err}diff --git a/kernel/model/attribute_view_location_test.go b/kernel/model/attribute_view_location_test.goindex a571e41454..c7e6abebe2 100644--- a/kernel/model/attribute_view_location_test.go+++ b/kernel/model/attribute_view_location_test.go@@ -15,9 +15,6 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-//go:fix inline-func modelLocationCoordinate(value float64) *float64 { return new(value) }-func TestUpdateAttributeViewLocationPartialAndInvalid(t *testing.T) {const keyID, itemID = "20261009000001-locakey", "20261009000002-locarow"value := &av.Value{ID: "20261009000003-locaval", KeyID: keyID, BlockID: itemID,diff --git a/kernel/model/attribute_view_new_item_group_fts5_test.go b/kernel/model/attribute_view_new_item_group_fts5_test.goindex f3540b751a..ca408ec33b 100644--- a/kernel/model/attribute_view_new_item_group_fts5_test.go+++ b/kernel/model/attribute_view_new_item_group_fts5_test.go@@ -34,13 +34,14 @@ func TestCreateAttributeViewItemPreservesFilteredGroups(t *testing.T) {MSelect: []*av.ValueSelect{{Content: "Feedback", Color: "1"}},}},})- if layout == av.LayoutTypeTable || layout == av.LayoutTypeList {+ switch layout {+ case av.LayoutTypeTable, av.LayoutTypeList:view.GetTableLayout().Columns = append(view.GetTableLayout().Columns,&av.ViewTableColumn{BaseField: &av.BaseField{ID: filterKey.ID}})- } else if layout == av.LayoutTypeGallery {+ case av.LayoutTypeGallery:view.Gallery.CardFields = append(view.Gallery.CardFields,&av.ViewGalleryCardField{BaseField: &av.BaseField{ID: filterKey.ID}})- } else {+ default:view.Kanban.Fields = append(view.Kanban.Fields,&av.ViewKanbanField{BaseField: &av.BaseField{ID: filterKey.ID}})}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex e6c3429e0d..8e49cbb2bf 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -447,7 +447,7 @@ func GetBackmentionDocInBox(defID, refTreeID, keyword string, containChildren, hif nil != backlink {ret = append(ret, backlink)}- if nil != tree && nil == refTree {+ if nil == refTree {refTree = tree}}@@ -466,7 +466,6 @@ func filterBlockPaths(blockLinks []*Backlink) {b.BlockPaths = []*BlockPath{}}}- return}func sortBacklinks(backlinks []*Backlink, tree *parse.Tree) {@@ -1114,7 +1113,8 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBac}buf := bytes.Buffer{}- buf.WriteString(columnFilter() + ":(")+ buf.WriteString(columnFilter())+ buf.WriteString(":(")for i, mentionKeyword := range mentionKeywords {if confSearchSnapshot.BacklinkMentionKeywordsLimit < i {if notify := backmentionNotifier(notifiers); notify != nil {@@ -1131,7 +1131,9 @@ func searchBackmentionInBox(mentionKeywords []string, keyword string, excludeBac}buf.WriteString(")")if "" != keyword {- buf.WriteString(" AND (" + quoteFTSPhrase(keyword) + ")")+ buf.WriteString(" AND (")+ buf.WriteString(quoteFTSPhrase(keyword))+ buf.WriteString(")")}terms := mentionKeywordsif "" != keyword {diff --git a/kernel/model/backlink_sort_fts5_test.go b/kernel/model/backlink_sort_fts5_test.goindex 36f4165e6d..47e07391d6 100644--- a/kernel/model/backlink_sort_fts5_test.go+++ b/kernel/model/backlink_sort_fts5_test.go@@ -154,9 +154,10 @@ func TestBacklinkAnchorSortContext(t *testing.T) {sql.FlushQueue()for _, mode := range []int{0, 1, 2, 0} {want := []string{fixture.targetID}- if mode == 1 {+ switch mode {+ case 1:want = []string{ids[2], ids[1], ids[3], ids[0]}- } else if mode == 2 {+ case 2:want = []string{ids[0], ids[1], ids[3], ids[2]}}for _, explicitBox := range []bool{false, true} {diff --git a/kernel/model/bazaar_test.go b/kernel/model/bazaar_test.goindex 349cf7fe6e..891c060137 100644--- a/kernel/model/bazaar_test.go+++ b/kernel/model/bazaar_test.go@@ -364,7 +364,7 @@ func TestFilterUpdatableBazaarPackages(t *testing.T) {allowed := &UpdatedPackage{Available: &bazaar.Package{Name: "allowed"}}blocked := &UpdatedPackage{Available: &bazaar.Package{Name: "blocked", DisallowUpdate: true}}- updatable, unmetRequirementCount := filterUpdatableBazaarPackages([]*UpdatedPackage{allowed, blocked, &UpdatedPackage{}})+ updatable, unmetRequirementCount := filterUpdatableBazaarPackages([]*UpdatedPackage{allowed, blocked, {}})if len(updatable) != 1 || updatable[0] != allowed {t.Fatalf("expected only the allowed package, got %#v", updatable)}diff --git a/kernel/model/block_swap_test.go b/kernel/model/block_swap_test.goindex 2e7f67a2cf..6afbb654bb 100644--- a/kernel/model/block_swap_test.go+++ b/kernel/model/block_swap_test.go@@ -41,12 +41,13 @@ func TestSwapBlockRefNodes(t *testing.T) {wrap(ref)}var child *ast.Node- if kind == "heading" {+ switch kind {+ case "heading":def.Type = ast.NodeHeadingdef.HeadingLevel = 1child = treenode.NewParagraph("")def.InsertAfter(child)- } else if kind == "list" || kind == "bothLists" {+ case "list", "bothLists":li := wrap(def)child = &ast.Node{Type: ast.NodeList, ListData: &ast.ListData{Typ: 0}}li.AppendChild(child)diff --git a/kernel/model/box.go b/kernel/model/box.goindex 7dc782344e..fe12cac5ff 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -589,7 +589,6 @@ func (box *Box) listFiles(files, ret *[]*FileInfo) {*ret = append(*ret, file)}}- return}type BoxInfo struct {@@ -939,7 +938,6 @@ func clearTempDir(dir string, count *int, size *int64) {if util.IsEmptyDir(dir) {util.RemoveEmptyDir(dir)}- return}func VacuumDataIndex() {diff --git a/kernel/model/cloud_service.go b/kernel/model/cloud_service.goindex ac787200dd..8c1de09847 100644--- a/kernel/model/cloud_service.go+++ b/kernel/model/cloud_service.go@@ -42,7 +42,7 @@ var ErrFailedToConnectCloudServer = errors.New("failed to connect cloud server")var (shorthandAudioPattern = regexp.MustCompile("<audio.*>.*</audio>")shorthandVideoPattern = regexp.MustCompile("<video.*>.*</video>")- shorthandFilePattern = regexp.MustCompile("\\[文件]\\(.*\\)")+ shorthandFilePattern = regexp.MustCompile(`\[文件\]\(.*\)`))func CloudChatGPT(msg string, contextMsgs []string) (ret string, stop bool, err error) {diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 75010c8413..0b1169fc8c 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -814,7 +814,11 @@ func closeKernel(force, setCurrentWorkspace bool, execInstallPkg int, recovery *// 等待正在执行的路径批次退出,未完成任务保留在配置目录供下次启动恢复。diagnostic.Stage("wait for path refresh")hpathRefresh.Lock()+ pendingPathRefresh := len(hpathRefresh.tasks)hpathRefresh.Unlock()+ if 0 < pendingPathRefresh {+ logging.LogInfof("pending path refresh tasks: %d", pendingPathRefresh)+ }diagnostic.Stage("check install package")newVerInstallPkgPath := getNewVerInstallPkgPath(2 == execInstallPkg || (force && 0 == execInstallPkg))if !skipNewVerInstallPkg() && "" != newVerInstallPkgPath {diff --git a/kernel/model/dav_delete_test.go b/kernel/model/dav_delete_test.goindex 1dc280e29f..345dcaeaf8 100644--- a/kernel/model/dav_delete_test.go+++ b/kernel/model/dav_delete_test.go@@ -4,7 +4,6 @@ import ("context""net/http""net/http/httptest"- "reflect""testing""github.com/emersion/go-webdav"@@ -52,7 +51,7 @@ func TestDAVDeleteMissingCollection(t *testing.T) {}for range 3 {err := calendarStore.DeleteCalendar(calendarPath)- if want := webdav.NewHTTPError(http.StatusNotFound, ErrorCalDavCalendarNotFound); !reflect.DeepEqual(err, want) {+ if want := webdav.NewHTTPError(http.StatusNotFound, ErrorCalDavCalendarNotFound); err == nil || err.Error() != want.Error() {t.Fatalf("DeleteCalendar error = %v, want %v", err, want)}}diff --git a/kernel/model/export.go b/kernel/model/export.goindex 2f1f20c9f7..effe19b1a5 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -680,7 +680,7 @@ func ExportSYs(ids []string) (zipPath string) {if block == nil {return}- if nil != block && IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {+ if IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {logging.LogErrorf("export encrypted doc [%s] failed: box [%s] locked", ids[0], block.BoxID)return}@@ -2376,7 +2376,7 @@ func exportPandocConvertZipWithConfig(ids []string, pandocTo, ext string, configif block == nil {return}- if nil != block && IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {+ if IsEncryptedBox(block.BoxID) && !IsBoxUnlocked(block.BoxID) {logging.LogErrorf("export pandoc zip [%s] failed: encrypted notebook locked", ids[0])return}diff --git a/kernel/model/file.go b/kernel/model/file.goindex 6a8d8a588a..47e7892910 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -2364,7 +2364,6 @@ func publishDocRename(tree *parse.Tree, titleChanged, emptyAttrUpdated bool) {if titleChanged || emptyAttrUpdated {IncSync()}- return}type createDocValidation struct {diff --git a/kernel/model/graph.go b/kernel/model/graph.goindex 50037e8d5e..f3b763a7d0 100644--- a/kernel/model/graph.go+++ b/kernel/model/graph.go@@ -646,7 +646,9 @@ func graphDailyNoteFilter(local bool) string {for _, p := range dailyNotesPaths {// 转义单引号,避免日记存储路径闭合 SQL 字符串字面量造成注入// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-xr4h-j7cg-q8pc- buf.WriteString(" AND ref.hpath NOT LIKE '" + strings.ReplaceAll(p, "'", "''") + "%'")+ buf.WriteString(" AND ref.hpath NOT LIKE '")+ buf.WriteString(strings.ReplaceAll(p, "'", "''"))+ buf.WriteString("%'")}return buf.String()}@@ -685,7 +687,9 @@ func nodeTitleLabel(node *GraphNode, blockContent string) {func query2Stmt(queryStr string) (ret string) {buf := bytes.Buffer{}if ast.IsNodeIDPattern(queryStr) {- buf.WriteString("id = '" + queryStr + "'")+ buf.WriteString("id = '")+ buf.WriteString(queryStr)+ buf.WriteString("'")} else {var tags []stringluteEngine := util.NewLute()@@ -711,7 +715,8 @@ func query2Stmt(queryStr string) (ret string) {if "" == part {continue}- buf.WriteString("(content LIKE " + conf.SearchLikePattern(part))+ buf.WriteString("(content LIKE ")+ buf.WriteString(conf.SearchLikePattern(part))buf.WriteString(Conf.Search.Load().NAMFilter(part))buf.WriteString(")")if i < len(parts)-1 {@@ -724,14 +729,18 @@ func query2Stmt(queryStr string) (ret string) {buf.WriteString(" OR ")}for i, tag := range tags {- buf.WriteString("(content LIKE " + conf.SearchLikePattern("#"+tag+"#") + ")")+ buf.WriteString("(content LIKE ")+ buf.WriteString(conf.SearchLikePattern("#" + tag + "#"))+ buf.WriteString(")")if i < len(tags)-1 {buf.WriteString(" AND ")}}buf.WriteString(" OR ")for i, tag := range tags {- buf.WriteString("ial LIKE '%tags=\"%" + conf.EscapeSearchLikePattern(tag) + "%\"%' ESCAPE '\\'")+ buf.WriteString("ial LIKE '%tags=\"%")+ buf.WriteString(conf.EscapeSearchLikePattern(tag))+ buf.WriteString("%\"%' ESCAPE '\\\\'")if i < len(tags)-1 {buf.WriteString(" AND ")}diff --git a/kernel/model/history.go b/kernel/model/history.goindex f1682a965d..3870ecfa5e 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -997,7 +997,6 @@ func (box *Box) generateDocHistory0() {}indexHistoryDir(filepath.Base(historyDir), util.NewLute())- return}func generateDocHistoryFile(boxID, file, historyDir string, luteEngine *lute.Lute) error {@@ -1201,7 +1200,6 @@ func generateTreeHistory(tree *parse.Tree, historyDir string) {logging.LogErrorf("generate history failed: %s", err)return}- return}func generateAvHistoryInTree(tree *parse.Tree, historyDir string) {@@ -1235,7 +1233,6 @@ func getHistoryDir(suffix string) (ret string, err error) {func ReindexHistory() {task.AppendTask(task.HistoryDatabaseIndexFull, fullReindexHistory)- return}func fullReindexHistory() {@@ -1258,7 +1255,6 @@ func fullReindexHistory() {name := historyDir.Name()indexHistoryDir(name, lutEngine)}- return}var validOps = []string{HistoryOpClean, HistoryOpUpdate, HistoryOpDelete, HistoryOpFormat, HistoryOpSync, HistoryOpReplace, HistoryOpOutline}@@ -1421,7 +1417,6 @@ func indexHistoryDir(name string, luteEngine *lute.Lute) {}sql.IndexHistoriesQueue(histories)- return}func fromSQLHistories(sqlHistories []*sql.History) (ret []*HistoryItem) {diff --git a/kernel/model/ocr.go b/kernel/model/ocr.goindex ec33639a3e..c9899f8f2f 100644--- a/kernel/model/ocr.go+++ b/kernel/model/ocr.go@@ -140,9 +140,10 @@ func currentPaddleConfig() ocr.PaddleConfig {value := Conf.GetOCR()directory := filepath.Join(util.WorkingDir, "stage", "ocr", "runtime", runtime.GOOS+"-"+runtime.GOARCH)filename := "libonnxruntime.so"- if runtime.GOOS == "windows" {+ switch runtime.GOOS {+ case "windows":filename = "onnxruntime.dll"- } else if runtime.GOOS == "darwin" {+ case "darwin":filename = "libonnxruntime.dylib"}result := ocr.PaddleConfig{Directory: ocrModelDirectory(value.Model), Library: filepath.Join(directory, filename), Thresholds: ocr.Thresholds(value.Thresholds)}diff --git a/kernel/model/oidc.go b/kernel/model/oidc.goindex 5e9cd1f1ef..caee5ad61a 100644--- a/kernel/model/oidc.go+++ b/kernel/model/oidc.go@@ -89,14 +89,6 @@ type oidcStartInput struct {RememberMe bool `json:"rememberMe"`}-type oidcMobileCallbackInput struct {- CallbackURL string `json:"callbackURL"`-}--type oidcPollInput struct {- PollToken string `json:"pollToken"`-}-func OIDCValidateStart(c *gin.Context, request apicontract.SystemOIDCRequest) (ret apicontract.Response[apicontract.SystemOIDCStartData]) {ret = apicontract.Success(apicontract.SystemOIDCStartData{})diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex db68cc33fe..a5462ae689 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -292,7 +292,6 @@ func PurgePublishAccess() {}}SetPublishAccess(tempPublishAccess)- return}func CheckPathAccessableByPublishIgnore(box string, path string, publishIgnore PublishAccess) bool {diff --git a/kernel/model/render.go b/kernel/model/render.goindex af3aa18c5b..949c9294ae 100644--- a/kernel/model/render.go+++ b/kernel/model/render.go@@ -456,7 +456,8 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolif 0 == blockEmbedMode { // 使用原始文本buf.WriteString(line)} else { // 使用引述块- buf.WriteString("> " + line)+ buf.WriteString("> ")+ buf.WriteString(line)}if i < len(lines)-1 {buf.WriteString("\n")@@ -504,7 +505,6 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolunlink.Unlink()}}- return}func renderBlockMarkdownR(id string, rendered *[]string, boxIDs ...string) (ret []*ast.Node) {diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 90d43eaa14..da75aaa677 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -420,7 +420,6 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText bif !displayInText {renderTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}}- var unlinks []*ast.Nodeast.Walk(snapshotTree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue@@ -431,10 +430,6 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText breturn ast.WalkContinue})- for _, unlink := range unlinks {- unlink.Unlink()- }-var appends []*ast.Nodefor n := snapshotTree.Root.FirstChild; nil != n; n = n.Next {appends = append(appends, n)diff --git a/kernel/model/repository_types_count_test.go b/kernel/model/repository_types_count_test.goindex 5beb1a0bdd..580c79f656 100644--- a/kernel/model/repository_types_count_test.go+++ b/kernel/model/repository_types_count_test.go@@ -136,7 +136,7 @@ func TestStatTypesByPathNoExt(t *testing.T) {func format(ret []*TypeCount) string {var s strings.Builderfor _, tc := range ret {- s.WriteString(fmt.Sprintf("%s=%d ", tc.Type, tc.Count))+ fmt.Fprintf(&s, "%s=%d ", tc.Type, tc.Count)}return s.String()}diff --git a/kernel/model/search.go b/kernel/model/search.goindex 1592c190e6..d0e194fb0b 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -1927,7 +1927,7 @@ func buildBoxesFilter(boxes []string, alias ...string) (clause string, args []anbuilder := bytes.Buffer{}builder.WriteString(" AND (")for i, box := range boxes {- builder.WriteString(fmt.Sprintf("%sbox = ?", prefix))+ fmt.Fprintf(&builder, "%sbox = ?", prefix)args = append(args, box)if i < len(boxes)-1 {builder.WriteString(" OR ")@@ -1951,7 +1951,7 @@ func buildPathsFilter(paths []string, alias ...string) (clause string, args []anbuilder := bytes.Buffer{}builder.WriteString(" AND (")for i, path := range paths {- builder.WriteString(fmt.Sprintf("%spath LIKE ?", prefix))+ fmt.Fprintf(&builder, "%spath LIKE ?", prefix)args = append(args, path+"%")if i < len(paths)-1 {builder.WriteString(" OR ")@@ -1972,7 +1972,7 @@ func buildRootIDExclusionFilter(rootIDs []string, alias ...string) (clause strinprefix = alias[0]}builder := bytes.Buffer{}- builder.WriteString(fmt.Sprintf(" AND %sroot_id NOT IN (", prefix))+ fmt.Fprintf(&builder, " AND %sroot_id NOT IN (", prefix)for i, rootID := range rootIDs {if 0 < i {builder.WriteString(", ")@@ -2312,13 +2312,12 @@ func removeLimitClause(stmt string) string {return stmt}- switch parsedStmt.(type) {+ switch stmtNode := parsedStmt.(type) {case *sqlparser.Select:- slct := parsedStmt.(*sqlparser.Select)- if nil != slct.Limit {- slct.Limit = nil+ if nil != stmtNode.Limit {+ stmtNode.Limit = nil}- stmt = sqlparser.String(slct)+ stmt = sqlparser.String(stmtNode)}return stmt}diff --git a/kernel/model/search_attribute_view.go b/kernel/model/search_attribute_view.goindex f6e1ca774b..89de39b7df 100644--- a/kernel/model/search_attribute_view.go+++ b/kernel/model/search_attribute_view.go@@ -234,7 +234,9 @@ func attributeViewSearchPartHTML(part *attributeViewSearchPart) string {break}result.WriteString(util.EscapeHTML(part.text[cursor:match.start]))- result.WriteString("<mark>" + util.EscapeHTML(part.text[match.start:match.end]) + "</mark>")+ result.WriteString("<mark>")+ result.WriteString(util.EscapeHTML(part.text[match.start:match.end]))+ result.WriteString("</mark>")cursor = match.end}result.WriteString(util.EscapeHTML(part.text[cursor:end]))diff --git a/kernel/model/search_attribute_view_test.go b/kernel/model/search_attribute_view_test.goindex 7e7f90b9ff..dacf973ade 100644--- a/kernel/model/search_attribute_view_test.go+++ b/kernel/model/search_attribute_view_test.go@@ -325,7 +325,9 @@ func TestAttributeViewSearchCompactFieldLimit(t *testing.T) {marked.WriteString("DB")for _, field := range []string{"one", "two", "three", "four", "five", "six", "seven", "eight"} {attrView.KeyValues = append(attrView.KeyValues, &av.KeyValues{Key: &av.Key{Name: field, Type: av.KeyTypeText}, Values: []*av.Value{attributeViewSearchTestText("match")}})- marked.WriteString(" " + field + " <mark>match</mark>")+ marked.WriteString(" ")+ marked.WriteString(field)+ marked.WriteString(" <mark>match</mark>")}got := compactAttributeViewSearchContent(attrView, marked.String())if strings.Count(got, `class="fn__code"`) != 6 || strings.Contains(got, "seven") || strings.Contains(got, "eight") {diff --git a/kernel/model/search_hpath_fts_test.go b/kernel/model/search_hpath_fts_test.goindex 553a91aab5..39314af74c 100644--- a/kernel/model/search_hpath_fts_test.go+++ b/kernel/model/search_hpath_fts_test.go@@ -66,6 +66,9 @@ func TestFTSAndHPathMatchesIntegration(t *testing.T) {ids = append(ids, id)sources = append(sources, source)}+ if err = rows.Err(); err != nil {+ t.Fatal(err)+ }if err = rows.Close(); err != nil {t.Fatal(err)}diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex d45d4ce706..604dc43340 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -461,6 +461,9 @@ func TestFTSAndHPathMatchesDeduplicateAndSort(t *testing.T) {ids = append(ids, id)sources = append(sources, source)}+ if err = rows.Err(); err != nil {+ t.Fatal(err)+ }expectedIDs := []string{"20260729120000-parent1", "20260729120002-block01", "20260729120001-child01"}if !slices.Equal(ids, expectedIDs) {t.Fatalf("单关键词路径搜索排序错误:got %v, want %v", ids, expectedIDs)@@ -724,6 +727,9 @@ func TestDocumentSearchFinalOrderPrioritizesDirectMatches(t *testing.T) {sources = append(sources, source)scores = append(scores, score)}+ if err = rows.Err(); err != nil {+ t.Fatal(err)+ }if err = rows.Close(); err != nil {t.Fatal(err)}diff --git a/kernel/model/session.go b/kernel/model/session.goindex e5a78a2acc..4d3925a6e2 100644--- a/kernel/model/session.go+++ b/kernel/model/session.go@@ -81,7 +81,7 @@ func LoginAuth(c *gin.Context, request apicontract.SystemLoginAuthRequest) (ret}inputCaptcha = request.Captcha- if strings.ToLower(workspaceSession.Captcha) != strings.ToLower(inputCaptcha) {+ if !strings.EqualFold(workspaceSession.Captcha, inputCaptcha) {ret = apicontract.Failure[apicontract.Null](1, Conf.Language(22))logging.LogWarnf("invalid captcha")diff --git a/kernel/model/shorthand_markdown.go b/kernel/model/shorthand_markdown.goindex 43b713993e..eedeaa80a1 100644--- a/kernel/model/shorthand_markdown.go+++ b/kernel/model/shorthand_markdown.go@@ -163,7 +163,8 @@ func normalizeShorthandMarkdown(md string, options *parse.Options) (string, map[if "" != marker.replacement {result.WriteString(marker.replacement)if probe && marker.opened {- result.WriteString(marker.token + " ")+ result.WriteString(marker.token)+ result.WriteString(" ")}} else {if probe {diff --git a/kernel/model/shorthand_markdown_test.go b/kernel/model/shorthand_markdown_test.goindex b918b4e3c3..1f103a02b5 100644--- a/kernel/model/shorthand_markdown_test.go+++ b/kernel/model/shorthand_markdown_test.go@@ -260,7 +260,7 @@ func BenchmarkShorthandMarkdownFalseClosings(b *testing.B) {md := "····go\n" + strings.Repeat("···\n ····\n", 1000) + "····"engine := util.NewLute()b.ReportAllocs()- for i := 0; i < b.N; i++ {+ for b.Loop() {parseShorthandMarkdown(md, time.Now(), engine)}}diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 8f2d956ab9..9b69f33b4c 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -239,7 +239,6 @@ func BootSyncData() {if iosAfterBoot {completeSyncPerception(cloudPublished, err)}- return}func SyncData(byHand bool) {diff --git a/kernel/model/sync_provider_completion_test.go b/kernel/model/sync_provider_completion_test.goindex cb857d80ba..bdabdf3f54 100644--- a/kernel/model/sync_provider_completion_test.go+++ b/kernel/model/sync_provider_completion_test.go@@ -72,9 +72,10 @@ func TestSyncProviderCompletionFailurePreservesSource(t *testing.T) {if err != nil {t.Fatal(err)}- if failure == "offline" {+ switch failure {+ case "offline":Conf.Sync.Load().Enabled = false- } else if failure == "missing-current-chunk" {+ case "missing-current-chunk":files, err := deferredSyncAssets()if err != nil || len(files) != 1 {t.Fatalf("expected deferred asset: %v %v", files, err)@@ -83,7 +84,7 @@ func TestSyncProviderCompletionFailurePreservesSource(t *testing.T) {if err = os.Remove(filepath.Join(Conf.Sync.Load().Local.Endpoint, "main", "objects", chunk[:2], chunk[2:])); err != nil {t.Fatal(err)}- } else {+ default:state, err := os.ReadFile(assetDownloadStatePath())if err != nil {t.Fatal(err)diff --git a/kernel/model/template_doc_tree_test.go b/kernel/model/template_doc_tree_test.goindex 282dcbc663..819cd5df5f 100644--- a/kernel/model/template_doc_tree_test.go+++ b/kernel/model/template_doc_tree_test.go@@ -522,7 +522,7 @@ func TestAttachTemplateDocTreePlansValidatesTransactionBoundary(t *testing.T) {t.Fatalf("render document tree plan failed: %v", err)}transaction, _ := newTemplateDocTreeInsertTransaction(summary.ID, fixture.sourceID)- if attached, attachErr := AttachTemplateDocTreePlans([]*Transaction{transaction, &Transaction{}}); nil == attachErr || attached {+ if attached, attachErr := AttachTemplateDocTreePlans([]*Transaction{transaction, {}}); nil == attachErr || attached {t.Fatalf("plan spanning multiple transactions was accepted: attached=%t, err=%v", attached, attachErr)}if _, ok := templateDocTreePlans.Load(summary.ID); !ok {diff --git a/kernel/model/template_export_attrs.go b/kernel/model/template_export_attrs.goindex 56b778f892..33e5ede191 100644--- a/kernel/model/template_export_attrs.go+++ b/kernel/model/template_export_attrs.go@@ -130,7 +130,8 @@ func templateDocumentAttributes(source []byte) [][]string {return nil}actions = append(actions, text[start:end+1])- masked.WriteString(prefix + strings.Repeat("x", len(actions)))+ masked.WriteString(prefix)+ masked.WriteString(strings.Repeat("x", len(actions)))text = text[end+1:]}attrs := parseTemplateDocumentAttributes(masked.String())diff --git a/kernel/model/template_manage_test.go b/kernel/model/template_manage_test.goindex 6566a0fbdd..e35a441c31 100644--- a/kernel/model/template_manage_test.go+++ b/kernel/model/template_manage_test.go@@ -474,7 +474,9 @@ func TestExportTemplateDocumentAttributeScope(t *testing.T) {tree.Root.SetIALAttr("icon", "default")var markdown strings.Builderfor _, chunk := range test.chunks {- markdown.WriteString("```template\n" + chunk + "\n```\n\n")+ markdown.WriteString("```template\n")+ markdown.WriteString(chunk)+ markdown.WriteString("\n```\n\n")}engine := NewLute()codeTree := parse.Parse("", []byte(markdown.String()), engine.ParseOptions)diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 152e27e741..d646e5b99b 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2294,9 +2294,7 @@ func getRemovedNodes(oldNode, newNode *ast.Node) (ret []*ast.Node) {if !entering || !n.IsBlock() {return ast.WalkContinue}- if _, ok := oldNodes[n.ID]; ok {- delete(oldNodes, n.ID)- }+ delete(oldNodes, n.ID)return ast.WalkContinue})for _, n := range oldNodes {@@ -3131,7 +3129,6 @@ func (tx *Transaction) rollback() {tx.writeTransactionTree = niltx.state.Store(3)tx.m.Unlock()- return}// cleanupRestoredCreatedDocs 清理提交失败前已经写入的计划文档,避免父文档失败后遗留孤儿文档。@@ -3270,7 +3267,6 @@ func (tx *Transaction) writeTree(tree *parse.Tree) {tx.collectionState().err = err}treenode.UpsertBlockTree(tree)- return}func getRefsCacheByDefNode(updateNode *ast.Node, boxID string) (ret []*sql.Ref, changedNodes []*ast.Node) {diff --git a/kernel/model/transaction_mindmap_summary_test.go b/kernel/model/transaction_mindmap_summary_test.goindex 91634fdde5..1ccb60a1e8 100644--- a/kernel/model/transaction_mindmap_summary_test.go+++ b/kernel/model/transaction_mindmap_summary_test.go@@ -171,9 +171,10 @@ func TestMindmapSummaryTransactionsAndListRoundTrip(t *testing.T) {// 转换块类型和折叠不改变成员或概要文字。ast.Walk(list, func(node *ast.Node, entering bool) ast.WalkStatus {if entering {- if node.Type == ast.NodeList {+ switch node.Type {+ case ast.NodeList:node.Type = ast.NodeMindmap- } else if node.Type == ast.NodeListItem {+ case ast.NodeListItem:node.Type = ast.NodeMindmapItemnode.SetIALAttr("fold", "1")}diff --git a/kernel/model/transaction_move_next_fts5_test.go b/kernel/model/transaction_move_next_fts5_test.goindex d7c6dacb22..164ca2d3ee 100644--- a/kernel/model/transaction_move_next_fts5_test.go+++ b/kernel/model/transaction_move_next_fts5_test.go@@ -62,10 +62,11 @@ func TestMoveNextIDOrderAndReplay(t *testing.T) {}}for step := range 3 {tx := forward- if step == 1 {+ switch step {+ case 1:tx = &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}tx.MarkReplay()- } else if step == 2 {+ case 2:tx = &Transaction{DoOperations: cloneOperations(forward.DoOperations)}tx.MarkReplay()}diff --git a/kernel/model/undolog.go b/kernel/model/undolog.goindex 80e8ff0f33..c66a3bcdc2 100644--- a/kernel/model/undolog.go+++ b/kernel/model/undolog.go@@ -79,7 +79,7 @@ type UndoLog struct {// GlobalUndoLog 全局撤销日志单例。内存态,重启清空。var GlobalUndoLog = newUndoLog(64)-var undoEntrySeq uint64+var undoEntrySeq atomic.Uint64func newUndoLog(max int) *UndoLog {return &UndoLog{@@ -89,7 +89,7 @@ func newUndoLog(max int) *UndoLog {}func newUndoEntryID() string {- seq := atomic.AddUint64(&undoEntrySeq, 1)+ seq := undoEntrySeq.Add(1)return fmt.Sprintf("undo-%d-%d", time.Now().UnixNano(), seq)}diff --git a/kernel/plugin/abort/controller.go b/kernel/plugin/abort/controller.goindex 43709456f8..0fad4cfd5e 100644--- a/kernel/plugin/abort/controller.go+++ b/kernel/plugin/abort/controller.go@@ -329,7 +329,7 @@ func newControllerConstructor(rt *goja.Runtime, prototype *goja.Object, signalCt}// newControllerPrototype 构造 AbortController.prototype:signal 访问器与 abort 方法。-func newControllerPrototype(rt *goja.Runtime, signalCtor *goja.Object) (*goja.Object, error) {+func newControllerPrototype(rt *goja.Runtime, _ *goja.Object) (*goja.Object, error) {prototype := rt.NewObject()self := func(call goja.FunctionCall, method string) *controllerState {diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.goindex 24f93de092..318abeb6cc 100644--- a/kernel/plugin/api_client.go+++ b/kernel/plugin/api_client.go@@ -572,7 +572,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {openPromises = append(openPromises, Promise{Resolve: resolve, Reject: reject})}- resolveOpenPromises := func(rt *goja.Runtime) {+ resolveOpenPromises := func(_ *goja.Runtime) {if openPromises != nil {for _, promise := range openPromises {if resolveErr := promise.Resolve(nil); resolveErr != nil {diff --git a/kernel/plugin/api_secrets_vars.go b/kernel/plugin/api_secrets_vars.goindex c115a58322..49338c5707 100644--- a/kernel/plugin/api_secrets_vars.go+++ b/kernel/plugin/api_secrets_vars.go@@ -28,7 +28,7 @@ import (// siyuan.secrets.resolve(tpl) 仅替换模板里的 {{secrets.NAME}} 占位符,// siyuan.vars.resolve(tpl) 仅替换 {{vars.NAME}}。两者各自只返回替换后的字符串,// 不向插件暴露密钥/变量清单。同步执行(纯内存操作,无 I/O)。-func injectSecretsVars(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {+func injectSecretsVars(_ *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {defer func() {if r := recover(); r != nil {err = fmt.Errorf("injectSecretsVars: %v", r)diff --git a/kernel/plugin/api_server.go b/kernel/plugin/api_server.goindex 49fd9a9da0..46a0daae2c 100644--- a/kernel/plugin/api_server.go+++ b/kernel/plugin/api_server.go@@ -24,7 +24,7 @@ import ()// injectServer adds siyuan.server to the goja context.-func injectServer(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {+func injectServer(_ *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {defer func() {if r := recover(); r != nil {err = fmt.Errorf("injectServer: %v", r)diff --git a/kernel/plugin/crypto/kdf.go b/kernel/plugin/crypto/kdf.goindex 4bd1be7574..9604101f01 100644--- a/kernel/plugin/crypto/kdf.go+++ b/kernel/plugin/crypto/kdf.go@@ -20,7 +20,6 @@ import ("bytes""crypto/hkdf""crypto/pbkdf2"- "hash")// importKDFKey 导入 HKDF/PBKDF2 的基础密钥材料,规范要求此类密钥不可导出。@@ -56,7 +55,7 @@ func deriveBitsHKDF(alg Algorithm, key *Key, length *int) ([]byte, error) {return nil, err}- ret, err := hkdf.Key[hash.Hash](h.New, key.secret, alg.Salt, string(alg.Info), size)+ ret, err := hkdf.Key(h.New, key.secret, alg.Salt, string(alg.Info), size)if err != nil {return nil, operationError("HKDF derivation failed: %s", err)}@@ -85,7 +84,7 @@ func deriveBitsPBKDF2(alg Algorithm, key *Key, length *int) ([]byte, error) {}// PBKDF2 的口令按字节处理,string 转换保留原始字节。- ret, err := pbkdf2.Key[hash.Hash](h.New, string(key.secret), alg.Salt, *alg.Iterations, size)+ ret, err := pbkdf2.Key(h.New, string(key.secret), alg.Salt, *alg.Iterations, size)if err != nil {return nil, operationError("PBKDF2 derivation failed: %s", err)}diff --git a/kernel/plugin/crypto/key.go b/kernel/plugin/crypto/key.goindex 7ff166049b..5224d3455a 100644--- a/kernel/plugin/crypto/key.go+++ b/kernel/plugin/crypto/key.go@@ -125,8 +125,3 @@ func filterUsages(usages []KeyUsage, allowed ...KeyUsage) []KeyUsage {}return ret}--//go:fix inline-func intPtr(value int) *int {- return new(value)-}diff --git a/kernel/plugin/crypto_binding.go b/kernel/plugin/crypto_binding.goindex 4626894d99..6c6cc5e3b6 100644--- a/kernel/plugin/crypto_binding.go+++ b/kernel/plugin/crypto_binding.go@@ -261,7 +261,7 @@ func (h *cryptoHost) cryptoBytesOf(rt *goja.Runtime, value goja.Value, name stri}// isBufferSource 判断值是 ArrayBuffer 还是 ArrayBuffer 视图。-func (h *cryptoHost) isBufferSource(rt *goja.Runtime, value goja.Value) (bool, error) {+func (h *cryptoHost) isBufferSource(_ *goja.Runtime, value goja.Value) (bool, error) {if !isJsValueNotNull(value) {return false, nil}diff --git a/kernel/plugin/formdata/formdata.go b/kernel/plugin/formdata/formdata.goindex 711d726f52..be78917a1a 100644--- a/kernel/plugin/formdata/formdata.go+++ b/kernel/plugin/formdata/formdata.go@@ -365,11 +365,16 @@ func (s *State) EncodeMultipart() (body []byte, contentType string) {var buffer bytes.Bufferfor _, e := range s.entries {- buffer.WriteString("--" + boundary + "\r\n")- buffer.WriteString(`Content-Disposition: form-data; name="` +- multipartNameEscaper.Replace(crlfReplacer.Replace(e.name)) + `"`)+ buffer.WriteString("--")+ buffer.WriteString(boundary)+ buffer.WriteString("\r\n")+ buffer.WriteString(`Content-Disposition: form-data; name="`)+ buffer.WriteString(multipartNameEscaper.Replace(crlfReplacer.Replace(e.name)))+ buffer.WriteString(`"`)if e.fileState == nil {- buffer.WriteString("\r\n\r\n" + crlfReplacer.Replace(e.value) + "\r\n")+ buffer.WriteString("\r\n\r\n")+ buffer.WriteString(crlfReplacer.Replace(e.value))+ buffer.WriteString("\r\n")continue}@@ -377,11 +382,17 @@ func (s *State) EncodeMultipart() (body []byte, contentType string) {if fileType == "" {fileType = "application/octet-stream"}- buffer.WriteString(`; filename="` + multipartNameEscaper.Replace(e.fileState.name) + `"` +- "\r\nContent-Type: " + fileType + "\r\n\r\n")+ buffer.WriteString(`; filename="`)+ buffer.WriteString(multipartNameEscaper.Replace(e.fileState.name))+ buffer.WriteString(`"`)+ buffer.WriteString("\r\nContent-Type: ")+ buffer.WriteString(fileType)+ buffer.WriteString("\r\n\r\n")buffer.Write(e.fileState.data)buffer.WriteString("\r\n")}- buffer.WriteString("--" + boundary + "--\r\n")+ buffer.WriteString("--")+ buffer.WriteString(boundary)+ buffer.WriteString("--\r\n")return buffer.Bytes(), "multipart/form-data; boundary=" + boundary}diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.goindex 1bd628ffcc..8efd435b33 100644--- a/kernel/plugin/sandbox.go+++ b/kernel/plugin/sandbox.go@@ -440,7 +440,7 @@ func getJsContextValue(rt *goja.Runtime, paths []any) (value goja.Value, err err}// dispatchEvent calls the globalThis.siyuan.event.on hook with the given event object.-func dispatchEvent(p *KernelPlugin, rt *goja.Runtime, e any) (async bool, err error) {+func dispatchEvent(_ *KernelPlugin, rt *goja.Runtime, e any) (async bool, err error) {defer func() {if r := recover(); r != nil {err = fmt.Errorf("goja panic during dispatchEvent: %v", r)diff --git a/kernel/plugin/source_file_identity_other.go b/kernel/plugin/source_file_identity_other.goindex 8cb70fd8bd..f3d6b35906 100644--- a/kernel/plugin/source_file_identity_other.go+++ b/kernel/plugin/source_file_identity_other.go@@ -20,6 +20,6 @@ package pluginimport "os"-func readPluginSourceFileIdentity(info os.FileInfo) (device, inode uint64, ctime int64) {+func readPluginSourceFileIdentity(_ os.FileInfo) (device, inode uint64, ctime int64) {return}diff --git a/kernel/plugin/streams/readable.go b/kernel/plugin/streams/readable.goindex 42174dee80..4b28d80d90 100644--- a/kernel/plugin/streams/readable.go+++ b/kernel/plugin/streams/readable.go@@ -415,7 +415,7 @@ func readableStreamClose(h *Host, stream *readableState) {// readableStreamError 对应 ReadableStreamError:置为 errored,拒绝 reader 的 closed Promise,并以同一 reason// 拒绝所有挂起的 read() 请求。-func readableStreamError(h *Host, stream *readableState, reason goja.Value) {+func readableStreamError(_ *Host, stream *readableState, reason goja.Value) {stream.status = statusErroredstream.storedError = reasonreader := stream.readerdiff --git a/kernel/plugin/streams/writable.go b/kernel/plugin/streams/writable.goindex 149e7063ba..113cc23a7d 100644--- a/kernel/plugin/streams/writable.go+++ b/kernel/plugin/streams/writable.go@@ -401,7 +401,7 @@ func writableStreamFinishInFlightWriteWithError(h *Host, stream *writableState,}// writableStreamFinishInFlightClose 对应 WritableStreamFinishInFlightClose。-func writableStreamFinishInFlightClose(h *Host, stream *writableState) {+func writableStreamFinishInFlightClose(_ *Host, stream *writableState) {stream.inFlightCloseRequest.settle(true, goja.Undefined())stream.inFlightCloseRequest = nildiff --git a/kernel/search/mark.go b/kernel/search/mark.goindex 10038e8849..3aaecbfb75 100644--- a/kernel/search/mark.go+++ b/kernel/search/mark.go@@ -136,7 +136,8 @@ func compileHighlightingRegexp(keywords []string, caseSensitive, splitWords bool}var re strings.Builder- re.WriteString(ic + "(")+ re.WriteString(ic)+ re.WriteString("(")for i, k := range keywords {if "" == k {continuediff --git a/kernel/server/serve.go b/kernel/server/serve.goindex c06380b2be..84615d8b20 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -851,29 +851,27 @@ func serveAppearance(ginServer *gin.Engine) {return}- for {- data, err := os.ReadFile(filePath)- if err != nil {- c.JSON(200, enUSMap)- return- }- data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))+ data, err := os.ReadFile(filePath)+ if err != nil {+ c.JSON(200, enUSMap)+ return+ }+ data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))- langMap := map[string]any{}- if err = gulu.JSON.UnmarshalJSON(data, &langMap); err != nil {- logging.LogErrorf("unmarshal json [%s] failed: %s", filePath, err)- c.JSON(200, enUSMap)- return- }+ langMap := map[string]any{}+ if err = gulu.JSON.UnmarshalJSON(data, &langMap); err != nil {+ logging.LogErrorf("unmarshal json [%s] failed: %s", filePath, err)+ c.JSON(200, enUSMap)+ return+ }- for enUSDataKey, enUSDataValue := range enUSMap {- if _, ok := langMap[enUSDataKey]; !ok {- langMap[enUSDataKey] = enUSDataValue- }+ for enUSDataKey, enUSDataValue := range enUSMap {+ if _, ok := langMap[enUSDataKey]; !ok {+ langMap[enUSDataKey] = enUSDataValue}- c.JSON(200, langMap)- return}+ c.JSON(200, langMap)+ return}}diff --git a/kernel/sql/av_rollup_target_test.go b/kernel/sql/av_rollup_target_test.goindex ae274ef7e1..8302adc298 100644--- a/kernel/sql/av_rollup_target_test.go+++ b/kernel/sql/av_rollup_target_test.go@@ -349,11 +349,12 @@ func newNestedRollupTestLeaf(typ av.KeyType) (*av.AttributeView, *av.Key) {values := &av.KeyValues{Key: key}for row, block := range attrView.GetBlockKeyValues().Values {value := &av.Value{ID: block.BlockID + "-value", KeyID: key.ID, BlockID: block.BlockID, Type: typ}- if typ == av.KeyTypeNumber {+ switch typ {+ case av.KeyTypeNumber:value.Number = &av.ValueNumber{Content: float64(row + 1), IsNotEmpty: true}- } else if typ == av.KeyTypeLocation {+ case av.KeyTypeLocation:value.Location = &av.ValueLocation{Name: fmt.Sprintf("fresh-%d", row), OriginalInput: "source"}- } else {+ default:value.Text = &av.ValueText{Content: fmt.Sprintf("fresh-%d", row)}}values.Values = append(values.Values, value)diff --git a/kernel/sql/block.go b/kernel/sql/block.goindex 2be0cf8d86..d18609ff97 100644--- a/kernel/sql/block.go+++ b/kernel/sql/block.go@@ -108,6 +108,9 @@ func queryBlockRowIDsTx(tx *sql.Tx, blocks []*Block) (ret map[string]int64, err}ret[id] = rowID}+ if err = rows.Err(); err != nil {+ logging.LogErrorf("iterate block rowids failed: %s", err)+ }return}@@ -244,9 +247,11 @@ func nodeStaticContent(node *ast.Node, excludeTypes []string, includeTextMarkATi}}if ast.NodeCallout == n.Type {- buf.WriteString(n.CalloutType + " ")+ buf.WriteString(n.CalloutType)+ buf.WriteString(" ")if "" != n.CalloutIcon && 0 == n.CalloutIconType {- buf.WriteString(n.CalloutIcon + " ")+ buf.WriteString(n.CalloutIcon)+ buf.WriteString(" ")}if "" != n.CalloutTitle {if titleTree := parse.Inline("", []byte(n.CalloutTitle), luteEngine.ParseOptions); nil != titleTree && nil != titleTree.Root.FirstChild.FirstChild {@@ -358,12 +363,14 @@ func nodeStaticContent(node *ast.Node, excludeTypes []string, includeTextMarkATiif n.IsTextMarkType("a") && includeTextMarkATitleURL {// 搜索不到超链接元素的 URL 和标题 https://github.com/siyuan-note/siyuan/issues/7352if "" != n.TextMarkATitle {- buf.WriteString(" " + util.UnescapeHTML(n.TextMarkATitle))+ buf.WriteString(" ")+ buf.WriteString(util.UnescapeHTML(n.TextMarkATitle))}if !strings.HasPrefix(n.TextMarkAHref, "assets/") || includeAssetPath {href := util.UnescapeHTML(n.TextMarkAHref)- buf.WriteString(" " + util.UnescapeHTML(href))+ buf.WriteString(" ")+ buf.WriteString(util.UnescapeHTML(href))}}case ast.NodeBackslashContent:diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 2e23a00860..826e291749 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -410,30 +410,28 @@ func queryWithLimitInfo(stmt string, limit int, info *QueryLimitInfo) (ret []mapreturn queryRawStmtWithLimitInfo(stmt, limit, info)}- switch parsedStmt.(type) {+ switch parsedStmt := parsedStmt.(type) {case *sqlparser.Select:- slct := parsedStmt.(*sqlparser.Select)- if info != nil && slct.Limit != nil && slct.Limit.Rowcount != nil {+ if info != nil && parsedStmt.Limit != nil && parsedStmt.Limit.Rowcount != nil {info.Limit = 0}- if nil == slct.Limit || nil == slct.Limit.Rowcount {+ if nil == parsedStmt.Limit || nil == parsedStmt.Limit.Rowcount {fallbackStmt += " LIMIT " + strconv.Itoa(limit)}limitClause := getLimitClause(parsedStmt, limit)- slct.Limit = limitClause- stmt = sqlparser.String(slct)+ parsedStmt.Limit = limitClause+ stmt = sqlparser.String(parsedStmt)case *sqlparser.Union:// Kernel API `/api/query/sql` support `UNION` statement https://github.com/siyuan-note/siyuan/issues/8226- union := parsedStmt.(*sqlparser.Union)- if info != nil && union.Limit != nil && union.Limit.Rowcount != nil {+ if info != nil && parsedStmt.Limit != nil && parsedStmt.Limit.Rowcount != nil {info.Limit = 0}- if nil == union.Limit || nil == union.Limit.Rowcount {+ if nil == parsedStmt.Limit || nil == parsedStmt.Limit.Rowcount {fallbackStmt += " LIMIT " + strconv.Itoa(limit)}limitClause := getLimitClause(parsedStmt, limit)- union.Limit = limitClause- stmt = sqlparser.String(union)+ parsedStmt.Limit = limitClause+ stmt = sqlparser.String(parsedStmt)default:return queryRawStmtWithLimitInfo(stmt, limit, info)}@@ -441,16 +439,15 @@ func queryWithLimitInfo(stmt string, limit int, info *QueryLimitInfo) (ret []mapreturn queryRawStmtWithLimitInfo(stmt, limit, info)}} else {- switch parsedStmt2.(type) {+ switch parsedStmt2 := parsedStmt2.(type) {case *sqlparser2.SelectStatement:- slct := parsedStmt2.(*sqlparser2.SelectStatement)- if info != nil && slct.LimitExpr != nil {+ if info != nil && parsedStmt2.LimitExpr != nil {info.Limit = 0}- if nil == slct.LimitExpr {+ if nil == parsedStmt2.LimitExpr {fallbackStmt += " LIMIT " + strconv.Itoa(limit)- slct.LimitExpr = &sqlparser2.NumberLit{Value: strconv.Itoa(limit)}- serialized, ok := stringifySelectStatement(slct)+ parsedStmt2.LimitExpr = &sqlparser2.NumberLit{Value: strconv.Itoa(limit)}+ serialized, ok := stringifySelectStatement(parsedStmt2)if !ok {return queryRawStmtWithLimitInfo(originalStmt, limit, info)}@@ -546,16 +543,14 @@ func ToBlocks(result []map[string]any) (ret []*Block) {}func getLimitClause(parsedStmt sqlparser.Statement, limit int) (ret *sqlparser.Limit) {- switch parsedStmt.(type) {+ switch stmtNode := parsedStmt.(type) {case *sqlparser.Select:- slct := parsedStmt.(*sqlparser.Select)- if nil != slct.Limit {- ret = slct.Limit+ if nil != stmtNode.Limit {+ ret = stmtNode.Limit}case *sqlparser.Union:- union := parsedStmt.(*sqlparser.Union)- if nil != union.Limit {- ret = union.Limit+ if nil != stmtNode.Limit {+ ret = stmtNode.Limit}}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex 9b4ab542a0..6d6acc4968 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -1165,7 +1165,12 @@ func deleteBlocksByIDs(tx *sql.Tx, ids []string) (err error) {}rowIDs = append(rowIDs, strconv.FormatInt(rowID, 10))}+ iterErr := rows.Err()rows.Close()+ if err = iterErr; err != nil {+ logging.LogErrorf("iterate block rowIDs failed: %s", err)+ return+ }if 1 > len(rowIDs) {return@@ -1662,6 +1667,10 @@ func migrateBlockEmbeddingsSchema() {}existing[name] = true}+ if err = rows.Err(); err != nil {+ logging.LogErrorf("iterate block_embeddings columns failed: %s", err)+ return+ }// 表不存在(首次启动还没建)时 existing 为空,跳过;待 initDBTables 建表if 0 == len(existing) {@@ -1921,7 +1930,6 @@ func closeDatabase() {debug.FreeOSMemory()db = nilruntime.GC()- return}func SQLTemplateFuncs(templateFuncMap *template.FuncMap, boxIDs ...string) {diff --git a/kernel/sql/delete_path_fts5_test.go b/kernel/sql/delete_path_fts5_test.goindex 7b8908318f..d5459ed038 100644--- a/kernel/sql/delete_path_fts5_test.go+++ b/kernel/sql/delete_path_fts5_test.go@@ -184,7 +184,8 @@ func TestDocumentPathDeletionQueryPlan(t *testing.T) {if err = rows.Scan(&id, &parent, &unused, &detail); err != nil {t.Fatal(err)}- plan.WriteString(detail + "\n")+ plan.WriteString(detail)+ plan.WriteString("\n")}rows.Close()if err = rows.Err(); err != nil {diff --git a/kernel/sql/query_limit.go b/kernel/sql/query_limit.goindex 6b4382cc89..c1c7addab7 100644--- a/kernel/sql/query_limit.go+++ b/kernel/sql/query_limit.go@@ -105,9 +105,10 @@ func containsOuterLimitClause(stmt string) bool {}continue}- if ch == '(' {+ switch ch {+ case '(':depth++- } else if ch == ')' {+ case ')':depth--}if isSQLLimitWordByte(ch) {diff --git a/kernel/sql/span.go b/kernel/sql/span.goindex 120267eb6e..5a04b6dde1 100644--- a/kernel/sql/span.go+++ b/kernel/sql/span.go@@ -88,11 +88,10 @@ func selectSpansRawStmt(stmt string, limit int, queryFn func(string) (*sql.Rows,//logging.LogErrorf("select [%s] failed: %s", stmt, err)return}- switch parsedStmt.(type) {+ switch parsedStmt := parsedStmt.(type) {case *sqlparser.Select:- slct := parsedStmt.(*sqlparser.Select)- if nil == slct.Limit {- slct.Limit = &sqlparser.Limit{+ if nil == parsedStmt.Limit {+ parsedStmt.Limit = &sqlparser.Limit{Rowcount: &sqlparser.SQLVal{Type: sqlparser.IntVal,Val: []byte(strconv.Itoa(limit)),@@ -100,7 +99,7 @@ func selectSpansRawStmt(stmt string, limit int, queryFn func(string) (*sql.Rows,}}- stmt = sqlparser.String(slct)+ stmt = sqlparser.String(parsedStmt)default:return}diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.goindex 1b17fe6480..7dd7f78292 100644--- a/kernel/treenode/blocktree.go+++ b/kernel/treenode/blocktree.go@@ -173,7 +173,6 @@ func closeDatabase() {debug.FreeOSMemory()db = nilruntime.GC()- return}func GetBlockTreesByType(typ string) (ret []*BlockTree) {diff --git a/kernel/treenode/blocktree_fix.go b/kernel/treenode/blocktree_fix.goindex fa995bb9db..20fe8a0b75 100644--- a/kernel/treenode/blocktree_fix.go+++ b/kernel/treenode/blocktree_fix.go@@ -117,5 +117,8 @@ func GetRootUpdated() (ret map[string]string) {}ret[rootID] = updated}+ if err = rows.Err(); err != nil {+ logging.LogErrorf("iterate block tree failed: %s", err)+ }return}diff --git a/kernel/treenode/hpath_test.go b/kernel/treenode/hpath_test.goindex 9390de7a83..7045f4894a 100644--- a/kernel/treenode/hpath_test.go+++ b/kernel/treenode/hpath_test.go@@ -53,7 +53,8 @@ func TestHPathRefreshIndexMigration(t *testing.T) {if err = rows.Scan(&id, &parent, &unused, &detail); err != nil {t.Fatal(err)}- plan.WriteString(detail + "\n")+ plan.WriteString(detail)+ plan.WriteString("\n")}if err = rows.Err(); err != nil {t.Fatal(err)diff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.goindex eafac55a5e..59c8443de5 100644--- a/kernel/treenode/tree.go+++ b/kernel/treenode/tree.go@@ -247,5 +247,4 @@ func upgradeSpec1(tree *parse.Tree) {parse.NestedInlines2FlattedSpans(tree, false)tree.Root.Spec = "1"- return}diff --git a/kernel/util/anthropic_stream.go b/kernel/util/anthropic_stream.goindex 13ec6dfad5..1b264cffe1 100644--- a/kernel/util/anthropic_stream.go+++ b/kernel/util/anthropic_stream.go@@ -175,9 +175,10 @@ func (s *anthropicStream) recv() (openai.ChatCompletionStreamResponse, error) {if s.block == nil || event.Index != s.blockIndex {return ret, errors.New("Anthropic content stop has no matching block")}- if s.blockType == "text" {+ switch s.blockType {+ case "text":s.block["text"] = anthropicJSON(s.text.String())- } else if s.blockType == "thinking" {+ case "thinking":s.block["thinking"] = anthropicJSON(s.thinking.String())s.block["signature"] = anthropicJSON(s.signature.String())}diff --git a/kernel/util/file.go b/kernel/util/file.goindex 4080f58ed8..8afd52f4d1 100644--- a/kernel/util/file.go+++ b/kernel/util/file.go@@ -416,7 +416,7 @@ func FilterUploadFileName(name string) string {return ret}-var pdfAnnoPngPattern = regexp.MustCompile("-{0,1}P{0,1}[0-9]{0,4}-{0,1}[0-9]{1,3}-[0-9]{14}-[0-9a-zA-Z]{7}\\.png$")+var pdfAnnoPngPattern = regexp.MustCompile(`-{0,1}P{0,1}[0-9]{0,4}-{0,1}[0-9]{1,3}-[0-9]{14}-[0-9a-zA-Z]{7}\.png$`)func TruncateLenFileName(name string) (ret string) {// 插入资源文件时文件名长度最大限制 189 字节 https://github.com/siyuan-note/siyuan/issues/7099diff --git a/kernel/util/font.go b/kernel/util/font.goindex bc6e8e84af..9f1107e988 100644--- a/kernel/util/font.go+++ b/kernel/util/font.go@@ -598,27 +598,3 @@ func inferFontWeight(weight int, subfamily string) int {}return weight}--func fontWeightFromNormalizedTrait(weight float64, style string) int {- if inferred := inferFontWeight(400, style); inferred != 400 {- return inferred- }- switch {- case weight <= -0.5:- return 100- case weight <= -0.25:- return 300- case weight < 0.15:- return 400- case weight < 0.28:- return 500- case weight < 0.35:- return 600- case weight < 0.5:- return 700- case weight < 0.6:- return 800- default:- return 900- }-}diff --git a/kernel/util/font_platform_darwin.go b/kernel/util/font_platform_darwin.goindex 075cd94f67..3eb2245ae7 100644--- a/kernel/util/font_platform_darwin.go+++ b/kernel/util/font_platform_darwin.go@@ -180,3 +180,29 @@ func loadPlatformFonts() (ret []*Font) {}return}++// fontWeightFromNormalizedTrait 把 CoreText 的归一化字重(-1 到 1)与样式映射为 CSS 字重。+// 样式能推断出明确字重时以样式为准,否则按归一化字重区间取值。+func fontWeightFromNormalizedTrait(weight float64, style string) int {+ if inferred := inferFontWeight(400, style); inferred != 400 {+ return inferred+ }+ switch {+ case weight <= -0.5:+ return 100+ case weight <= -0.25:+ return 300+ case weight < 0.15:+ return 400+ case weight < 0.28:+ return 500+ case weight < 0.35:+ return 600+ case weight < 0.5:+ return 700+ case weight < 0.6:+ return 800+ default:+ return 900+ }+}diff --git a/kernel/util/ocr.go b/kernel/util/ocr.goindex 6f639600f1..2e996b6de5 100644--- a/kernel/util/ocr.go+++ b/kernel/util/ocr.go@@ -71,7 +71,6 @@ func CleanNotExistAssetsTexts(exists func(string) bool) {delete(assetsTexts, asset)assetsTextsChanged.Store(true)}- return}func LoadAssetsTexts() {@@ -111,7 +110,6 @@ func LoadAssetsTexts() {if elapsed := time.Since(start).Seconds(); 2 < elapsed {logging.LogWarnf("read assets texts [%s] to [%s], elapsed [%.2fs]", humanize.BytesCustomCeil(uint64(len(data)), 2), assetsTextsPath, elapsed)}- return}func SaveAssetsTexts() {diff --git a/kernel/util/openai_completion.go b/kernel/util/openai_completion.goindex fd0a6cd81d..580e8bf4e1 100644--- a/kernel/util/openai_completion.go+++ b/kernel/util/openai_completion.go@@ -547,118 +547,116 @@ func (stream *OpenAICompletionStream) Recv() (openai.ChatCompletionStreamResponsreturn openai.ChatCompletionStreamResponse{}, io.EOF}- for {- event, err := stream.responses.Recv()- if err != nil {- if errors.Is(err, io.EOF) {- return openai.ChatCompletionStreamResponse{}, errors.New("response stream ended before a terminal event")- }- return openai.ChatCompletionStreamResponse{}, err- }- response := openai.ChatCompletionStreamResponse{Object: "chat.completion.chunk"}- switch event.Type {- case openai.ResponseStreamEventOutputTextDelta:- stream.responseContent.WriteString(event.Delta)- response.Choices = []openai.ChatCompletionStreamChoice{{- Index: 0,- Delta: openai.ChatCompletionStreamChoiceDelta{Content: event.Delta},- }}- return response, nil- case openai.ResponseStreamEventRefusalDelta:- stream.responseContent.WriteString(event.Delta)- response.Choices = []openai.ChatCompletionStreamChoice{{- Index: 0,- Delta: openai.ChatCompletionStreamChoiceDelta{Content: event.Delta, Refusal: event.Delta},- }}- return response, nil- case openai.ResponseStreamEventReasoningSummaryTextDelta, openai.ResponseStreamEventReasoningTextDelta:- response.Choices = []openai.ChatCompletionStreamChoice{{- Index: 0,- Delta: openai.ChatCompletionStreamChoiceDelta{ReasoningContent: event.Delta},- }}+ event, err := stream.responses.Recv()+ if err != nil {+ if errors.Is(err, io.EOF) {+ return openai.ChatCompletionStreamResponse{}, errors.New("response stream ended before a terminal event")+ }+ return openai.ChatCompletionStreamResponse{}, err+ }+ response := openai.ChatCompletionStreamResponse{Object: "chat.completion.chunk"}+ switch event.Type {+ case openai.ResponseStreamEventOutputTextDelta:+ stream.responseContent.WriteString(event.Delta)+ response.Choices = []openai.ChatCompletionStreamChoice{{+ Index: 0,+ Delta: openai.ChatCompletionStreamChoiceDelta{Content: event.Delta},+ }}+ return response, nil+ case openai.ResponseStreamEventRefusalDelta:+ stream.responseContent.WriteString(event.Delta)+ response.Choices = []openai.ChatCompletionStreamChoice{{+ Index: 0,+ Delta: openai.ChatCompletionStreamChoiceDelta{Content: event.Delta, Refusal: event.Delta},+ }}+ return response, nil+ case openai.ResponseStreamEventReasoningSummaryTextDelta, openai.ResponseStreamEventReasoningTextDelta:+ response.Choices = []openai.ChatCompletionStreamChoice{{+ Index: 0,+ Delta: openai.ChatCompletionStreamChoiceDelta{ReasoningContent: event.Delta},+ }}+ return response, nil+ case openai.ResponseStreamEventOutputItemAdded:+ if event.Item == nil || event.Item.Type != "function_call" {return response, nil- case openai.ResponseStreamEventOutputItemAdded:- if event.Item == nil || event.Item.Type != "function_call" {- return response, nil- }- index := event.OutputIndex- call := openai.ToolCall{+ }+ index := event.OutputIndex+ call := openai.ToolCall{+ Index: &index,+ ID: event.Item.CallID,+ Type: openai.ToolTypeFunction,+ Function: openai.FunctionCall{+ Name: event.Item.Name,+ Arguments: event.Item.Arguments,+ },+ }+ stream.responseToolCalls[index] = call+ response.Choices = []openai.ChatCompletionStreamChoice{{+ Index: 0,+ Delta: openai.ChatCompletionStreamChoiceDelta{ToolCalls: []openai.ToolCall{call}},+ }}+ return response, nil+ case openai.ResponseStreamEventFunctionArgumentsDelta:+ index := event.OutputIndex+ call := stream.responseToolCalls[index]+ call.Index = &index+ call.Type = openai.ToolTypeFunction+ call.Function.Arguments += event.Delta+ stream.responseToolCalls[index] = call+ response.Choices = []openai.ChatCompletionStreamChoice{{+ Index: 0,+ Delta: openai.ChatCompletionStreamChoiceDelta{ToolCalls: []openai.ToolCall{{Index: &index,- ID: event.Item.CallID,Type: openai.ToolTypeFunction,Function: openai.FunctionCall{- Name: event.Item.Name,- Arguments: event.Item.Arguments,+ Arguments: event.Delta,},- }- stream.responseToolCalls[index] = call- response.Choices = []openai.ChatCompletionStreamChoice{{- Index: 0,- Delta: openai.ChatCompletionStreamChoiceDelta{ToolCalls: []openai.ToolCall{call}},- }}- return response, nil- case openai.ResponseStreamEventFunctionArgumentsDelta:- index := event.OutputIndex- call := stream.responseToolCalls[index]- call.Index = &index- call.Type = openai.ToolTypeFunction- call.Function.Arguments += event.Delta- stream.responseToolCalls[index] = call- response.Choices = []openai.ChatCompletionStreamChoice{{- Index: 0,- Delta: openai.ChatCompletionStreamChoiceDelta{ToolCalls: []openai.ToolCall{{- Index: &index,- Type: openai.ToolTypeFunction,- Function: openai.FunctionCall{- Arguments: event.Delta,- },- }}},- }}- return response, nil- case openai.ResponseStreamEventOutputItemDone:- if !stream.chatGPT {- break- }- var completed struct {- Item json.RawMessage `json:"item"`- }- if err = json.Unmarshal(event.Raw, &completed); err != nil || len(completed.Item) == 0 || string(completed.Item) == "null" {- return openai.ChatCompletionStreamResponse{}, errors.New("completed response output item is missing")- }- stream.completedOutput[event.OutputIndex] = completed.Item- case openai.ResponseStreamEventCompleted, openai.ResponseStreamEventIncomplete:- if event.Response == nil {- return openai.ChatCompletionStreamResponse{}, errors.New("response stream terminal event is missing response")- }- if stream.chatGPT && (event.Type != openai.ResponseStreamEventCompleted || event.Response.Status != openai.ResponseStatusCompleted) {- return openai.ChatCompletionStreamResponse{}, errors.New("ChatGPT response did not complete")- }- terminal := *event.Response- // 套餐流的结束事件可能省略输出,按输出索引恢复已完成项,保留工具命名空间及加密推理字段。- if stream.chatGPT && len(terminal.Output) == 0 && len(stream.completedOutput) > 0 {- terminal.Output = make([]any, len(stream.completedOutput))- for index := range terminal.Output {- item, ok := stream.completedOutput[index]- if !ok {- return openai.ChatCompletionStreamResponse{}, errors.New("completed response output items are missing")- }- terminal.Output[index] = item+ }}},+ }}+ return response, nil+ case openai.ResponseStreamEventOutputItemDone:+ if !stream.chatGPT {+ break+ }+ var completed struct {+ Item json.RawMessage `json:"item"`+ }+ if err = json.Unmarshal(event.Raw, &completed); err != nil || len(completed.Item) == 0 || string(completed.Item) == "null" {+ return openai.ChatCompletionStreamResponse{}, errors.New("completed response output item is missing")+ }+ stream.completedOutput[event.OutputIndex] = completed.Item+ case openai.ResponseStreamEventCompleted, openai.ResponseStreamEventIncomplete:+ if event.Response == nil {+ return openai.ChatCompletionStreamResponse{}, errors.New("response stream terminal event is missing response")+ }+ if stream.chatGPT && (event.Type != openai.ResponseStreamEventCompleted || event.Response.Status != openai.ResponseStatusCompleted) {+ return openai.ChatCompletionStreamResponse{}, errors.New("ChatGPT response did not complete")+ }+ terminal := *event.Response+ // 套餐流的结束事件可能省略输出,按输出索引恢复已完成项,保留工具命名空间及加密推理字段。+ if stream.chatGPT && len(terminal.Output) == 0 && len(stream.completedOutput) > 0 {+ terminal.Output = make([]any, len(stream.completedOutput))+ for index := range terminal.Output {+ item, ok := stream.completedOutput[index]+ if !ok {+ return openai.ChatCompletionStreamResponse{}, errors.New("completed response output items are missing")}+ terminal.Output[index] = item}- if err = stream.queueResponseTerminal(terminal); err != nil {- return openai.ChatCompletionStreamResponse{}, err- }- stream.responsesDone = true- response = stream.pending[0]- stream.pending = stream.pending[1:]- return response, nil- case openai.ResponseStreamEventFailed:- return openai.ChatCompletionStreamResponse{}, responseEventError(event, "response failed")- case openai.ResponseStreamEventError:- return openai.ChatCompletionStreamResponse{}, responseEventError(event, "response stream failed")}+ if err = stream.queueResponseTerminal(terminal); err != nil {+ return openai.ChatCompletionStreamResponse{}, err+ }+ stream.responsesDone = true+ response = stream.pending[0]+ stream.pending = stream.pending[1:]return response, nil+ case openai.ResponseStreamEventFailed:+ return openai.ChatCompletionStreamResponse{}, responseEventError(event, "response failed")+ case openai.ResponseStreamEventError:+ return openai.ChatCompletionStreamResponse{}, responseEventError(event, "response stream failed")}+ return response, nil}func (stream *OpenAICompletionStream) queueResponseTerminal(response openai.CreateResponseResponse) error {diff --git a/kernel/util/plugin_project_test.go b/kernel/util/plugin_project_test.goindex 3d75562e56..969fa583d8 100644--- a/kernel/util/plugin_project_test.go+++ b/kernel/util/plugin_project_test.go@@ -423,7 +423,8 @@ func TestPluginProjectReplanFailuresKeepRecoverableBaseline(t *testing.T) {previousPlan := grant.PlanHashgrant.PlanHash, grant.PlanVersion = "next plan", 2blocked := private- if phase == "cleanup-before" {+ switch phase {+ case "cleanup-before":blocked = filepath.Join(private, "checkpoints", PluginProjectDigest([]byte("obsolete checkpoint")))if err = os.MkdirAll(blocked, 0700); err != nil {t.Fatal(err)@@ -431,7 +432,7 @@ func TestPluginProjectReplanFailuresKeepRecoverableBaseline(t *testing.T) {if err = os.WriteFile(filepath.Join(blocked, "index.js"), []byte("obsolete"), 0600); err != nil {t.Fatal(err)}- } else if phase == "cleanup-after" {+ case "cleanup-after":blocked = filepath.Join(private, "baseline")}t.Cleanup(func() { _ = os.Chmod(blocked, 0700) })diff --git a/kernel/util/rune.go b/kernel/util/rune.goindex e0fb903dfa..8b550afa65 100644--- a/kernel/util/rune.go+++ b/kernel/util/rune.go@@ -122,5 +122,4 @@ func InitEmojiChars() {nativeEmojiCharsLock.Lock()nativeEmojiChars = charsnativeEmojiCharsLock.Unlock()- return}diff --git a/kernel/util/session.go b/kernel/util/session.goindex 00e31bd6c5..ebaa4c4a47 100644--- a/kernel/util/session.go+++ b/kernel/util/session.go@@ -97,7 +97,7 @@ func AuthThrottleCheck(key string) (retryAfter int) {delete(authThrottles, key)return 0}- if authThrottleWindowSec*time.Second <= time.Now().Sub(throttle.LastFail) {+ if authThrottleWindowSec*time.Second <= time.Since(throttle.LastFail) {// 超过窗口期未再失败,清除计数避免误锁delete(authThrottles, key)}diff --git a/kernel/util/skill_test.go b/kernel/util/skill_test.goindex a70d77cb23..1d0fc8c927 100644--- a/kernel/util/skill_test.go+++ b/kernel/util/skill_test.go@@ -40,13 +40,6 @@ func touchSkillMd(t *testing.T, parts ...string) {}}-// sorted 把 findSkillDirs 的返回结果排序后比较,避免遍历顺序影响断言。-func sorted(ss []string) []string {- out := append([]string(nil), ss...)- sort.Strings(out)- return out-}-// toSlashSet 把路径分隔符统一为 /,便于跨平台断言。func toSlashSet(ss []string) []string {out := make([]string, len(ss))diff --git a/kernel/util/time.go b/kernel/util/time.goindex 669860c23b..b3988fba15 100644--- a/kernel/util/time.go+++ b/kernel/util/time.go@@ -127,37 +127,37 @@ func HumanizeDiffTime(a, b time.Time, lang string) string {buf := bytes.Buffer{}if 0 < year {if 1 == year {- buf.WriteString(fmt.Sprintf(labels["1y"].(string), " "))+ fmt.Fprintf(&buf, labels["1y"].(string), " ")} else {- buf.WriteString(fmt.Sprintf(labels["xy"].(string), year, " "))+ fmt.Fprintf(&buf, labels["xy"].(string), year, " ")}}if 0 < month {if 1 == month {- buf.WriteString(fmt.Sprintf(labels["1M"].(string), " "))+ fmt.Fprintf(&buf, labels["1M"].(string), " ")} else {- buf.WriteString(fmt.Sprintf(labels["xM"].(string), month, " "))+ fmt.Fprintf(&buf, labels["xM"].(string), month, " ")}}if 0 < day {if 1 == day {- buf.WriteString(fmt.Sprintf(labels["1d"].(string), " "))+ fmt.Fprintf(&buf, labels["1d"].(string), " ")} else {- buf.WriteString(fmt.Sprintf(labels["xd"].(string), day, " "))+ fmt.Fprintf(&buf, labels["xd"].(string), day, " ")}}if 0 < hour {if 1 == hour {- buf.WriteString(fmt.Sprintf(labels["1h"].(string), " "))+ fmt.Fprintf(&buf, labels["1h"].(string), " ")} else {- buf.WriteString(fmt.Sprintf(labels["xh"].(string), hour, " "))+ fmt.Fprintf(&buf, labels["xh"].(string), hour, " ")}}if 0 < min {if 1 == min {- buf.WriteString(fmt.Sprintf(labels["1m"].(string), " "))+ fmt.Fprintf(&buf, labels["1m"].(string), " ")} else {- buf.WriteString(fmt.Sprintf(labels["xm"].(string), min, " "))+ fmt.Fprintf(&buf, labels["xm"].(string), min, " ")}}return strings.TrimSpace(buf.String())