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: Modernize kernel Go code with go fix https://github.com/siyuan-note/siyuan/pull/20616
Jeffrey Chen44ac28c72c3c
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 9d23f91b0a..726c448ace 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -32,9 +32,9 @@ export type AIBrowserCapabilityResultRequestInput = { "callID"?: string | null;export type AIBuiltinSkillInfo = { "description": string; "digest": string; "enabled": boolean; "id": string; "name": string; "source": string; "version": string; };-export type AICapabilityAction = { "effects"?: AIToolEffects; "name": string; };+export type AICapabilityAction = { "effects": AIToolEffects; "name": string; };-export type AICapabilityManifest = { "actions"?: Array<AICapabilityAction>; "agentOnly"?: boolean; "available": boolean; "description": string; "effects"?: AIToolEffects; "id": string; "name": string; "ownerId"?: string; "ownerName"?: string; "runtime": string; "source": string; "title"?: string; };+export type AICapabilityManifest = { "actions"?: Array<AICapabilityAction>; "agentOnly"?: boolean; "available": boolean; "description": string; "effects": AIToolEffects; "id": string; "name": string; "ownerId"?: string; "ownerName"?: string; "runtime": string; "source": string; "title"?: string; };export type AIConfirmRequestInput = { "always"?: boolean | null; "approved"?: boolean | null; "confirmID"?: string | null; };diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex d914cd8041..9b927c7afe 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -23,10 +23,12 @@ import ("fmt""html""io"+ "maps""math/rand/v2""net/http""os""path/filepath"+ "slices""strings""sync""time"@@ -589,8 +591,8 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagcurrentUserExists := falseif regenerate {lastUserIdx := -1- for i := len(truncated) - 1; i >= 0; i-- {- if truncated[i].Role == "user" && (userEntryID == "" || truncated[i].EntryID == userEntryID) {+ for i, t := range slices.Backward(truncated) {+ if t.Role == "user" && (userEntryID == "" || t.EntryID == userEntryID) {lastUserIdx = ibreak}@@ -602,12 +604,12 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagreturn}} else {- for i := len(truncated) - 1; i >= 0; i-- {- if truncated[i].Role != "user" {+ for _, t := range slices.Backward(truncated) {+ if t.Role != "user" {continue}- currentUserExists = userEntryID != "" && truncated[i].EntryID == userEntryID- if userEntryID == "" && (truncated[i].Content == userMessage || truncated[i].Content == rawUserMessage) {+ currentUserExists = userEntryID != "" && t.EntryID == userEntryID+ if userEntryID == "" && (t.Content == userMessage || t.Content == rawUserMessage) {currentUserExists = true}break@@ -683,8 +685,8 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagsaveTurn := func(state string) bool {turn.State = statedeltaStart := turnBaseIndex- for i := len(checkpointMsgs) - 1; i >= 0; i-- {- message := checkpointMsgs[i]+ for i, message := range slices.Backward(checkpointMsgs) {+if message.Role == "user" && ((userEntryID != "" && message.EntryID == userEntryID) ||(userEntryID == "" && message.Content == userMessage)) {deltaStart = i + 1@@ -1251,9 +1253,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagtoolInputErr = previewErr} else if preview != nil {confirmationArgs = make(map[string]any, len(args)+1)- for key, value := range args {- confirmationArgs[key] = value- }+ maps.Copy(confirmationArgs, args)confirmationArgs["verifiedPackage"] = preview}}@@ -1263,9 +1263,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagtoolInputErr = previewErr} else if preview != nil {confirmationArgs = make(map[string]any, len(args)+1)- for key, value := range args {- confirmationArgs[key] = value- }+ maps.Copy(confirmationArgs, args)confirmationArgs["currentSnippet"] = preview}}@@ -2223,7 +2221,7 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCsb.WriteString("Visible block ids:\n")}limit := min(totalVisible, maxVisibleBlockIDs)- for i := 0; i < limit; i++ {+ for i := range limit {sb.WriteString("- ")sb.WriteString(editorCtx.VisibleBlockIDs[i])sb.WriteString("\n")@@ -2699,16 +2697,14 @@ func classifyRetry(err error) string {if errors.Is(err, errModelRequestTimeout) || errors.Is(err, errModelStreamIdleTimeout) || errors.Is(err, context.DeadlineExceeded) {return "timeout"}- var subscriptionErr *chatgpt.RequestError- if errors.As(err, &subscriptionErr) {+ if subscriptionErr, ok := errors.AsType[*chatgpt.RequestError](err); ok {if subscriptionErr.Status >= 500 {return "server_error"}return "fatal"}- var apiErr *openai.APIError- if errors.As(err, &apiErr) {+ if apiErr, ok := errors.AsType[*openai.APIError](err); ok {code := strings.ToLower(strings.TrimSpace(fmt.Sprint(apiErr.Code)))if code == "subscription_sharing_usage_limit_exceeded" {return "fatal"@@ -2767,8 +2763,7 @@ func getAgentErrorMessage(err error) string {}func getAgentRequestErrorMessage(err error, _ []openai.ChatCompletionMessage) string {- var apiErr *openai.APIError- if errors.As(err, &apiErr) {+ if apiErr, ok := errors.AsType[*openai.APIError](err); ok {message := strings.TrimSpace(apiErr.Message)if message != "" {runes := []rune(message)diff --git a/kernel/agent/attachments.go b/kernel/agent/attachments.goindex 4fbf52c3a6..d8d703d19f 100644--- a/kernel/agent/attachments.go+++ b/kernel/agent/attachments.go@@ -21,6 +21,7 @@ import ("encoding/base64""errors""fmt"+ "slices""strings""sync""time"@@ -184,8 +185,8 @@ func agentMessageAttachments(message AgentMessage) (ret []AgentAttachment) {}func latestAgentMessageAttachments(messages []AgentMessage) (index int, attachments []AgentAttachment) {- for i := len(messages) - 1; i >= 0; i-- {- if attachments = agentMessageAttachments(messages[i]); len(attachments) > 0 {+ for i, message := range slices.Backward(messages) {+ if attachments = agentMessageAttachments(message); len(attachments) > 0 {return i, attachments}}@@ -328,16 +329,14 @@ func isImageInputUnsupportedError(err error) bool {}func imageInputValidationError(err error) (statusCode int, detail string, ok bool) {- var apiErr *openai.APIError- if errors.As(err, &apiErr) {+ if apiErr, ok := errors.AsType[*openai.APIError](err); ok {detail = apiErr.Message + " " + apiErr.Type + " " + fmt.Sprint(apiErr.Code)if apiErr.Param != nil {detail += " " + *apiErr.Param}return apiErr.HTTPStatusCode, detail, true}- var requestErr *openai.RequestError- if errors.As(err, &requestErr) {+ if requestErr, ok := errors.AsType[*openai.RequestError](err); ok {return requestErr.HTTPStatusCode, requestErr.Error(), true}return 0, "", falsediff --git a/kernel/agent/compaction.go b/kernel/agent/compaction.goindex 8c9d275dba..9b695ff77a 100644--- a/kernel/agent/compaction.go+++ b/kernel/agent/compaction.go@@ -24,6 +24,7 @@ import ("errors""fmt""io"+ "slices""strings""time"@@ -123,11 +124,11 @@ func runtimeCompactionMatchesProtocol(compaction *runtimeCompaction, protocol st}func sessionUserEntryIndex(entries []SessionEntry, userEntryID string) int {- for i := len(entries) - 1; i >= 0; i-- {- if entries[i].Type != "user" {+ for i, entrie := range slices.Backward(entries) {+ if entrie.Type != "user" {continue}- if userEntryID == "" || entries[i].ID == userEntryID {+ if userEntryID == "" || entrie.ID == userEntryID {return i}}diff --git a/kernel/agent/compaction_context.go b/kernel/agent/compaction_context.goindex ec547e77c4..192e737775 100644--- a/kernel/agent/compaction_context.go+++ b/kernel/agent/compaction_context.go@@ -14,6 +14,7 @@ import ("encoding/hex""encoding/json""fmt"+ "slices""strings""time"@@ -121,10 +122,10 @@ func projectCompactionContext(messages []AgentMessage, covered int) []AgentMessacovered = 0}var projected []AgentMessage- for i := len(history) - 1; i >= 0; i-- {- if history[i].Role == "user" {+ for i, h := range slices.Backward(history) {+ if h.Role == "user" {if i < covered {- projected = append(projected, history[i])+ projected = append(projected, h)}break}@@ -200,8 +201,8 @@ func compactionCandidateMessageCounts(messages []AgentMessage, covered int, prot}func sessionUserMessageIndex(messages []AgentMessage) int {- for i := len(messages) - 1; i >= 0; i-- {- if messages[i].Role == "user" {+ for i, message := range slices.Backward(messages) {+ if message.Role == "user" {return i}}diff --git a/kernel/agent/instructions_test.go b/kernel/agent/instructions_test.goindex 95876292b7..77258a7be9 100644--- a/kernel/agent/instructions_test.go+++ b/kernel/agent/instructions_test.go@@ -63,7 +63,7 @@ func TestAgentInstructionsTurnSnapshot(t *testing.T) {writeAssistantContextStream(t, w, "", "done")}))defer server.Close()- for i := 0; i < 2; i++ {+ for range 2 {sessionID := ast.NewNodeID()session := map[string]any{"id": sessionID, "title": "instructions", "createdAt": 1, "updatedAt": 1,"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "test preferences"}}}diff --git a/kernel/agent/plugin_workflow_test.go b/kernel/agent/plugin_workflow_test.goindex 8e2c6f0a30..b028474fb0 100644--- a/kernel/agent/plugin_workflow_test.go+++ b/kernel/agent/plugin_workflow_test.go@@ -421,7 +421,7 @@ func TestPluginWorkflowPlanValidationAndEffects(t *testing.T) {func(p map[string]any) { p["sourcePath"] = "other" },func(p map[string]any) {files := []any{"plugin.json", "index.js"}- for i := 0; i < 100; i++ {+ for i := range 100 {files = append(files, fmt.Sprintf("%03d-%s.js", i, strings.Repeat("a", 200)))}p["files"] = filesdiff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.goindex e8b71927d9..e85aee64a3 100644--- a/kernel/agent/runtime.go+++ b/kernel/agent/runtime.go@@ -21,6 +21,7 @@ import ("fmt""os""path/filepath"+ "slices""sync""sync/atomic""time"@@ -441,8 +442,8 @@ func isRuntimeTurnTerminal(turn *agentRuntimeTurn) bool {func findRuntimeUserAnchor(session map[string]any, userEntryID string) int {entries, _ := session["entries"].([]any)- for i := len(entries) - 1; i >= 0; i-- {- entry, _ := entries[i].(map[string]any)+ for i, entrie := range slices.Backward(entries) {+ entry, _ := entrie.(map[string]any)if entry["type"] != "user" {continue}diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.goindex 73e39193e3..5dcf3de2fe 100644--- a/kernel/agent/session_test.go+++ b/kernel/agent/session_test.go@@ -10,6 +10,7 @@ package agentimport ("errors"+ "maps""os""path/filepath""testing"@@ -311,9 +312,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {t.Fatalf("runtime token metadata was not restored: %#v", recovered)}wrongCommit := map[string]any{}- for key, value := range recovered {- wrongCommit[key] = value- }+ maps.Copy(wrongCommit, recovered)wrongCommit["expectedRevision"] = int64(1)wrongCommit["commitTurnID"] = "20260715120009-abcdefg"if revision, _, err := SaveSessionState(marshalSession(t, wrongCommit)); !errors.Is(err, ErrSessionConflict) || revision != 1 {@@ -363,9 +362,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {}}repeatedCommit := map[string]any{}- for key, value := range committed {- repeatedCommit[key] = value- }+ maps.Copy(repeatedCommit, committed)repeatedCommit["entries"].([]any)[1].(map[string]any)["content"] = "tampered repeated commit"// 模拟提交已落盘但响应丢失:客户端会携带旧修订号原样重试。repeatedCommit["expectedRevision"] = int64(1)diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.goindex ebf4bdf171..a720dff25f 100644--- a/kernel/agent/stream_timeout_test.go+++ b/kernel/agent/stream_timeout_test.go@@ -15,6 +15,7 @@ import ("io""net/http""net/http/httptest"+ "strings""sync/atomic""testing""time"@@ -28,7 +29,7 @@ import (func TestStreamIdleTimeoutResetsAfterEachChunk(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {flusher := prepareTestStream(t, w)- for i := 0; i < 6; i++ {+ for i := range 6 {writeTestStreamChunk(t, w, flusher, fmt.Sprintf("%d", i))if i < 5 {time.Sleep(60 * time.Millisecond)@@ -97,11 +98,11 @@ func TestResponsesProgressEventsResetIdleTimeout(t *testing.T) {defer cancel()defer stream.Close()- content := ""+ var content strings.Builderresponse := firstResponsefor {for _, choice := range response.Choices {- content += choice.Delta.Content+ content.WriteString(choice.Delta.Content)}response, err = recvStreamWithIdleTimeout(stream, 100*time.Millisecond, cancel)if errors.Is(err, io.EOF) {@@ -111,8 +112,8 @@ func TestResponsesProgressEventsResetIdleTimeout(t *testing.T) {t.Fatalf("receive Responses progress stream failed: %v", err)}}- if content != "done" {- t.Fatalf("unexpected Responses content: %q", content)+ if content.String() != "done" {+ t.Fatalf("unexpected Responses content: %q", content.String())}}diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex b44680d94d..106f1a007f 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -155,7 +155,7 @@ func TestParseToolArgsRejectsInvalidJSON(t *testing.T) {func TestDoomLoopTracksFailedQuestionCalls(t *testing.T) {var tracker doomLoopTracker- for i := 0; i < doomLoopStopThreshold; i++ {+ for range doomLoopStopThreshold {tracker.record("question", "", map[string]any{}, true)}if tracker.count != doomLoopStopThreshold || tracker.prevName != "question" {diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex b68945f9dd..6be8b46b69 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -86,10 +86,7 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) aclient := model.NewAIProviderClient(selectedProvider, selectedModel.Name)confirmTimeout := resolveAgentConfirmTimeout(confAISnapshot.Agent.ConfirmTimeout)- maxRetries := confAISnapshot.Agent.MaxRetries- if maxRetries < 0 {- maxRetries = 0- }+ maxRetries := max(confAISnapshot.Agent.MaxRetries, 0)// Provider 请求超时只限制建立上游流;流建立后由可重置的空闲超时检测连续无输出,// 避免持续正常输出的长回答被固定截止时间中断。requestTimeout := time.Duration(selectedProvider.RequestTimeout) * time.Seconddiff --git a/kernel/api/asset.go b/kernel/api/asset.goindex 288dfdb380..c3151458ff 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -132,7 +132,7 @@ var setImageOCRText = contractHandler(apicontract.SetImageOCRText, func(c *gin.Cvar ocr = contractHandler(apicontract.AssetOCR, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetOCRData] {- path := strings.SplitN(request.Path, "#", 2)[0]+ path, _, _ := strings.Cut(request.Path, "#")// 加密笔记本的资源不参与全局 OCRif model.IsEncryptedOCRAsset(path) {diff --git a/kernel/api/box_lease.go b/kernel/api/box_lease.goindex 65e4a4d213..4c3d3f0acc 100644--- a/kernel/api/box_lease.go+++ b/kernel/api/box_lease.go@@ -18,6 +18,7 @@ package apiimport ("errors"+ "slices""sort""github.com/88250/lute/ast"@@ -38,10 +39,8 @@ func holdEncryptedBoxRequest(c *gin.Context, boxID string) error {return nil}leases := requestBoxLeases(c)- for _, heldBoxID := range leases {- if heldBoxID == boxID {- return nil- }+ if slices.Contains(leases, boxID) {+ return nil}if err := model.AcquireEncryptedBoxOperation(boxID); err != nil {@@ -101,8 +100,8 @@ func requestBoxLeases(c *gin.Context) []string {func releaseEncryptedBoxRequest(c *gin.Context, boxID string) {leases := requestBoxLeases(c)- for i := len(leases) - 1; i >= 0; i-- {- if leases[i] != boxID {+ for i, lease := range slices.Backward(leases) {+ if lease != boxID {continue}leases = append(leases[:i], leases[i+1:]...)@@ -114,8 +113,8 @@ func releaseEncryptedBoxRequest(c *gin.Context, boxID string) {func releaseRequestBoxLeases(c *gin.Context) {leases := requestBoxLeases(c)- for i := len(leases) - 1; i >= 0; i-- {- model.ReleaseEncryptedBoxOperation(leases[i])+ for _, lease := range slices.Backward(leases) {+ model.ReleaseEncryptedBoxOperation(lease)}c.Set(requestBoxLeasesKey, []string{})}diff --git a/kernel/api/contract_ai_test.go b/kernel/api/contract_ai_test.goindex 681f789813..72c64737dd 100644--- a/kernel/api/contract_ai_test.go+++ b/kernel/api/contract_ai_test.go@@ -222,7 +222,7 @@ func TestAPIContractAIEditorSSE(t *testing.T) {if err = bundle.ValidateHTTPResponse("POST", "/api/ai/editor/chat", recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {t.Fatalf("%v: %s", err, recorder.Body.String())}- for _, frame := range strings.Split(strings.TrimSpace(recorder.Body.String()), "\n\n") {+ for frame := range strings.SplitSeq(strings.TrimSpace(recorder.Body.String()), "\n\n") {lines := strings.SplitN(frame, "\n", 2)if len(lines) != 2 {t.Fatalf("invalid frame: %s", frame)diff --git a/kernel/api/contract_anthropic_test.go b/kernel/api/contract_anthropic_test.goindex 8716cb7d99..65aee00e0d 100644--- a/kernel/api/contract_anthropic_test.go+++ b/kernel/api/contract_anthropic_test.go@@ -94,7 +94,7 @@ func testNativeProviderContract(t *testing.T, baseURL, protocol string) {t.Fatal(err)}if tc.path == "/api/ai/editor/chat" {- for _, frame := range strings.Split(strings.TrimSpace(recorder.Body.String()), "\n\n") {+ for frame := range strings.SplitSeq(strings.TrimSpace(recorder.Body.String()), "\n\n") {lines := strings.SplitN(frame, "\n", 2)if len(lines) != 2 {t.Fatalf("invalid SSE frame: %s", frame)diff --git a/kernel/api/contract_asset_test.go b/kernel/api/contract_asset_test.goindex aa2c144b1d..13ddd83a51 100644--- a/kernel/api/contract_asset_test.go+++ b/kernel/api/contract_asset_test.go@@ -70,7 +70,7 @@ func TestAssetUploadContractAdapter(t *testing.T) {var body bytes.Bufferwriter := multipart.NewWriter(&body)if test.files {- for i := 0; i < 2; i++ {+ for range 2 {part, err := writer.CreateFormFile("file[]", "sample.txt")if err != nil {t.Fatal(err)@@ -99,7 +99,7 @@ func TestAssetUploadContractAdapter(t *testing.T) {}return request}- var responses []map[string]interface{}+ var responses []map[string]anyfor _, handler := range []gin.HandlerFunc{model.Upload, uploadAsset} {engine := gin.New()engine.POST("/api/asset/upload", handler)@@ -108,7 +108,7 @@ func TestAssetUploadContractAdapter(t *testing.T) {if err := bundle.ValidateHTTPResponse("POST", "/api/asset/upload", recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {t.Fatal(err)}- var response map[string]interface{}+ var response map[string]anyif err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_av_relation_sort_test.go b/kernel/api/contract_av_relation_sort_test.goindex 6f7dea4559..a239efebbf 100644--- a/kernel/api/contract_av_relation_sort_test.go+++ b/kernel/api/contract_av_relation_sort_test.go@@ -22,7 +22,7 @@ func TestAVRelationCandidateUntitledContract(t *testing.T) {t.Cleanup(func() { util.SearchCaseSensitive.Store(oldCaseSensitive) })key := fixture.attrView.GetBlockKey()var ids []string- for i := 0; i < 2; i++ {+ for i := range 2 {id := ast.NewNodeID()ids = append(ids, id)fixture.attrView.KeyValues[0].Values = append(fixture.attrView.KeyValues[0].Values, &av.Value{diff --git a/kernel/api/contract_bazaar_test.go b/kernel/api/contract_bazaar_test.goindex af7af72644..1b1c688ab3 100644--- a/kernel/api/contract_bazaar_test.go+++ b/kernel/api/contract_bazaar_test.go@@ -10,6 +10,7 @@ import ("github.com/siyuan-note/siyuan/kernel/bazaar""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util"+ "maps""mime/multipart""net/http""net/http/httptest"@@ -42,9 +43,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -96,9 +95,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -155,9 +152,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -212,9 +207,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -270,9 +263,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -328,9 +319,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -386,9 +375,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -443,9 +430,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -502,9 +487,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -560,9 +543,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -617,9 +598,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -674,9 +653,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -735,9 +712,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -793,9 +768,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -847,9 +820,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -901,9 +872,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -961,9 +930,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1018,9 +985,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1072,9 +1037,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1126,9 +1089,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1186,9 +1147,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1243,9 +1202,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1297,9 +1254,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1351,9 +1306,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1411,9 +1364,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1468,9 +1419,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1525,9 +1474,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1582,9 +1529,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1643,9 +1588,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1701,9 +1644,7 @@ func TestBazaarContractInputCompatibility(t *testing.T) {for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -1744,7 +1685,7 @@ func TestBazaarContractTransportCompatibility(t *testing.T) {appearance.BodyGradient = &conf.BodyGradient{Mode: "custom", Light: conf.BodyGradientColor{Color: "#000000", Opacity: 50}}appearance.EntryVisibility.Profiles = []*conf.EntryVisibilityProfile{nil, {ID: "custom", Orders: map[string][]string{"menu": {"item"}}}}appearance.GlobalFontFamilies = []*conf.EditorFont{nil, {Family: "serif", Weight: 500}}- cases := [][2]interface{}{{pkg, bazaarPackage(pkg)}, {&bazaar.Package{}, bazaarPackage(&bazaar.Package{})}, {appearance, bazaarAppearance(appearance)}, {(*conf.Appearance)(nil), bazaarAppearance(nil)}, {[]*bazaar.Package{nil, pkg}, bazaarPackages([]*bazaar.Package{nil, pkg})}, {([]*bazaar.Package)(nil), bazaarPackages(nil)}, {[]*bazaar.Package{}, bazaarPackages([]*bazaar.Package{})}}+ cases := [][2]any{{pkg, bazaarPackage(pkg)}, {&bazaar.Package{}, bazaarPackage(&bazaar.Package{})}, {appearance, bazaarAppearance(appearance)}, {(*conf.Appearance)(nil), bazaarAppearance(nil)}, {[]*bazaar.Package{nil, pkg}, bazaarPackages([]*bazaar.Package{nil, pkg})}, {([]*bazaar.Package)(nil), bazaarPackages(nil)}, {[]*bazaar.Package{}, bazaarPackages([]*bazaar.Package{})}}for _, pair := range cases {left, _ := json.Marshal(pair[0])right, _ := json.Marshal(pair[1])diff --git a/kernel/api/contract_block_remaining_test.go b/kernel/api/contract_block_remaining_test.goindex d8feb803f0..d877509442 100644--- a/kernel/api/contract_block_remaining_test.go+++ b/kernel/api/contract_block_remaining_test.go@@ -51,7 +51,7 @@ func testAPIContractRemainingBlockQueries(t *testing.T, engine *gin.Engine, boxIsource, target intchildren bool}{{0, 0, false}, {1, 3, false}, {1, 2, true}, {6, 1, true}} {- input := map[string]interface{}{"id": docID, "notebook": boxID, "source": entry.source, "target": entry.target, "withSubheadings": entry.children}+ input := map[string]any{"id": docID, "notebook": boxID, "source": entry.source, "target": entry.target, "withSubheadings": entry.children}body, _ := json.Marshal(input)data := post("getDocHeadingLevelTransaction", string(body), 0)want, err := model.GetDocHeadingLevelTransaction(docID, boxID, entry.source, entry.target, entry.children)diff --git a/kernel/api/contract_export_test.go b/kernel/api/contract_export_test.goindex 08e9d93a5d..4fca839f67 100644--- a/kernel/api/contract_export_test.go+++ b/kernel/api/contract_export_test.go@@ -113,7 +113,7 @@ func TestAPIContractExportMarkdownOptions(t *testing.T) {if err != nil || request.Validate() != nil {t.Fatalf("decode failed: %v", err)}- var fields map[string]interface{}+ var fields map[string]anyif err = json.Unmarshal([]byte(input), &fields); err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_file_concurrency_test.go b/kernel/api/contract_file_concurrency_test.goindex 1965a12e33..ca002df1e0 100644--- a/kernel/api/contract_file_concurrency_test.go+++ b/kernel/api/contract_file_concurrency_test.go@@ -5,6 +5,7 @@ import ("context""encoding/json""io"+ "maps""mime/multipart""net""net/http"@@ -209,9 +210,7 @@ func startPutFileUpload(client *http.Client, request *http.Request) <-chan putFidefer response.Body.Close()result.protocol = response.ProtoMajorresult.recorder = httptest.NewRecorder()- for key, values := range response.Header {- result.recorder.Header()[key] = values- }+ maps.Copy(result.recorder.Header(), response.Header)result.recorder.Code = response.StatusCode_, result.err = io.Copy(result.recorder.Body, response.Body)}diff --git a/kernel/api/contract_filetree_test.go b/kernel/api/contract_filetree_test.goindex a808dfb9db..09e207e574 100644--- a/kernel/api/contract_filetree_test.go+++ b/kernel/api/contract_filetree_test.go@@ -119,7 +119,7 @@ func TestAPIContractFileTreeDailyNoteDate(t *testing.T) {func TestAPIContractFileTreePayloadConversions(t *testing.T) {compare := func(before, after []byte) {t.Helper()- var left, right interface{}+ var left, right anyif err := json.Unmarshal(before, &left); err != nil {t.Fatal(err)}diff --git a/kernel/api/contract_history_snapshots_test.go b/kernel/api/contract_history_snapshots_test.goindex f901bf92c7..efb0f3651e 100644--- a/kernel/api/contract_history_snapshots_test.go+++ b/kernel/api/contract_history_snapshots_test.go@@ -89,7 +89,7 @@ func TestAPIContractDocHistorySnapshots(t *testing.T) {engine.POST("/api/repo/getRepoSnapshots", getRepoSnapshots)engine.POST("/api/repo/getRepoDocHistory", getRepoDocHistory)for _, include := range []bool{false, true} {- body, _ := json.Marshal(map[string]interface{}{"id": index.ID, "page": 1, "includeFiles": include})+ body, _ := json.Marshal(map[string]any{"id": index.ID, "page": 1, "includeFiles": include})recorder := httptest.NewRecorder()engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/repo/getRepoSnapshots", bytes.NewReader(body)))requireAPIContract(t, "POST", "/api/repo/getRepoSnapshots", recorder)diff --git a/kernel/api/contract_move_block_test.go b/kernel/api/contract_move_block_test.goindex 4f53e9dcd5..cde487de19 100644--- a/kernel/api/contract_move_block_test.go+++ b/kernel/api/contract_move_block_test.go@@ -23,7 +23,7 @@ func testAPIContractMoveBlock(t *testing.T, engine *gin.Engine, boxID string) {paragraphID := tree.Root.FirstChild.IDlist := &ast.Node{Type: ast.NodeList, ID: ast.NewNodeID(), ListData: &ast.ListData{Typ: 0}}list.SetIALAttr("id", list.ID)- for i := 0; i < 3; i++ {+ for range 3 {item := &ast.Node{Type: ast.NodeListItem, ID: ast.NewNodeID(), ListData: &ast.ListData{Typ: 0}}item.SetIALAttr("id", item.ID)paragraph := treenode.NewParagraph(ast.NewNodeID())diff --git a/kernel/api/contract_ocr_clear_test.go b/kernel/api/contract_ocr_clear_test.goindex cbc6d21306..147807e08a 100644--- a/kernel/api/contract_ocr_clear_test.go+++ b/kernel/api/contract_ocr_clear_test.go@@ -53,7 +53,7 @@ func TestAPIContractOCRClearDuringDownload(t *testing.T) {const path = "assets/plain.bin"defer util.RemoveAssetText(path)cleared := false- if err := eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadChunks, func(_ map[string]interface{}, _ int) {+ if err := eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadChunks, func(_ map[string]any, _ int) {if cleared {return}diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.goindex 4054f57eac..71a422ef7f 100644--- a/kernel/api/contract_ocr_test.go+++ b/kernel/api/contract_ocr_test.go@@ -100,7 +100,6 @@ func TestAPIContractOCRNotebookIsolation(t *testing.T) {engine.POST("/api/asset/getImageOCRText", getImageOCRText)results := map[string]string{path: "global OCR", path + "?box=" + firstBox: "first notebook OCR", path + "?box=" + secondBox: "second notebook OCR"}for reference, text := range results {- reference := referencet.Cleanup(func() { util.RemoveAssetText(reference) })body, _ := json.Marshal(map[string]string{"path": reference + "#preview", "text": text})recorder := httptest.NewRecorder()diff --git a/kernel/api/contract_repo_test.go b/kernel/api/contract_repo_test.goindex 308494f389..ebd58b019c 100644--- a/kernel/api/contract_repo_test.go+++ b/kernel/api/contract_repo_test.go@@ -15,6 +15,7 @@ import ("github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util""io"+ "maps""mime""net/http""net/http/httptest"@@ -477,9 +478,7 @@ func checkRepoInputCompatibility(t *testing.T, name, valid string, legacy func(*for key := range base {for _, value := range []string{"null", "false", "1", "[]", "{}", `""`, `" "`} {changed := map[string]json.RawMessage{}- for k, v := range base {- changed[k] = v- }+ maps.Copy(changed, base)changed[key] = json.RawMessage(value)data, _ := json.Marshal(changed)bodies = append(bodies, data)@@ -575,7 +574,7 @@ func TestRepoFileWireCompatibility(t *testing.T) {func TestRepoContractTransport(t *testing.T) {log := &dejavu.Log{ID: "index", Memo: "memo", Created: 9223372036854775807, HCreated: "created", Files: []*entity.File{nil, {ID: "file", Path: "box/doc.sy", Size: 42, Updated: 2, Chunks: []string{"chunk"}}}, Count: 1, Size: 42, HSize: "42B", SystemID: "system", SystemName: "name", SystemOS: "os", Tag: "tag", HTagUpdated: "updated"}snapshot := &model.Snapshot{Log: log, TypesCount: []*model.TypeCount{nil, {Type: "sy", Count: 1}}, RequiresDownload: true}- for _, pair := range [][2]interface{}{{log, repoLog(log)}, {snapshot, repoSnapshots([]*model.Snapshot{snapshot})[0]}, {[]*dejavu.Log{nil, log}, repoLogs([]*dejavu.Log{nil, log})}, {([]*dejavu.Log)(nil), repoLogs(nil)}, {[]*dejavu.Log{}, repoLogs([]*dejavu.Log{})}, {[]*model.DiffFile{nil, {FileID: "f", IndexID: "i", Title: "t", Path: "p", HPath: "h", HSize: "s", Updated: 5}}, repoDiffFiles([]*model.DiffFile{nil, {FileID: "f", IndexID: "i", Title: "t", Path: "p", HPath: "h", HSize: "s", Updated: 5}})}} {+ for _, pair := range [][2]any{{log, repoLog(log)}, {snapshot, repoSnapshots([]*model.Snapshot{snapshot})[0]}, {[]*dejavu.Log{nil, log}, repoLogs([]*dejavu.Log{nil, log})}, {([]*dejavu.Log)(nil), repoLogs(nil)}, {[]*dejavu.Log{}, repoLogs([]*dejavu.Log{})}, {[]*model.DiffFile{nil, {FileID: "f", IndexID: "i", Title: "t", Path: "p", HPath: "h", HSize: "s", Updated: 5}}, repoDiffFiles([]*model.DiffFile{nil, {FileID: "f", IndexID: "i", Title: "t", Path: "p", HPath: "h", HSize: "s", Updated: 5}})}} {left, _ := json.Marshal(pair[0])right, _ := json.Marshal(pair[1])if !bytes.Equal(left, right) {diff --git a/kernel/api/contract_riff_test.go b/kernel/api/contract_riff_test.goindex 0702a623d0..635579556a 100644--- a/kernel/api/contract_riff_test.go+++ b/kernel/api/contract_riff_test.go@@ -23,11 +23,11 @@ func TestAPIContractRiffSerialization(t *testing.T) {if err != nil {t.Fatal(err)}- expected, err := json.Marshal(map[string]interface{}{"cards": cards, "unreviewedCount": 3, "unreviewedNewCardCount": 1, "unreviewedOldCardCount": 2})+ expected, err := json.Marshal(map[string]any{"cards": cards, "unreviewedCount": 3, "unreviewedNewCardCount": 1, "unreviewedOldCardCount": 2})if err != nil {t.Fatal(err)}- var got, want interface{}+ var got, want anyif json.Unmarshal(actual, &got) != nil || json.Unmarshal(expected, &want) != nil || !reflect.DeepEqual(got, want) {t.Fatalf("due card serialization changed: %s != %s", actual, expected)}diff --git a/kernel/api/contract_setting_ranges_test.go b/kernel/api/contract_setting_ranges_test.goindex c43c94c1e1..24371a8b2e 100644--- a/kernel/api/contract_setting_ranges_test.go+++ b/kernel/api/contract_setting_ranges_test.go@@ -78,7 +78,7 @@ func TestAPIContractSettingValueRanges(t *testing.T) {}for field, want := range entry.want {value := actual[entry.namespace]- for _, key := range strings.Split(field, ".") {+ for key := range strings.SplitSeq(field, ".") {value = value.(map[string]any)[key]}if value != want {diff --git a/kernel/api/contract_setting_test.go b/kernel/api/contract_setting_test.goindex 8a85f21f69..6b99d81a1c 100644--- a/kernel/api/contract_setting_test.go+++ b/kernel/api/contract_setting_test.go@@ -245,9 +245,9 @@ func fillSettingPayload(value reflect.Value) {value.Set(reflect.New(value.Type().Elem()))fillSettingPayload(value.Elem())case reflect.Struct:- for i := 0; i < value.NumField(); i++ {- if value.Field(i).CanSet() {- fillSettingPayload(value.Field(i))+ for _, field := range value.Fields() {+ if field.CanSet() {+ fillSettingPayload(field)}}if value.Type() == reflect.TypeFor[conf.EntryVisibilityProfile]() {diff --git a/kernel/api/contract_sync_test.go b/kernel/api/contract_sync_test.goindex 644df8865b..9c03e1e00b 100644--- a/kernel/api/contract_sync_test.go+++ b/kernel/api/contract_sync_test.go@@ -64,7 +64,7 @@ func compareSyncDecode[Request, Data, Value any](t *testing.T, endpoint apicontrfunc TestAPIContractSyncProviderConfigCompatibility(t *testing.T) {for _, raw := range []string{`{}`, `{"ENDPOINT":" example ","timeout":1.0,"concurrentReqs":9007199254740993}`, `{"endpoint":false}`, `{"timeout":1.5}`, `{"pathStyle":null}`, `{"endpoint":"first","endpoint":"second"}`} {- var object map[string]interface{}+ var object map[string]anyif err := json.Unmarshal([]byte(raw), &object); err != nil {t.Fatal(err)}@@ -218,7 +218,7 @@ func TestAPIContractSyncProviderMultipart(t *testing.T) {for _, count := range []int{0, 1, 2} {var body bytes.Bufferwriter := multipart.NewWriter(&body)- for i := 0; i < count; i++ {+ for range count {part, err := writer.CreateFormFile("file", "config.txt")if err != nil {t.Fatal(err)diff --git a/kernel/api/export.go b/kernel/api/export.goindex 4d6b4e7bb6..45d7c88147 100644--- a/kernel/api/export.go+++ b/kernel/api/export.go@@ -24,6 +24,7 @@ import ("os""path""path/filepath"+ "slices""strings""time"@@ -265,12 +266,10 @@ var exportNotebooksMd = contractHandler(apicontract.ExportNotebooksMd, func(c *gret.Code = -1return contractFailure[apicontract.ExportNamedZipData](ret)}- for _, notebook := range notebooks {- if model.IsEncryptedBox(notebook) {- ret.Code = -1- ret.Msg = model.Conf.Language(395)- return contractFailure[apicontract.ExportNamedZipData](ret)- }+ if slices.ContainsFunc(notebooks, model.IsEncryptedBox) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(395)+ return contractFailure[apicontract.ExportNamedZipData](ret)}if err := request.Validate(); err != nil {ret.Code = -1@@ -335,12 +334,10 @@ var exportNotebooksSY = contractHandler(apicontract.ExportNotebooksSY, func(c *gret.Code = -1return contractFailure[apicontract.ExportZipData](ret)}- for _, notebook := range notebooks {- if model.IsEncryptedBox(notebook) {- ret.Code = -1- ret.Msg = model.Conf.Language(395)- return contractFailure[apicontract.ExportZipData](ret)- }+ if slices.ContainsFunc(notebooks, model.IsEncryptedBox) {+ ret.Code = -1+ ret.Msg = model.Conf.Language(395)+ return contractFailure[apicontract.ExportZipData](ret)}zipPath := model.ExportNotebooksSY(notebooks)return apicontract.Success(apicontract.ExportZipData{Zip: zipPath})diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.goindex 3835463f07..667a234d24 100644--- a/kernel/api/filetree_test.go+++ b/kernel/api/filetree_test.go@@ -348,7 +348,7 @@ func TestAuthFilePublishAccessThrottlesBruteForce(t *testing.T) {defer util.AuthThrottleReset(attackerIP)// 前 5 次失败为普通失败响应,第 6 次失败触发锁定但本次仍返回普通响应(与 util.AuthThrottleFail 语义一致)- for i := 0; i < 6; i++ {+ for i := range 6 {recorder := post(passwordWrong)if recorder.Code != http.StatusOK {t.Fatalf("attempt %d expected %d, got %d", i+1, http.StatusOK, recorder.Code)diff --git a/kernel/api/lute.go b/kernel/api/lute.goindex d5b8cca2ca..d8ffb4ce5d 100644--- a/kernel/api/lute.go+++ b/kernel/api/lute.go@@ -323,7 +323,7 @@ func normalizeIFramePosition(node *ast.Node) {func isOutOfFlowPosition(style string) bool {position := ""- for _, declaration := range strings.Split(style, ";") {+ for declaration := range strings.SplitSeq(style, ";") {property, value, ok := strings.Cut(declaration, ":")if !ok || !strings.EqualFold(strings.TrimSpace(property), "position") {continuediff --git a/kernel/api/lute_escape_test.go b/kernel/api/lute_escape_test.goindex 45c9beaa79..550229a27a 100644--- a/kernel/api/lute_escape_test.go+++ b/kernel/api/lute_escape_test.go@@ -83,7 +83,7 @@ func TestHTML2BlockDOMContractEscapedText(t *testing.T) {t.Fatalf("conversion failed: %s, %v", recorder.Body.String(), err)}engine := util.NewLute()- for round := 0; round < 3; round++ {+ for round := range 3 {doc, parseErr := goquery.NewDocumentFromReader(strings.NewReader(response.Data))if parseErr != nil {t.Fatal(parseErr)diff --git a/kernel/api/lute_text_style_test.go b/kernel/api/lute_text_style_test.goindex 2402be06da..dafa9014a5 100644--- a/kernel/api/lute_text_style_test.go+++ b/kernel/api/lute_text_style_test.go@@ -61,7 +61,7 @@ func TestHTML2BlockDOMQuotedFontFamily(t *testing.T) {t.Fatalf("conversion failed: %s, %v", recorder.Body.String(), err)}engine := util.NewLute()- for round := 0; round < 3; round++ {+ for round := range 3 {if strings.Contains(response.Data, "{: style=") {t.Fatalf("round %d leaked attributes: %s", round, response.Data)}diff --git a/kernel/api/notebook_test.go b/kernel/api/notebook_test.goindex bd94a0db26..f58a07945f 100644--- a/kernel/api/notebook_test.go+++ b/kernel/api/notebook_test.go@@ -131,7 +131,7 @@ func writeNotebookSortFixture(t *testing.T, boxID string, childCount, boxIndex iwriteNotebookSortDoc(t, boxID, boxID)childIDs := make([]string, 0, childCount)- for i := 0; i < childCount; i++ {+ for i := range childCount {childID := fmt.Sprintf("2026081201%02d%02d-doc%04d", boxIndex, i, boxIndex*100+i)writeNotebookSortDoc(t, boxID, childID)childIDs = append(childIDs, childID)diff --git a/kernel/api/setting_contract_fields_test.go b/kernel/api/setting_contract_fields_test.goindex 90b6983851..c191aaac31 100644--- a/kernel/api/setting_contract_fields_test.go+++ b/kernel/api/setting_contract_fields_test.go@@ -1,6 +1,7 @@package apiimport (+ "maps""reflect""sort""strings"@@ -108,8 +109,7 @@ func structType(typ reflect.Type) reflect.Type {func jsonFields(typ reflect.Type) map[string]reflect.Type {ret := map[string]reflect.Type{}- for i := 0; i < typ.NumField(); i++ {- field := typ.Field(i)+ for field := range typ.Fields() {if !field.IsExported() {continue}@@ -118,9 +118,7 @@ func jsonFields(typ reflect.Type) map[string]reflect.Type {continue}if field.Anonymous && name == "" {- for embedded, embeddedType := range jsonFields(structType(field.Type)) {- ret[embedded] = embeddedType- }+ maps.Copy(ret, jsonFields(structType(field.Type)))continue}if name == "" {diff --git a/kernel/api/setting_patch_test.go b/kernel/api/setting_patch_test.goindex 53b93d94c5..6962b3ac34 100644--- a/kernel/api/setting_patch_test.go+++ b/kernel/api/setting_patch_test.go@@ -27,14 +27,12 @@ func TestAPIContractSettingPatchConcurrentFields(t *testing.T) {fontSize := model.Conf.Editor.Load().FontSizevar group sync.WaitGroupfor _, body := range []string{`{"editor":{"displayImgName":true}}`, `{"editor":{"displayImgAlt":true}}`} {- group.Add(1)- go func() {- defer group.Done()+ group.Go(func() {code, message, _ := settingContractRequest(t, "patch", patchSetting, body)if code != 0 {t.Errorf("patch failed: %d %s", code, message)}- }()+ })}group.Wait()if !model.Conf.Editor.Load().DisplayImgName || !model.Conf.Editor.Load().DisplayImgAlt || model.Conf.Editor.Load().FontSize != fontSize {diff --git a/kernel/api/setting_write_contract_test.go b/kernel/api/setting_write_contract_test.goindex af3b7c05ec..d7875088f1 100644--- a/kernel/api/setting_write_contract_test.go+++ b/kernel/api/setting_write_contract_test.go@@ -108,19 +108,20 @@ func TestSettingWriteEndpointsAreDeclared(t *testing.T) {body = funcs[ident.Name]}// 展开同文件中被直接调用的辅助函数一层- expanded := body+ var expanded strings.Builder+ expanded.WriteString(body)for fn, fnBody := range funcs {if strings.Contains(body, fn+"(") {- expanded += fnBody+ expanded.WriteString(fnBody)}}path := paths[selector.Sel.Name]definition := definitions[path]- if directSettingWritePattern.MatchString(expanded) && !definition.Setting.Declared() {+ if directSettingWritePattern.MatchString(expanded.String()) && !definition.Setting.Declared() {t.Errorf("%s (%s) writes configuration directly but declares no setting namespace", path, name)}if definition.Setting.Declared() && definition.Setting.Mode != apicontract.SettingSelfManaged &&- strings.Contains(expanded, "settingMutationMu.Lock()") {+ strings.Contains(expanded.String(), "settingMutationMu.Lock()") {t.Errorf("%s locks the setting mutex itself; declare SettingSelfManaged instead", path)}return truediff --git a/kernel/api/settings_reset.go b/kernel/api/settings_reset.goindex dcddbd476c..aab3f3c78e 100644--- a/kernel/api/settings_reset.go+++ b/kernel/api/settings_reset.go@@ -3,6 +3,7 @@ package apiimport ("context""errors"+ "slices""sync""time"@@ -98,13 +99,7 @@ var resetSettings = contractHandler(apicontract.ResetSettings,defer settingMutationMu.Unlock()// 等待期间新接入的客户端尚未保存输入,此次操作应取消并由用户重试。for _, current := range util.SessionsByType("main") {- prepared := false- for _, session := range sessions {- if current == session {- prepared = true- break- }- }+ prepared := slices.Contains(sessions, current)if !prepared {return apicontract.Failure[apicontract.Null](-1, util.I18nTerm(model.Conf.Lang, "settingsPendingSaveError"))}diff --git a/kernel/api/storage.go b/kernel/api/storage.goindex b94e4550a4..9d99dba68c 100644--- a/kernel/api/storage.go+++ b/kernel/api/storage.go@@ -19,6 +19,7 @@ package apiimport ("encoding/json""github.com/siyuan-note/siyuan/kernel/apicontract"+ "slices""strings""github.com/88250/gulu"@@ -60,10 +61,8 @@ var getLocalStorageVals = contractHandler(apicontract.GetLocalStorageVals, func(if len(keys) == 0 {return apicontract.Failure[map[string]apicontract.JSONValue](-1, "Field [keys] must not be empty")}- for _, key := range keys {- if key == "" {- return apicontract.Failure[map[string]apicontract.JSONValue](-1, "Field [keys]: each element must not be empty")- }+ if slices.Contains(keys, "") {+ return apicontract.Failure[map[string]apicontract.JSONValue](-1, "Field [keys]: each element must not be empty")}data := model.GetLocalStorage()if model.IsReadOnlyRoleContext(c) {@@ -152,10 +151,8 @@ var removeLocalStorageVals = contractHandler(apicontract.RemoveLocalStorageVals,if len(keys) == 0 {return apicontract.Failure[apicontract.Null](-1, "Field [keys] must not be empty")}- for _, key := range keys {- if key == "" {- return apicontract.Failure[apicontract.Null](-1, "Field [keys]: each element must not be empty")- }+ if slices.Contains(keys, "") {+ return apicontract.Failure[apicontract.Null](-1, "Field [keys]: each element must not be empty")}app := request.Apperr := model.RemoveLocalStorageVals(keys)diff --git a/kernel/apicontract/ai.go b/kernel/apicontract/ai.goindex 121ccee965..49b3756a58 100644--- a/kernel/apicontract/ai.go+++ b/kernel/apicontract/ai.go@@ -160,14 +160,14 @@ type AICapabilityManifest struct {OwnerName string `json:"ownerName,omitempty"`Runtime string `json:"runtime"`AgentOnly bool `json:"agentOnly,omitempty"`- Effects AIToolEffects `json:"effects,omitempty"`+ Effects AIToolEffects `json:"effects"`Available bool `json:"available"`Actions []AICapabilityAction `json:"actions,omitempty"`}type AICapabilityAction struct {Name string `json:"name"`- Effects AIToolEffects `json:"effects,omitempty"`+ Effects AIToolEffects `json:"effects"`}type AIMessageRequest struct {diff --git a/kernel/apicontract/av_union.go b/kernel/apicontract/av_union.goindex 8a4a4977ad..7344a50008 100644--- a/kernel/apicontract/av_union.go+++ b/kernel/apicontract/av_union.go@@ -103,8 +103,7 @@ func avEmbeddedPayloadSchema(b *schemaBuilder, t reflect.Type, input bool) (*Schb.definitions[name] = resultvar base reflect.Typevar own []reflect.StructField- for i := 0; i < t.NumField(); i++ {- field := t.Field(i)+ for field := range t.Fields() {if field.Anonymous && field.Type.Kind() == reflect.Pointer {base = field.Type.Elem()} else {@@ -117,8 +116,7 @@ func avEmbeddedPayloadSchema(b *schemaBuilder, t reflect.Type, input bool) (*Schfor _, present := range []bool{true, false} {fields := append([]reflect.StructField{}, own...)if present {- for i := 0; i < base.NumField(); i++ {- field := base.Field(i)+ for field := range base.Fields() {shadowed := falsefor _, child := range own {if child.Name == field.Name {diff --git a/kernel/apicontract/decode.go b/kernel/apicontract/decode.goindex 92ee9e210e..a6662b3558 100644--- a/kernel/apicontract/decode.go+++ b/kernel/apicontract/decode.go@@ -63,7 +63,7 @@ func legacyJSONObjectError(err error) error {func decodeRequestFields(value reflect.Value, fields map[string]json.RawMessage) error {for i := 0; i < value.NumField(); i++ {field := value.Type().Field(i)- name := strings.Split(field.Tag.Get("json"), ",")[0]+ name, _, _ := strings.Cut(field.Tag.Get("json"), ",")if (!field.IsExported() && !field.Anonymous) || name == "-" {continue}@@ -133,13 +133,13 @@ func decodeRequestFields(value reflect.Value, fields map[string]json.RawMessage)}value.Field(i).SetString(trimmed)}- for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ for option := range strings.SplitSeq(field.Tag.Get("api"), ",") {if strings.HasPrefix(option, "enum=") {if field.Type.Kind() != reflect.String {return fmt.Errorf("unsupported enum field: %s", name)}found := false- for _, choice := range strings.Split(strings.TrimPrefix(option, "enum="), "|") {+ for choice := range strings.SplitSeq(strings.TrimPrefix(option, "enum="), "|") {if value.Field(i).String() == choice {found = truebreakdiff --git a/kernel/apicontract/export.go b/kernel/apicontract/export.goindex 761cf8b5f1..450097905b 100644--- a/kernel/apicontract/export.go+++ b/kernel/apicontract/export.go@@ -222,7 +222,7 @@ func decodeExportFields(value reflect.Value, fields map[string]json.RawMessage)}continue}- name := strings.Split(field.Tag.Get("json"), ",")[0]+ name, _, _ := strings.Cut(field.Tag.Get("json"), ",")opts := "," + field.Tag.Get("api") + ","has := func(option string) bool { return strings.Contains(opts, ","+option+",") }if has("filterstrings") {diff --git a/kernel/apicontract/filetree_input.go b/kernel/apicontract/filetree_input.goindex 4e81e631a6..8194b6e9d9 100644--- a/kernel/apicontract/filetree_input.go+++ b/kernel/apicontract/filetree_input.go@@ -6,6 +6,7 @@ import ("errors""fmt""io"+ "maps""reflect""strings")@@ -91,9 +92,7 @@ func (r FileTreeSetPublishRequest) Options() (FileTreePublishOptions, error) {}func (r FileTreeGetDocRequest) Options() (FileTreeGetDocOptions, error) {fields := make(fileTreeFields, len(r.fields))- for key, value := range r.fields {- fields[key] = value- }+ maps.Copy(fields, r.fields)var includeDocInfo boolif json.Unmarshal(fields["includeDocInfo"], &includeDocInfo) != nil {delete(fields, "includeDocInfo")diff --git a/kernel/apicontract/graph_query.go b/kernel/apicontract/graph_query.goindex 64d2c0dade..448e83118f 100644--- a/kernel/apicontract/graph_query.go+++ b/kernel/apicontract/graph_query.go@@ -172,15 +172,13 @@ func init() {return}GetGraph.decodeFailure = func(err error) Response[GlobalGraphData] {- var failure *graphQueryDecodeError- if errors.As(err, &failure) {+ if failure, ok := errors.AsType[*graphQueryDecodeError](err); ok {return GetGraph.FailureWithData(-1, err.Error(), GraphQueryEcho[GlobalGraphResult](failure.reqID))}return Failure[GlobalGraphData](-1, err.Error())}GetLocalGraph.decodeFailure = func(err error) Response[LocalGraphData] {- var failure *graphQueryDecodeError- if errors.As(err, &failure) {+ if failure, ok := errors.AsType[*graphQueryDecodeError](err); ok {return GetLocalGraph.FailureWithData(-1, err.Error(), GraphQueryEcho[LocalGraphResult](failure.reqID))}return Failure[LocalGraphData](-1, err.Error())diff --git a/kernel/apicontract/multipart.go b/kernel/apicontract/multipart.goindex 2072c89873..3a2e033089 100644--- a/kernel/apicontract/multipart.go+++ b/kernel/apicontract/multipart.go@@ -17,15 +17,14 @@ func validateMultipartRequest(t reflect.Type) error {if t == reflect.TypeFor[MultipartFields]() || t == reflect.TypeFor[ExtensionCopyRequest]() {return nil}- for i := 0; i < t.NumField(); i++ {- field := t.Field(i)+ for field := range t.Fields() {if !field.IsExported() || field.Anonymous || field.Tag.Get("json") == "" {return fmt.Errorf("multipart fields must be named and exported: %s", field.Name)}if field.Type != reflect.TypeFor[string]() && field.Type != reflect.TypeFor[*string]() && field.Type != reflect.TypeFor[*multipart.FileHeader]() && field.Type != reflect.TypeFor[[]*multipart.FileHeader]() {return fmt.Errorf("unsupported multipart field: %s", field.Name)}- for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ for option := range strings.SplitSeq(field.Tag.Get("api"), ",") {if option != "" && option != "optional" && option != "nonnullable" {return fmt.Errorf("unsupported multipart option: %s", option)}@@ -63,7 +62,7 @@ func (e Endpoint[Request, Data]) DecodeMultipart(form *multipart.Form) (request}for i := 0; i < value.NumField(); i++ {field := value.Type().Field(i)- name := strings.Split(field.Tag.Get("json"), ",")[0]+ name, _, _ := strings.Cut(field.Tag.Get("json"), ",")optional := strings.Contains(","+field.Tag.Get("api")+",", ",optional,")switch field.Type {case reflect.TypeFor[*multipart.FileHeader](), reflect.TypeFor[[]*multipart.FileHeader]():diff --git a/kernel/apicontract/plugin.go b/kernel/apicontract/plugin.goindex 1f91f64db6..3a0f5d13ea 100644--- a/kernel/apicontract/plugin.go+++ b/kernel/apicontract/plugin.go@@ -47,8 +47,7 @@ func init() {return request, nil}endpoint.decodeFailure = func(err error) Response[*LoadedPlugin] {- var nameError *pluginNameError- if errors.As(err, &nameError) {+ if nameError, ok := errors.AsType[*pluginNameError](err); ok {return Failure[*LoadedPlugin](nameError.code, nameError.message)}return Failure[*LoadedPlugin](-1, err.Error())diff --git a/kernel/apicontract/repo_test.go b/kernel/apicontract/repo_test.goindex ecbd4dfaa6..193741fc28 100644--- a/kernel/apicontract/repo_test.go+++ b/kernel/apicontract/repo_test.go@@ -33,7 +33,7 @@ func TestRepoSnapshotTimeRangeContract(t *testing.T) {func TestRepoSnapshotIDContract(t *testing.T) {for _, enabled := range []bool{false, true} {- body, _ := json.Marshal(map[string]interface{}{"page": 1, "includeFiles": enabled})+ body, _ := json.Marshal(map[string]any{"page": 1, "includeFiles": enabled})request, err := GetRepoSnapshots.Decode(strings.NewReader(string(body)))if err != nil || request.IncludeFiles != enabled {t.Fatalf("includeFiles: %+v %v", request, err)diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.goindex c789116829..7b75bc3cdc 100644--- a/kernel/apicontract/schema.go+++ b/kernel/apicontract/schema.go@@ -442,8 +442,7 @@ func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {}func (b *schemaBuilder) fields(object *Schema, t reflect.Type, input bool) error {- for i := 0; i < t.NumField(); i++ {- field := t.Field(i)+ for field := range t.Fields() {if !field.IsExported() && !field.Anonymous {continue}@@ -478,7 +477,7 @@ func (b *schemaBuilder) fields(object *Schema, t reflect.Type, input bool) error}options := "," + field.Tag.Get("api") + ","has := func(option string) bool { return strings.Contains(options, ","+option+",") }- for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ for option := range strings.SplitSeq(field.Tag.Get("api"), ",") {switch {case option == "", option == "optional", option == "nullable", option == "nonnullable":case option == "legacyobject":@@ -521,10 +520,10 @@ func (b *schemaBuilder) fields(object *Schema, t reflect.Type, input bool) errorif has("nonnullable") {child = nonnullable(child)}- for _, option := range strings.Split(field.Tag.Get("api"), ",") {+ for option := range strings.SplitSeq(field.Tag.Get("api"), ",") {if strings.HasPrefix(option, "enum=") {child.Enum = nil- for _, value := range strings.Split(strings.TrimPrefix(option, "enum="), "|") {+ for value := range strings.SplitSeq(strings.TrimPrefix(option, "enum="), "|") {child.Enum = append(child.Enum, value)}}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 982be5631e..829566c3cb 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -761,6 +761,7 @@}},"required": [+ "effects","name"],"additionalProperties": false@@ -811,6 +812,7 @@"required": ["available","description",+ "effects","id","name","runtime",diff --git a/kernel/apicontract/setting_patch.go b/kernel/apicontract/setting_patch.goindex 232d2ff4f8..bac2eeb31d 100644--- a/kernel/apicontract/setting_patch.go+++ b/kernel/apicontract/setting_patch.go@@ -89,8 +89,8 @@ func init() {if restricted != nil {allowed := map[string]bool{}typ := reflect.TypeOf(restricted)- for i := 0; i < typ.NumField(); i++ {- allowed[strings.Split(typ.Field(i).Tag.Get("json"), ",")[0]] = true+ for field := range typ.Fields() {+ allowed[strings.Split(field.Tag.Get("json"), ",")[0]] = true}for field := range object {if !allowed[field] {diff --git a/kernel/apicontract/system_input.go b/kernel/apicontract/system_input.goindex f1373949fd..67dbb06976 100644--- a/kernel/apicontract/system_input.go+++ b/kernel/apicontract/system_input.go@@ -74,8 +74,7 @@ func init() {SystemSetOIDC.decodeRequest = decodeOIDCSystemOIDCValidateStart.decodeRequest = decodeOIDCSystemImportCustomFont.decodeFailure = func(err error) Response[*SystemCustomFont] {- var sizeError *http.MaxBytesError- if errors.As(err, &sizeError) {+ if _, ok := errors.AsType[*http.MaxBytesError](err); ok {return Failure[*SystemCustomFont](413, "font file is too large")}return Failure[*SystemCustomFont](400, "Field [file] must not be empty")diff --git a/kernel/apicontract/system_test.go b/kernel/apicontract/system_test.goindex 801628d37b..e446ac6049 100644--- a/kernel/apicontract/system_test.go+++ b/kernel/apicontract/system_test.go@@ -18,7 +18,7 @@ func TestNoBodyContractRequests(t *testing.T) {func TestAPIContractSystemRequestCompatibility(t *testing.T) {for _, body := range []string{`{}`, `null`, `{"force":null}`, `{"force":true}`, `{"force":true} {}`, `{"unknown":1e1000}`, ``} {- var legacy map[string]interface{}+ var legacy map[string]anylegacyErr := json.NewDecoder(strings.NewReader(body)).Decode(&legacy)request, err := SystemGetChangelog.Decode(strings.NewReader(body))if err != nil {diff --git a/kernel/apicontract/transaction_schema.go b/kernel/apicontract/transaction_schema.goindex e9aefaf4e5..a90087d84a 100644--- a/kernel/apicontract/transaction_schema.go+++ b/kernel/apicontract/transaction_schema.go@@ -1,6 +1,10 @@package apicontract-import "reflect"+import (+ "maps"+ "reflect"+ "slices"+)type transactionActionPayload struct {action string@@ -237,9 +241,7 @@ func transactionPayloadSchema(b *schemaBuilder, t reflect.Type, input bool) (*Scfunc transactionOperationBranch(base *Schema, action, data, result *Schema, input bool) *Schema {properties := map[string]*Schema{}- for key, value := range base.Properties {- properties[key] = value- }+ maps.Copy(properties, base.Properties)properties["action"], properties["data"], properties["retData"] = action, data, resultrequired := append([]string{}, base.Required...)addRequired := []string{"data", "retData"}@@ -247,13 +249,7 @@ func transactionOperationBranch(base *Schema, action, data, result *Schema, inpuaddRequired = []string{"action"}}for _, name := range addRequired {- found := false- for _, existing := range required {- if existing == name {- found = true- break- }- }+ found := slices.Contains(required, name)if !found {required = append(required, name)}diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.goindex 08fd395c72..769577ed58 100644--- a/kernel/apicontract/typescript.go+++ b/kernel/apicontract/typescript.go@@ -141,7 +141,7 @@ func (b *Bundle) TypeScript(documentation map[string]string) []byte {}if text := documentation[endpoint.Handler]; text != "" {output.WriteString(" /**\n")- for _, line := range strings.Split(strings.ReplaceAll(text, "*/", "*\\/"), "\n") {+ for line := range strings.SplitSeq(strings.ReplaceAll(text, "*/", "*\\/"), "\n") {if line == "" {output.WriteString(" *\n")} else {diff --git a/kernel/av/automation_template.go b/kernel/av/automation_template.goindex b661abc7bf..b43611d238 100644--- a/kernel/av/automation_template.go+++ b/kernel/av/automation_template.go@@ -6,6 +6,7 @@ import ("fmt""io""math"+ "slices""sort""strconv""strings"@@ -126,23 +127,17 @@ func automationTemplate(context AutomationTemplateContext, source string) (*tempcase *parse.WithNode:children = []parse.Node{node.Pipe, node.List, node.ElseList}case *parse.ChainNode:- for _, field := range node.Field {- if field == "Local" {- return fmt.Errorf("automation templates use the saved time zone")- }+ if slices.Contains(node.Field, "Local") {+ return fmt.Errorf("automation templates use the saved time zone")}children = []parse.Node{node.Node}case *parse.FieldNode:- for _, field := range node.Ident {- if field == "Local" {- return fmt.Errorf("automation templates use the saved time zone")- }+ if slices.Contains(node.Ident, "Local") {+ return fmt.Errorf("automation templates use the saved time zone")}case *parse.VariableNode:- for _, field := range node.Ident {- if field == "Local" {- return fmt.Errorf("automation templates use the saved time zone")- }+ if slices.Contains(node.Ident, "Local") {+ return fmt.Errorf("automation templates use the saved time zone")}case *parse.RangeNode, *parse.TemplateNode:return fmt.Errorf("automation template loops and recursion are unavailable")diff --git a/kernel/av/av.go b/kernel/av/av.goindex b1891ec941..6821a7b45b 100644--- a/kernel/av/av.go+++ b/kernel/av/av.go@@ -24,6 +24,7 @@ import ("os""path/filepath""regexp"+ "slices""sort""strconv""strings"@@ -657,7 +658,7 @@ func loadAttributeViewSearchInfoInBox(avID, avJSONPath, avBoxID string) (ret *At}defer release()- for i := 0; i < 3; i++ {+ for range 3 {if cached, ok := cache.GetAVSearchDataInBox[*AttributeViewSearchInfo](avID, avBoxID); ok {return cached, nil}@@ -1066,8 +1067,8 @@ func saveAttributeView(av *AttributeView, original []byte) (err error) {// 清理渲染回填值for _, kv := range av.KeyValues {- for i := len(kv.Values) - 1; i >= 0; i-- {- if kv.Values[i].IsRenderAutoFill {+ for i, v := range slices.Backward(kv.Values) {+ if v.IsRenderAutoFill {kv.Values = append(kv.Values[:i], kv.Values[i+1:]...)}}diff --git a/kernel/av/av_fix.go b/kernel/av/av_fix.goindex da812ea016..5619ff10d5 100644--- a/kernel/av/av_fix.go+++ b/kernel/av/av_fix.go@@ -17,6 +17,7 @@package avimport (+ "slices""time""github.com/88250/lute"@@ -69,18 +70,11 @@ func upgradeSpec10(av *AttributeView) {if nil != view.List || nil != view.Calendar {return true}- for _, group := range view.Groups {- if needsUpgrade(group) {- return true- }- }- return false+ return slices.ContainsFunc(view.Groups, needsUpgrade)}- for _, view := range av.Views {- if needsUpgrade(view) {- av.Spec = 10- return- }+ if slices.ContainsFunc(av.Views, needsUpgrade) {+ av.Spec = 10+ return}}diff --git a/kernel/av/av_search_test.go b/kernel/av/av_search_test.goindex 9b82a24912..073ddf37da 100644--- a/kernel/av/av_search_test.go+++ b/kernel/av/av_search_test.go@@ -49,7 +49,7 @@ func TestParseAttributeViewSearchInfo(t *testing.T) {t.Fatalf("unexpected second view: %+v", info.Views[1])}- if _, err = parseAttributeViewSearchInfo([]byte(fmt.Sprintf(`{"spec": %d}`, CurrentSpec+1))); err != ErrSpecTooNew {+ if _, err = parseAttributeViewSearchInfo(fmt.Appendf(nil, `{"spec": %d}`, CurrentSpec+1)); err != ErrSpecTooNew {t.Fatalf("expected newer spec error, got %v", err)}}diff --git a/kernel/av/collection_index.go b/kernel/av/collection_index.goindex 5a439a9288..443597a3fa 100644--- a/kernel/av/collection_index.go+++ b/kernel/av/collection_index.go@@ -2,6 +2,7 @@ package avimport ("encoding/json"+ "maps""os""path/filepath""sort"@@ -86,9 +87,7 @@ func BlockCollectionViewIDsInBox(boxID string) ([]string, error) {collectionIndex.Unlock()return BlockCollectionViewIDsInBox(boxID)}- for id, enabled := range collectionIndex.boxes[boxID] {- ids[id] = enabled- }+ maps.Copy(ids, collectionIndex.boxes[boxID])collectionIndex.boxes[boxID], collectionIndex.loaded[boxID] = ids, truecollectionIndex.Unlock()}diff --git a/kernel/av/filter.go b/kernel/av/filter.goindex 7ff7bb6fae..55df38e13b 100644--- a/kernel/av/filter.go+++ b/kernel/av/filter.go@@ -18,6 +18,7 @@ package avimport ("reflect"+ "slices""strconv""strings""time"@@ -749,12 +750,7 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sreturn true}- for _, c := range value.Rollup.Contents {- if isRollupStoredValueEmpty(c) {- return true- }- }- return false+ return slices.ContainsFunc(value.Rollup.Contents, isRollupStoredValueEmpty)} else if FilterOperatorIsNotEmpty == filter.Operator {if 1 > len(value.Rollup.Contents) {return false@@ -806,12 +802,7 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sreturn false}- for _, c := range value.Rollup.Contents {- if isRollupStoredValueEmpty(c) {- return false- }- }- return true+ return !slices.ContainsFunc(value.Rollup.Contents, isRollupStoredValueEmpty)}if 1 > len(filter.Value.Rollup.Contents) {@@ -838,12 +829,7 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sreturn true}- for _, c := range value.Rollup.Contents {- if isRollupStoredValueEmpty(c) {- return false- }- }- return true+ return !slices.ContainsFunc(value.Rollup.Contents, isRollupStoredValueEmpty)} else if FilterOperatorIsNotEmpty == filter.Operator {if 1 > len(value.Rollup.Contents) {return true@@ -883,10 +869,8 @@ func (value *Value) Filter(filter *ViewFilter, attrView *AttributeView, itemID sif nil != value.Relation {for _, blockID := range value.Relation.BlockIDs {- for _, filterBlockID := range filter.Value.Relation.BlockIDs {- if blockID == filterBlockID {- return FilterOperatorContainsAnyItem == filter.Operator- }+ if slices.Contains(filter.Value.Relation.BlockIDs, blockID) {+ return FilterOperatorContainsAnyItem == filter.Operator}}}diff --git a/kernel/av/layout_legacy_map_test.go b/kernel/av/layout_legacy_map_test.goindex 8aee462aab..e6543d2afe 100644--- a/kernel/av/layout_legacy_map_test.go+++ b/kernel/av/layout_legacy_map_test.go@@ -25,7 +25,7 @@ func TestLegacyMapLayoutPreservesStorageAsTable(t *testing.T) {}}locationBefore := *database.KeyValues[0].Values[0].Location- for i := 0; i < 2; i++ {+ for range 2 {data, marshalErr := json.Marshal(database)if marshalErr != nil {t.Fatal(marshalErr)diff --git a/kernel/av/normalized_cache_test.go b/kernel/av/normalized_cache_test.goindex 3e9bafbbea..fc8612d3fa 100644--- a/kernel/av/normalized_cache_test.go+++ b/kernel/av/normalized_cache_test.go@@ -21,7 +21,7 @@ func normalizedRichCacheFixture(t testing.TB) (string, []byte) {view := &AttributeView{ID: id, Spec: RichTextSpec, Name: "Original", KeyValues: []*KeyValues{{Key: &Key{ID: "text", Type: KeyTypeText},}}}- for i := 0; i < 100; i++ {+ for range 100 {view.KeyValues[0].Values = append(view.KeyValues[0].Values, &Value{Type: KeyTypeText, Text: &ValueText{Content: "incorrect projection",Rich: &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "**bold**\n"},diff --git a/kernel/av/number_calc_test.go b/kernel/av/number_calc_test.goindex 2e15bd4175..af8a0b897d 100644--- a/kernel/av/number_calc_test.go+++ b/kernel/av/number_calc_test.go@@ -187,7 +187,7 @@ func TestDecimalSumNonFinite(t *testing.T) {func BenchmarkDecimalSum(b *testing.B) {for i := 0; i < b.N; i++ {var sum decimalSum- for j := 0; j < 10000; j++ {+ for range 10000 {sum.add(0.1)}if 1000 != sum.float64() {diff --git a/kernel/av/sort.go b/kernel/av/sort.goindex 6dedbcc615..00f59e008b 100644--- a/kernel/av/sort.go+++ b/kernel/av/sort.go@@ -376,16 +376,16 @@ func (value *Value) compare(other *Value, optionSort map[string]int, dateEndpoinfor _, v := range value.MAsset {v1.WriteString(v.Content)}- var v2 string+ var v2 strings.Builderfor _, v := range other.MAsset {- v2 += v.Content+ v2.WriteString(v.Content)}- if 0 == strings.Compare(v1.String(), v2) {+ if 0 == strings.Compare(v1.String(), v2.String()) {return 0}- if util.EmojiPinYinCompare(v1.String(), v2) {+ if util.EmojiPinYinCompare(v1.String(), v2.String()) {return -1}return 1diff --git a/kernel/av/table_cell_rich.go b/kernel/av/table_cell_rich.goindex edb1236454..965527bfff 100644--- a/kernel/av/table_cell_rich.go+++ b/kernel/av/table_cell_rich.go@@ -4,6 +4,7 @@ import ("fmt""net/url""regexp"+ "slices""sort""strconv""strings"@@ -49,12 +50,7 @@ func isTableCellRichCustomTextMark(node *ast.Node) bool {if nil == node || ast.NodeTextMark != node.Type {return false}- for _, typ := range strings.Fields(node.TextMarkType) {- if tableCellRichCustomTypePattern.MatchString(typ) {- return true- }- }- return false+ return slices.ContainsFunc(strings.Fields(node.TextMarkType), tableCellRichCustomTypePattern.MatchString)}func isAllowedTableCellRichCustomNode(node *ast.Node) bool {@@ -68,7 +64,7 @@ func isAllowedTableCellRichCustomNode(node *ast.Node) bool {"" != node.TextMarkFlashcardOcclusionID || !isAllowedValueTextMarkReferenceData(node, true) {return false}- for _, typ := range strings.Fields(node.TextMarkType) {+ for typ := range strings.FieldsSeq(node.TextMarkType) {if tableCellRichCustomTypePattern.MatchString(typ) {continue}diff --git a/kernel/av/table_cell_rich_test.go b/kernel/av/table_cell_rich_test.goindex f6e2810228..2700634374 100644--- a/kernel/av/table_cell_rich_test.go+++ b/kernel/av/table_cell_rich_test.go@@ -17,7 +17,7 @@ func TestTableCellRichCodeSettings(t *testing.T) {t.Run(attribute+"/"+value, func(t *testing.T) {source := "before\n\n```go\na | b\n```\n{: id=\"20260921000000-code001\" " + attribute + "=\"" + value + "\"}\n\nafter"rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}- for pass := 0; pass < 3; pass++ {+ for pass := range 3 {tree, err := ParseTableCellRich(rich)if err != nil {t.Fatal(err)@@ -75,7 +75,7 @@ func TestTableCellRichCustomInlineStyle(t *testing.T) {} {source := `before <span data-type="custom_symble_strong_CJK_rectangle_yin" style="` + style + `">after</span>`rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}- for pass := 0; pass < 3; pass++ {+ for pass := range 3 {tree, err := ParseTableCellRich(rich)if err != nil {t.Fatal(err)@@ -125,7 +125,7 @@ func TestTableCellRichLocalLinks(t *testing.T) {t.Run(target, func(t *testing.T) {source := `<span data-type="a strong" data-href="` + target + `" data-title="title">anchor</span>`rich := &ast.TableCellRich{Spec: 1, Format: "kramdown", Content: source}- for pass := 0; pass < 3; pass++ {+ for pass := range 3 {tree, err := ParseTableCellRich(rich)if err != nil {t.Fatal(err)diff --git a/kernel/av/value.go b/kernel/av/value.goindex 652c698ec8..179dd9449a 100644--- a/kernel/av/value.go+++ b/kernel/av/value.go@@ -24,6 +24,7 @@ import ("path""reflect""regexp"+ "slices""sort""strconv""strings"@@ -755,7 +756,7 @@ func isAllowedValueTextMarkType(node *ast.Node) bool {if "" == node.TextMarkType || "" != node.TextMarkFlashcardOcclusionID {return false}- for _, typ := range strings.Fields(node.TextMarkType) {+ for typ := range strings.FieldsSeq(node.TextMarkType) {switch typ {case "text", "block-ref", "kbd", "file-annotation-ref", "a", "strong", "em", "u", "s", "mark","sup", "sub", "tag", "code", "inline-math", "inline-memo":@@ -846,7 +847,7 @@ func isAllowedValueTextRichLinkTarget(target string) bool {func decodeValueTextRichLinkTarget(target string) (ret, decoded string, ok bool) {ret = target- for iteration := 0; iteration < 8; iteration++ {+ for range 8 {next := html.UnescapeString(ret)if next == ret {decoded, err := url.PathUnescape(ret)@@ -883,7 +884,7 @@ func isAllowedValueTextRichInlineMemoContent(content string) bool {return false}decoded := content- for iteration := 0; iteration < 8; iteration++ {+ for range 8 {next := html.UnescapeString(decoded)if next == decoded {return !containsValueTextRichHTMLTag(decoded)@@ -1545,12 +1546,7 @@ func valueTextRichBlockDOMAttribute(tag, name string) (value string, ok bool) {}func containsValueTextRichDataType(dataType, expected string) bool {- for _, typ := range strings.Fields(dataType) {- if expected == typ {- return true- }- }- return false+ return slices.Contains(strings.Fields(dataType), expected)}type valueTextRichStyleEntityProtection struct {@@ -1727,8 +1723,8 @@ func valueTextRichBlockLiteralMarkdownRanges(markdown string) (ret []valueTextRifunc stripValueTextRichMarkdownContainer(line string) string {for {line = strings.TrimLeft(line, " \t")- if strings.HasPrefix(line, ">") {- line = strings.TrimPrefix(line, ">")+ if after, ok := strings.CutPrefix(line, ">"); ok {+ line = aftercontinue}if 2 <= len(line) && ('-' == line[0] || '+' == line[0] || '*' == line[0]) &&@@ -2202,7 +2198,7 @@ func normalizeValueTextRichTreeSourceWithImages(tree *parse.Tree, images bool) (func normalizeValueTextRichTreeSourceWithLute(tree *parse.Tree, images bool, luteEngine *lute.Lute) (content string, normalizedTree *parse.Tree, err error) {normalizedTree = treeprevious := ""- for iteration := 0; iteration < 4; iteration++ {+ for iteration := range 4 {if err = normalizeValueTextRichTreeStyles(normalizedTree, images); nil != err {return "", nil, err}diff --git a/kernel/av/value_location.go b/kernel/av/value_location.goindex b5592f43b3..ae759e658e 100644--- a/kernel/av/value_location.go+++ b/kernel/av/value_location.go@@ -5,6 +5,7 @@ import ("encoding/json""fmt""math"+ "slices""strconv""strings")@@ -104,17 +105,10 @@ func (view *AttributeView) HasLocation() bool {if nil != current.GroupKey && KeyTypeLocation == current.GroupKey.Type {return true}- for _, group := range current.Groups {- if hasLocationKey(group) {- return true- }- }- return false+ return slices.ContainsFunc(current.Groups, hasLocationKey)}- for _, current := range view.Views {- if hasLocationKey(current) {- return true- }+ if slices.ContainsFunc(view.Views, hasLocationKey) {+ return true}found := falseview.visitPersistedValues(func(value *Value) {diff --git a/kernel/av/value_location_test.go b/kernel/av/value_location_test.goindex c298a77b32..2c5ac84466 100644--- a/kernel/av/value_location_test.go+++ b/kernel/av/value_location_test.go@@ -7,7 +7,8 @@ import ("testing")-func locationCoordinate(value float64) *float64 { return &value }+//go:fix inline+func locationCoordinate(value float64) *float64 { return new(value) }func TestLocationValueValidationAndDisplay(t *testing.T) {for _, test := range []struct {@@ -20,17 +21,17 @@ func TestLocationValueValidationAndDisplay(t *testing.T) {{"missing", nil, "", true, false},{"name", &ValueLocation{Name: " Home "}, "Home", false, false},{"raw only", &ValueLocation{OriginalInput: "source"}, "", true, false},- {"zero", &ValueLocation{Latitude: locationCoordinate(0), Longitude: locationCoordinate(0)}, "0, 0 [WGS84]", false, false},- {"negative zero", &ValueLocation{Latitude: locationCoordinate(math.Copysign(0, -1)), Longitude: locationCoordinate(math.Copysign(0, -1))}, "0, 0 [WGS84]", false, false},- {"named zero", &ValueLocation{Name: "Home", Latitude: locationCoordinate(0), Longitude: locationCoordinate(0)}, "Home; 0, 0 [WGS84]", false, false},- {"lower latitude upper longitude", &ValueLocation{Latitude: locationCoordinate(-90), Longitude: locationCoordinate(180)}, "-90, 180 [WGS84]", false, false},- {"upper latitude lower longitude", &ValueLocation{Latitude: locationCoordinate(90), Longitude: locationCoordinate(-180)}, "90, -180 [WGS84]", false, false},- {"latitude missing", &ValueLocation{Longitude: locationCoordinate(0)}, "", false, true},- {"longitude missing", &ValueLocation{Latitude: locationCoordinate(0)}, "", false, true},- {"latitude range", &ValueLocation{Latitude: locationCoordinate(90.001), Longitude: locationCoordinate(0)}, "", false, true},- {"longitude range", &ValueLocation{Latitude: locationCoordinate(0), Longitude: locationCoordinate(-180.001)}, "", false, true},- {"nan", &ValueLocation{Latitude: locationCoordinate(math.NaN()), Longitude: locationCoordinate(0)}, "", false, true},- {"infinity", &ValueLocation{Latitude: locationCoordinate(0), Longitude: locationCoordinate(math.Inf(1))}, "", false, true},+ {"zero", &ValueLocation{Latitude: new(float64(0)), Longitude: new(float64(0))}, "0, 0 [WGS84]", false, false},+ {"negative zero", &ValueLocation{Latitude: new(math.Copysign(0, -1)), Longitude: new(math.Copysign(0, -1))}, "0, 0 [WGS84]", false, false},+ {"named zero", &ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0))}, "Home; 0, 0 [WGS84]", false, false},+ {"lower latitude upper longitude", &ValueLocation{Latitude: new(float64(-90)), Longitude: new(float64(180))}, "-90, 180 [WGS84]", false, false},+ {"upper latitude lower longitude", &ValueLocation{Latitude: new(float64(90)), Longitude: new(float64(-180))}, "90, -180 [WGS84]", false, false},+ {"latitude missing", &ValueLocation{Longitude: new(float64(0))}, "", false, true},+ {"longitude missing", &ValueLocation{Latitude: new(float64(0))}, "", false, true},+ {"latitude range", &ValueLocation{Latitude: new(90.001), Longitude: new(float64(0))}, "", false, true},+ {"longitude range", &ValueLocation{Latitude: new(float64(0)), Longitude: new(-180.001)}, "", false, true},+ {"nan", &ValueLocation{Latitude: new(math.NaN()), Longitude: new(float64(0))}, "", false, true},+ {"infinity", &ValueLocation{Latitude: new(float64(0)), Longitude: new(math.Inf(1))}, "", false, true},} {t.Run(test.name, func(t *testing.T) {if err := test.location.Normalize(); (err != nil) != test.invalid {@@ -51,7 +52,7 @@ func TestLocationValueValidationAndDisplay(t *testing.T) {}func TestLocationFilterSortAndStatistics(t *testing.T) {- value := &Value{Type: KeyTypeLocation, Location: &ValueLocation{Name: "Home", Latitude: locationCoordinate(0), Longitude: locationCoordinate(0), OriginalInput: "private provenance"}}+ value := &Value{Type: KeyTypeLocation, Location: &ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "private provenance"}}for _, test := range []struct {operator FilterOperatortext string@@ -82,7 +83,7 @@ func TestLocationFilterSortAndStatistics(t *testing.T) {if value.Compare(other, nil) != 0 {t.Fatal("provenance affected sort order")}- other.Location.Longitude = locationCoordinate(1)+ other.Location.Longitude = new(float64(1))if value.Compare(other, nil) == 0 {t.Fatal("coordinates did not distinguish values")}@@ -121,7 +122,7 @@ func TestLocationFilterSortAndStatistics(t *testing.T) {func TestLocationPersistedSpecAndValidation(t *testing.T) {location := func() *Value {- return &Value{Type: KeyTypeLocation, Location: &ValueLocation{Latitude: locationCoordinate(0), Longitude: locationCoordinate(0)}}+ return &Value{Type: KeyTypeLocation, Location: &ValueLocation{Latitude: new(float64(0)), Longitude: new(float64(0))}}}for _, test := range []struct {name string@@ -160,7 +161,7 @@ func TestLocationPersistedSpecAndValidation(t *testing.T) {}valid := location()invalid := location()- invalid.Location.Latitude = locationCoordinate(91)+ invalid.Location.Latitude = new(float64(91))view := &AttributeView{Spec: LocationSpec, KeyValues: []*KeyValues{{Values: []*Value{valid, invalid}}}}before, _ := json.Marshal(view)err := view.NormalizeLocations()@@ -204,7 +205,7 @@ func TestLocationConditionalColorsAndAutomationFilters(t *testing.T) {func TestLocationTemplatePreservation(t *testing.T) {key := &Key{ID: "location", Type: KeyTypeLocation}- value := &Value{Type: KeyTypeLocation, Location: &ValueLocation{Name: "Home", Latitude: locationCoordinate(0), Longitude: locationCoordinate(0), OriginalInput: "source"}}+ value := &Value{Type: KeyTypeLocation, Location: &ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "source"}}view := &AttributeView{Spec: LocationSpec, KeyValues: []*KeyValues{{Key: key, Values: []*Value{value}}}}if err := view.NormalizeLocations(); err != nil {t.Fatal(err)@@ -230,7 +231,7 @@ func TestLocationJSONRejectsUnknownFieldsWithoutMutation(t *testing.T) {`{"latitude":0,"longitude":0,"coordinateSystem":null}`,`{"name":"Changed","unknown":true}`,} {- location := &ValueLocation{Name: "Home", Latitude: locationCoordinate(1), Longitude: locationCoordinate(2), OriginalInput: "source"}+ location := &ValueLocation{Name: "Home", Latitude: new(float64(1)), Longitude: new(float64(2)), OriginalInput: "source"}before, _ := json.Marshal(location)if err := json.Unmarshal([]byte(payload), location); err == nil {t.Fatalf("unknown location field accepted: %s", payload)diff --git a/kernel/av/value_text_escape_test.go b/kernel/av/value_text_escape_test.goindex 9131a4c8c0..c2db500545 100644--- a/kernel/av/value_text_escape_test.go+++ b/kernel/av/value_text_escape_test.go@@ -14,7 +14,7 @@ func TestValueTextRichEscapedContentRoundTrip(t *testing.T) {Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown,Content: `<span data-type="` + mark + `" data-href="https://example.com">` + html.EscapeHTMLStr(content) + `</span>`,}}- for i := 0; i < 3; i++ {+ for i := range 3 {if err := value.NormalizeRichContent(); err != nil {t.Fatal(err)}diff --git a/kernel/av/value_text_test.go b/kernel/av/value_text_test.goindex 70c6e5561f..1ee8436143 100644--- a/kernel/av/value_text_test.go+++ b/kernel/av/value_text_test.go@@ -39,7 +39,7 @@ func TestValueTextRichEmptyParagraphs(t *testing.T) {}rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown,Content: valueTextRichBlockDOM2Kramdown(newValueTextRichLute(), dom.String())}- for round := 0; round < 3; round++ {+ for range 3 {before := rich.Contenttree, err := NormalizeValueTextRich(rich)if nil != err {@@ -674,17 +674,17 @@ func TestValueTextRichStyleEntityScannerManyMarkers(t *testing.T) {`var(--b3-font-family-editor), var(--b3-font-family);"}`)var markdown strings.Builder- for i := 0; i < repetitions; i++ {+ for range repetitions {markdown.WriteString(styled)markdown.WriteByte('\n')}markdown.WriteString("```\n")- for i := 0; i < repetitions; i++ {+ for range repetitions {markdown.WriteString(styled)markdown.WriteByte('\n')}markdown.WriteString("```\n")- for i := 0; i < repetitions; i++ {+ for range repetitions {markdown.WriteByte('`')markdown.WriteString(styled)markdown.WriteString("`\n")@@ -790,7 +790,7 @@ func TestValueTextRichInlineRoundTrip(t *testing.T) {}for _, test := range tests {rich := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: test.content}- for pass := 0; pass < 2; pass++ {+ for pass := range 2 {tree, err := ParseValueTextRich(rich)if nil != err {t.Fatalf("parse inline type %q failed: %s", test.typ, err)@@ -826,7 +826,7 @@ func TestValueTextRichInlineRoundTrip(t *testing.T) {}combined := &ValueTextRich{Spec: ValueTextRichSpec, Format: ValueTextRichFormatKramdown, Content: "***combined***"}- for pass := 0; pass < 2; pass++ {+ for pass := range 2 {tree, err := ParseValueTextRich(combined)if nil != err {t.Fatal(err)diff --git a/kernel/bazaar/index.go b/kernel/bazaar/index.goindex 975f1b1807..07b8b0a6bf 100644--- a/kernel/bazaar/index.go+++ b/kernel/bazaar/index.go@@ -278,8 +278,8 @@ func parseBazaarIndex(data []byte) (ret *bazaarIndexSnapshot, err error) {func normalizeLegacyBazaarRepo(repo string) (string, bool) {const githubPrefix = "https://github.com/"- if strings.HasPrefix(repo, githubPrefix) {- repo = strings.TrimPrefix(repo, githubPrefix)+ if after, ok := strings.CutPrefix(repo, githubPrefix); ok {+ repo = after}if !isValidBazaarRepo(repo) {return "", false@@ -291,7 +291,7 @@ func isValidBazaarRepo(repo string) bool {if 1 != strings.Count(repo, "/") || strings.HasPrefix(repo, "/") || strings.HasSuffix(repo, "/") {return false}- for _, part := range strings.Split(repo, "/") {+ for part := range strings.SplitSeq(repo, "/") {if "" == part || "." == part || ".." == part {return false}diff --git a/kernel/bazaar/install_revision.go b/kernel/bazaar/install_revision.goindex 1eb1804a27..43f10a4f8c 100644--- a/kernel/bazaar/install_revision.go+++ b/kernel/bazaar/install_revision.go@@ -98,7 +98,7 @@ func validateInstallRelativePath(name string) error {strings.ContainsAny(name, "\\:\x00") {return errors.New("invalid marketplace package path")}- for _, component := range strings.Split(name, "/") {+ for component := range strings.SplitSeq(name, "/") {if component == ".." || strings.TrimRight(component, ". ") != component {return errors.New("invalid marketplace package path")}diff --git a/kernel/bazaar/installed.go b/kernel/bazaar/installed.goindex e9bee006d5..7350d131f9 100644--- a/kernel/bazaar/installed.go+++ b/kernel/bazaar/installed.go@@ -143,10 +143,7 @@ func RefreshInstalledPackageREADME(pkg *Package, installPath, baseURLPath, repoU}func installedPackageCacheVersion(pkg *Package) int64 {- ret := pkg.InstallTime- if pkg.UpdateTime > ret {- ret = pkg.UpdateTime- }+ ret := max(pkg.UpdateTime, pkg.InstallTime)return ret}diff --git a/kernel/bazaar/rating.go b/kernel/bazaar/rating.goindex b7129cd112..b33cceba28 100644--- a/kernel/bazaar/rating.go+++ b/kernel/bazaar/rating.go@@ -22,6 +22,7 @@ import ("encoding/json""errors""fmt"+ "maps""math""sync""time"@@ -514,9 +515,7 @@ func validBazaarRatingDistribution(distribution bazaarRatingDistribution) bool {func cloneBazaarRatingDistributions(source map[string]bazaarRatingDistribution) map[string]bazaarRatingDistribution {ret := make(map[string]bazaarRatingDistribution, len(source))- for packageName, distribution := range source {- ret[packageName] = distribution- }+ maps.Copy(ret, source)return ret}diff --git a/kernel/cache/av_test.go b/kernel/cache/av_test.goindex 0eb886a31b..a1de0b8e07 100644--- a/kernel/cache/av_test.go+++ b/kernel/cache/av_test.go@@ -139,7 +139,7 @@ func TestAVCacheRejectsStaleAsyncAdmission(t *testing.T) {entered, release := make(chan struct{}), make(chan struct{})controlled, err := ristretto.NewCache(&ristretto.Config{NumCounters: 100, MaxCost: 1 << 20, BufferItems: 64,- Cost: func(value interface{}) int64 {+ Cost: func(value any) int64 {close(entered)<-releasereturn 1diff --git a/kernel/cache/tree_test.go b/kernel/cache/tree_test.goindex 1f6e3ce9a1..6234afdd49 100644--- a/kernel/cache/tree_test.go+++ b/kernel/cache/tree_test.go@@ -17,7 +17,7 @@ func TestTreeCacheRejectsStaleAsyncAdmission(t *testing.T) {entered, release := make(chan struct{}), make(chan struct{})controlled, err := ristretto.NewCache(&ristretto.Config{NumCounters: 100, MaxCost: 1 << 20, BufferItems: 64,- Cost: func(value interface{}) int64 {+ Cost: func(value any) int64 {close(entered)<-releasereturn 1diff --git a/kernel/chatgpt/inference.go b/kernel/chatgpt/inference.goindex e63f2cf3ca..8dcc8a451a 100644--- a/kernel/chatgpt/inference.go+++ b/kernel/chatgpt/inference.go@@ -65,7 +65,7 @@ func (s *Service) Do(request *http.Request, accountID string) (*http.Response, erelease()}}()- for attempt := 0; attempt < 2; attempt++ {+ for attempt := range 2 {token, err := s.Token(ctx, accountID, attempt != 0)if err != nil {return nil, errdiff --git a/kernel/chatgpt/oauth.go b/kernel/chatgpt/oauth.goindex 9573272827..9c05ed73d5 100644--- a/kernel/chatgpt/oauth.go+++ b/kernel/chatgpt/oauth.go@@ -416,8 +416,7 @@ func (s *Service) refresh(ctx context.Context, a *Account) error {var tokens tokenResponseform := url.Values{"grant_type": {"refresh_token"}, "client_id": {a.ClientID}, "refresh_token": {a.RefreshToken}, "resource": {s.resource}}if err := s.readJSON(ctx, "POST", s.issuer+"/api/accounts/oauth/token", form.Encode(), &tokens); err != nil {- var requestErr *RequestError- if errors.As(err, &requestErr) {+ if requestErr, ok := errors.AsType[*RequestError](err); ok {switch requestErr.Code {case "invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused":clearTokens(a)@@ -497,7 +496,7 @@ func (s *Service) endSession(ctx context.Context, id string, remove bool) (revokd, metadataErr := s.metadata(ctx)if metadataErr == nil && s.identityEndpoint(d.Revocation) {form := url.Values{"token": {a.RefreshToken}, "token_type_hint": {"refresh_token"}, "client_id": {a.ClientID}}- for i := 0; i < 2; i++ {+ for i := range 2 {if s.readJSON(ctx, "POST", d.Revocation, form.Encode(), nil) == nil {revoked = truebreakdiff --git a/kernel/cli/cmd/file_limit_test.go b/kernel/cli/cmd/file_limit_test.goindex c66bdd036b..2c57809a96 100644--- a/kernel/cli/cmd/file_limit_test.go+++ b/kernel/cli/cmd/file_limit_test.go@@ -24,7 +24,7 @@ func TestFileQueryLimits(t *testing.T) {if err := os.Mkdir(query, 0755); err != nil {t.Fatal(err)}- for i := 0; i < 205; i++ {+ for i := range 205 {if err := os.WriteFile(filepath.Join(query, fmt.Sprintf("%03d.txt", i)), []byte("match\n"), 0644); err != nil {t.Fatal(err)}diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.goindex f87ddff98c..d215429aca 100644--- a/kernel/cli/cmd/root.go+++ b/kernel/cli/cmd/root.go@@ -247,7 +247,7 @@ func isEncryptedNotebookWorkspacePathWith(p, workspaceDir, dataDir string, isEncif err != nil || rel == "." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) || rel == ".." {return false}- boxID := strings.Split(rel, string(filepath.Separator))[0]+ boxID, _, _ := strings.Cut(rel, string(filepath.Separator))return isEncryptedBox(boxID)}diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex b417570f52..cd1dfcc2f1 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -677,7 +677,7 @@ func (ai *AI) Normalize() {serverIDs := map[string]bool{}for i := range ai.MCP.Servers {if ai.MCP.Servers[i].ID == "" || serverIDs[ai.MCP.Servers[i].ID] {- data := []byte(fmt.Sprintf("mcp:%d:%s:%s", i, ai.MCP.Servers[i].Name, ai.MCP.Servers[i].Type))+ data := fmt.Appendf(nil, "mcp:%d:%s:%s", i, ai.MCP.Servers[i].Name, ai.MCP.Servers[i].Type)ai.MCP.Servers[i].ID = uuid.NewSHA1(uuid.NameSpaceOID, data).String()}serverIDs[ai.MCP.Servers[i].ID] = truediff --git a/kernel/conf/chart_height_menu_test.go b/kernel/conf/chart_height_menu_test.goindex 81ed8d9043..6cd6d16fd6 100644--- a/kernel/conf/chart_height_menu_test.go+++ b/kernel/conf/chart_height_menu_test.go@@ -17,7 +17,7 @@ func TestMigrateChartHeightMenu(t *testing.T) {if existing != "unset" {profile.Entries["gutter.single.height"] = existing == "visible"}- for i := 0; i < 2; i++ {+ for range 2 {migrateChartHeightMenu(profile)if !reflect.DeepEqual(profile.Entries, map[string]bool{"gutter.single.height": existing == "visible"}) ||!reflect.DeepEqual(profile.Orders["gutter.single.chart"], []string{"pluginBefore", "update", "pluginAfter"}) ||diff --git a/kernel/conf/task_status_menu_test.go b/kernel/conf/task_status_menu_test.goindex 9805f97d60..3a07295766 100644--- a/kernel/conf/task_status_menu_test.go+++ b/kernel/conf/task_status_menu_test.go@@ -23,7 +23,7 @@ func TestTaskStatusMenuMigration(t *testing.T) {t.Run(fixture.Name, func(t *testing.T) {fixture.Input.ID, fixture.Input.Name = "custom", "Custom"config := &EntryVisibility{Version: 5, Active: "custom", Profiles: []*EntryVisibilityProfile{&fixture.Input}}- for i := 0; i < 2; i++ {+ for range 2 {NormalizeEntryVisibility(config, EntryVisibilityProfileFull)if config.Version != EntryVisibilityVersion || !reflect.DeepEqual(fixture.Input.Entries, fixture.Expected.Entries) ||!reflect.DeepEqual(fixture.Input.Orders, fixture.Expected.Orders) {diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 3053896efe..0181456114 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -181,7 +181,7 @@ func validateTreePath(boxID, p string) error {if !strings.HasSuffix(rel, ".sy") {return fmt.Errorf("invalid document path [%s]", p)}- for _, id := range strings.Split(strings.TrimSuffix(rel, ".sy"), "/") {+ for id := range strings.SplitSeq(strings.TrimSuffix(rel, ".sy"), "/") {if !ast.IsNodeIDPattern(id) {return fmt.Errorf("invalid document path [%s]", p)}diff --git a/kernel/heif/convert.go b/kernel/heif/convert.goindex 3b9879dcb0..45c7d1c903 100644--- a/kernel/heif/convert.go+++ b/kernel/heif/convert.go@@ -208,12 +208,6 @@ func validDimensions(width, height int) bool {func estimatedJPEGSize(img image.Image) int {pixels := int64(img.Bounds().Dx()) * int64(img.Bounds().Dy())- estimate := pixels / 2- if estimate < 64*1024 {- estimate = 64 * 1024- }- if estimate > 32*1024*1024 {- estimate = 32 * 1024 * 1024- }+ estimate := min(max(pixels/2, 64*1024), 32*1024*1024)return int(estimate)}diff --git a/kernel/heif/internal/h265heic/grid.go b/kernel/heif/internal/h265heic/grid.goindex ea01aa8a7b..8cc7fc0828 100644--- a/kernel/heif/internal/h265heic/grid.go+++ b/kernel/heif/internal/h265heic/grid.go@@ -134,10 +134,8 @@ func (f *file) decodeTiles(g gridInfo, tiles []uint32) (*hevc.Picture, error) {perTile := max(f.workers(0)/tileWorkers, 1)for range tileWorkers - 1 {- wg.Add(1)- go func() {- defer wg.Done()+ wg.Go(func() {var dec itemDecoder@@ -176,7 +174,7 @@ func (f *file) decodeTiles(g gridInfo, tiles []uint32) (*hevc.Picture, error) {blit(out, p, g, i, tw, th)p.Release()}- }()+ })}var dec itemDecoderdiff --git a/kernel/mcp/bazaar_test.go b/kernel/mcp/bazaar_test.goindex d6b8f69ea4..e7acfa5662 100644--- a/kernel/mcp/bazaar_test.go+++ b/kernel/mcp/bazaar_test.go@@ -21,7 +21,7 @@ func TestBazaarMCPPagination(t *testing.T) {model.Conf.Bazaar.Store(&conf.Bazaar{})util.DataDir = t.TempDir()t.Cleanup(func() { model.Conf, util.DataDir = oldConf, oldDataDir })- for i := 0; i < 23; i++ {+ for i := range 23 {name := fmt.Sprintf("widget-%02d", i)dir := filepath.Join(util.DataDir, "widgets", name)if err := os.MkdirAll(dir, 0755); err != nil {diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex 0bf8f4d9e1..47284d582e 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -23,6 +23,7 @@ import ("errors""fmt""io"+ "maps""net/http""os""os/exec"@@ -359,7 +360,7 @@ func listAllMCPTools(ctx context.Context,params *mcp.ListToolsParams)seenCursors := map[string]struct{}{}- for page := 0; page < maxMCPToolListPages; page++ {+ for range maxMCPToolListPages {result, err := listPage(ctx, params)if err != nil {return nil, err@@ -1121,9 +1122,7 @@ func MCPStatus() []MCPStatusItem {mcpMu.Lock()servers := append([]conf.MCPServer(nil), mcpServers...)runtimeStates := make(map[string]mcpRuntimeState, len(mcpRuntime))- for serverID, state := range mcpRuntime {- runtimeStates[serverID] = state- }+ maps.Copy(runtimeStates, mcpRuntime)mcpMu.Unlock()items := make([]MCPStatusItem, 0, len(servers))diff --git a/kernel/mcp/client/oauth.go b/kernel/mcp/client/oauth.goindex 75db23b261..6441e8e711 100644--- a/kernel/mcp/client/oauth.go+++ b/kernel/mcp/client/oauth.go@@ -274,7 +274,7 @@ func (h *mcpOAuthHandler) Authorize(ctx context.Context, req *http.Request, respif len(scopes) == 0 {scopes = append(scopes, asm.ScopesSupported...)}- for _, scope := range strings.Fields(bearerChallengeParam(challenges, "scope")) {+ for scope := range strings.FieldsSeq(bearerChallengeParam(challenges, "scope")) {if !slices.Contains(scopes, scope) {scopes = append(scopes, scope)}diff --git a/kernel/mcp/client/oauth_store.go b/kernel/mcp/client/oauth_store.goindex f080a2c1f5..c940fb9417 100644--- a/kernel/mcp/client/oauth_store.go+++ b/kernel/mcp/client/oauth_store.go@@ -20,6 +20,7 @@ import ("encoding/hex""encoding/json""fmt"+ "slices""strings""sync""time"@@ -38,14 +39,14 @@ type oauthCredential struct {RedirectURL string `json:"redirectUrl,omitempty"`ClientID string `json:"clientId"`ClientSecret string `json:"clientSecret,omitempty"`- ClientSecretExpiry time.Time `json:"clientSecretExpiry,omitempty"`+ ClientSecretExpiry time.Time `json:"clientSecretExpiry"`TokenEndpoint string `json:"tokenEndpoint"`RevocationEndpoint string `json:"revocationEndpoint,omitempty"`TokenAuthMethod string `json:"tokenAuthMethod,omitempty"`AccessToken string `json:"accessToken"`RefreshToken string `json:"refreshToken,omitempty"`TokenType string `json:"tokenType,omitempty"`- Expiry time.Time `json:"expiry,omitempty"`+ Expiry time.Time `json:"expiry"`Scopes []string `json:"scopes,omitempty"`Rejected bool `json:"rejected,omitempty"`}@@ -118,8 +119,8 @@ func getOAuthCredential(serverID, endpoint string) (oauthCredential, bool) {oauthCredentialStore.Lock()defer oauthCredentialStore.Unlock()loadOAuthCredentialsLocked()- for i := len(oauthCredentialStore.credentials) - 1; i >= 0; i-- {- credential := oauthCredentialStore.credentials[i]+ for _, credential := range slices.Backward(oauthCredentialStore.credentials) {+credentialEndpoint := credential.Endpointif credentialEndpoint == "" {credentialEndpoint = credential.Resourcediff --git a/kernel/mcp/tools/box_lease.go b/kernel/mcp/tools/box_lease.goindex 78f5046775..b96b65f914 100644--- a/kernel/mcp/tools/box_lease.go+++ b/kernel/mcp/tools/box_lease.go@@ -127,7 +127,7 @@ func resolveEncryptedBoxLeases(args map[string]any) []string {addValue := func(value any, add func(string)) {switch typed := value.(type) {case string:- for _, item := range strings.Split(typed, ",") {+ for item := range strings.SplitSeq(typed, ",") {add(item)}case []string:@@ -154,7 +154,7 @@ func resolveEncryptedBoxLeases(args map[string]any) []string {}for _, key := range []string{"path", "historyPath"} {pathValue, _ := args[key].(string)- for _, segment := range strings.Split(filepath.ToSlash(pathValue), "/") {+ for segment := range strings.SplitSeq(filepath.ToSlash(pathValue), "/") {addBoxID(segment)}}diff --git a/kernel/mcp/tools/capability.go b/kernel/mcp/tools/capability.goindex 2d972215cb..958bcb1289 100644--- a/kernel/mcp/tools/capability.go+++ b/kernel/mcp/tools/capability.go@@ -29,14 +29,14 @@ type CapabilityManifest struct {OwnerName string `json:"ownerName,omitempty"`Runtime string `json:"runtime"`AgentOnly bool `json:"agentOnly,omitempty"`- Effects ToolEffects `json:"effects,omitempty"`+ Effects ToolEffects `json:"effects"`Available bool `json:"available"`Actions []CapabilityActionManifest `json:"actions,omitempty"`}type CapabilityActionManifest struct {Name string `json:"name"`- Effects ToolEffects `json:"effects,omitempty"`+ Effects ToolEffects `json:"effects"`}// CapabilityIDForTool 返回工具的稳定能力 ID,并为未显式声明 ID 的动态工具构造回退值。diff --git a/kernel/mcp/tools/database.go b/kernel/mcp/tools/database.goindex 1efc7b3c57..4d79c1f044 100644--- a/kernel/mcp/tools/database.go+++ b/kernel/mcp/tools/database.go@@ -20,6 +20,7 @@ import ("encoding/json""errors""fmt"+ "slices""strings""github.com/88250/lute/ast"@@ -370,10 +371,8 @@ func databasePreviousKeyID(attrView *av.AttributeView, args map[string]any) (retif "" == prev {return "", nil}- for _, fieldID := range fieldIDs {- if fieldID == prev {- return prev, nil- }+ if slices.Contains(fieldIDs, prev) {+ return prev, nil}return "", fmt.Errorf("previous key not found in current view: %s", prev)}diff --git a/kernel/mcp/tools/file.go b/kernel/mcp/tools/file.goindex 24b2bea75d..37e8a10999 100644--- a/kernel/mcp/tools/file.go+++ b/kernel/mcp/tools/file.go@@ -27,6 +27,7 @@ import ("os""path/filepath""regexp"+ "slices""strings""unicode/utf8"@@ -781,10 +782,8 @@ func fileManagedRelative(grant *util.PluginDevelopmentGrant, p string) (string,if err = util.ValidateTextFilePath(rel); err != nil {return "", err}- for _, allowed := range grant.AllowFiles {- if rel == allowed {- return rel, nil- }+ if slices.Contains(grant.AllowFiles, rel) {+ return rel, nil}return "", fileInvalid("invalid_path", "file is outside the approved project allowlist")}diff --git a/kernel/mcp/tools/file_limit_test.go b/kernel/mcp/tools/file_limit_test.goindex a0ee8966c0..23e8a9d696 100644--- a/kernel/mcp/tools/file_limit_test.go+++ b/kernel/mcp/tools/file_limit_test.go@@ -9,7 +9,7 @@ import (func TestFileQueryLimits(t *testing.T) {workspace := setupProbeWorkspace(t)- for i := 0; i < 205; i++ {+ for i := range 205 {writeProbeFile(t, filepath.Join(workspace, "data", "query", fmt.Sprintf("%03d.txt", i)), "match\n")}writeProbeFile(t, filepath.Join(workspace, "data", "lines.txt"), strings.Repeat("match\n", 205))diff --git a/kernel/mcp/tools/log.go b/kernel/mcp/tools/log.goindex 3880450ee9..f94d21f520 100644--- a/kernel/mcp/tools/log.go+++ b/kernel/mcp/tools/log.go@@ -148,10 +148,7 @@ func agentLogTail(args map[string]any) (CallToolResult, error) {}func agentLogRead(args map[string]any) (CallToolResult, error) {- offset := int(getFloat64Arg(args, "offset"))- if offset < 1 {- offset = 1- }+ offset := max(int(getFloat64Arg(args, "offset")), 1)limit := resolveAgentLogLimit(args, agentLogDefaultReadLimit, agentLogMaxReadLimit)lines := make([]numberedAgentLogLine, 0, limit)total, err := scanAgentLog(func(number int, line string) bool {@@ -343,7 +340,7 @@ func collectAgentLogSecrets(value reflect.Value, ownerType string, secrets map[sif fieldType.PkgPath != "" {continue}- name := strings.Split(fieldType.Tag.Get("json"), ",")[0]+ name, _, _ := strings.Cut(fieldType.Tag.Get("json"), ",")if name == "" || name == "-" {name = fieldType.Name}diff --git a/kernel/mcp/tools/snippet_test.go b/kernel/mcp/tools/snippet_test.goindex 2bd9823886..af94933f4b 100644--- a/kernel/mcp/tools/snippet_test.go+++ b/kernel/mcp/tools/snippet_test.go@@ -48,7 +48,7 @@ func snippetToolResult(t *testing.T, args map[string]any) map[string]any {func TestSnippetToolPaginationAndPreview(t *testing.T) {snippets := []*conf.Snippet{}- for i := 0; i < 25; i++ {+ for i := range 25 {snippets = append(snippets, &conf.Snippet{ID: fmt.Sprint(i), Name: "Theme", Type: "js", Content: strings.Repeat("字", 8010)})}setupSnippetToolTest(t, snippets)diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.goindex 45cf9ee38a..be8c9162b7 100644--- a/kernel/model/asset_download_read.go+++ b/kernel/model/asset_download_read.go@@ -10,6 +10,7 @@ import ("os""path""path/filepath"+ "slices""sort""strings"@@ -34,8 +35,8 @@ func ResolveAssetPathWithMissingLeaf(absPath string) (string, error) {for {resolved, err := ResolveRealPath(current)if err == nil {- for i := len(missing) - 1; i >= 0; i-- {- resolved = filepath.Join(resolved, missing[i])+ for _, m := range slices.Backward(missing) {+ resolved = filepath.Join(resolved, m)}return resolved, nil}diff --git a/kernel/model/asset_download_regression_test.go b/kernel/model/asset_download_regression_test.goindex 277b236ab9..82c19f4590 100644--- a/kernel/model/asset_download_regression_test.go+++ b/kernel/model/asset_download_regression_test.go@@ -26,7 +26,7 @@ func prepareAssetDownloadDocumentTest(t *testing.T) (*fileOperationTestFixture,}Conf.FileTree.Store(conf.NewFileTree())Conf.NotebookCrypto = conf.NewNotebookCrypto()- for i := 0; i < 3; i++ {+ for range 3 {writeAssetDownloadDocumentTest(t, treenode.NewTree(fixture.box.ID, "/"+ast.NewNodeID()+".sy", "/Seed", "Seed"))}if err := fixture.box.SaveConf(conf.NewBoxConf()); err != nil {diff --git a/kernel/model/asset_relink.go b/kernel/model/asset_relink.goindex 28ef4af83a..dae7c3a327 100644--- a/kernel/model/asset_relink.go+++ b/kernel/model/asset_relink.go@@ -468,7 +468,7 @@ func newAssetRelinkHistoryDir() (string, error) {if err := os.MkdirAll(util.HistoryDir, 0755); err != nil {return "", err}- for offset := 0; offset < 1000; offset++ {+ for offset := range 1000 {dir := filepath.Join(util.HistoryDir, time.Now().Add(time.Duration(offset)*time.Second).Format("2006-01-02-150405")+"-"+HistoryOpReplace)if err := os.Mkdir(dir, 0755); err == nil {return dir, nildiff --git a/kernel/model/asset_relink_references.go b/kernel/model/asset_relink_references.goindex 4bbae35aa8..9cfb73d15c 100644--- a/kernel/model/asset_relink_references.go+++ b/kernel/model/asset_relink_references.go@@ -43,7 +43,7 @@ func relinkPath(value string) (string, error) {if !strings.HasPrefix(p, "assets/") || path.Clean(p) != p || strings.ContainsAny(p, "\\\x00\r\n") || strings.HasSuffix(p, "/") {return "", fmt.Errorf("invalid asset path: %q", value)}- for _, segment := range strings.Split(p, "/") {+ for segment := range strings.SplitSeq(p, "/") {if strings.Contains(segment, ":") {return "", fmt.Errorf("invalid asset path: %q", value)}diff --git a/kernel/model/asset_rename_test.go b/kernel/model/asset_rename_test.goindex c662775186..9e793d3d50 100644--- a/kernel/model/asset_rename_test.go+++ b/kernel/model/asset_rename_test.go@@ -80,7 +80,7 @@ func TestRenameAssetReferences(t *testing.T) {treenode.UpsertBlockTree(tree)t.Cleanup(func() { cache.RemoveTreeData(tree.ID) })avPath := filepath.Join(util.DataDir, "storage", "av", test.id+".json")- avData, _ := json.Marshal(map[string]interface{}{"paths": hrefs, "text": path.Base(oldPath)})+ avData, _ := json.Marshal(map[string]any{"paths": hrefs, "text": path.Base(oldPath)})writeAssetRelinkTestFile(t, "storage/av/"+test.id+".json", avData)newPath, err := RenameAsset(oldPath+test.suffix, "习题2")@@ -121,7 +121,7 @@ func TestRenameAssetReferences(t *testing.T) {t.Fatalf("document references: %v, want %v", got, want)}updated, err := os.ReadFile(avPath)- wantAV, _ := json.Marshal(map[string]interface{}{"paths": want, "text": path.Base(oldPath)})+ wantAV, _ := json.Marshal(map[string]any{"paths": want, "text": path.Base(oldPath)})if err != nil || !bytes.Equal(updated, wantAV) {t.Fatalf("database references: %s, want %s: %v", updated, wantAV, err)}diff --git a/kernel/model/asset_search.go b/kernel/model/asset_search.goindex 34454e1cfd..8607b36e8b 100644--- a/kernel/model/asset_search.go+++ b/kernel/model/asset_search.go@@ -24,7 +24,7 @@ func imageAssetMetadataHits(markdowns, keywords []string) map[string]int {if dest == nil {return ast.WalkSkipChildren}- assetPath := strings.SplitN(util.UnescapeHTML(dest.TokensStr()), "?", 2)[0]+ assetPath, _, _ := strings.Cut(util.UnescapeHTML(dest.TokensStr()), "?")if decoded, err := url.PathUnescape(assetPath); err == nil {assetPath = decoded}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex c8ed1d45ee..f71a681fee 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -1087,10 +1087,7 @@ func SearchAssetsByNamePage(keyword string, exts []string, match *AssetSearchMatif start >= len(ret) {return []*cache.Asset{}, nil}- end := start + pageSize- if end > len(ret) {- end = len(ret)- }+ end := min(start+pageSize, len(ret))ret = ret[start:end]// 仅处理当前页的高亮内容,避免对其他页重复渲染。highlightKeyword := strings.Join(keywords, search.TermSep)diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.goindex 68d96ed74e..d5c58f48ee 100644--- a/kernel/model/attribute_view.go+++ b/kernel/model/attribute_view.go@@ -22,6 +22,7 @@ import ("encoding/json""errors""fmt"+ "maps""math""math/rand""os"@@ -755,17 +756,13 @@ func applyFilterDefaultValues0(filters []*av.ViewFilter, attrView *av.AttributeVfunc cloneDefaultValues(values map[string]*av.Value) (ret map[string]*av.Value) {ret = make(map[string]*av.Value, len(values))- for key, value := range values {- ret[key] = value- }+ maps.Copy(ret, values)return}func cloneBoolMap(values map[string]bool) (ret map[string]bool) {ret = make(map[string]bool, len(values))- for key, value := range values {- ret[key] = value- }+ maps.Copy(ret, values)return}@@ -867,16 +864,12 @@ func applyAttributeViewContextFilterDefaultValue(attrView *av.AttributeView, addfunc replaceDefaultValues(target, source map[string]*av.Value) {clear(target)- for key, value := range source {- target[key] = value- }+ maps.Copy(target, source)}func replaceBoolMap(target, source map[string]bool) {clear(target)- for key, value := range source {- target[key] = value- }+ maps.Copy(target, source)}func (tx *Transaction) doSortAttrViewGroup(operation *Operation) (ret *TxErr) {@@ -2679,10 +2672,7 @@ func GetAttributeViewPrimaryKeyValues(avID, keyword string, blockIDs []string, pif 1 > pageSize {pageSize = 16}- start := (page - 1) * pageSize- if len(keyValues.Values) < start {- start = len(keyValues.Values)- }+ start := min(len(keyValues.Values), (page-1)*pageSize)end := min(len(keyValues.Values), start+pageSize)keyValues.Values = keyValues.Values[start:end]returndiff --git a/kernel/model/attribute_view_automation.go b/kernel/model/attribute_view_automation.goindex 5c716c7416..f1268b7a2d 100644--- a/kernel/model/attribute_view_automation.go+++ b/kernel/model/attribute_view_automation.go@@ -230,8 +230,7 @@ func (tx *Transaction) runAttributeViewAutomations() error {continue}validationErr := tx.validateAutomationRule(current, rule, source.boxID)- var unavailable *automationUnavailableReference- if errors.As(validationErr, &unavailable) {+ if unavailable, ok := errors.AsType[*automationUnavailableReference](validationErr); ok {rule.Enabled = falsepaused = truestate.paused = append(state.paused, automationPausedRule{rule.Name, unavailable})diff --git a/kernel/model/attribute_view_automation_fts5_test.go b/kernel/model/attribute_view_automation_fts5_test.goindex a345e1d5c7..ffe20bf1f0 100644--- a/kernel/model/attribute_view_automation_fts5_test.go+++ b/kernel/model/attribute_view_automation_fts5_test.go@@ -342,7 +342,7 @@ func TestAutomationLargeDatabaseNoOp(t *testing.T) {status, _ := source.GetKeyValues(statusID)primaryTemplate, statusTemplate := primary.Values[0].Clone(), status.Values[0].Clone()primary.Values, status.Values = nil, nil- for i := 0; i < 20000; i++ {+ for range 20000 {id := ast.NewNodeID()p, s := primaryTemplate.Clone(), statusTemplate.Clone()p.ID, p.BlockID, s.ID, s.BlockID = ast.NewNodeID(), id, ast.NewNodeID(), id@@ -479,7 +479,7 @@ func BenchmarkAutomationChangedItems(b *testing.B) {{Key: &av.Key{ID: "primary", Type: av.KeyTypeBlock}},{Key: &av.Key{ID: "status", Type: av.KeyTypeText}},}, Automations: &av.AutomationConfig{Rules: []*av.AutomationRule{{Enabled: true, Trigger: "changed", KeyID: "status"}}}}- for i := 0; i < size; i++ {+ for i := range size {id := fmt.Sprint(i)view.KeyValues[0].Values = append(view.KeyValues[0].Values, &av.Value{BlockID: id, Type: av.KeyTypeBlock, Block: &av.ValueBlock{Content: "Task"}})view.KeyValues[1].Values = append(view.KeyValues[1].Values, &av.Value{BlockID: id, Type: av.KeyTypeText, Text: &av.ValueText{Content: "Pending"}})diff --git a/kernel/model/attribute_view_binding_undo_fts5_test.go b/kernel/model/attribute_view_binding_undo_fts5_test.goindex 94f0f0e6d7..66889aadc4 100644--- a/kernel/model/attribute_view_binding_undo_fts5_test.go+++ b/kernel/model/attribute_view_binding_undo_fts5_test.go@@ -39,7 +39,7 @@ func TestAttributeViewBindingUndoRedo(t *testing.T) {if after.GetBlockValue(itemID).Block.ID != fixture.sourceID {t.Fatal("replacement did not bind the new block")}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {assertAttributeViewBindingBacklink(t, fixture.targetID, before.ID, false)assertAttributeViewBindingBacklink(t, fixture.sourceID, before.ID, true)if err = PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {@@ -93,7 +93,7 @@ func TestAttributeViewBindingCreatedDocumentReplay(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {if err := PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {t.Fatal(err)}diff --git a/kernel/model/attribute_view_block_undo_fts5_test.go b/kernel/model/attribute_view_block_undo_fts5_test.goindex c9aa47fde6..49d5284cfd 100644--- a/kernel/model/attribute_view_block_undo_fts5_test.go+++ b/kernel/model/attribute_view_block_undo_fts5_test.go@@ -27,7 +27,7 @@ func TestAttributeViewDeletedBlockUndoRedo(t *testing.T) {if entry == nil || len(entry.undoOperations) <= len(tx.DoOperations) {t.Fatal("database restoration was not recorded after the block operations")}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {deleted := readAttributeViewItemsTest(t, before.ID)for _, primary := range before.GetBlockKeyValues().Values {if !primary.IsDetached && deleted.GetBlockValue(primary.BlockID) != nil {@@ -203,7 +203,7 @@ func TestAttributeViewDeletedBlockUndoRelations(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {back := readAttributeViewItemsTest(t, dest.ID).GetValue(backID, targetID)if !slices.Equal(back.Relation.BlockIDs, []string{keptID}) {t.Fatalf("deletion retained stale back relations: %v", back.Relation.BlockIDs)diff --git a/kernel/model/attribute_view_calendar_test.go b/kernel/model/attribute_view_calendar_test.goindex 2730e8811d..6196e698e9 100644--- a/kernel/model/attribute_view_calendar_test.go+++ b/kernel/model/attribute_view_calendar_test.go@@ -99,7 +99,7 @@ func TestAttributeViewCalendarRenderFilterSortAndExport(t *testing.T) {dateValues, _ := attrView.GetKeyValues(date.ID)primary := attrView.GetBlockKeyValues()start := time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC).UnixMilli()- for i := 0; i < 120; i++ {+ for i := range 120 {id := ast.NewNodeID()view.ItemIDs = append(view.ItemIDs, id)primary.Values = append(primary.Values, &av.Value{ID: ast.NewNodeID(), KeyID: primary.Key.ID, BlockID: id,diff --git a/kernel/model/attribute_view_collection.go b/kernel/model/attribute_view_collection.goindex 707fc29be1..57dcb31bdd 100644--- a/kernel/model/attribute_view_collection.go+++ b/kernel/model/attribute_view_collection.go@@ -102,7 +102,7 @@ func collectionBlockMatches(source *av.AutomationBlockSource, node *ast.Node, tr}tags := map[string]bool{}if node.Type == ast.NodeDocument {- for _, tag := range strings.Split(node.IALAttr("tags"), ",") {+ for tag := range strings.SplitSeq(node.IALAttr("tags"), ",") {tags[strings.Trim(strings.TrimSpace(tag), "#")] = true}}@@ -348,8 +348,7 @@ func (tx *Transaction) runAttributeViewCollections() error {for _, rule := range view.Automations.Rules {if rule != nil && rule.Enabled && rule.Trigger == "block" {validationErr := tx.validateBlockCollectionRule(view, rule, boxID)- var unavailable *automationUnavailableReference- if errors.As(validationErr, &unavailable) {+ if unavailable, ok := errors.AsType[*automationUnavailableReference](validationErr); ok {if err = tx.rememberAutomationView(view, ""); err != nil {return err}diff --git a/kernel/model/attribute_view_custom_color_history_test.go b/kernel/model/attribute_view_custom_color_history_test.goindex 478cf7ca70..ef10cacd83 100644--- a/kernel/model/attribute_view_custom_color_history_test.go+++ b/kernel/model/attribute_view_custom_color_history_test.go@@ -84,10 +84,8 @@ func TestAttributeViewCustomColorRenderContextReturnsIndependentPalettes(t *testconst goroutines = 32var waitGroup sync.WaitGrouperrs := make(chan string, goroutines)- for i := 0; i < goroutines; i++ {- waitGroup.Add(1)- go func() {- defer waitGroup.Done()+ for range goroutines {+ waitGroup.Go(func() {colors, order, found := resolver("20260824000000-target1")if !found || 1 != len(colors) || "#0a0b0c" != colors[0].Dark.BackgroundColor {errs <- "resolver returned an invalid palette"@@ -96,7 +94,7 @@ func TestAttributeViewCustomColorRenderContextReturnsIndependentPalettes(t *testerrs <- "resolver returned an invalid palette order"}colors[0].Light.Color = "#ffffff"- }()+ })}waitGroup.Wait()close(errs)diff --git a/kernel/model/attribute_view_fields_fts5_test.go b/kernel/model/attribute_view_fields_fts5_test.goindex 17b9d32b7a..6afc96b2ab 100644--- a/kernel/model/attribute_view_fields_fts5_test.go+++ b/kernel/model/attribute_view_fields_fts5_test.go@@ -48,7 +48,7 @@ func TestAttributeViewFieldsUndoRedo(t *testing.T) {t.Fatal("deleted field left a filter or group behind")}}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())assertAttributeViewFieldsTest(t, before, readAttributeViewItemsTest(t, before.ID))replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())@@ -75,7 +75,7 @@ func TestAttributeViewFieldsEmptyLayout(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())assertAttributeViewFieldsTest(t, before, readAttributeViewItemsTest(t, before.ID))replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())@@ -103,7 +103,7 @@ func TestAttributeViewFieldsUndoAfterKanbanRender(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {current := readAttributeViewItemsTest(t, source.ID)if _, err := renderAttributeView(current, fixture.sourceID, layout.ID, "", "", 1, 50, nil, false, true, nil, ""); err != nil {t.Fatal(err)@@ -192,7 +192,7 @@ func TestAttributeViewFieldsRelations(t *testing.T) {if !self && slices.Contains(av.GetSrcAvIDs(dest.ID), source.ID) {t.Fatal("deleted source relation remained indexed")}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {for _, view := range []*av.AttributeView{source, dest} {current := readAttributeViewItemsTest(t, view.ID)sql.RenderView(current, current.Views[0], "", false)diff --git a/kernel/model/attribute_view_group_undo_fts5_test.go b/kernel/model/attribute_view_group_undo_fts5_test.goindex ba4bb8bb44..7e8e79d7b6 100644--- a/kernel/model/attribute_view_group_undo_fts5_test.go+++ b/kernel/model/attribute_view_group_undo_fts5_test.go@@ -36,7 +36,7 @@ func TestAttributeViewGroupMoveUndoRedo(t *testing.T) {t.Fatalf("private group move snapshot leaked: %s, %v", encoded, err)}after := readAttributeViewItemsTest(t, before.ID)- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())assertAttributeViewFieldsTest(t, before, readAttributeViewItemsTest(t, before.ID))rendered := readAttributeViewItemsTest(t, before.ID)@@ -90,7 +90,7 @@ func TestAttributeViewGroupMoveBoundItem(t *testing.T) {if err := PerformTxSync(tx); err != nil {t.Fatal(err)}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {current := readAttributeViewItemsTest(t, before.ID)for _, view := range current.Views {sql.RenderView(current, view, "", false)diff --git a/kernel/model/attribute_view_icon_fts5_test.go b/kernel/model/attribute_view_icon_fts5_test.goindex 757b397771..7f3676ab0c 100644--- a/kernel/model/attribute_view_icon_fts5_test.go+++ b/kernel/model/attribute_view_icon_fts5_test.go@@ -116,7 +116,7 @@ func TestAttributeViewItemIconBindingInheritance(t *testing.T) {return}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {if err = PerformTxSync(&Transaction{DoOperations: entry.UndoOperationsForReplay(), isReplay: true}); err != nil {t.Fatal(err)}diff --git a/kernel/model/attribute_view_initialization_test.go b/kernel/model/attribute_view_initialization_test.goindex e000bc91e3..c8c2942f5c 100644--- a/kernel/model/attribute_view_initialization_test.go+++ b/kernel/model/attribute_view_initialization_test.go@@ -122,10 +122,10 @@ func TestRenderAttributeViewConcurrentInitialization(t *testing.T) {fields []stringerr error}- for round := 0; round < 32; round++ {+ for round := range 32 {avID := ast.NewNodeID()start, done := make(chan struct{}), make(chan result, 2)- for i := 0; i < 2; i++ {+ for range 2 {go func() {<-startview, definition, _, err := RenderAttributeViewWithTarget("", avID, "", "", 1, -1, nil,diff --git a/kernel/model/attribute_view_items_fts5_test.go b/kernel/model/attribute_view_items_fts5_test.goindex 2250117d6f..e609fb3997 100644--- a/kernel/model/attribute_view_items_fts5_test.go+++ b/kernel/model/attribute_view_items_fts5_test.go@@ -44,7 +44,7 @@ func TestAttributeViewItemsUndoRedo(t *testing.T) {if err != nil || strings.Contains(string(data), "private field contents") {t.Fatalf("private field snapshots leaked into response: %s, %v", data, err)}- for cycle := 0; cycle < 3; cycle++ {+ for cycle := range 3 {deleted := readAttributeViewItemsTest(t, before.ID)for _, kv := range deleted.KeyValues {for _, value := range kv.Values {@@ -98,7 +98,7 @@ func TestAttributeViewItemsUndoRelationConfiguration(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {for _, before := range []*av.AttributeView{source, peer} {current := readAttributeViewItemsTest(t, before.ID)if len(current.Views[0].Filters[0].Filters) != 0 || len(current.NewItemTemplates[0].FieldValues) != 0 {@@ -246,7 +246,7 @@ func TestAttributeViewItemsUndoRelations(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {deletedDest := readAttributeViewItemsTest(t, dest.ID)if got := av.GetValue(deletedDest.KeyValues, backID, targetID).Relation.BlockIDs; !slices.Equal(got, []string{keptID}) {t.Fatalf("delete did not clear back relations: %v", got)diff --git a/kernel/model/attribute_view_location_export_test.go b/kernel/model/attribute_view_location_export_test.goindex 9c435ecd70..f5a6cfa2ac 100644--- a/kernel/model/attribute_view_location_export_test.go+++ b/kernel/model/attribute_view_location_export_test.go@@ -32,7 +32,7 @@ func TestAttributeViewLocationCSVAndMarkdownExport(t *testing.T) {primary.Values = []*av.Value{{ID: ast.NewNodeID(), KeyID: primary.Key.ID, BlockID: rowID, Type: av.KeyTypeBlock, IsDetached: true, Block: &av.ValueBlock{Content: "Entry"}}}key := av.NewKey(ast.NewNodeID(), "Location", "", av.KeyTypeLocation)view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: key, Values: []*av.Value{{ID: ast.NewNodeID(), KeyID: key.ID, BlockID: rowID, Type: av.KeyTypeLocation,- Location: &av.ValueLocation{Name: "Home", Latitude: modelLocationCoordinate(0), Longitude: modelLocationCoordinate(0), OriginalInput: "private provenance"}}}})+ Location: &av.ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "private provenance"}}}})view.Views[0].ItemIDs = []string{rowID}view.Views[0].Table.Columns = []*av.ViewTableColumn{{BaseField: &av.BaseField{ID: primary.Key.ID}}, {BaseField: &av.BaseField{ID: key.ID}}}for _, test := range []struct{ name, template, want string }{diff --git a/kernel/model/attribute_view_location_test.go b/kernel/model/attribute_view_location_test.goindex c845245bea..a571e41454 100644--- a/kernel/model/attribute_view_location_test.go+++ b/kernel/model/attribute_view_location_test.go@@ -15,14 +15,15 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-func modelLocationCoordinate(value float64) *float64 { return &value }+//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,Type: av.KeyTypeLocation, CreatedAt: 100, UpdatedAt: 200,- Location: &av.ValueLocation{Name: "Home", Latitude: modelLocationCoordinate(0),- Longitude: modelLocationCoordinate(120), OriginalInput: "original"}}+ Location: &av.ValueLocation{Name: "Home", Latitude: new(float64(0)),+ Longitude: new(float64(120)), OriginalInput: "original"}}view := &av.AttributeView{ID: "20261009000000-locatav", KeyValues: []*av.KeyValues{{Key: &av.Key{ID: "20261009000004-locabky", Type: av.KeyTypeBlock}, Values: []*av.Value{{BlockID: itemID, Type: av.KeyTypeBlock, IsDetached: true, Block: &av.ValueBlock{Content: "Entry"}}}},@@ -90,7 +91,7 @@ func TestUpdateAttributeViewLocationPartialAndInvalid(t *testing.T) {}func TestAttributeViewLocationNoOpProvenance(t *testing.T) {- previous := &av.ValueLocation{Latitude: modelLocationCoordinate(0), Longitude: modelLocationCoordinate(0), OriginalInput: "source"}+ previous := &av.ValueLocation{Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "source"}updated := *previousnormalizeAttributeViewLocationProvenance(previous, &updated, []byte(`{"location":{"latitude":0,"longitude":0}}`))if updated.OriginalInput != "source" {@@ -99,20 +100,20 @@ func TestAttributeViewLocationNoOpProvenance(t *testing.T) {}func TestAttributeViewLocationAutomationReplacement(t *testing.T) {- previous := &av.Value{Type: av.KeyTypeLocation, Location: &av.ValueLocation{Name: "Home", Latitude: modelLocationCoordinate(0), Longitude: modelLocationCoordinate(0), OriginalInput: "original"}}+ previous := &av.Value{Type: av.KeyTypeLocation, Location: &av.ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "original"}}next := previous.Clone()next.Location.OriginalInput = "different provenance"if !equalAutomationValues(previous, next) {t.Fatal("provenance triggered an automation value change")}- next.Location.Longitude = modelLocationCoordinate(1)+ next.Location.Longitude = new(float64(1))if equalAutomationValues(previous, next) {t.Fatal("coordinate change was ignored")}for _, desired := range []*av.Value{{Type: av.KeyTypeLocation},{Type: av.KeyTypeLocation, Location: &av.ValueLocation{Name: "Office"}},- {Type: av.KeyTypeLocation, Location: &av.ValueLocation{Latitude: modelLocationCoordinate(0), Longitude: modelLocationCoordinate(0)}},+ {Type: av.KeyTypeLocation, Location: &av.ValueLocation{Latitude: new(float64(0)), Longitude: new(float64(0))}},} {merged := previous.Clone()data, _ := json.Marshal(automationValuePatch(desired))@@ -162,7 +163,7 @@ func TestAttributeViewLocationEncryptedRecovery(t *testing.T) {t.Fatalf("legacy authenticated read: %v", err)}value := &av.Value{ID: "20261009000002-locaval", KeyID: locationKeyID, BlockID: "20260921000003-example", Type: av.KeyTypeLocation,- Location: &av.ValueLocation{Name: "Home", Latitude: modelLocationCoordinate(0), Longitude: modelLocationCoordinate(0), OriginalInput: "original"}}+ Location: &av.ValueLocation{Name: "Home", Latitude: new(float64(0)), Longitude: new(float64(0)), OriginalInput: "original"}}view.KeyValues = append(view.KeyValues, &av.KeyValues{Key: &av.Key{ID: locationKeyID, Name: "Location", Type: av.KeyTypeLocation}, Values: []*av.Value{value}})if err = av.SaveAttributeView(view); err != nil {t.Fatal(err)@@ -268,7 +269,7 @@ func TestAttributeViewLocationSaveRejectsInvalidAndFuture(t *testing.T) {for _, spec := range []int{av.LocationSpec, av.CurrentSpec + 1} {view := &av.AttributeView{ID: avID, Spec: spec, KeyValues: []*av.KeyValues{{Key: &av.Key{Type: av.KeyTypeLocation}, Values: []*av.Value{{Type: av.KeyTypeLocation,- Location: &av.ValueLocation{Latitude: modelLocationCoordinate(91), Longitude: modelLocationCoordinate(0)}}},+ Location: &av.ValueLocation{Latitude: new(float64(91)), Longitude: new(float64(0))}}},}}}if err := av.SaveAttributeView(view); err == nil || spec > av.CurrentSpec && err != av.ErrSpecTooNew {t.Fatalf("invalid/future save result: %v", err)diff --git a/kernel/model/attribute_view_option_undo_fts5_test.go b/kernel/model/attribute_view_option_undo_fts5_test.goindex 15f42f4a4b..04d11c29e0 100644--- a/kernel/model/attribute_view_option_undo_fts5_test.go+++ b/kernel/model/attribute_view_option_undo_fts5_test.go@@ -68,7 +68,7 @@ func TestAttributeViewOptionUndoRedo(t *testing.T) {if action == "merge" && field.Key.GetOption("B").Desc != "Target description" {t.Fatal("merge changed the target option definition")}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())assertAttributeViewFieldsTest(t, source, readAttributeViewItemsTest(t, source.ID))assertAttributeViewFieldsTest(t, peer, readAttributeViewItemsTest(t, peer.ID))@@ -105,7 +105,7 @@ func TestAttributeViewOptionDeleteLastUndo(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {deleted := readAttributeViewItemsTest(t, source.ID)key, _ := deleted.GetKey(field.Key.ID)if len(key.Options) != 0 {diff --git a/kernel/model/attribute_view_recovery_fts5_test.go b/kernel/model/attribute_view_recovery_fts5_test.goindex 82e83ada55..5cb0a3aa57 100644--- a/kernel/model/attribute_view_recovery_fts5_test.go+++ b/kernel/model/attribute_view_recovery_fts5_test.go@@ -260,7 +260,7 @@ func TestDeletedFlashcardBlockReplayRetainsDeckAttribute(t *testing.T) {t.Fatal(err)}entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())restored, err := LoadTreeByBlockID(fixture.sourceID)if err != nil {@@ -308,7 +308,7 @@ func TestFlashcardCopyRedoPreservesNormalizedAttributes(t *testing.T) {}check()entry := GlobalUndoLog.Peek(fixture.sourceID)- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())replayAttributeViewFieldsTest(t, entry.DoOperationsForReplay())check()diff --git a/kernel/model/attribute_view_render.go b/kernel/model/attribute_view_render.goindex 368185772b..430c2c1156 100644--- a/kernel/model/attribute_view_render.go+++ b/kernel/model/attribute_view_render.go@@ -1153,7 +1153,7 @@ func findAttributeViewTargetIndex(targetItemID string, length int, getID func(inif targetItemID == "" {return -1}- for i := 0; i < length; i++ {+ for i := range length {if getID(i) == targetItemID {return i}diff --git a/kernel/model/attribute_view_search_test.go b/kernel/model/attribute_view_search_test.goindex f800370d9a..284844d836 100644--- a/kernel/model/attribute_view_search_test.go+++ b/kernel/model/attribute_view_search_test.go@@ -51,7 +51,7 @@ func TestMatchAttributeViewSearchName(t *testing.T) {func TestSortAndLimitAttributeViewSearchResults(t *testing.T) {var results []*AvSearchTempResult- for i := 0; i < 15; i++ {+ for i := range 15 {results = append(results, &AvSearchTempResult{AvID: string(rune('a' + i)), AvUpdated: int64(i)})}@@ -136,7 +136,7 @@ func resetAttributeViewSearchCacheWarmups() {func waitAttributeViewSearchCacheLoads(t *testing.T, loaded <-chan struct{}, expected int) {t.Helper()- for i := 0; i < expected; i++ {+ for i := range expected {select {case <-loaded:case <-time.After(time.Second):diff --git a/kernel/model/attribute_view_validation_test.go b/kernel/model/attribute_view_validation_test.goindex 9687123e74..8d7461c100 100644--- a/kernel/model/attribute_view_validation_test.go+++ b/kernel/model/attribute_view_validation_test.go@@ -162,7 +162,7 @@ func TestAddAttributeViewBlocksAcceptsDetachedItemsInBatch(t *testing.T) {const itemCount = 100itemIDs := make([]string, 0, itemCount)srcs := make([]map[string]any, 0, itemCount)- for i := 0; i < itemCount; i++ {+ for range itemCount {itemID := ast.NewNodeID()itemIDs = append(itemIDs, itemID)srcs = append(srcs, map[string]any{diff --git a/kernel/model/auth_test.go b/kernel/model/auth_test.goindex 3a5a3bb80f..f778b3e340 100644--- a/kernel/model/auth_test.go+++ b/kernel/model/auth_test.go@@ -154,7 +154,7 @@ func TestPublishSessionPerAccountCapEvictsOldest(t *testing.T) {base := time.Now()sessionLock.Lock()- for i := 0; i < publishSessionPerAccountCap; i++ {+ for i := range publishSessionPerAccountCap {sessionsMap["id-"+strconv.Itoa(i)] = &PublishSession{Username: "alice",LastActive: base.Add(time.Duration(i) * time.Second),@@ -350,13 +350,13 @@ func TestConcurrentPublishAccountRefreshAndJWTParsing(t *testing.T) {wait.Add(2)go func() {defer wait.Done()- for i := 0; i < 100; i++ {+ for range 100 {InitPublishAccounts()}}()go func() {defer wait.Done()- for i := 0; i < 100; i++ {+ for range 100 {_, _ = ParseJWT(account.Token)}}()diff --git a/kernel/model/backlink_global_fts5_test.go b/kernel/model/backlink_global_fts5_test.goindex 0329057b6d..b0cc7acdcb 100644--- a/kernel/model/backlink_global_fts5_test.go+++ b/kernel/model/backlink_global_fts5_test.go@@ -210,7 +210,7 @@ func TestGlobalBacklinkSnapshotBounds(t *testing.T) {t.Cleanup(func() { ClearGlobalBacklinkSnapshots("") })query := GlobalBacklinkQuery{ID: "id", Sort: 1}first := ""- for i := 0; i < globalBacklinkSnapshotLimit+1; i++ {+ for i := range globalBacklinkSnapshotLimit + 1 {token, _, err := globalBacklinkSnapshotPut(query, []*GlobalBacklinkItem{{ID: fmt.Sprint(i)}})if err != nil {t.Fatal(err)@@ -254,7 +254,7 @@ func TestGlobalBacklinkLargeDataset(t *testing.T) {t.Fatal(err)}sql.IndexTreeQueue(definition)- for doc := 0; doc < documents; doc++ {+ for doc := range documents {tree := addFileOperationTestDoc(t, fixture, fmt.Sprintf("20260923000000-d%06d", doc), fmt.Sprintf("Source%d", doc), false)for tree.Root.FirstChild != nil {tree.Root.FirstChild.Unlink()diff --git a/kernel/model/backlink_sort.go b/kernel/model/backlink_sort.goindex 48fc803bfa..769899025e 100644--- a/kernel/model/backlink_sort.go+++ b/kernel/model/backlink_sort.go@@ -1,6 +1,7 @@package modelimport (+ "maps""sort""strings"@@ -30,9 +31,7 @@ func expandBacklinkDocumentEntries(blocks []*Block, refs []*sql.Ref, defRootID s}}entries, _, _, mappings := buildLinkRefsInBoxWithDocumentGrouping(defRootID, removeDuplicatedRefs(documentRefs), keywords, boxID, false)- for parentID, refID := range mappings {- originalRefBlockIDs[parentID] = refID- }+ maps.Copy(originalRefBlockIDs, mappings)result = append(result, entries...)}return resultdiff --git a/kernel/model/bazaar_install_test.go b/kernel/model/bazaar_install_test.goindex 03c94c9773..2aff6dae8b 100644--- a/kernel/model/bazaar_install_test.go+++ b/kernel/model/bazaar_install_test.go@@ -130,7 +130,7 @@ func TestBoundInstallUpdatesWithoutSeparateBackups(t *testing.T) {t.Fatal(err)}previous := first.InstalledRevision- for i := 0; i < 33; i++ {+ for i := range 33 {installed := installBoundFixture(t, fmt.Sprintf("version %d", i), previous)if !installed.Updated || installed.PreviousRevision != previous {t.Fatalf("update binding = %+v", installed)diff --git a/kernel/model/block_operation_test.go b/kernel/model/block_operation_test.goindex 0c23b3d445..4cc02ec6bf 100644--- a/kernel/model/block_operation_test.go+++ b/kernel/model/block_operation_test.go@@ -178,7 +178,7 @@ func TestLargeInsertSiblingAnchors(t *testing.T) {setupFoldTransactionDatabase(t, fixture)tx := &Transaction{}var ids []string- for index := 0; index < 32; index++ {+ for range 32 {id := ast.NewNodeID()ids = append(ids, id)dom := util.NewLute().Md2BlockDOM("inserted\n{: id=\""+id+"\"}", false)diff --git a/kernel/model/block_swap_test.go b/kernel/model/block_swap_test.goindex a9caec66ed..2e7f67a2cf 100644--- a/kernel/model/block_swap_test.go+++ b/kernel/model/block_swap_test.go@@ -122,7 +122,7 @@ func TestSwapBlockRefNodes(t *testing.T) {for _, tree := range trees {treeMap[tree.ID] = tree}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {if err := restoreBlockSwapFragments(state.after, state.before, treeMap); err != nil {t.Fatalf("undo: %v", err)}diff --git a/kernel/model/boot_appearance.go b/kernel/model/boot_appearance.goindex c00bd5d78f..b292be47a2 100644--- a/kernel/model/boot_appearance.go+++ b/kernel/model/boot_appearance.go@@ -25,6 +25,7 @@ import ("os""path/filepath""regexp"+ "slices""sort""strings""sync"@@ -335,13 +336,7 @@ func getBootAppearanceByID(provider, appearanceID string) (ret *BootAppearance,if parseErr != nil || !bazaar.IsValidInstalledPackage(pkg, provider) {return nil, ErrBootAppearanceNotFound}- found := false- for _, declaredID := range pkg.BootAppearances {- if declaredID == appearanceID {- found = true- break- }- }+ found := slices.Contains(pkg.BootAppearances, appearanceID)if !found {return nil, ErrBootAppearanceNotFound}@@ -658,7 +653,7 @@ func ensureBootAppearancePathHasNoSymlink(root, target string) error {return ErrBootAppearanceAssetForbidden}current := rootAbs- for _, part := range strings.Split(relative, string(os.PathSeparator)) {+ for part := range strings.SplitSeq(relative, string(os.PathSeparator)) {if part == "." || part == "" {continue}diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.goindex 7608843cfd..7b8bdc0737 100644--- a/kernel/model/box_doc.go+++ b/kernel/model/box_doc.go@@ -313,8 +313,8 @@ func normalizeBoxDocPath(boxID, p string) string {return p}prefix := "/" + box.ID + "/"- if strings.HasPrefix(p, prefix) {- return "/" + strings.TrimPrefix(p, prefix)+ if after, ok := strings.CutPrefix(p, prefix); ok {+ return "/" + after}return p}diff --git a/kernel/model/conf_consistency_test.go b/kernel/model/conf_consistency_test.goindex 2efee696eb..126258b1be 100644--- a/kernel/model/conf_consistency_test.go+++ b/kernel/model/conf_consistency_test.go@@ -118,10 +118,10 @@ func TestConfNormalizeIsSharedAndIdempotent(t *testing.T) {normalizeAppConf(whole)section.normalize(single)a, _ := json.Marshal(reflect.ValueOf(whole).Elem().FieldByNameFunc(func(name string) bool {- return jsonFieldName(reflect.TypeOf(*whole), name) == section.name+ return jsonFieldName(reflect.TypeFor[AppConf](), name) == section.name}).Interface())b, _ := json.Marshal(reflect.ValueOf(single).Elem().FieldByNameFunc(func(name string) bool {- return jsonFieldName(reflect.TypeOf(*single), name) == section.name+ return jsonFieldName(reflect.TypeFor[AppConf](), name) == section.name}).Interface())if string(a) != string(b) {t.Fatalf("section %s differs between startup and write normalization:\n%s\n%s", section.name, a, b)@@ -217,7 +217,7 @@ func TestConfSectionSnapshotsAreConsistent(t *testing.T) {held := Conf.Sync.Load()heldInterval, heldMode := held.Interval, held.Modevar wg sync.WaitGroup- for i := 0; i < 20; i++ {+ for i := range 20 {wg.Add(1)go func(i int) {defer wg.Done()diff --git a/kernel/model/conf_regression_test.go b/kernel/model/conf_regression_test.goindex 63356c31fb..55a0c30858 100644--- a/kernel/model/conf_regression_test.go+++ b/kernel/model/conf_regression_test.go@@ -39,7 +39,7 @@ func TestConfAllSectionsShareStartupAndWriteNormalization(t *testing.T) {t.Fatal(err)}var value any- typ := reflect.TypeOf(*input)+ typ := reflect.TypeFor[AppConf]()for i := 0; i < typ.NumField(); i++ {if jsonFieldName(typ, typ.Field(i).Name) == namespace {data, _ := json.Marshal(reflect.ValueOf(input).Elem().Field(i).Interface())@@ -133,14 +133,14 @@ func TestConfConcurrentReadersHoldCoherentSnapshots(t *testing.T) {group.Add(2)go func() {defer group.Done()- for i := 0; i < 100; i++ {+ for range 100 {UpdateSyncConf(func(value *conf.Sync) { value.Interval = 200; value.CloudName = "200" })UpdateSyncConf(func(value *conf.Sync) { value.Interval = 100; value.CloudName = "100" })}}()go func() {defer group.Done()- for i := 0; i < 100000; i++ {+ for range 100000 {snapshot := Conf.Sync.Load()if snapshot.Interval == 100 && snapshot.CloudName != "100" || snapshot.Interval == 200 && snapshot.CloudName != "200" {t.Error("reader observed fields from different commits")diff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex b338dc2621..5cf88099f4 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -2319,10 +2319,7 @@ func EncryptAsset(boxID, diskName, originalName string, dek, plaintext []byte) (ret.Write(encryptedMetadata)for chunkIndex := uint64(0); chunkIndex < chunkCount; chunkIndex++ {start := int(chunkIndex) * encryptedAssetChunkSize- end := start + encryptedAssetChunkSize- if end > len(plaintext) {- end = len(plaintext)- }+ end := min(start+encryptedAssetChunkSize, len(plaintext))encryptedChunk, encryptErr := util.EncryptWithAAD(assetKey,plaintext[start:end],@@ -2366,7 +2363,7 @@ func decryptAssetMetadata(boxID, diskName string, dek, ciphertext []byte) (metad// encryptedAssetChunkAAD 将分块绑定到本次写入的容器,阻止同名资源的不同版本互换分块。func encryptedAssetChunkAAD(prefix string, containerID []byte, index uint64) []byte {- return []byte(fmt.Sprintf("%s:content:v%d:%x:%d", prefix, encryptedAssetSpec, containerID, index))+ return fmt.Appendf(nil, "%s:content:v%d:%x:%d", prefix, encryptedAssetSpec, containerID, index)}func parseEncryptedAssetMetadata(data []byte) (*encryptedAssetMetadata, error) {@@ -2501,7 +2498,7 @@ func DecryptAssetToWriter(boxID, diskName string, dek []byte, reader io.Reader,}aad := encryptedAssetChunkAAD(aadPrefix, metadata.ContainerID, chunkIndex)if metadata.Spec == encryptedAssetLegacySpec {- aad = []byte(fmt.Sprintf("%s:content:%d", aadPrefix, chunkIndex))+ aad = fmt.Appendf(nil, "%s:content:%d", aadPrefix, chunkIndex)}plainChunk, chunkErr := util.DecryptWithAAD(assetKey,diff --git a/kernel/model/crypto_asset_legacy_test.go b/kernel/model/crypto_asset_legacy_test.goindex ea6663eea6..d5185d2f12 100644--- a/kernel/model/crypto_asset_legacy_test.go+++ b/kernel/model/crypto_asset_legacy_test.go@@ -44,7 +44,7 @@ func legacyEncryptedAssetFixture(t *testing.T, boxID, diskName, originalName strret = append(ret, encryptedMetadata...)for i := range chunks {start, end := i*chunkSize, min((i+1)*chunkSize, len(plaintext))- chunk, encryptErr := util.EncryptWithAAD(key, plaintext[start:end], []byte(fmt.Sprintf("%s:content:%d", prefix, i)))+ chunk, encryptErr := util.EncryptWithAAD(key, plaintext[start:end], fmt.Appendf(nil, "%s:content:%d", prefix, i))if encryptErr != nil {t.Fatal(encryptErr)}diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.goindex e783250cdf..3ff822472a 100644--- a/kernel/model/crypto_lifecycle.go+++ b/kernel/model/crypto_lifecycle.go@@ -20,6 +20,7 @@ import ("bytes""context""errors"+ "slices""sort""sync"@@ -238,16 +239,16 @@ func AcquireEncryptedBoxOperations(ctx context.Context, boxIDs []string) (releasvar acquired []stringfor _, boxID := range sortedBoxIDs {if err = AcquireEncryptedBoxOperation(boxID); err != nil {- for i := len(acquired) - 1; i >= 0; i-- {- ReleaseEncryptedBoxOperation(acquired[i])+ for _, a := range slices.Backward(acquired) {+ ReleaseEncryptedBoxOperation(a)}return func() {}, err}acquired = append(acquired, boxID)}return func() {- for i := len(acquired) - 1; i >= 0; i-- {- ReleaseEncryptedBoxOperation(acquired[i])+ for _, a := range slices.Backward(acquired) {+ ReleaseEncryptedBoxOperation(a)}}, nil}@@ -282,7 +283,7 @@ func (scope *encryptedBoxOperationScope) release() {scope.boxIDs = nilscope.boxIDSet = nilscope.lock.Unlock()- for i := len(boxIDs) - 1; i >= 0; i-- {- ReleaseEncryptedBoxOperation(boxIDs[i])+ for _, boxID := range slices.Backward(boxIDs) {+ ReleaseEncryptedBoxOperation(boxID)}}diff --git a/kernel/model/daily_note.go b/kernel/model/daily_note.goindex 4ad084b472..3d4d622ff2 100644--- a/kernel/model/daily_note.go+++ b/kernel/model/daily_note.go@@ -3,6 +3,7 @@ package modelimport ("errors""path"+ "slices""strings""time"@@ -46,13 +47,7 @@ func resolveDailyNote(box *Box, now time.Time, findByDate bool) (hPath string, treturn}if len(ids) > 0 {- matched := false- for _, id := range ids {- if rootID == id {- matched = true- break- }- }+ matched := slices.Contains(ids, rootID)if !matched {rootID = ids[0]}diff --git a/kernel/model/dav_delete_test.go b/kernel/model/dav_delete_test.goindex fe1a8ea4a0..1dc280e29f 100644--- a/kernel/model/dav_delete_test.go+++ b/kernel/model/dav_delete_test.go@@ -50,7 +50,7 @@ func TestDAVDeleteMissingCollection(t *testing.T) {}})}- for i := 0; i < 3; i++ {+ for range 3 {err := calendarStore.DeleteCalendar(calendarPath)if want := webdav.NewHTTPError(http.StatusNotFound, ErrorCalDavCalendarNotFound); !reflect.DeepEqual(err, want) {t.Fatalf("DeleteCalendar error = %v, want %v", err, want)diff --git a/kernel/model/delete_stress_fts5_test.go b/kernel/model/delete_stress_fts5_test.goindex ee2d9759d7..80e575d21d 100644--- a/kernel/model/delete_stress_fts5_test.go+++ b/kernel/model/delete_stress_fts5_test.go@@ -102,9 +102,7 @@ func TestRapidDeletionLargeIndex(t *testing.T) {stop := make(chan struct{})var workers sync.WaitGroupstartWorker := func(interval time.Duration, run func()) {- workers.Add(1)- go func() {- defer workers.Done()+ workers.Go(func() {ticker := time.NewTicker(interval)defer ticker.Stop()for {@@ -115,7 +113,7 @@ func TestRapidDeletionLargeIndex(t *testing.T) {run()}}- }()+ })}startWorker(100*time.Millisecond, task.ExecTaskJob)startWorker(100*time.Millisecond, task.ExecAsyncTaskJob)diff --git a/kernel/model/duplicate_doc_tree.go b/kernel/model/duplicate_doc_tree.goindex 0cdf272208..48243eb466 100644--- a/kernel/model/duplicate_doc_tree.go+++ b/kernel/model/duplicate_doc_tree.go@@ -310,8 +310,8 @@ func (plan *duplicateDocTreePlan) commit(writeTree func(*parse.Tree) (uint64, ererr = errors.Join(err, removeErr)}}- for i := len(attempted) - 1; i >= 0; i-- {- tree := attempted[i]+ for i, tree := range slices.Backward(attempted) {+abs := filepath.Join(util.DataDir, tree.Box, tree.Path)if removeErr := os.Remove(abs); removeErr != nil && !os.IsNotExist(removeErr) {err = errors.Join(err, removeErr)diff --git a/kernel/model/elevator_windows.go b/kernel/model/elevator_windows.goindex b0f8b1b21d..0497bfd32f 100644--- a/kernel/model/elevator_windows.go+++ b/kernel/model/elevator_windows.go@@ -73,8 +73,7 @@ func AddMicrosoftDefenderExclusion() (err error) {// 提权工具等待添加命令结束并核验两个路径,只有最终退出码为零才记录完成args := []string{"add-defender-exclusion", syscall.EscapeArg(installPath), syscall.EscapeArg(util.WorkspaceDir)}if err = elevator.Run(elevatorBin, util.WorkingDir, strings.Join(args, " ")); err != nil {- var processError *elevator.ProcessError- if errors.As(err, &processError) {+ if processError, ok := errors.AsType[*elevator.ProcessError](err); ok {logging.LogErrorf("Windows Defender exclusion helper [%s] diagnostics: %s", elevatorBin, processError.Diagnostics)}logging.LogErrorf("add Windows Defender exclusion path [%s, %s] failed: %s", installPath, util.WorkspaceDir, err)diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex b110b0149a..0658735a26 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -539,7 +539,7 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes mascoredCh := make(chan []scoredBlock, numWorkers)var wg sync.WaitGroup- for w := 0; w < numWorkers; w++ {+ for w := range numWorkers {start := w * chunkSizeend := min(start+chunkSize, len(rows))if start >= end {diff --git a/kernel/model/export_merge.go b/kernel/model/export_merge.goindex 8a8bdfca6f..cb9377a531 100644--- a/kernel/model/export_merge.go+++ b/kernel/model/export_merge.go@@ -17,6 +17,8 @@package modelimport (+ "slices"+"github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/filesys"@@ -105,8 +107,8 @@ func mergeSubDocs(rootTree *parse.Tree, options MergeHeadingOptions, addRootTitlfunc walkBlock(insertPoint *ast.Node, block *Block, level int, options MergeHeadingOptions, addRootTitle bool) (err error) {level++- for i := len(block.Children) - 1; i >= 0; i-- {- c := block.Children[i]+ for _, c := range slices.Backward(block.Children) {+if err = walkBlock(insertPoint, c, level, options, addRootTitle); err != nil {return}diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 0c4dee9ad3..95756f3d8b 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -18,6 +18,7 @@ package modelimport ("errors"+ "maps""path""path/filepath""reflect"@@ -153,9 +154,7 @@ func TestListDocTreeUsesPathIDForInvalidPropertiesID(t *testing.T) {for _, test := range tests {t.Run(test.name, func(t *testing.T) {invalidIAL := make(map[string]string, len(ial))- for key, value := range ial {- invalidIAL[key] = value- }+ maps.Copy(invalidIAL, ial)if "" == test.id {delete(invalidIAL, "id")} else {diff --git a/kernel/model/format_mindmap_test.go b/kernel/model/format_mindmap_test.goindex c54f34a1ad..ce5be7cef5 100644--- a/kernel/model/format_mindmap_test.go+++ b/kernel/model/format_mindmap_test.go@@ -41,7 +41,7 @@ func TestAutoSpacePreservesMindmapBlocks(t *testing.T) {}return ast.WalkContinue})- for pass := 0; pass < 2; pass++ {+ for pass := range 2 {// 已保存的 .sy 树只在属性中保存 IAL,移除 Markdown 解析使用的辅助节点。var ialNodes []*ast.Nodeast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {diff --git a/kernel/model/heading_number.go b/kernel/model/heading_number.goindex e339d4ff2e..fa31602f98 100644--- a/kernel/model/heading_number.go+++ b/kernel/model/heading_number.go@@ -320,8 +320,8 @@ func chineseNumber(number int) string {number /= 10000unitIndex++}- if strings.HasPrefix(ret, "一十") {- ret = "十" + strings.TrimPrefix(ret, "一十")+ if after, ok := strings.CutPrefix(ret, "一十"); ok {+ ret = "十" + after}return ret}diff --git a/kernel/model/history_snapshots.go b/kernel/model/history_snapshots.goindex 750aef3819..87671b8562 100644--- a/kernel/model/history_snapshots.go+++ b/kernel/model/history_snapshots.go@@ -121,7 +121,7 @@ func GetDocHistorySnapshots(ctx context.Context, id string, histories []*DocHistif path.Base(file.Path) != id+".sy" {continue}- boxID := strings.Split(strings.TrimPrefix(file.Path, "/"), "/")[0]+ boxID, _, _ := strings.Cut(strings.TrimPrefix(file.Path, "/"), "/")if !IsEncryptedBox(boxID) {boxID = ""}diff --git a/kernel/model/hpath_refresh.go b/kernel/model/hpath_refresh.goindex 1af6ca03e0..7852a5541e 100644--- a/kernel/model/hpath_refresh.go+++ b/kernel/model/hpath_refresh.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "maps""os""path/filepath""sort"@@ -392,9 +393,7 @@ func RefreshHPathsJob() {}delete(hpathRefresh.tasks, key)if err = saveHPathRefreshLocked(); err != nil {- for removedKey, removedTask := range removed {- hpathRefresh.tasks[removedKey] = removedTask- }+ maps.Copy(hpathRefresh.tasks, removed)logging.LogErrorf("save hpath refresh tasks failed: %s", err)return}diff --git a/kernel/model/import_attribute_view.go b/kernel/model/import_attribute_view.goindex 79fe8ab33d..9508a95145 100644--- a/kernel/model/import_attribute_view.go+++ b/kernel/model/import_attribute_view.go@@ -103,7 +103,7 @@ func retainImportedAttributeViewBindings(node *ast.Node, avIDs map[string]stringallowed[id] = true}var retained []string- for _, id := range strings.Split(node.IALAttr(av.NodeAttrNameAvs), ",") {+ for id := range strings.SplitSeq(node.IALAttr(av.NodeAttrNameAvs), ",") {id = strings.TrimSpace(id)if allowed[id] {retained = append(retained, id)diff --git a/kernel/model/import_markdown.go b/kernel/model/import_markdown.goindex aec96cadc9..2cb0a863bb 100644--- a/kernel/model/import_markdown.go+++ b/kernel/model/import_markdown.go@@ -67,7 +67,7 @@ func (spool *markdownImportSpool) close() {}func markdownImportAAD(index int) []byte {- return []byte(fmt.Sprintf("siyuan/markdown-import/v1/%d", index))+ return fmt.Appendf(nil, "siyuan/markdown-import/v1/%d", index)}func (spool *markdownImportSpool) add(tree *parse.Tree) error {diff --git a/kernel/model/import_obsidian.go b/kernel/model/import_obsidian.goindex 5c2c4c872f..129f06b575 100644--- a/kernel/model/import_obsidian.go+++ b/kernel/model/import_obsidian.go@@ -30,6 +30,7 @@ import ("path/filepath""regexp""runtime"+ "slices""sort""strconv""strings"@@ -552,10 +553,7 @@ func analyzeObsidianVault(ctx context.Context, localPath string, progress func(iret.Analysis.ImportableAssetCount++ret.Analysis.ImportableAssetSize += asset.Source.Size}- ret.Analysis.UnreferencedFileCount = len(ret.ImportAssets) - len(ret.ReferencedAssets)- if ret.Analysis.UnreferencedFileCount < 0 {- ret.Analysis.UnreferencedFileCount = 0- }+ ret.Analysis.UnreferencedFileCount = max(len(ret.ImportAssets)-len(ret.ReferencedAssets), 0)progress(100, "Analysis completed")return ret, nil}@@ -1057,9 +1055,9 @@ func resolveObsidianTarget(vault *obsidianVaultContext, current *obsidianDocPlandocPart := targetfragment := ""- if index := strings.Index(target, "#"); index >= 0 {- docPart = target[:index]- fragment = target[index+1:]+ if before, after, ok := strings.Cut(target, "#"); ok {+ docPart = before+ fragment = after}if docPart == "" {return resolveObsidianDocumentFragment(current, fragment)@@ -1147,8 +1145,8 @@ func resolveObsidianDocumentFragment(doc *obsidianDocPlan, fragment string) obsiif fragment == "" {return obsidianResolvedTarget{Status: "resolved", Doc: doc, ID: doc.ID}}- if strings.HasPrefix(fragment, "^") {- blockID := strings.TrimPrefix(fragment, "^")+ if after, ok := strings.CutPrefix(fragment, "^"); ok {+ blockID := afterif doc.DuplicateBlocks[blockID] {if id := doc.BlockIDs[blockID]; id != "" {return obsidianResolvedTarget{Status: "resolved", Doc: doc, ID: id, Ambiguous: true}@@ -1273,8 +1271,8 @@ func resolveObsidianMarkdownDestination(vault *obsidianVaultContext, current *obif destination == "" {return obsidianResolvedTarget{Status: "unsupported"}}- if strings.HasPrefix(destination, "#") {- return resolveObsidianDocumentFragment(current, strings.TrimPrefix(destination, "#"))+ if after, ok := strings.CutPrefix(destination, "#"); ok {+ return resolveObsidianDocumentFragment(current, after)}lowerDestination := strings.ToLower(destination)if strings.HasPrefix(destination, "/") || strings.Contains(destination, "://") || strings.HasPrefix(lowerDestination, "data:") ||@@ -2010,12 +2008,7 @@ func escapeObsidianMarkdownText(text string) string {func isObsidianImage(filePath string) bool {ext := strings.ToLower(path.Ext(filePath))- for _, imageExt := range util.SiYuanAssetsImage {- if ext == imageExt {- return true- }- }- return false+ return slices.Contains(util.SiYuanAssetsImage, ext)}func parseObsidianImageSize(value string) (width, height int, ok bool) {@@ -2161,8 +2154,8 @@ func injectObsidianBlockIAL(data []byte, doc *obsidianDocPlan) []byte {}}ret := append([]byte(nil), data...)- for index := len(matches) - 1; index >= 0; index-- {- match := matches[index]+ for index, match := range slices.Backward(matches) {+blockID := string(data[match[2]:match[3]])if doc.BlockIDs[blockID] == "" || (doc.DuplicateBlocks[blockID] && firstMatches[blockID] != index) {continuediff --git a/kernel/model/lan_sync.go b/kernel/model/lan_sync.goindex e3534ca36d..56270a1fab 100644--- a/kernel/model/lan_sync.go+++ b/kernel/model/lan_sync.go@@ -360,11 +360,8 @@ func GetSyncLANStatus() SyncLANStatus {connectedCount := 0if nil != manager {connectedCount = manager.ConnectedPeerCount()- discoveredCount = manager.DiscoveredPeerCount()// 已认证设备必然已经被发现,避免两次状态采样之间完成认证时出现数量倒序。- if discoveredCount < connectedCount {- discoveredCount = connectedCount- }+ discoveredCount = max(manager.DiscoveredPeerCount(), connectedCount)}enabled := falsemaxConcurrentReqs := 16diff --git a/kernel/model/mcpoauth/service.go b/kernel/model/mcpoauth/service.goindex 4e607857ad..74d2b6872b 100644--- a/kernel/model/mcpoauth/service.go+++ b/kernel/model/mcpoauth/service.go@@ -280,7 +280,7 @@ func normalizeScope(value string) (string, error) {return scope, nil}hasMCP, offline := false, false- for _, item := range strings.Fields(value) {+ for item := range strings.FieldsSeq(value) {switch item {case scope:hasMCP = truediff --git a/kernel/model/mount.go b/kernel/model/mount.goindex 6961d9cc67..65fd56fee5 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -189,7 +189,7 @@ func isEncryptedBoxMounted(boxID string) bool {// Go 的 os.RemoveAll 在 Windows 上遇到"目录非空"(并发写入或句柄占用)不会重试,// 因此这里在每次重试前主动清空残留内容,并在最终失败时返回残留条目供定位。func removeBoxDir(p string) (err error) {- for i := 0; i < 5; i++ {+ for i := range 5 {err = filelock.RemoveWithoutFatal(p)if nil == err {returndiff --git a/kernel/model/notebook_archive.go b/kernel/model/notebook_archive.goindex e34a25a271..6f558a101e 100644--- a/kernel/model/notebook_archive.go+++ b/kernel/model/notebook_archive.go@@ -4,9 +4,11 @@ import ("bytes""encoding/json""fmt"+ "maps""os""path/filepath""reflect"+ "slices""sort""strings""sync"@@ -242,8 +244,8 @@ func notebookArchiveRoots(ids []string) ([]string, error) {func holdNotebookArchiveBoxes(ids []string) (func(), error) {var releases []func()release := func() {- for i := len(releases) - 1; i >= 0; i-- {- releases[i]()+ for _, release := range slices.Backward(releases) {+ release()}}for _, id := range ids {@@ -434,8 +436,8 @@ func checkNotebookArchiveSources(manifest *notebookArchiveManifest) error {}expected := map[string]notebookArchiveFile{}for name, file := range manifest.Files {- if strings.HasPrefix(name, root+"/") {- expected[strings.TrimPrefix(name, root+"/")] = file+ if after, ok := strings.CutPrefix(name, root+"/"); ok {+ expected[after] = file}}if !reflect.DeepEqual(files, expected) {@@ -585,8 +587,8 @@ func CommitNotebookArchive(id string, saved bool) error {}func rollbackNotebookArchive(directory string, operation *notebookArchiveOperation) error {- for i := len(operation.Roots) - 1; i >= 0; i-- {- root := operation.Roots[i]+ for _, root := range slices.Backward(operation.Roots) {+source, err := archiveSourcePath(root)if err != nil {return err@@ -714,9 +716,7 @@ func preserveNotebookCryptoBeforeDisable() error {return readErr}// 已提交归档保留其生成时的密钥;之后重新启用或改密不影响这些旧快照的归档覆盖。- for name, fingerprint := range manifest.Files {- covered[name] = fingerprint- }+ maps.Copy(covered, manifest.Files)}err = walkNotebookArchiveSnapshots(func(repo *dejavu.Repo, index *entity.Index, files []*entity.File) error {encrypted := map[string]bool{}diff --git a/kernel/model/notebook_archive_file.go b/kernel/model/notebook_archive_file.goindex 0b662bcf10..b82aa07c90 100644--- a/kernel/model/notebook_archive_file.go+++ b/kernel/model/notebook_archive_file.go@@ -62,7 +62,7 @@ func archiveRelativePath(name string) bool {if name == "" || path.Clean(name) != name || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\:\x00<>\"|?*") {return false}- for _, part := range strings.Split(name, "/") {+ for part := range strings.SplitSeq(name, "/") {base := strings.ToUpper(strings.SplitN(part, ".", 2)[0])reserved := base == "CON" || base == "PRN" || base == "AUX" || base == "NUL" ||(len(base) == 4 && (strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) && base[3] >= '1' && base[3] <= '9')diff --git a/kernel/model/notebook_archive_import.go b/kernel/model/notebook_archive_import.goindex 605f475141..f03f983d1d 100644--- a/kernel/model/notebook_archive_import.go+++ b/kernel/model/notebook_archive_import.go@@ -8,6 +8,7 @@ import ("os""path""path/filepath"+ "slices""sort""strings""time"@@ -383,8 +384,8 @@ func stageNotebookArchiveImport(payload, install string, manifest *notebookArchi}func rollbackNotebookArchiveImport(directory string, operation *notebookArchiveOperation) error {- for i := len(operation.Roots) - 1; i >= 0; i-- {- root := operation.Roots[i]+ for _, root := range slices.Backward(operation.Roots) {+destination, err := archiveSourcePath(root)if err != nil {return errdiff --git a/kernel/model/notebook_archive_test.go b/kernel/model/notebook_archive_test.goindex 1d1ef1b8b4..e41ce05d22 100644--- a/kernel/model/notebook_archive_test.go+++ b/kernel/model/notebook_archive_test.go@@ -56,7 +56,7 @@ func notebookArchiveTestBox(t *testing.T, boxID string, kek []byte) []byte {if err = os.MkdirAll(filepath.Join(directory, ".siyuan"), 0700); err != nil {t.Fatal(err)}- for name, value := range map[string]interface{}{"conf.json": boxConf, notebookCryptoBackupFilename: crypt} {+ for name, value := range map[string]any{"conf.json": boxConf, notebookCryptoBackupFilename: crypt} {data, _ := json.Marshal(value)if err = os.WriteFile(filepath.Join(directory, ".siyuan", name), data, 0600); err != nil {t.Fatal(err)diff --git a/kernel/model/oidc.go b/kernel/model/oidc.goindex ce2875735c..5e9cd1f1ef 100644--- a/kernel/model/oidc.go+++ b/kernel/model/oidc.go@@ -17,6 +17,7 @@ import ("fmt""net/http""net/url"+ "slices""strings""sync""time"@@ -483,10 +484,8 @@ func ValidateOIDCConfiguration(config *conf.OIDC) error {if rule.Operator != conf.OIDCClaimOperatorEquals && rule.Operator != conf.OIDCClaimOperatorContains {return errors.New("Unsupported OIDC claim rule operator")}- for _, value := range rule.Values {- if value == "" {- return errors.New("OIDC claim rule values cannot be empty")- }+ if slices.Contains(rule.Values, "") {+ return errors.New("OIDC claim rule values cannot be empty")}}return nildiff --git a/kernel/model/oidc_test.go b/kernel/model/oidc_test.goindex 2bb38d7c35..12bc9c1664 100644--- a/kernel/model/oidc_test.go+++ b/kernel/model/oidc_test.go@@ -215,13 +215,11 @@ func TestOIDCTransactionCanOnlyBeClaimedOnceConcurrently(t *testing.T) {}results := make(chan claimResult, workers)var waitGroup sync.WaitGroup- for i := 0; i < workers; i++ {- waitGroup.Add(1)- go func() {- defer waitGroup.Done()+ for range workers {+ waitGroup.Go(func() {_, repeated, err := claimOIDCTransaction(context.Background(), transaction.State, transaction.Binding, false)results <- claimResult{repeated: repeated, err: err}- }()+ })}first := <-resultsif first.err != nil || first.repeated {@@ -520,7 +518,7 @@ func TestOIDCTransactionLimitsRejectWithoutEviction(t *testing.T) {return &oidcTransaction{State: state, Binding: binding, ClientIP: clientIP,ConfigVersion: oidcConfigurationVersion(Conf.GetOIDC()), ExpiresAt: time.Now().Add(time.Minute)}}- for i := 0; i < oidcTransactionPerBind; i++ {+ for i := range oidcTransactionPerBind {if err := storeOIDCTransaction(newTransaction(fmt.Sprintf("binding-%d", i), "same-binding", "")); err != nil {t.Fatal(err)}@@ -536,7 +534,7 @@ func TestOIDCTransactionLimitsRejectWithoutEviction(t *testing.T) {oidcTransactions.byState = map[string]*oidcTransaction{}oidcTransactions.byPoll = map[string]string{}oidcTransactions.Unlock()- for i := 0; i < oidcTransactionPerIP; i++ {+ for i := range oidcTransactionPerIP {if err := storeOIDCTransaction(newTransaction(fmt.Sprintf("ip-%d", i), fmt.Sprintf("binding-%d", i), "192.0.2.1")); err != nil {t.Fatal(err)}@@ -549,7 +547,7 @@ func TestOIDCTransactionLimitsRejectWithoutEviction(t *testing.T) {oidcTransactions.byState = map[string]*oidcTransaction{}oidcTransactions.byPoll = map[string]string{}oidcTransactions.Unlock()- for i := 0; i < oidcTransactionMax; i++ {+ for i := range oidcTransactionMax {if err := storeOIDCTransaction(newTransaction(fmt.Sprintf("capacity-%d", i), "", "")); err != nil {t.Fatal(err)}diff --git a/kernel/model/outline.go b/kernel/model/outline.goindex a305d13cd2..533e798df9 100644--- a/kernel/model/outline.go+++ b/kernel/model/outline.go@@ -17,6 +17,8 @@package modelimport (+ "slices"+"github.com/88250/gulu""github.com/88250/lute/ast""github.com/88250/lute/html"@@ -102,8 +104,8 @@ func (tx *Transaction) doMoveOutlineHeading(operation *Operation) (ret *TxErr) {diffLevel := heading.HeadingLevel - previousHeading.HeadingLevelheading.HeadingLevel = previousHeading.HeadingLevel- for i := len(headingChildren) - 1; i >= 0; i-- {- child := headingChildren[i]+ for _, child := range slices.Backward(headingChildren) {+if ast.NodeHeading == child.Type {child.HeadingLevel -= diffLevelif 6 < child.HeadingLevel {@@ -158,8 +160,8 @@ func (tx *Transaction) doMoveOutlineHeading(operation *Operation) (ret *TxErr) {diffLevel := heading.HeadingLevel - parentHeading.HeadingLevel - 1heading.HeadingLevel = min(6, parentHeading.HeadingLevel+1)- for i := len(headingChildren) - 1; i >= 0; i-- {- child := headingChildren[i]+ for _, child := range slices.Backward(headingChildren) {+if ast.NodeHeading == child.Type {child.HeadingLevel -= diffLevelif 6 < child.HeadingLevel {diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex 29520e90c4..f8527ffaf4 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -18,6 +18,7 @@ package modelimport ("errors"+ "maps""os""path""path/filepath"@@ -47,15 +48,13 @@ var backgroundRefreshWaitGroup sync.WaitGroup// runBackgroundRefresh 跟踪延迟刷新任务,便于工作区释放前等待任务结束。func runBackgroundRefresh(delay time.Duration, refresh func()) {- backgroundRefreshWaitGroup.Add(1)- go func() {- defer backgroundRefreshWaitGroup.Done()+ backgroundRefreshWaitGroup.Go(func() {time.Sleep(delay)// 与编辑事务串行刷新,避免异步分组写回覆盖撤销、重做后的数据。flushLock.Lock()defer flushLock.Unlock()refresh()- }()+ })}func PushReloadSnippet(snippet *conf.Snpt) {@@ -521,9 +520,7 @@ func refreshDynamicRefTexts0(updatedDefNodes map[string]*ast.Node, updatedTreesif ok {updatedTrees[refTreeID] = refTree}- for id, node := range changedRefNodes {- updatedRefNodes[id] = node- }+ maps.Copy(updatedRefNodes, changedRefNodes)for _, update := range updates {appendSetRefDynamicTextTask(refTreeID, update.blockID, update.defNode.id, update.defNode.refText, refTree.Box)}diff --git a/kernel/model/render.go b/kernel/model/render.goindex 1eaa13e407..af3aa18c5b 100644--- a/kernel/model/render.go+++ b/kernel/model/render.go@@ -18,6 +18,7 @@ package modelimport ("bytes"+ "maps""regexp""strconv""strings"@@ -201,9 +202,7 @@ func cloneRenderNode(node *ast.Node) *ast.Node {}if nil != node.Properties {cloned.Properties = make(map[string]string, len(node.Properties))- for name, value := range node.Properties {- cloned.Properties[name] = value- }+ maps.Copy(cloned.Properties, node.Properties)}for child := node.FirstChild; nil != child; child = child.Next {diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex f8590a3963..90d43eaa14 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -2945,8 +2945,8 @@ func appendLANSyncTrafficStat(message string, trafficStat *dejavu.TrafficStat) sfunc removeLANSyncTrafficStat(message string) string {const marker = `<br data-type="lanSyncTraffic">`- if index := strings.Index(message, marker); 0 <= index {- return message[:index]+ if before, _, ok := strings.Cut(message, marker); ok {+ return before}// 兼容已保存的无标记局域网流量统计。diff --git a/kernel/model/repository_range_test.go b/kernel/model/repository_range_test.goindex 3bb58ef153..2a6906d902 100644--- a/kernel/model/repository_range_test.go+++ b/kernel/model/repository_range_test.go@@ -21,7 +21,7 @@ func TestRepoSnapshotTimeRange(t *testing.T) {if err != nil {t.Fatal(err)}- for i := 0; i < 70; i++ {+ for i := range 70 {clone := *indexclone.ID = fmt.Sprintf("%040x", i+19943000)clone.Created = 1000 + int64(i)@@ -65,7 +65,7 @@ func TestCloudRepoSnapshotTimeRange(t *testing.T) {load := func(page int) ([]*dejavu.Log, int, int, error) {calls = append(calls, page)logs := []*dejavu.Log{}- for i := 0; i < 32; i++ {+ for i := range 32 {logs = append(logs, &dejavu.Log{Created: int64(1000 + (page-1)*32 + i)})}return logs, 3, 96, nildiff --git a/kernel/model/repository_types_count_test.go b/kernel/model/repository_types_count_test.goindex 928446aa19..5beb1a0bdd 100644--- a/kernel/model/repository_types_count_test.go+++ b/kernel/model/repository_types_count_test.go@@ -18,6 +18,7 @@ package modelimport ("fmt"+ "strings""testing""github.com/siyuan-note/dejavu/entity"@@ -26,7 +27,7 @@ import (// files 构造 counts 指定的文件列表:扩展名 -> 文件数。func files(counts map[string]int) (ret []*entity.File) {for ext, count := range counts {- for i := 0; i < count; i++ {+ for i := range count {ret = append(ret, &entity.File{Path: fmt.Sprintf("/assets/%s-%d.%s", ext, i, ext)})}}@@ -133,9 +134,9 @@ func TestStatTypesByPathNoExt(t *testing.T) {}func format(ret []*TypeCount) string {- s := ""+ var s strings.Builderfor _, tc := range ret {- s += fmt.Sprintf("%s=%d ", tc.Type, tc.Count)+ s.WriteString(fmt.Sprintf("%s=%d ", tc.Type, tc.Count))}- return s+ return s.String()}diff --git a/kernel/model/search.go b/kernel/model/search.goindex c38604b020..1592c190e6 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -22,6 +22,7 @@ import ("errors""fmt"stdhtml "html"+ "maps""math""os""path"@@ -1080,9 +1081,7 @@ func findReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,return}reloadTreeIDs = append(reloadTreeIDs, rootID)- for id, node := range pendingNodes[rootID] {- updateNodes[id] = node- }+ maps.Copy(updateNodes, pendingNodes[rootID])}return}@@ -1486,9 +1485,7 @@ func cloneReplaceTextNode(node *ast.Node) *ast.Node {ret.Tokens = bytes.Clone(node.Tokens)if nil != node.Properties {ret.Properties = map[string]string{}- for key, value := range node.Properties {- ret.Properties[key] = value- }+ maps.Copy(ret.Properties, node.Properties)}if nil != node.KramdownIAL {ret.KramdownIAL = make([][]string, len(node.KramdownIAL))diff --git a/kernel/model/search_attribute_view.go b/kernel/model/search_attribute_view.goindex 826252c60d..f6e1ca774b 100644--- a/kernel/model/search_attribute_view.go+++ b/kernel/model/search_attribute_view.go@@ -166,7 +166,7 @@ func mapAttributeViewSearchRanges(source, marked string) ([]attributeViewSearchR}var mapped []attributeViewSearchRangeoffset, after := 0, 0- for _, window := range strings.Split(plain, "...") {+ for window := range strings.SplitSeq(plain, "...") {var matches []attributeViewSearchRangefor _, match := range ranges {if offset <= match.start && match.end <= offset+len(window) {diff --git a/kernel/model/session_test.go b/kernel/model/session_test.goindex 325aa62f76..bf1f4f8154 100644--- a/kernel/model/session_test.go+++ b/kernel/model/session_test.go@@ -61,7 +61,7 @@ func TestAuthByAPITokenThrottle(t *testing.T) {t.Run("wrong tokens trigger lockout", func(t *testing.T) {ip := "192.0.2.11:1234"defer util.AuthThrottleReset(ip)- for i := 0; i < 5; i++ {+ for i := range 5 {if recorder := newRequest(ip, "wrong-token"); recorder.Code != http.StatusUnauthorized {t.Fatalf("guess %d status = %d, want %d", i+1, recorder.Code, http.StatusUnauthorized)}@@ -79,7 +79,7 @@ func TestAuthByAPITokenThrottle(t *testing.T) {t.Run("lockout is per IP", func(t *testing.T) {attackerIP := "192.0.2.12:1234"defer util.AuthThrottleReset(attackerIP)- for i := 0; i < 6; i++ {+ for i := range 6 {if recorder := newRequest(attackerIP, "wrong-token"); recorder.Code != http.StatusUnauthorized {t.Fatalf("guess %d status = %d, want %d", i+1, recorder.Code, http.StatusUnauthorized)}diff --git a/kernel/model/slash_frequent_test.go b/kernel/model/slash_frequent_test.goindex 7ae3609624..5dc35c924b 100644--- a/kernel/model/slash_frequent_test.go+++ b/kernel/model/slash_frequent_test.go@@ -2,6 +2,7 @@ package modelimport ("errors"+ "maps""reflect""testing"@@ -42,9 +43,7 @@ func TestMigrateSlashFrequent(t *testing.T) {} {t.Run(test.name, func(t *testing.T) {originalStorage := make(map[string]any, len(test.storage))- for key, value := range test.storage {- originalStorage[key] = value- }+ maps.Copy(originalStorage, test.storage)config := conf.NormalizeEntryVisibility(&conf.EntryVisibility{Version: conf.EntryVisibilityVersion,Active: "custom",diff --git a/kernel/model/sort_conf_append_test.go b/kernel/model/sort_conf_append_test.goindex 71f63a49eb..b64560ba24 100644--- a/kernel/model/sort_conf_append_test.go+++ b/kernel/model/sort_conf_append_test.go@@ -37,7 +37,7 @@ func TestSortConfAppendReadersObserveCompleteJSON(t *testing.T) {}}()defer func() { close(stop); <-done }()- for i := 0; i < 20; i++ {+ for i := range 20 {_, data, err := readSortConfMapData(confPath)if err != nil {t.Fatal(err)diff --git a/kernel/model/sync_error.go b/kernel/model/sync_error.goindex 366ec95656..47ab0c0ce9 100644--- a/kernel/model/sync_error.go+++ b/kernel/model/sync_error.go@@ -57,7 +57,7 @@ func safeCloudErrorHost(host string) bool {if nil != net.ParseIP(host) {return true}- for _, label := range strings.Split(strings.TrimSuffix(host, "."), ".") {+ for label := range strings.SplitSeq(strings.TrimSuffix(host, "."), ".") {if "" == label || 63 < len(label) || '-' == label[0] || '-' == label[len(label)-1] {return false}diff --git a/kernel/model/sync_plugin_rename_uninstall_test.go b/kernel/model/sync_plugin_rename_uninstall_test.goindex bd097ab70c..bcd4598757 100644--- a/kernel/model/sync_plugin_rename_uninstall_test.go+++ b/kernel/model/sync_plugin_rename_uninstall_test.go@@ -65,7 +65,7 @@ func lastReloadPluginsLog(t *testing.T) string {t.Fatal(err)}var line string- for _, l := range strings.Split(string(data), "\n") {+ for l := range strings.SplitSeq(string(data), "\n") {if strings.Contains(l, "reload plugins, uninstalls=") {line = strings.TrimSpace(l)}diff --git a/kernel/model/table_cell_rich_fts5_test.go b/kernel/model/table_cell_rich_fts5_test.goindex f1172f6eb2..e1c5bf2f61 100644--- a/kernel/model/table_cell_rich_fts5_test.go+++ b/kernel/model/table_cell_rich_fts5_test.go@@ -73,7 +73,7 @@ func TestTableCellRichUpgradeUndoRedo(t *testing.T) {t.Fatalf("unexpected restored table: %s, %#v", cell.Text(), cell.TableCellRich)}}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {for _, text := range []string{"edited", "initial"} {entry := GlobalUndoLog.Undo(fixture.sourceID)if entry == nil {diff --git a/kernel/model/template.go b/kernel/model/template.goindex d08f34dd42..8c0c873e10 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -703,7 +703,7 @@ func validateTemplateAttributeViewNode(node *ast.Node, attrView *av.AttributeViereturn}visibleViewCount := 0- for _, visibleViewID := range strings.Split(visibleViewIDs, ",") {+ for visibleViewID := range strings.SplitSeq(visibleViewIDs, ",") {visibleViewID = strings.TrimSpace(visibleViewID)if "" == visibleViewID {continue@@ -866,7 +866,7 @@ func applyTemplateAttributeViewPlan(node *ast.Node, plan *templateAttributeViewP}if visibleViewIDs := strings.TrimSpace(node.IALAttr(av.NodeAttrVisibleViewIDs)); "" != visibleViewIDs {var copiedVisibleViewIDs []string- for _, sourceViewID := range strings.Split(visibleViewIDs, ",") {+ for sourceViewID := range strings.SplitSeq(visibleViewIDs, ",") {sourceViewID = strings.TrimSpace(sourceViewID)if copiedViewID := plan.copiedViewIDs[sourceViewID]; "" != copiedViewID {copiedVisibleViewIDs = append(copiedVisibleViewIDs, copiedViewID)diff --git a/kernel/model/template_doc_tree_fts5_test.go b/kernel/model/template_doc_tree_fts5_test.goindex 7e81b93bf3..f47a5fbd49 100644--- a/kernel/model/template_doc_tree_fts5_test.go+++ b/kernel/model/template_doc_tree_fts5_test.go@@ -24,6 +24,7 @@ import ("os/exec""path/filepath""regexp"+ "slices""strings""testing""time"@@ -75,7 +76,6 @@ Child: .action{renderDocRef "path" "/资料"}`)t.Fatalf("unexpected document tree plan: %+v", summary)}for _, node := range summary.Nodes {- node := nodet.Cleanup(func() {cache.RemoveTreeData(node.ID)cache.RemoveDocIAL(node.path)@@ -177,7 +177,6 @@ func TestTemplateDocTreeTransactionFailureCleansCreatedDocuments(t *testing.T) {plan := value.(*templateDocTreePlan)plan.trees[len(plan.trees)-1].Path = "/\x00/invalid.sy"for _, node := range summary.Nodes {- node := nodet.Cleanup(func() {cache.RemoveTreeData(node.ID)cache.RemoveDocIAL(node.path)@@ -416,7 +415,6 @@ func cleanupTemplateDocTreeTestNodes(t *testing.T, fixture *fileOperationTestFixsummary *TemplateDocTreePlanSummary) {t.Helper()for _, node := range summary.Nodes {- node := nodet.Cleanup(func() {cache.RemoveTreeData(node.ID)cache.RemoveDocIAL(node.path)@@ -529,10 +527,8 @@ func assertTemplateDocTreeApplied(t *testing.T, fixture *fileOperationTestFixturfunc assertTemplateDocTreeRef(t *testing.T, tree *parse.Tree, defID, source string) {t.Helper()- for _, id := range getRefDefIDs(tree.Root) {- if defID == id {- return- }+ if slices.Contains(getRefDefIDs(tree.Root), defID) {+ return}t.Fatalf("%s block reference to planned document [%s] was degraded", source, defID)}diff --git a/kernel/model/template_doc_tree_test.go b/kernel/model/template_doc_tree_test.goindex b913300320..282dcbc663 100644--- a/kernel/model/template_doc_tree_test.go+++ b/kernel/model/template_doc_tree_test.go@@ -697,7 +697,7 @@ func nestedTemplateDocTreeDefinition(depth int) []any {func templateCallChainForTest(t *testing.T, depth int) *template.Template {t.Helper()var source strings.Builder- for index := 0; index < depth; index++ {+ for index := range depth {fmt.Fprintf(&source, `.action{define "call-%d"}`, index)if index+1 < depth {fmt.Fprintf(&source, `.action{template "call-%d" .}`, index+1)diff --git a/kernel/model/template_export_attrs.go b/kernel/model/template_export_attrs.goindex bc7bce63a5..56b778f892 100644--- a/kernel/model/template_export_attrs.go+++ b/kernel/model/template_export_attrs.go@@ -19,6 +19,7 @@ package modelimport ("bytes""errors"+ "slices""strings""github.com/88250/lute/ast"@@ -135,8 +136,8 @@ func templateDocumentAttributes(source []byte) [][]string {attrs := parseTemplateDocumentAttributes(masked.String())for _, attr := range attrs {// 长占位符优先替换,避免前缀相同的动作相互覆盖。- for i := len(actions) - 1; i >= 0; i-- {- attr[1] = strings.ReplaceAll(attr[1], prefix+strings.Repeat("x", i+1), actions[i])+ for i, action := range slices.Backward(actions) {+ attr[1] = strings.ReplaceAll(attr[1], prefix+strings.Repeat("x", i+1), action)}}return attrsdiff --git a/kernel/model/template_manage.go b/kernel/model/template_manage.goindex 8094974b3a..cfdf1eea06 100644--- a/kernel/model/template_manage.go+++ b/kernel/model/template_manage.go@@ -61,7 +61,7 @@ func validateTemplateRelativePath(p string, allowRoot bool) error {if p == "" || !fs.ValidPath(p) || strings.ContainsAny(p, "\\:\x00") {return errors.New("invalid template path")}- for _, part := range strings.Split(p, "/") {+ for part := range strings.SplitSeq(p, "/") {if strings.HasPrefix(part, ".") {return errors.New("hidden template paths are reserved")}diff --git a/kernel/model/template_test.go b/kernel/model/template_test.goindex 97d48eb380..5663b3faac 100644--- a/kernel/model/template_test.go+++ b/kernel/model/template_test.go@@ -19,6 +19,7 @@ import ("fmt""os""path/filepath"+ "slices""strings""testing"@@ -200,12 +201,7 @@ func attributeViewFileCount(t *testing.T) int {}func containsString(values []string, expected string) bool {- for _, value := range values {- if value == expected {- return true- }- }- return false+ return slices.Contains(values, expected)}func TestTemplateDatabaseReferencePreservesViews(t *testing.T) {diff --git a/kernel/model/transaction_block_swap_fts5_test.go b/kernel/model/transaction_block_swap_fts5_test.goindex 6e74431eab..f9c3e9d820 100644--- a/kernel/model/transaction_block_swap_fts5_test.go+++ b/kernel/model/transaction_block_swap_fts5_test.go@@ -187,7 +187,7 @@ func testBlockSwapTransactionUndoRedo(t *testing.T, kind string, sameTree, childif err != nil || strings.Contains(string(data), "Secret definition") {t.Fatalf("undo snapshots leaked into response: %s, %v", data, err)}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {replay := &Transaction{DoOperations: entry.UndoOperationsForReplay()}replay.MarkReplay()if err = PerformTxSync(replay); err != nil {diff --git a/kernel/model/transaction_cancel_list_fts5_test.go b/kernel/model/transaction_cancel_list_fts5_test.goindex 7206908aff..b5acbf90f7 100644--- a/kernel/model/transaction_cancel_list_fts5_test.go+++ b/kernel/model/transaction_cancel_list_fts5_test.go@@ -124,7 +124,7 @@ func TestListConversionFrontendTransactions(t *testing.T) {}assertAttributeViewFieldsTest(t, view, readAttributeViewItemsTest(t, view.ID))}- for cycle := 0; cycle < 2; cycle++ {+ for range 2 {check(testCase.After)replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())check(testCase.Before)@@ -217,7 +217,7 @@ func TestCancelListPreservesDatabaseFields(t *testing.T) {}}}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {check(false)replayAttributeViewFieldsTest(t, entry.UndoOperationsForReplay())check(true)diff --git a/kernel/model/transaction_completion_test.go b/kernel/model/transaction_completion_test.goindex 69c4f8b559..2b6a062d45 100644--- a/kernel/model/transaction_completion_test.go+++ b/kernel/model/transaction_completion_test.go@@ -191,7 +191,7 @@ func TestTransactionCompletionOnAllExecutionExits(t *testing.T) {func TestTransactionCompletionRepeatedSyncExecution(t *testing.T) {tx := &Transaction{}- for i := 0; i < 2; i++ {+ for range 2 {if err := PerformTxSync(tx); err != nil {t.Fatal(err)}diff --git a/kernel/model/transaction_list_conversion.go b/kernel/model/transaction_list_conversion.goindex 664970ba42..6d6912ae3f 100644--- a/kernel/model/transaction_list_conversion.go+++ b/kernel/model/transaction_list_conversion.go@@ -320,8 +320,8 @@ func (tx *Transaction) prepareListConversionBindings(originals []*parse.Tree, trif !deleting {return ast.WalkContinue}- avIDs := strings.Split(source.IALAttr(av.NodeAttrNameAvs), ",")- for _, avID := range avIDs {+ avIDs := strings.SplitSeq(source.IALAttr(av.NodeAttrNameAvs), ",")+ for avID := range avIDs {if avID == "" {continue}diff --git a/kernel/model/transaction_list_conversion_fts5_test.go b/kernel/model/transaction_list_conversion_fts5_test.goindex c3902bce2c..5672736770 100644--- a/kernel/model/transaction_list_conversion_fts5_test.go+++ b/kernel/model/transaction_list_conversion_fts5_test.go@@ -108,7 +108,7 @@ func TestListConversionBindingReplay(t *testing.T) {if strings.Contains(string(encoded), "Static primary") {t.Fatal("private binding snapshot leaked")}- for cycle := 0; cycle < 3; cycle++ {+ for range 3 {current := readAttributeViewItemsTest(t, view.ID)assertListConversionFields(t, view, current)for i, id := range targets {@@ -368,7 +368,7 @@ func TestAttributeViewGroupRegenerationIdentity(t *testing.T) {if err != nil {t.Fatal(err)}- for cycle := 0; cycle < 10; cycle++ {+ for range 10 {regenAttrViewGroups(view)for i, v := range view.Views {for j, group := range v.Groups {diff --git a/kernel/model/transaction_list_item_fold_test.go b/kernel/model/transaction_list_item_fold_test.goindex 57ede1b967..849b8b420b 100644--- a/kernel/model/transaction_list_item_fold_test.go+++ b/kernel/model/transaction_list_item_fold_test.go@@ -18,7 +18,7 @@ func newFoldedListItemTree(blockCount int, task bool) (*parse.Tree, *ast.Node) {item.ListData.Typ = 3item.AppendChild(&ast.Node{Type: ast.NodeTaskListItemMarker})}- for i := 0; i < blockCount; i++ {+ for i := range blockCount {item.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: fmt.Sprintf("20260729000000-block%03d", i)})}item.AppendChild(&ast.Node{Type: ast.NodeKramdownBlockIAL})diff --git a/kernel/model/transaction_move_next_fts5_test.go b/kernel/model/transaction_move_next_fts5_test.goindex 4c582feb50..d7c6dacb22 100644--- a/kernel/model/transaction_move_next_fts5_test.go+++ b/kernel/model/transaction_move_next_fts5_test.go@@ -60,7 +60,7 @@ func TestMoveNextIDOrderAndReplay(t *testing.T) {{Action: "move", ID: first, NextID: end},{Action: "move", ID: second, NextID: end},}}- for step := 0; step < 3; step++ {+ for step := range 3 {tx := forwardif step == 1 {tx = &Transaction{DoOperations: cloneOperations(forward.UndoOperations)}diff --git a/kernel/model/tree_notification_test.go b/kernel/model/tree_notification_test.goindex becc816545..070bda5130 100644--- a/kernel/model/tree_notification_test.go+++ b/kernel/model/tree_notification_test.go@@ -24,14 +24,12 @@ func TestClosedBoxNotification(t *testing.T) {})var count atomic.Int32var group sync.WaitGroup- for i := 0; i < 32; i++ {- group.Add(1)- go func() {- defer group.Done()+ for range 32 {+ group.Go(func() {if markClosedBoxNotification("first") {count.Add(1)}- }()+ })}group.Wait()if count.Load() != 1 {diff --git a/kernel/model/undolog.go b/kernel/model/undolog.goindex 855ee2ff2d..80e8ff0f33 100644--- a/kernel/model/undolog.go+++ b/kernel/model/undolog.go@@ -18,6 +18,7 @@ package modelimport ("fmt"+ "maps""regexp""slices""sync"@@ -433,9 +434,7 @@ func cloneOperations(ops []*Operation) []*Operation {cloned.BlockIDs = cloneOperationBlockIDs(op.BlockIDs)if nil != op.Context {cloned.Context = make(map[string]any, len(op.Context))- for key, value := range op.Context {- cloned.Context[key] = value- }+ maps.Copy(cloned.Context, op.Context)}ret[i] = &cloned}diff --git a/kernel/model/updater_link_windows.go b/kernel/model/updater_link_windows.goindex 5b6cda979b..f81ff5c204 100644--- a/kernel/model/updater_link_windows.go+++ b/kernel/model/updater_link_windows.go@@ -17,8 +17,8 @@ func createInstallPackageDirectoryLink(target, link string) (err error) {return err}name := "\\??\\" + target- if strings.HasPrefix(target, "\\\\") {- name = "\\??\\UNC\\" + strings.TrimPrefix(target, "\\\\")+ if after, ok := strings.CutPrefix(target, "\\\\"); ok {+ name = "\\??\\UNC\\" + after}substitute, err := windows.UTF16FromString(name)if err != nil {diff --git a/kernel/model/updater_ready_diagnostics.go b/kernel/model/updater_ready_diagnostics.goindex ea8c3cccbe..4395e240b5 100644--- a/kernel/model/updater_ready_diagnostics.go+++ b/kernel/model/updater_ready_diagnostics.go@@ -29,8 +29,7 @@ func readyInstallPackageFailureReason(err error) string {// JSON 类型错误可能包含字段原文,诊断只记录固定分类。return "invalid install package metadata JSON"}- var pathError *os.PathError- if errors.As(err, &pathError) {+ if pathError, ok := errors.AsType[*os.PathError](err); ok {return fmt.Sprintf("%s failed: %s", pathError.Op, pathError.Err)}return err.Error()diff --git a/kernel/model/updater_ready_diagnostics_test.go b/kernel/model/updater_ready_diagnostics_test.goindex 9cc5b431d4..8bb56d5fe1 100644--- a/kernel/model/updater_ready_diagnostics_test.go+++ b/kernel/model/updater_ready_diagnostics_test.go@@ -31,7 +31,7 @@ func TestReadyInstallPackageDiagnosticsDoNotExposeMetadata(t *testing.T) {func TestReadyInstallPackageDiagnosticLimit(t *testing.T) {diagnostics := readyInstallPackageDiagnostics{}- for i := 0; i < 8; i++ {+ for i := range 8 {message := diagnostics.rejected("package\nname.json", errors.New("metadata authentication failed"))if i < readyInstallPackageDiagnosticLimit {if !strings.Contains(message, "metadata authentication failed") || strings.Contains(message, "\n") {diff --git a/kernel/model/updater_release.go b/kernel/model/updater_release.goindex c01e68d2e2..3a9fd93d22 100644--- a/kernel/model/updater_release.go+++ b/kernel/model/updater_release.go@@ -291,7 +291,7 @@ func isReleaseAllowed(channel, version string) bool {}func prereleaseChannelLabel(prerelease string) string {- identifier := strings.SplitN(prerelease, ".", 2)[0]+ identifier, _, _ := strings.Cut(prerelease, ".")for _, channel := range []string{"alpha", "beta", "rc"} {if channel == identifier {return channel@@ -415,7 +415,7 @@ func getGitHubManifestChecksum(ctx context.Context, release *githubRelease, pkgN}func parseChecksumManifest(manifest, pkgName string) string {- for _, line := range strings.Split(manifest, "\n") {+ for line := range strings.SplitSeq(manifest, "\n") {fields := strings.Fields(line)if 2 > len(fields) {continuediff --git a/kernel/model/view_state.go b/kernel/model/view_state.goindex f702456c61..43b9b04e9b 100644--- a/kernel/model/view_state.go+++ b/kernel/model/view_state.go@@ -19,6 +19,7 @@ package modelimport ("errors""fmt"+ "maps""math""os""path/filepath"@@ -126,9 +127,7 @@ func PatchViewState(key string, values map[string]any, removeKeys []string) (ret} else if nil == state.Data {state.Data = map[string]any{}}- for valueKey, value := range values {- state.Data[valueKey] = value- }+ maps.Copy(state.Data, values)for _, removeKey := range removeKeys {delete(state.Data, removeKey)}diff --git a/kernel/model/view_state_test.go b/kernel/model/view_state_test.goindex 5296d31caa..ae5809adbe 100644--- a/kernel/model/view_state_test.go+++ b/kernel/model/view_state_test.go@@ -128,7 +128,7 @@ func TestPatchViewStateConcurrently(t *testing.T) {const count = 32errs := make(chan error, count)var waitGroup sync.WaitGroup- for i := 0; i < count; i++ {+ for i := range count {waitGroup.Add(1)go func(index int) {defer waitGroup.Done()@@ -210,7 +210,7 @@ func TestLoadViewStateAppliesLimits(t *testing.T) {})views := map[string]*ViewState{}- for i := 0; i < maxViewStateCount+2; i++ {+ for i := range maxViewStateCount + 2 {views[fmt.Sprintf("view-%04d", i)] = &ViewState{Updated: int64(i),Data: map[string]any{"value": i},@@ -219,7 +219,7 @@ func TestLoadViewStateAppliesLimits(t *testing.T) {latest := views[fmt.Sprintf("view-%04d", maxViewStateCount+1)]latest.Data = map[string]any{}latest.Order = []string{}- for i := 0; i < maxViewStateDataCount+2; i++ {+ for i := range maxViewStateDataCount + 2 {key := fmt.Sprintf("field-%05d", i)latest.Data[key] = ilatest.Order = append(latest.Order, key)@@ -328,7 +328,7 @@ func oversizedViewStateStorage() *viewStateStorage {func TestPruneViewStates(t *testing.T) {views := map[string]*ViewState{}- for i := 0; i < maxViewStateCount+2; i++ {+ for i := range maxViewStateCount + 2 {views[fmt.Sprintf("view-%04d", i)] = &ViewState{Updated: int64(i), Data: map[string]any{"value": i}}}pruneViewStates(views)@@ -353,7 +353,7 @@ func TestNextViewStateUpdatedRebasesOverflow(t *testing.T) {func TestPruneViewStateFieldsUsesFieldOrder(t *testing.T) {state := &ViewState{Data: map[string]any{}, Order: []string{}}- for i := 0; i < maxViewStateDataCount+2; i++ {+ for i := range maxViewStateDataCount + 2 {key := fmt.Sprintf("field-%05d", i)state.Data[key] = istate.Order = append(state.Order, key)diff --git a/kernel/ocr/boxes.go b/kernel/ocr/boxes.goindex f96c83e82b..d20d8f9f05 100644--- a/kernel/ocr/boxes.go+++ b/kernel/ocr/boxes.go@@ -203,8 +203,8 @@ func cropBox(img image.Image, box textBox) image.Image {ix, iy := int(math.Floor(sx)), int(math.Floor(sy))fx, fy := sx-float64(ix), sy-float64(iy)var channels [4]float64- for dy := 0; dy < 2; dy++ {- for dx := 0; dx < 2; dx++ {+ for dy := range 2 {+ for dx := range 2 {weight := ((1-fx)*float64(1-dx) + fx*float64(dx)) * ((1-fy)*float64(1-dy) + fy*float64(dy))pixel := source.NRGBAAt(max(0, min(source.Bounds().Dx()-1, ix+dx)), max(0, min(source.Bounds().Dy()-1, iy+dy)))for c, value := range [4]uint8{pixel.R, pixel.G, pixel.B, pixel.A} {diff --git a/kernel/ocr/paddle.go b/kernel/ocr/paddle.goindex 82385d91b8..aa5052c28f 100644--- a/kernel/ocr/paddle.go+++ b/kernel/ocr/paddle.go@@ -388,8 +388,8 @@ func imageTensor(img image.Image, w, h int, detector bool) []float32 {resized := imaging.Resize(img, w, h, imaging.Linear)data := make([]float32, 3*w*h)mean, std := [3]float32{.485, .456, .406}, [3]float32{.229, .224, .225}- for y := 0; y < h; y++ {- for x := 0; x < w; x++ {+ for y := range h {+ for x := range w {pixel := resized.NRGBAAt(x, y)channels := [3]uint8{pixel.B, pixel.G, pixel.R}for c, value := range channels {@@ -410,8 +410,8 @@ func recognitionTensor(img image.Image, width int) []float32 {w := min(width, max(1, int(math.Ceil(float64(img.Bounds().Dx())*48/float64(img.Bounds().Dy())))))resized := imageTensor(img, w, 48, false)result := make([]float32, 3*48*width)- for c := 0; c < 3; c++ {- for y := 0; y < 48; y++ {+ for c := range 3 {+ for y := range 48 {copy(result[c*48*width+y*width:c*48*width+y*width+w], resized[c*48*w+y*w:c*48*w+(y+1)*w])}}diff --git a/kernel/ocr/provider_test.go b/kernel/ocr/provider_test.goindex 40568b04af..ce471b6de9 100644--- a/kernel/ocr/provider_test.go+++ b/kernel/ocr/provider_test.go@@ -22,7 +22,6 @@ func (p *testProvider) Recognize(ctx context.Context, path string) ([]map[stringfunc TestProviderSelection(t *testing.T) {r := NewRegistry()for _, id := range []ProviderID{Tesseract, PaddleOCR} {- id := idif err := r.Register(id, &testProvider{available: true,recognize: func(_ context.Context, path string) ([]map[string]string, error) {diff --git a/kernel/plugin/abort/controller.go b/kernel/plugin/abort/controller.goindex e2287b61a5..43709456f8 100644--- a/kernel/plugin/abort/controller.go+++ b/kernel/plugin/abort/controller.go@@ -37,7 +37,7 @@ func (c *controllerState) Keys() []string { return nil }// controllerStateType 用于在 Object.Export() 前用 Object.ExportType() 做判定,原因见 signalStateType// 的注释:AbortController.prototype 本身作为 receiver 时,直接 Export() 会因 signal 访问器无限递归。-var controllerStateType = reflect.TypeOf((*controllerState)(nil))+var controllerStateType = reflect.TypeFor[*controllerState]()// Enable 把 AbortController 与 AbortSignal 挂到 runtime 的 globalThis,调用方式与// url、buffer、console、encoding 一致,失败时 panic。@@ -107,10 +107,7 @@ func newSignalConstructor(rt *goja.Runtime, prototype *goja.Object) (*goja.Objec// AbortSignal.timeout(milliseconds) -> 到时后以 TimeoutError 中止的新信号。if err := ctor.Set("timeout", rt.ToValue(func(call goja.FunctionCall) goja.Value {- milliseconds := call.Argument(0).ToInteger()- if milliseconds < 0 {- milliseconds = 0- }+ milliseconds := max(call.Argument(0).ToInteger(), 0)state := &SignalState{}object := newSignalObject(rt, prototype, state)@@ -165,7 +162,7 @@ func signalArrayOf(rt *goja.Runtime, value goja.Value) []*SignalState {length := int64(object.Get("length").ToInteger())states := make([]*SignalState, 0, length)- for i := int64(0); i < length; i++ {+ for i := range length {state, err := SignalOf(rt, object.Get(fmt.Sprint(i)), fmt.Sprintf("signals[%d]", i))if err != nil {panic(rt.NewTypeError(err.Error()))diff --git a/kernel/plugin/abort/signal.go b/kernel/plugin/abort/signal.goindex e769b24a96..9c8fd9f10c 100644--- a/kernel/plugin/abort/signal.go+++ b/kernel/plugin/abort/signal.go@@ -31,7 +31,7 @@ import (// 对动态对象返回宿主类型,都不会访问任何属性;而 Object.Export() 对普通对象会遍历其所有自有可枚举属性并调用// 它们的访问器:当接收者是 AbortSignal.prototype 本身时(aborted 等访问器就定义在它自己身上),直接 Export()// 会再次进入这些访问器而无限递归,因此必须先用 ExportType() 过滤。-var signalStateType = reflect.TypeOf((*SignalState)(nil))+var signalStateType = reflect.TypeFor[*SignalState]()// signalListener 是 addEventListener("abort", ...) 登记的一个监听器。type signalListener struct {diff --git a/kernel/plugin/api_agent.go b/kernel/plugin/api_agent.goindex af9e295135..fdc4c9d968 100644--- a/kernel/plugin/api_agent.go+++ b/kernel/plugin/api_agent.go@@ -20,6 +20,7 @@ import ("crypto/sha256""encoding/json""fmt"+ "maps""strings""github.com/dop251/goja"@@ -206,9 +207,7 @@ func bindAgentRegisterCapability(p *KernelPlugin, rt *goja.Runtime, agentAPI *gofullToolName := pluginCapabilityModelName(p.Name, name)declaredActionEffects := make(map[string]tools.ToolEffects, len(actionEffects)+1)- for action, actionEffect := range actionEffects {- declaredActionEffects[action] = actionEffect- }+ maps.Copy(declaredActionEffects, actionEffects)if effects != nil {declaredActionEffects[""] = *effects}diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.goindex daef954a13..24f93de092 100644--- a/kernel/plugin/api_client.go+++ b/kernel/plugin/api_client.go@@ -567,7 +567,7 @@ func bindClientSocket(p *KernelPlugin, rt *goja.Runtime, client *goja.Object) {var openOnce sync.Oncevar openPromises []Promise- addOpenPromise := func(resolve, reject func(reason interface{}) error) {+ addOpenPromise := func(resolve, reject func(reason any) error) {// nil slice 也可以直接 appendopenPromises = append(openPromises, Promise{Resolve: resolve, Reject: reject})}diff --git a/kernel/plugin/crypto/aes.go b/kernel/plugin/crypto/aes.goindex 43d3a4397f..9e5e140f67 100644--- a/kernel/plugin/crypto/aes.go+++ b/kernel/plugin/crypto/aes.go@@ -23,6 +23,7 @@ import ("crypto/rand""crypto/subtle""math/big"+ "slices")// aesKeyLengths 是 AES 允许的密钥位长。@@ -54,7 +55,7 @@ func generateAESKey(alg Algorithm, extractable bool, usages []KeyUsage) (*Key, eType: KeyTypeSecret,Extractable: extractable,Usages: cloneUsages(usages),- Algorithm: KeyAlgorithm{Name: alg.Name, Length: intPtr(*alg.Length)},+ Algorithm: KeyAlgorithm{Name: alg.Name, Length: new(*alg.Length)},secret: secret,}, nil}@@ -71,7 +72,7 @@ func importAESKey(alg Algorithm, secret []byte, extractable bool, usages []KeyUsType: KeyTypeSecret,Extractable: extractable,Usages: cloneUsages(usages),- Algorithm: KeyAlgorithm{Name: alg.Name, Length: intPtr(length)},+ Algorithm: KeyAlgorithm{Name: alg.Name, Length: new(length)},secret: bytes.Clone(secret),}, nil}@@ -293,7 +294,7 @@ func unpadPKCS7(algName string, data []byte, blockSize int) ([]byte, error) {valid := subtle.ConstantTimeLessOrEq(1, padding) & subtle.ConstantTimeLessOrEq(padding, blockSize)// 密文长度是分组长度的整数倍,因此始终比较整个末尾分组,填充字节数不合法时结果必然不匹配。- for i := 0; i < blockSize; i++ {+ for i := range blockSize {expected := subtle.ConstantTimeLessOrEq(i+1, padding)matched := subtle.ConstantTimeByteEq(data[len(data)-1-i], byte(padding))valid &= matched | (1 ^ expected)@@ -306,10 +307,5 @@ func unpadPKCS7(algName string, data []byte, blockSize int) ([]byte, error) {}func containsInt(values []int, value int) bool {- for _, cur := range values {- if cur == value {- return true- }- }- return false+ return slices.Contains(values, value)}diff --git a/kernel/plugin/crypto/aes_test.go b/kernel/plugin/crypto/aes_test.goindex 912297ab0b..61cfd0d81c 100644--- a/kernel/plugin/crypto/aes_test.go+++ b/kernel/plugin/crypto/aes_test.go@@ -84,7 +84,7 @@ func TestAESGCMTagLength(t *testing.T) {// 96 到 128 位的标签长度按请求长度生效。for _, tagLength := range []int{96, 104, 112, 120, 128} {- alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(tagLength)}+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: new(tagLength)}ciphertext, err := Encrypt(alg, key, []byte("x"))if err != nil {t.Fatalf("tagLength %d: %v", tagLength, err)@@ -96,14 +96,14 @@ func TestAESGCMTagLength(t *testing.T) {// Go 不支持 32、64 位标签,按设计返回 NotSupportedError。for _, tagLength := range []int{32, 64} {- alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(tagLength)}+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: new(tagLength)}if _, err := Encrypt(alg, key, []byte("x")); errorName(t, err) != ErrNameNotSupported {t.Fatalf("tagLength %d: error = %v, want NotSupportedError", tagLength, err)}}// 其他取值不符合规范,返回 OperationError。- alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: intPtr(100)}+ alg := Algorithm{Name: AlgAESGCM, IV: iv, TagLength: new(100)}if _, err := Encrypt(alg, key, []byte("x")); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}@@ -125,7 +125,7 @@ func TestAESGCMNonStandardIVRequiresFullTag(t *testing.T) {t.Fatalf("plaintext = %q, want %q", plaintext, "data")}- alg.TagLength = intPtr(96)+ alg.TagLength = new(96)if _, err = Encrypt(alg, key, []byte("data")); errorName(t, err) != ErrNameNotSupported {t.Fatalf("error = %v, want NotSupportedError", err)}@@ -211,7 +211,7 @@ func TestAESCTRMatchesStandardLibraryWithoutWrap(t *testing.T) {data := bytes.Repeat([]byte{0xab}, 64)// 计数器从 0 开始且不回绕时,结果与标准库一致。- alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: intPtr(64)}+ alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: new(64)}got, err := Encrypt(alg, key, data)if err != nil {t.Fatal(err)@@ -243,7 +243,7 @@ func TestAESCTRWrapsWithinCounterBits(t *testing.T) {counter[aes.BlockSize-1] = 0x03data := bytes.Repeat([]byte{0}, 4*aes.BlockSize)- alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: intPtr(2)}+ alg := Algorithm{Name: AlgAESCTR, Counter: counter, Length: new(2)}got, err := Encrypt(alg, key, data)if err != nil {t.Fatal(err)@@ -274,7 +274,7 @@ func TestAESCTRWrapsWithinCounterBits(t *testing.T) {func TestAESCTRRejectsTooSmallCounterSpace(t *testing.T) {key := newSecretKey(AlgAESCTR, "", bytes.Repeat([]byte{6}, 16), UsageEncrypt, UsageDecrypt)- alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: intPtr(1)}+ alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: new(1)}// 计数空间为 2 个分组,3 个分组的数据会导致计数器重复。data := bytes.Repeat([]byte{0}, 3*aes.BlockSize)@@ -287,7 +287,7 @@ func TestAESCTRRejectsInvalidParameters(t *testing.T) {key := newSecretKey(AlgAESCTR, "", bytes.Repeat([]byte{6}, 16), UsageEncrypt, UsageDecrypt)// counter 必须是 16 字节。- short := Algorithm{Name: AlgAESCTR, Counter: make([]byte, 8), Length: intPtr(64)}+ short := Algorithm{Name: AlgAESCTR, Counter: make([]byte, 8), Length: new(64)}if _, err := Encrypt(short, key, []byte("data")); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}@@ -300,7 +300,7 @@ func TestAESCTRRejectsInvalidParameters(t *testing.T) {// length 超出 1 到 128 的范围。for _, length := range []int{0, 129} {- alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: intPtr(length)}+ alg := Algorithm{Name: AlgAESCTR, Counter: make([]byte, aes.BlockSize), Length: new(length)}if _, err := Encrypt(alg, key, []byte("data")); errorName(t, err) != ErrNameOperation {t.Fatalf("length %d: error = %v, want OperationError", length, err)}diff --git a/kernel/plugin/crypto/algorithm.go b/kernel/plugin/crypto/algorithm.goindex 6edaf81571..ed38361c58 100644--- a/kernel/plugin/crypto/algorithm.go+++ b/kernel/plugin/crypto/algorithm.go@@ -16,7 +16,10 @@package crypto-import "strings"+import (+ "slices"+ "strings"+)// 受支持的算法名称,取值与 Web Crypto 规范一致。const (@@ -167,10 +170,8 @@ func checkFormat(algName string, format KeyFormat) error {return notSupportedError("%s keys cannot be imported or exported", algName)}- for _, cur := range formats {- if cur == format {- return nil- }+ if slices.Contains(formats, format) {+ return nil}return notSupportedError("%s keys do not support the %s format", algName, format)}diff --git a/kernel/plugin/crypto/asymmetric_test.go b/kernel/plugin/crypto/asymmetric_test.goindex c2bc9b396a..72a70b09cf 100644--- a/kernel/plugin/crypto/asymmetric_test.go+++ b/kernel/plugin/crypto/asymmetric_test.go@@ -29,9 +29,9 @@ func TestSignVerifyRoundTrip(t *testing.T) {alg Algorithm}{{"RSASSA-PKCS1-v1_5", Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}},+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}},{"RSA-PSS", Algorithm{Name: AlgRSAPSS, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}, SaltLength: intPtr(32)}},+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}, SaltLength: new(32)}},{"ECDSA P-256", Algorithm{Name: AlgECDSA, Hash: AlgSHA256, NamedCurve: CurveP256}},{"ECDSA P-384", Algorithm{Name: AlgECDSA, Hash: AlgSHA384, NamedCurve: CurveP384}},{"ECDSA P-521", Algorithm{Name: AlgECDSA, Hash: AlgSHA512, NamedCurve: CurveP521}},@@ -99,7 +99,7 @@ func TestECDSASignatureIsFixedLength(t *testing.T) {}// 多次签名长度必须恒定,不能随 r、s 的前导零变化。- for i := 0; i < 8; i++ {+ for i := range 8 {signature, signErr := Sign(alg, pair.PrivateKey, []byte{byte(i)})if signErr != nil {t.Fatalf("%s: %v", curve, signErr)@@ -117,7 +117,7 @@ func TestECDSASignatureIsFixedLength(t *testing.T) {func TestRSAOAEPRoundTrip(t *testing.T) {alg := Algorithm{Name: AlgRSAOAEP, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}pair, err := GenerateKey(alg, true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {@@ -165,7 +165,7 @@ func TestRSAOAEPRoundTrip(t *testing.T) {func TestRSALimits(t *testing.T) {base := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}usages := []KeyUsage{UsageSign, UsageVerify}// 公开指数只支持 65537。@@ -177,7 +177,7 @@ func TestRSALimits(t *testing.T) {// 模数长度下限。short := base- short.ModulusLength = intPtr(512)+ short.ModulusLength = new(512)if _, err := GenerateKey(short, true, usages); errorName(t, err) != ErrNameNotSupported {t.Fatalf("error = %v, want NotSupportedError", err)}@@ -190,13 +190,13 @@ func TestRSALimits(t *testing.T) {// RSA-PSS 的零长度盐无法用 Go 表达。pssAlg := Algorithm{Name: AlgRSAPSS, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}pair, err := GenerateKey(pssAlg, true, usages)if err != nil {t.Fatal(err)}zeroSalt := pssAlg- zeroSalt.SaltLength = intPtr(0)+ zeroSalt.SaltLength = new(0)if _, err = Sign(zeroSalt, pair.PrivateKey, []byte("data")); errorName(t, err) != ErrNameNotSupported {t.Fatalf("error = %v, want NotSupportedError", err)}@@ -228,11 +228,11 @@ func TestECDHDeriveBits(t *testing.T) {bobAlg := algbobAlg.Public = alice.PublicKey- fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, intPtr(256))+ fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, new(256))if err != nil {t.Fatalf("%s: %v", curve, err)}- fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, intPtr(256))+ fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, new(256))if err != nil {t.Fatalf("%s: %v", curve, err)}@@ -250,7 +250,7 @@ func TestECDHDeriveBits(t *testing.T) {}// 请求超过共享密钥长度必须报错。- if _, err = DeriveBits(aliceAlg, alice.PrivateKey, intPtr(len(full)*8+8)); errorName(t, err) != ErrNameOperation {+ if _, err = DeriveBits(aliceAlg, alice.PrivateKey, new(len(full)*8+8)); errorName(t, err) != ErrNameOperation {t.Fatalf("%s: error = %v, want OperationError", curve, err)}}@@ -272,11 +272,11 @@ func TestX25519DeriveBits(t *testing.T) {bobAlg := algbobAlg.Public = alice.PublicKey- fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, intPtr(256))+ fromAlice, err := DeriveBits(aliceAlg, alice.PrivateKey, new(256))if err != nil {t.Fatal(err)}- fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, intPtr(256))+ fromBob, err := DeriveBits(bobAlg, bob.PrivateKey, new(256))if err != nil {t.Fatal(err)}@@ -308,19 +308,19 @@ func TestECDHRejectsMismatchedPublicKey(t *testing.T) {// 曲线不一致。mismatched := p256mismatched.Public = other.PublicKey- if _, err = DeriveBits(mismatched, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameInvalidAccess {+ if _, err = DeriveBits(mismatched, alice.PrivateKey, new(128)); errorName(t, err) != ErrNameInvalidAccess {t.Fatalf("error = %v, want InvalidAccessError", err)}// 算法不一致。wrongAlg := p256wrongAlg.Public = x25519.PublicKey- if _, err = DeriveBits(wrongAlg, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameInvalidAccess {+ if _, err = DeriveBits(wrongAlg, alice.PrivateKey, new(128)); errorName(t, err) != ErrNameInvalidAccess {t.Fatalf("error = %v, want InvalidAccessError", err)}// 缺少 public 成员。- if _, err = DeriveBits(p256, alice.PrivateKey, intPtr(128)); errorName(t, err) != ErrNameType {+ if _, err = DeriveBits(p256, alice.PrivateKey, new(128)); errorName(t, err) != ErrNameType {t.Fatalf("error = %v, want TypeError", err)}}@@ -339,7 +339,7 @@ func TestECDHDeriveKey(t *testing.T) {derive := algderive.Public = bob.PublicKeykey, err := DeriveKey(derive, alice.PrivateKey,- Algorithm{Name: AlgAESGCM, Length: intPtr(256)}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})+ Algorithm{Name: AlgAESGCM, Length: new(256)}, true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatal(err)}@@ -393,12 +393,12 @@ func TestAESKWRFC3394(t *testing.T) {}func TestAESKWWrapUnwrapKey(t *testing.T) {- wrappingKey, err := GenerateKey(Algorithm{Name: AlgAESKW, Length: intPtr(256)},+ wrappingKey, err := GenerateKey(Algorithm{Name: AlgAESKW, Length: new(256)},true, []KeyUsage{UsageWrapKey, UsageUnwrapKey})if err != nil {t.Fatal(err)}- target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: intPtr(128)},+ target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: new(128)},true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatal(err)diff --git a/kernel/plugin/crypto/crypto_test.go b/kernel/plugin/crypto/crypto_test.goindex ed89bc609d..06b99d2962 100644--- a/kernel/plugin/crypto/crypto_test.go+++ b/kernel/plugin/crypto/crypto_test.go@@ -134,7 +134,7 @@ func TestHKDFRFC5869(t *testing.T) {Info: mustHex(t, "f0f1f2f3f4f5f6f7f8f9"),}- got, err := DeriveBits(alg, key, intPtr(42*8))+ got, err := DeriveBits(alg, key, new(42*8))if err != nil {t.Fatal(err)}@@ -150,9 +150,9 @@ func TestPBKDF2RFC6070(t *testing.T) {Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),}- alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA1, Salt: []byte("salt"), Iterations: intPtr(2)}+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA1, Salt: []byte("salt"), Iterations: new(2)}- got, err := DeriveBits(alg, key, intPtr(20*8))+ got, err := DeriveBits(alg, key, new(20*8))if err != nil {t.Fatal(err)}@@ -169,7 +169,7 @@ func TestDeriveBitsRejectsInvalidLength(t *testing.T) {}alg := Algorithm{Name: AlgHKDF, Hash: AlgSHA256, Salt: []byte{}, Info: []byte{}}- for _, length := range []*int{nil, intPtr(0), intPtr(7)} {+ for _, length := range []*int{nil, new(0), new(7)} {if _, err := DeriveBits(alg, key, length); errorName(t, err) != ErrNameOperation {t.Fatalf("length %v: error = %v, want OperationError", length, err)}@@ -181,9 +181,9 @@ func TestPBKDF2RejectsZeroIterations(t *testing.T) {Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveBits},Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),}- alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: intPtr(0)}+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: new(0)}- if _, err := DeriveBits(alg, key, intPtr(128)); errorName(t, err) != ErrNameOperation {+ if _, err := DeriveBits(alg, key, new(128)); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}}@@ -209,8 +209,8 @@ func TestDeriveKeyProducesUsableKey(t *testing.T) {Type: KeyTypeSecret, Usages: []KeyUsage{UsageDeriveKey},Algorithm: KeyAlgorithm{Name: AlgPBKDF2}, secret: []byte("password"),}- alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: intPtr(16)}- derived := Algorithm{Name: AlgAESGCM, Length: intPtr(256)}+ alg := Algorithm{Name: AlgPBKDF2, Hash: AlgSHA256, Salt: []byte("salt"), Iterations: new(16)}+ derived := Algorithm{Name: AlgAESGCM, Length: new(256)}key, err := DeriveKey(alg, base, derived, true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {diff --git a/kernel/plugin/crypto/format_test.go b/kernel/plugin/crypto/format_test.goindex 7edfa8275b..682c1b9ece 100644--- a/kernel/plugin/crypto/format_test.go+++ b/kernel/plugin/crypto/format_test.go@@ -20,6 +20,7 @@ import ("bytes""encoding/base64""encoding/json"+ "maps""testing")@@ -36,7 +37,7 @@ type formatCase struct {func asymmetricFormatCases() []formatCase {rsa := func(name string, hash string) Algorithm {- return Algorithm{Name: name, Hash: hash, ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ return Algorithm{Name: name, Hash: hash, ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}}return []formatCase{@@ -282,7 +283,7 @@ func TestImportRejectsMismatchedKeyMaterial(t *testing.T) {// 用 RSA 的密钥冒充 Ed25519。rsaPair, err := GenerateKey(Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}, true, []KeyUsage{UsageSign, UsageVerify})+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}, true, []KeyUsage{UsageSign, UsageVerify})if err != nil {t.Fatal(err)}@@ -392,9 +393,7 @@ func TestECJWKRejectsInvalidPrivateKey(t *testing.T) {"d = n": base64.RawURLEncoding.EncodeToString(mustHex(t, order)),} {invalid := map[string]any{}- for member, value := range firstJWK {- invalid[member] = value- }+ maps.Copy(invalid, firstJWK)invalid["d"] = ddata, marshalErr := json.Marshal(invalid)diff --git a/kernel/plugin/crypto/hmac.go b/kernel/plugin/crypto/hmac.goindex e21afd4b26..51dd81e89e 100644--- a/kernel/plugin/crypto/hmac.go+++ b/kernel/plugin/crypto/hmac.go@@ -46,7 +46,7 @@ func generateHMACKey(alg Algorithm, extractable bool, usages []KeyUsage) (*Key,Type: KeyTypeSecret,Extractable: extractable,Usages: cloneUsages(usages),- Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: intPtr(length)},+ Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: new(length)},secret: secret,}, nil}@@ -77,7 +77,7 @@ func importHMACKey(alg Algorithm, secret []byte, extractable bool, usages []KeyUType: KeyTypeSecret,Extractable: extractable,Usages: cloneUsages(usages),- Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: intPtr(length)},+ Algorithm: KeyAlgorithm{Name: alg.Name, Hash: h.Name, Length: new(length)},secret: bytes.Clone(secret),}, nil}diff --git a/kernel/plugin/crypto/interop_test.go b/kernel/plugin/crypto/interop_test.goindex 1a63f855b2..b08d87f855 100644--- a/kernel/plugin/crypto/interop_test.go+++ b/kernel/plugin/crypto/interop_test.go@@ -110,7 +110,7 @@ func signAlgorithmOf(c interopCase) Algorithm {case c.NamedCurve != "":return Algorithm{Name: AlgECDSA, Hash: c.Hash, NamedCurve: c.NamedCurve}case bytes.Contains([]byte(c.Label), []byte("RSA-PSS")):- return Algorithm{Name: AlgRSAPSS, Hash: c.Hash, SaltLength: intPtr(32)}+ return Algorithm{Name: AlgRSAPSS, Hash: c.Hash, SaltLength: new(32)}default:return Algorithm{Name: AlgRSASSAPKCS1, Hash: c.Hash}}@@ -272,13 +272,13 @@ func runInteropAESCase(t *testing.T, c interopCase, message []byte) {var alg Algorithmswitch {case c.Counter != "":- alg = Algorithm{Name: AlgAESCTR, Counter: decodeB64(t, c.Counter), Length: intPtr(c.CounterLength)}+ alg = Algorithm{Name: AlgAESCTR, Counter: decodeB64(t, c.Counter), Length: new(c.CounterLength)}case len(decodeB64(t, c.IV)) == 16 && c.TagLength == 0 && c.AAD == "":alg = Algorithm{Name: AlgAESCBC, IV: decodeB64(t, c.IV)}default:alg = Algorithm{Name: AlgAESGCM, IV: decodeB64(t, c.IV), AAD: decodeB64(t, c.AAD)}if c.TagLength != 0 {- alg.TagLength = intPtr(c.TagLength)+ alg.TagLength = new(c.TagLength)}}@@ -391,10 +391,10 @@ func runInteropKDFCase(t *testing.T, c interopCase) {if c.Kind == "hkdf" {alg.Info = decodeB64(t, c.Info)} else {- alg.Iterations = intPtr(c.Iterations)+ alg.Iterations = new(c.Iterations)}- bits, err := DeriveBits(alg, key, intPtr(c.Length))+ bits, err := DeriveBits(alg, key, new(c.Length))if err != nil {t.Fatalf("deriveBits: %v", err)}@@ -423,7 +423,7 @@ func runInteropECDHCase(t *testing.T, c interopCase) {derive := algderive.Public = publicKey- bits, err := DeriveBits(derive, privateKey, intPtr(c.Length))+ bits, err := DeriveBits(derive, privateKey, new(c.Length))if err != nil {t.Fatalf("deriveBits: %v", err)}diff --git a/kernel/plugin/crypto/key.go b/kernel/plugin/crypto/key.goindex cb1c484fa7..7ff166049b 100644--- a/kernel/plugin/crypto/key.go+++ b/kernel/plugin/crypto/key.go@@ -16,6 +16,8 @@package crypto+import "slices"+// KeyType 对应 CryptoKey.type。type KeyType string@@ -100,12 +102,7 @@ type KeyData struct {}func containsUsage(usages []KeyUsage, usage KeyUsage) bool {- for _, cur := range usages {- if cur == usage {- return true- }- }- return false+ return slices.Contains(usages, usage)}// cloneUsages 复制用法列表,避免调用方持有的切片被后续修改影响。@@ -129,6 +126,7 @@ func filterUsages(usages []KeyUsage, allowed ...KeyUsage) []KeyUsage {return ret}+//go:fix inlinefunc intPtr(value int) *int {- return &value+ return new(value)}diff --git a/kernel/plugin/crypto/key_test.go b/kernel/plugin/crypto/key_test.goindex 2a52e69e4c..6a42d346b2 100644--- a/kernel/plugin/crypto/key_test.go+++ b/kernel/plugin/crypto/key_test.go@@ -25,7 +25,7 @@ import (func TestGenerateAESKeyLengths(t *testing.T) {for _, length := range []int{128, 192, 256} {- alg := Algorithm{Name: AlgAESGCM, Length: intPtr(length)}+ alg := Algorithm{Name: AlgAESGCM, Length: new(length)}pair, err := GenerateKey(alg, true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatalf("length %d: %v", length, err)@@ -36,7 +36,7 @@ func TestGenerateAESKeyLengths(t *testing.T) {}// 非法长度返回 OperationError,缺少 length 返回 TypeError。- bad := Algorithm{Name: AlgAESGCM, Length: intPtr(100)}+ bad := Algorithm{Name: AlgAESGCM, Length: new(100)}if _, err := GenerateKey(bad, true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}@@ -67,7 +67,7 @@ func TestGenerateHMACKeyDefaultLength(t *testing.T) {if _, err := GenerateKey(Algorithm{Name: AlgHMAC}, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameType {t.Fatalf("error = %v, want TypeError", err)}- zero := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: intPtr(0)}+ zero := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: new(0)}if _, err := GenerateKey(zero, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}@@ -75,7 +75,7 @@ func TestGenerateHMACKeyDefaultLength(t *testing.T) {func TestCheckUsagesRejectsDisallowedAndEmpty(t *testing.T) {// AES 密钥不能用于签名。- alg := Algorithm{Name: AlgAESGCM, Length: intPtr(128)}+ alg := Algorithm{Name: AlgAESGCM, Length: new(128)}if _, err := GenerateKey(alg, true, []KeyUsage{UsageSign}); errorName(t, err) != ErrNameSyntax {t.Fatalf("error = %v, want SyntaxError", err)}@@ -134,8 +134,8 @@ func TestImportExportRawAES(t *testing.T) {// 规范的 AES 导入参数只有 name,参数中的 length 不参与导入,位长取自密钥数据。for _, other := range []Algorithm{- {Name: AlgAESGCM, Length: intPtr(128)},- {Name: AlgAESCTR, Counter: make([]byte, 16), Length: intPtr(64)},+ {Name: AlgAESGCM, Length: new(128)},+ {Name: AlgAESCTR, Counter: make([]byte, 16), Length: new(64)},} {imported, importErr := ImportKey(FormatRaw, KeyData{Raw: secret}, other, true, []KeyUsage{UsageEncrypt})if importErr != nil {@@ -153,7 +153,7 @@ func TestImportHMACKeyLength(t *testing.T) {raw := make([]byte, 8)cases := map[int]bool{64: true, 63: true, 57: true, 56: false, 65: false, 0: false}for length, ok := range cases {- alg := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: intPtr(length)}+ alg := Algorithm{Name: AlgHMAC, Hash: AlgSHA256, Length: new(length)}key, err := ImportKey(FormatRaw, KeyData{Raw: raw}, alg, true, []KeyUsage{UsageSign})if ok {if err != nil {@@ -325,7 +325,7 @@ func TestJWKImportValidation(t *testing.T) {func TestJWKUseFollowsAlgorithm(t *testing.T) {rsa := func(name string) Algorithm {- return Algorithm{Name: name, Hash: AlgSHA256, ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ return Algorithm{Name: name, Hash: AlgSHA256, ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}}// use 的取值由算法决定,与请求的用法无关。@@ -335,9 +335,9 @@ func TestJWKUseFollowsAlgorithm(t *testing.T) {usages []KeyUsagewant string}{- {Algorithm{Name: AlgAESGCM, Length: intPtr(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},- {Algorithm{Name: AlgAESKW, Length: intPtr(128)}, []KeyUsage{UsageWrapKey}, []KeyUsage{UsageWrapKey}, "enc"},- {Algorithm{Name: AlgAESECB, Length: intPtr(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},+ {Algorithm{Name: AlgAESGCM, Length: new(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},+ {Algorithm{Name: AlgAESKW, Length: new(128)}, []KeyUsage{UsageWrapKey}, []KeyUsage{UsageWrapKey}, "enc"},+ {Algorithm{Name: AlgAESECB, Length: new(128)}, []KeyUsage{UsageEncrypt}, []KeyUsage{UsageEncrypt}, "enc"},{Algorithm{Name: AlgHMAC, Hash: AlgSHA256}, []KeyUsage{UsageSign}, []KeyUsage{UsageSign}, "sig"},{rsa(AlgRSASSAPKCS1), []KeyUsage{UsageSign, UsageVerify}, []KeyUsage{UsageSign}, "sig"},{rsa(AlgRSAOAEP), []KeyUsage{UsageEncrypt, UsageDecrypt}, []KeyUsage{UsageDecrypt}, "enc"},diff --git a/kernel/plugin/crypto/legacy_test.go b/kernel/plugin/crypto/legacy_test.goindex b8d03a5271..b466c8bcbe 100644--- a/kernel/plugin/crypto/legacy_test.go+++ b/kernel/plugin/crypto/legacy_test.go@@ -103,7 +103,7 @@ func TestMD5WorksWithKeyDerivation(t *testing.T) {// HKDF 与 PBKDF2 把摘要算法当作伪随机函数使用,因此接受 MD5。for _, alg := range []Algorithm{{Name: AlgHKDF, Hash: AlgMD5, Salt: []byte("salt"), Info: []byte("info")},- {Name: AlgPBKDF2, Hash: AlgMD5, Salt: []byte("salt"), Iterations: intPtr(16)},+ {Name: AlgPBKDF2, Hash: AlgMD5, Salt: []byte("salt"), Iterations: new(16)},} {key, err := ImportKey(FormatRaw, KeyData{Raw: []byte("password")},Algorithm{Name: alg.Name}, false, []KeyUsage{UsageDeriveBits})@@ -111,7 +111,7 @@ func TestMD5WorksWithKeyDerivation(t *testing.T) {t.Fatalf("%s: %v", alg.Name, err)}- bits, err := DeriveBits(alg, key, intPtr(128))+ bits, err := DeriveBits(alg, key, new(128))if err != nil {t.Fatalf("%s: %v", alg.Name, err)}@@ -119,7 +119,7 @@ func TestMD5WorksWithKeyDerivation(t *testing.T) {t.Fatalf("%s: derived %d bytes, want 16", alg.Name, len(bits))}// 派生结果必须可复现。- again, err := DeriveBits(alg, key, intPtr(128))+ again, err := DeriveBits(alg, key, new(128))if err != nil {t.Fatalf("%s: %v", alg.Name, err)}@@ -139,7 +139,7 @@ func TestMD5RejectedBySignatureAlgorithms(t *testing.T) {}alg := Algorithm{Name: algName, Hash: AlgMD5,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}if _, err := GenerateKey(alg, true, usages); errorName(t, err) != ErrNameNotSupported {t.Errorf("%s generateKey: error = %v, want NotSupportedError", algName, err)}@@ -161,7 +161,7 @@ func TestMD5RejectedBySignatureAlgorithms(t *testing.T) {// 导入 RSA 密钥时同样拒绝,避免绕过生成时的检查。sha256Alg := Algorithm{Name: AlgRSASSAPKCS1, Hash: AlgSHA256,- ModulusLength: intPtr(2048), PublicExponent: []byte{1, 0, 1}}+ ModulusLength: new(2048), PublicExponent: []byte{1, 0, 1}}valid, err := GenerateKey(sha256Alg, true, []KeyUsage{UsageSign, UsageVerify})if err != nil {t.Fatal(err)@@ -243,7 +243,7 @@ func TestAESECBNISTVectors(t *testing.T) {func TestAESECBIsDeterministic(t *testing.T) {// ECB 对相同明文分组产生相同密文分组,这正是它泄漏明文结构的原因。- key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: intPtr(256)},+ key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: new(256)},true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatal(err)@@ -310,7 +310,7 @@ func TestAESECBPaddingAndLengthChecks(t *testing.T) {func TestAESECBRejectsKeyWrapping(t *testing.T) {// AES-ECB 不支持包装密钥,因此连带 wrapKey 用法一起被拒绝。- alg := Algorithm{Name: AlgAESECB, Length: intPtr(256)}+ alg := Algorithm{Name: AlgAESECB, Length: new(256)}for _, usages := range [][]KeyUsage{{UsageWrapKey},{UsageUnwrapKey},@@ -326,7 +326,7 @@ func TestAESECBRejectsKeyWrapping(t *testing.T) {if err != nil {t.Fatal(err)}- target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: intPtr(128)},+ target, err := GenerateKey(Algorithm{Name: AlgAESGCM, Length: new(128)},true, []KeyUsage{UsageEncrypt})if err != nil {t.Fatal(err)@@ -338,7 +338,7 @@ func TestAESECBRejectsKeyWrapping(t *testing.T) {}func TestAESECBKeyFormats(t *testing.T) {- key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: intPtr(192)},+ key, err := GenerateKey(Algorithm{Name: AlgAESECB, Length: new(192)},true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatal(err)@@ -412,7 +412,7 @@ func TestAESECBDerivedKey(t *testing.T) {}hkdf := Algorithm{Name: AlgHKDF, Hash: AlgSHA256, Salt: []byte("salt"), Info: []byte("info")}- derived, err := DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: intPtr(256)},+ derived, err := DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: new(256)},true, []KeyUsage{UsageEncrypt, UsageDecrypt})if err != nil {t.Fatal(err)@@ -421,7 +421,7 @@ func TestAESECBDerivedKey(t *testing.T) {t.Fatalf("derived key length = %v", derived.Algorithm.Length)}- if _, err = DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: intPtr(200)},+ if _, err = DeriveKey(hkdf, base, Algorithm{Name: AlgAESECB, Length: new(200)},true, []KeyUsage{UsageEncrypt}); errorName(t, err) != ErrNameOperation {t.Fatalf("error = %v, want OperationError", err)}diff --git a/kernel/plugin/crypto/rsa.go b/kernel/plugin/crypto/rsa.goindex db98714848..95dd1cf3c4 100644--- a/kernel/plugin/crypto/rsa.go+++ b/kernel/plugin/crypto/rsa.go@@ -60,7 +60,7 @@ func generateRSAKeyPair(alg Algorithm, extractable bool, usages []KeyUsage) (*KekeyAlg := KeyAlgorithm{Name: alg.Name,Hash: h.Name,- ModulusLength: intPtr(privateKey.N.BitLen()),+ ModulusLength: new(privateKey.N.BitLen()),PublicExponent: big.NewInt(rsaPublicExponent).Bytes(),}privateUsages, publicUsages := splitAsymmetricUsages(alg.Name, usages)@@ -101,7 +101,7 @@ func newRSAKey(alg Algorithm, hashName string, material any, extractable bool, uUsages: cloneUsages(usages),Algorithm: KeyAlgorithm{Name: alg.Name, Hash: hashName,- ModulusLength: intPtr(typed.N.BitLen()),+ ModulusLength: new(typed.N.BitLen()),PublicExponent: rsaExponentBytes(typed.E),},private: typed,@@ -116,7 +116,7 @@ func newRSAKey(alg Algorithm, hashName string, material any, extractable bool, uUsages: cloneUsages(usages),Algorithm: KeyAlgorithm{Name: alg.Name, Hash: hashName,- ModulusLength: intPtr(typed.N.BitLen()),+ ModulusLength: new(typed.N.BitLen()),PublicExponent: rsaExponentBytes(typed.E),},public: typed,diff --git a/kernel/plugin/crypto/subtle.go b/kernel/plugin/crypto/subtle.goindex 51b334ff5e..ecfeaacca6 100644--- a/kernel/plugin/crypto/subtle.go+++ b/kernel/plugin/crypto/subtle.go@@ -345,7 +345,7 @@ func derivedKeyLength(derived Algorithm) (*int, error) {if err != nil {return nil, err}- return intPtr(h.New().BlockSize() * 8), nil+ return new(h.New().BlockSize() * 8), nildefault:return nil, notSupportedError("%s keys cannot be derived", derived.Name)}diff --git a/kernel/plugin/crypto_params.go b/kernel/plugin/crypto_params.goindex 6585089dde..ec0b49c134 100644--- a/kernel/plugin/crypto_params.go+++ b/kernel/plugin/crypto_params.go@@ -18,6 +18,7 @@ package pluginimport ("math"+ "slices""github.com/dop251/goja""github.com/siyuan-note/siyuan/kernel/plugin/crypto"@@ -176,19 +177,12 @@ func keyFormatOf(value goja.Value) (crypto.KeyFormat, error) {}format := crypto.KeyFormat(value.String())- for _, cur := range crypto.KeyFormats {- if cur == format {- return format, nil- }+ if slices.Contains(crypto.KeyFormats, format) {+ return format, nil}return "", crypto.NewError(crypto.ErrNameType, "%q is not a valid key format", value.String())}func containsKeyUsage(usages []crypto.KeyUsage, usage crypto.KeyUsage) bool {- for _, cur := range usages {- if cur == usage {- return true- }- }- return false+ return slices.Contains(usages, usage)}diff --git a/kernel/plugin/encoding/goja.go b/kernel/plugin/encoding/goja.goindex c2fca7b592..ec80d59185 100644--- a/kernel/plugin/encoding/goja.go+++ b/kernel/plugin/encoding/goja.go@@ -175,8 +175,7 @@ func newTextEncoderObject(rt *goja.Runtime, te *TextEncoder) *goja.Object {}func throwAsJSError(rt *goja.Runtime, err error) {- var encErr *Error- if errors.As(err, &encErr) {+ if encErr, ok := errors.AsType[*Error](err); ok {panic(encErr.JSError(rt))}diff --git a/kernel/plugin/formdata/blob.go b/kernel/plugin/formdata/blob.goindex e08cfb31b5..bd8fa2a3a5 100644--- a/kernel/plugin/formdata/blob.go+++ b/kernel/plugin/formdata/blob.go@@ -32,9 +32,9 @@ import (var (// blobStateType 用于在 Object.Export() 前先以 Object.ExportType() 做品牌判定,原因见 kernel/plugin/abort 中// signalStateType 的注释。- blobStateType = reflect.TypeOf((*blobState)(nil))+ blobStateType = reflect.TypeFor[*blobState]()// arrayBufferExportType 是 ArrayBuffer 对象的导出类型,用于在不调用 Export() 的前提下识别 ArrayBuffer。- arrayBufferExportType = reflect.TypeOf(goja.ArrayBuffer{})+ arrayBufferExportType = reflect.TypeFor[goja.ArrayBuffer]())var (diff --git a/kernel/plugin/formdata/formdata.go b/kernel/plugin/formdata/formdata.goindex 4ac4b25594..711d726f52 100644--- a/kernel/plugin/formdata/formdata.go+++ b/kernel/plugin/formdata/formdata.go@@ -32,8 +32,8 @@ import (var (// stateType 与 iteratorStateType 用于在 Object.Export() 前先以 Object.ExportType() 做品牌判定,// 原因见 kernel/plugin/abort 中 signalStateType 的注释。- stateType = reflect.TypeOf((*State)(nil))- iteratorStateType = reflect.TypeOf((*iteratorState)(nil))+ stateType = reflect.TypeFor[*State]()+ iteratorStateType = reflect.TypeFor[*iteratorState]())// multipartNameEscaper 按 HTML 规范转义 Content-Disposition 的 name 与 filename 参数:只把 LF、CR、双引号替换为百分号编码。diff --git a/kernel/plugin/rpc_cancellation_test.go b/kernel/plugin/rpc_cancellation_test.goindex a7e3fceeff..761d19fd76 100644--- a/kernel/plugin/rpc_cancellation_test.go+++ b/kernel/plugin/rpc_cancellation_test.go@@ -75,7 +75,7 @@ func TestRPCHTTPWaitCancellation(t *testing.T) {t.Run(path, func(t *testing.T) {p := newRPCCancellationTestPlugin(t)started := make(chan struct{})- var resolve func(interface{}) error+ var resolve func(any) errorrpcCancellationTestRun(t, p, func(rt *goja.Runtime) (any, error) {p.rpcMethods.Store("pending", &RpcMethod{Method: func(goja.Value, ...goja.Value) (goja.Value, error) {promise, resolvePromise, _ := rt.NewPromise()diff --git a/kernel/plugin/rpc_contract.go b/kernel/plugin/rpc_contract.goindex 670a726aa5..3374a46476 100644--- a/kernel/plugin/rpc_contract.go+++ b/kernel/plugin/rpc_contract.go@@ -181,7 +181,7 @@ func pluginRPCReply(response *JsonRpcProcessingResponse) (apicontract.PluginRPCRreturn apicontract.RPCFailureReply(result), nil}-func pluginRPCID(value interface{}) (id apicontract.PluginRPCID, err error) {+func pluginRPCID(value any) (id apicontract.PluginRPCID, err error) {data, err := json.Marshal(value)if err == nil {err = json.Unmarshal(data, &id)diff --git a/kernel/plugin/rpc_contract_test.go b/kernel/plugin/rpc_contract_test.goindex 089e881664..f8c7195929 100644--- a/kernel/plugin/rpc_contract_test.go+++ b/kernel/plugin/rpc_contract_test.go@@ -57,7 +57,7 @@ func TestRPCContractParserCompatibility(t *testing.T) {}}-func compareRPCJSON(t *testing.T, label string, expected, actual interface{}) {+func compareRPCJSON(t *testing.T, label string, expected, actual any) {t.Helper()left, err := json.Marshal(expected)if err != nil {@@ -67,7 +67,7 @@ func compareRPCJSON(t *testing.T, label string, expected, actual interface{}) {if err != nil {t.Fatal(err)}- var leftValue, rightValue interface{}+ var leftValue, rightValue anyif err := json.Unmarshal(left, &leftValue); err != nil {t.Fatal(err)}diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.goindex 045cd046f8..1bd628ffcc 100644--- a/kernel/plugin/sandbox.go+++ b/kernel/plugin/sandbox.go@@ -69,8 +69,8 @@ var ()type Promise struct {- Resolve func(reason interface{}) error- Reject func(reason interface{}) error+ Resolve func(reason any) error+ Reject func(reason any) error}type FunctionResult[T any] struct {diff --git a/kernel/plugin/sse_test.go b/kernel/plugin/sse_test.goindex 558d26887d..dcfc767bec 100644--- a/kernel/plugin/sse_test.go+++ b/kernel/plugin/sse_test.go@@ -134,7 +134,7 @@ func TestSSESendBurstPreservesEvents(t *testing.T) {sseTestWait(t, done, "SSE request completion")sseTestWait(t, closed, "onclose")var expected strings.Builder- for i := 0; i < count; i++ {+ for i := range count {fmt.Fprintf(&expected, "id:%d\nevent:item\nretry:1000\ndata:value-%d\n\n", i, i)}if got := recorder.Body.String(); got != expected.String() {diff --git a/kernel/plugin/streams/readable.go b/kernel/plugin/streams/readable.goindex d773599991..42174dee80 100644--- a/kernel/plugin/streams/readable.go+++ b/kernel/plugin/streams/readable.go@@ -89,9 +89,9 @@ type readRequest struct {}var (- readableStateType = reflect.TypeOf((*readableState)(nil))- readableControllerType = reflect.TypeOf((*readableController)(nil))- readableReaderType = reflect.TypeOf((*readableReaderState)(nil))+ readableStateType = reflect.TypeFor[*readableState]()+ readableControllerType = reflect.TypeFor[*readableController]()+ readableReaderType = reflect.TypeFor[*readableReaderState]())// readableStateOf 取出 ReadableStream 的内部状态,只接受本包创建的对象。diff --git a/kernel/plugin/streams/transform.go b/kernel/plugin/streams/transform.goindex 040009b626..6806ef4430 100644--- a/kernel/plugin/streams/transform.go+++ b/kernel/plugin/streams/transform.go@@ -57,8 +57,8 @@ type transformController struct {}var (- transformStateType = reflect.TypeOf((*transformState)(nil))- transformControllerType = reflect.TypeOf((*transformController)(nil))+ transformStateType = reflect.TypeFor[*transformState]()+ transformControllerType = reflect.TypeFor[*transformController]())func transformStateOf(value goja.Value) (*transformState, bool) {diff --git a/kernel/plugin/streams/writable.go b/kernel/plugin/streams/writable.goindex 9d8a5ad7ef..149e7063ba 100644--- a/kernel/plugin/streams/writable.go+++ b/kernel/plugin/streams/writable.go@@ -114,9 +114,9 @@ type writableWriterState struct {}var (- writableStateType = reflect.TypeOf((*writableState)(nil))- writableControllerType = reflect.TypeOf((*writableController)(nil))- writableWriterType = reflect.TypeOf((*writableWriterState)(nil))+ writableStateType = reflect.TypeFor[*writableState]()+ writableControllerType = reflect.TypeFor[*writableController]()+ writableWriterType = reflect.TypeFor[*writableWriterState]())func writableStateOf(value goja.Value) (*writableState, bool) {diff --git a/kernel/server/appearance_diagnostic.go b/kernel/server/appearance_diagnostic.goindex 5c26a5454b..90e498ab22 100644--- a/kernel/server/appearance_diagnostic.go+++ b/kernel/server/appearance_diagnostic.go@@ -21,6 +21,7 @@ import ("fmt""os""path/filepath"+ "slices""sync""syscall"@@ -46,8 +47,8 @@ func logAppearanceRootDiagnostic(root, target string) {break}}- for i := len(ancestors) - 1; i >= 0; i-- {- path := ancestors[i]+ for _, path := range slices.Backward(ancestors) {+_, lstatErr := os.Lstat(path)_, statErr := os.Stat(path)resolved, resolveErr := evalAppearanceSymlinks(path)@@ -68,8 +69,7 @@ func appearanceDiagnosticError(err error) string {if err == nil {return "ok"}- var errno syscall.Errno- if errors.As(err, &errno) {+ if errno, ok := errors.AsType[syscall.Errno](err); ok {return fmt.Sprintf("%s (errno %d)", err, errno)}return err.Error()diff --git a/kernel/server/serve_heif_accept.go b/kernel/server/serve_heif_accept.goindex a49a1444a6..a34da601ef 100644--- a/kernel/server/serve_heif_accept.go+++ b/kernel/server/serve_heif_accept.go@@ -149,7 +149,7 @@ func addHEIFVaryAccept(context *gin.Context) {return}for _, vary := range context.Writer.Header().Values("Vary") {- for _, value := range strings.Split(vary, ",") {+ for value := range strings.SplitSeq(vary, ",") {if strings.EqualFold(strings.TrimSpace(value), "Accept") || strings.TrimSpace(value) == "*" {return}diff --git a/kernel/server/serve_heif_accept_test.go b/kernel/server/serve_heif_accept_test.goindex d2e09de799..f241a5423b 100644--- a/kernel/server/serve_heif_accept_test.go+++ b/kernel/server/serve_heif_accept_test.go@@ -144,7 +144,7 @@ func TestAddHEIFVaryAccept(t *testing.T) {acceptCount := 0originFound := falsefor _, value := range recorder.Header().Values("Vary") {- for _, field := range strings.Split(value, ",") {+ for field := range strings.SplitSeq(value, ",") {switch {case strings.EqualFold(strings.TrimSpace(field), "Accept"):acceptCount++diff --git a/kernel/sql/av.go b/kernel/sql/av.goindex 07665a9c0c..1c938ecebd 100644--- a/kernel/sql/av.go+++ b/kernel/sql/av.go@@ -19,6 +19,8 @@ package sqlimport ("bytes""fmt"+ "maps"+ "slices""sort""strings""text/template"@@ -607,9 +609,7 @@ func fillAttributeViewBlockRefSubtypes(attrView *av.AttributeView, attrs map[straddedBlockIDs[value.Block.ID] = true}}- for blockID, blockAttrs := range BatchGetBlockAttrs(missingBlockIDs) {- attrs[blockID] = blockAttrs- }+ maps.Copy(attrs, BatchGetBlockAttrs(missingBlockIDs))for _, value := range blockValues.Values {if nil == value || nil == value.Block {continue@@ -1391,13 +1391,7 @@ func GetTemplateKeyRelevantKeys(attrView *av.AttributeView, templateKey *av.Key)if nil != err {return}- dynamicDependency := false- for _, variable := range vars {- if dynamicTemplateKeyVar == variable {- dynamicDependency = true- break- }- }+ dynamicDependency := slices.Contains(vars, dynamicTemplateKeyVar)if dynamicDependency {for _, keyValues := range attrView.KeyValues {if nil != keyValues && nil != keyValues.Key {diff --git a/kernel/sql/av_relation_template.go b/kernel/sql/av_relation_template.goindex efff0ae261..015725d284 100644--- a/kernel/sql/av_relation_template.go+++ b/kernel/sql/av_relation_template.go@@ -1,6 +1,7 @@package sqlimport (+ "maps""strings""github.com/88250/lute/ast"@@ -49,9 +50,7 @@ func fillRelationPrimaryTemplates(target *av.AttributeView, relations []*av.Valuview.Table.Columns = append(view.Table.Columns, &av.ViewTableColumn{BaseField: &av.BaseField{ID: key.ID}})}cache := make(map[string]*av.AttributeView, len(cachedAttrViews))- for id, attrView := range cachedAttrViews {- cache[id] = attrView- }+ maps.Copy(cache, cachedAttrViews)cache[target.ID] = &cloned// 显示模板只能读取原始值,计算目标模板时无需再次展开关联主键显示模板。diff --git a/kernel/sql/av_rollup_target.go b/kernel/sql/av_rollup_target.goindex 29890424d3..252085d5b5 100644--- a/kernel/sql/av_rollup_target.go+++ b/kernel/sql/av_rollup_target.go@@ -1,6 +1,8 @@package sqlimport (+ "maps"+"github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/av")@@ -56,9 +58,7 @@ func renderRollupTarget(target *av.AttributeView, key *av.Key, depth *int,}}cache := make(map[string]*av.AttributeView, len(cachedAttrViews)+1)- for avID, attrView := range cachedAttrViews {- cache[avID] = attrView- }+ maps.Copy(cache, cachedAttrViews)cache[target.ID] = &cloned// 每条依赖分支使用独立深度,兄弟字段不会消耗彼此的递归预算。diff --git a/kernel/sql/av_rollup_target_test.go b/kernel/sql/av_rollup_target_test.goindex c851f34f66..ae274ef7e1 100644--- a/kernel/sql/av_rollup_target_test.go+++ b/kernel/sql/av_rollup_target_test.go@@ -25,7 +25,7 @@ func TestNestedRollupRefreshWithoutRenderingIntermediate(t *testing.T) {}}before := nestedRollupTestSnapshot(t, intermediate)- for update := 0; update < 4; update++ {+ for update := range 4 {for row, value := range nestedRollupTestKeyValues(t, leaf, leafKey.ID).Values {switch typ {case av.KeyTypeText:@@ -102,13 +102,13 @@ func TestNestedRollupDiamondDoesNotConsumeSiblingDepth(t *testing.T) {cache := map[string]*av.AttributeView{leaf.ID: leaf, shared.ID: shared}outer := newNestedRollupTestDatabase("outer")var keys []*av.Key- for branch := 0; branch < 12; branch++ {+ for branch := range 12 {target, targetKey := newNestedRollupTestLevel(fmt.Sprintf("branch-%d", branch), shared, sharedKey, true)cache[target.ID] = targetkeys = append(keys, addNestedRollupTestFields(outer, target, targetKey, false))}cache[outer.ID] = outer- for repeat := 0; repeat < 2; repeat++ {+ for repeat := range 2 {if repeat == 1 {for _, key := range keys {key.Rollup.Filters = nestedRollupTestFilters(key.Rollup.KeyID, "fresh-0")@@ -148,7 +148,7 @@ func TestRenderRollupTargetCyclesAndDepthDoNotUseStoredContents(t *testing.T) {before := nestedRollupTestSnapshot(t, []*av.AttributeView{first, second})context := NewAttributeViewRenderContext()depth := 2- for repeat := 0; repeat < 2; repeat++ {+ for range 2 {collection := renderRollupTarget(first, firstKey, &depth, cache, context)for _, item := range collection.GetItems() {if value := collection.GetValue(item.GetID(), firstKey.ID); value == nil || value.String(true) != "" {@@ -192,7 +192,7 @@ func TestRenderRollupTargetCyclicFilterDependencyTerminates(t *testing.T) {cache := map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target}context := NewAttributeViewRenderContext()depth := 2- for repeat := 0; repeat < 2; repeat++ {+ for range 2 {collection := renderRollupTarget(target, key, &depth, cache, context)for _, item := range collection.GetItems() {if value := collection.GetValue(item.GetID(), key.ID); value == nil || value.String(true) != "" {@@ -245,7 +245,7 @@ func TestNestedRollupTargetFiltersAndSortUseFreshValues(t *testing.T) {target, targetKey := newNestedRollupTestLevel("target", leaf, leafKey, true)outer, outerKey := newNestedRollupTestLevel("outer", target, targetKey, true)cache := map[string]*av.AttributeView{leaf.ID: leaf, target.ID: target, outer.ID: outer}- for update := 0; update < 2; update++ {+ for update := range 2 {values := nestedRollupTestKeyValues(t, leaf, leafKey.ID).Valuesvalues[update].Text.Content = "alpha"values[1-update].Text.Content = "zulu"@@ -296,7 +296,7 @@ func TestNestedRollupQuantifiedEmptyFiltersUseFreshValues(t *testing.T) {outer.Views[0].Filters = []*av.ViewFilter{{Column: outerKey.ID, Qualifier: qualifier, Operator: operator,Value: &av.Value{Type: av.KeyTypeRollup, Rollup: &av.ValueRollup{}}}}relations := nestedRollupTestKeyValues(t, target, targetKey.Rollup.RelationKeyID).Values- for emptyRow := 0; emptyRow < 2; emptyRow++ {+ for emptyRow := range 2 {for row, value := range relations {value.Relation.BlockIDs = nilif row != emptyRow {@@ -327,7 +327,7 @@ func TestNestedRollupQuantifiedEmptyFiltersUseFreshValues(t *testing.T) {func newNestedRollupTestDatabase(id string) *av.AttributeView {key := &av.Key{ID: id + "-primary", Name: "Primary", Type: av.KeyTypeBlock}values := &av.KeyValues{Key: key}- for row := 0; row < 2; row++ {+ for row := range 2 {itemID := fmt.Sprintf("2026100800000%d-%s", row, id)values.Values = append(values.Values, &av.Value{ID: itemID + "-primary", KeyID: key.ID, BlockID: itemID, Type: key.Type,diff --git a/kernel/sql/backlink_ref_defs_test.go b/kernel/sql/backlink_ref_defs_test.goindex 22f6a0d691..41b952f137 100644--- a/kernel/sql/backlink_ref_defs_test.go+++ b/kernel/sql/backlink_ref_defs_test.go@@ -28,7 +28,7 @@ func TestQueryBacklinkRefDefsInBox(t *testing.T) {}}ids := []string{"a", "b", "'); DELETE FROM refs --"}- for i := 0; i < queryRefsByDefIDsBatchSize; i++ {+ for range queryRefsByDefIDsBatchSize {ids = append(ids, "missing")}refs, err := QueryBacklinkRefDefsInBox(ids, boxID)diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.goindex a929df9a0f..ac50085d43 100644--- a/kernel/sql/block_ref_query.go+++ b/kernel/sql/block_ref_query.go@@ -123,10 +123,7 @@ func ExistRefByDefIDsInBox(defIDs, defRootIDs, excludeBlockIDs, excludeRootIDs [}exist := func(column string, ids []string) (bool, error) {for start := 0; start < len(ids); start += batchSize {- end := start + batchSize- if len(ids) < end {- end = len(ids)- }+ end := min(len(ids), start+batchSize)batch := ids[start:end]placeholders := strings.TrimSuffix(strings.Repeat("?,", len(batch)), ",")args := make([]any, 0, len(batch))@@ -197,10 +194,7 @@ func QueryBoundBlockAVIDsInBox(blockIDs, rootIDs []string, boxID string) (ret maret = map[string][]string{}queryByColumn := func(column string, ids []string) error {for start := 0; start < len(ids); start += batchSize {- end := start + batchSize- if len(ids) < end {- end = len(ids)- }+ end := min(len(ids), start+batchSize)batch := ids[start:end]placeholders := strings.TrimSuffix(strings.Repeat("?,", len(batch)), ",")args := make([]any, 0, len(batch))diff --git a/kernel/sql/bookmark_index_test.go b/kernel/sql/bookmark_index_test.goindex 0a7dd9ed0e..a064d03615 100644--- a/kernel/sql/bookmark_index_test.go+++ b/kernel/sql/bookmark_index_test.go@@ -80,7 +80,7 @@ func TestBookmarkIndexPreservesBlockFieldsAndLabels(t *testing.T) {t.Fatal(err)}rows.Close()- for i := 0; i < 2; i++ {+ for range 2 {if err = ensureBookmarkAttributesIndex(database); err != nil {t.Fatal(err)}diff --git a/kernel/sql/cache.go b/kernel/sql/cache.goindex 5ef2b38a5b..94ff6b9d36 100644--- a/kernel/sql/cache.go+++ b/kernel/sql/cache.go@@ -17,6 +17,7 @@package sqlimport (+ "maps""strings""sync""time"@@ -255,9 +256,7 @@ func getRefsCacheByDefIDInBox(defID, boxID string,cacheable = append(cacheable, ref)}}- for blockID, ref := range partial {- merged[blockID] = ref- }+ maps.Copy(merged, partial)ret = ret[:0]for _, ref := range merged {ret = append(ret, ref)@@ -301,9 +300,7 @@ func putRefCacheIfGeneration(defID, boxID string, generation refCacheGeneration,key := refCacheKey(defID, boxID)if cached, ok := defIDRefsCache.Get(key); ok {if entry, valid := cached.(*refCacheEntry); valid {- for blockID, ref := range entry.refs {- complete[blockID] = ref- }+ maps.Copy(complete, entry.refs)}}defIDRefsCache.SetDefault(key, &refCacheEntry{refs: complete, complete: true})diff --git a/kernel/sql/cache_budget_test.go b/kernel/sql/cache_budget_test.goindex d0f91afeeb..2dde773c03 100644--- a/kernel/sql/cache_budget_test.go+++ b/kernel/sql/cache_budget_test.go@@ -37,7 +37,7 @@ func TestBlockCacheReplacementRemainsInvalidatable(t *testing.T) {cacheDisabled = falseClearCache()t.Cleanup(func() { ClearCache(); cacheDisabled = previousDisabled })- for i := 0; i < 64; i++ {+ for i := range 64 {putBlockCache(&Block{ID: "replaced", Content: strings.Repeat("x", i+1)})}blockCache.Wait()diff --git a/kernel/sql/delete_path_fts5_test.go b/kernel/sql/delete_path_fts5_test.goindex 3aa998bb9e..7b8908318f 100644--- a/kernel/sql/delete_path_fts5_test.go+++ b/kernel/sql/delete_path_fts5_test.go@@ -177,21 +177,21 @@ func TestDocumentPathDeletionQueryPlan(t *testing.T) {if err != nil {t.Fatal(err)}- var plan string+ var plan strings.Builderfor rows.Next() {var id, parent, unused intvar detail stringif err = rows.Scan(&id, &parent, &unused, &detail); err != nil {t.Fatal(err)}- plan += detail + "\n"+ plan.WriteString(detail + "\n")}rows.Close()if err = rows.Err(); err != nil {t.Fatal(err)}- if !strings.Contains(plan, "idx_"+table+"_box_docpath") || !strings.Contains(plan, column+">? AND "+column+"<?") {- t.Fatalf("encrypted=%t case=%s: deletion lacks path range search: %s", encrypted, sensitive, plan)+ if !strings.Contains(plan.String(), "idx_"+table+"_box_docpath") || !strings.Contains(plan.String(), column+">? AND "+column+"<?") {+ t.Fatalf("encrypted=%t case=%s: deletion lacks path range search: %s", encrypted, sensitive, plan.String())}}}diff --git a/kernel/sql/encrypted_query_test.go b/kernel/sql/encrypted_query_test.goindex bcff5d2457..91cc97cd96 100644--- a/kernel/sql/encrypted_query_test.go+++ b/kernel/sql/encrypted_query_test.go@@ -64,7 +64,7 @@ func TestQueryRefsByDefIDInBoxContainsChildren(t *testing.T) {func TestQueryRefsRecentInBoxPrioritizesUsageBeforeLimit(t *testing.T) {testDB, boxID := useEncryptedQueryTestDB(t)- for i := 0; i < 40; i++ {+ for i := range 40 {defID := fmt.Sprintf("def-%02d", i)insertEncryptedQueryTestBlock(t, testDB, defID, "", defID, "d")insertEncryptedQueryTestRef(t, testDB, fmt.Sprintf("ref-%02d", i), defID, defID)diff --git a/kernel/sql/recent_index_test.go b/kernel/sql/recent_index_test.goindex 305ea20d57..d32e6b90b1 100644--- a/kernel/sql/recent_index_test.go+++ b/kernel/sql/recent_index_test.go@@ -19,7 +19,7 @@ func TestRecentUpdatedBlocksIndexesPreserveResults(t *testing.T) {}}for _, blockType := range []string{"p", "d"} {- for i := 0; i < 40; i++ {+ for i := range 40 {insert(fmt.Sprintf("%s-%02d", blockType, i), blockType, fmt.Sprintf("20261008%06d", i), 8)}}@@ -38,7 +38,7 @@ func TestRecentUpdatedBlocksIndexesPreserveResults(t *testing.T) {before = append(before, ids(SelectBlocksRawStmt("SELECT * FROM blocks WHERE "+condition+" ORDER BY updated DESC", 1, 16)))before = append(before, ids(SelectBlocksRawStmt("SELECT * FROM blocks WHERE "+condition+" AND id NOT LIKE '%-39' ORDER BY updated DESC", 1, 16)))}- for i := 0; i < 2; i++ {+ for range 2 {if err := ensureRecentUpdatedBlocksIndexes(database); err != nil {t.Fatal(err)}diff --git a/kernel/task/queue_timeout_test.go b/kernel/task/queue_timeout_test.goindex 48f7d3d9cd..b5f4083409 100644--- a/kernel/task/queue_timeout_test.go+++ b/kernel/task/queue_timeout_test.go@@ -99,7 +99,7 @@ func TestTimedOutTaskRemainsTrackedUntilHandlerCompletes(t *testing.T) {func TestConcurrentTaskAdmissionIsAtomic(t *testing.T) {isolateTaskQueue(t)var wait sync.WaitGroup- for i := 0; i < 64; i++ {+ for range 64 {wait.Go(func() { AppendTask(OCRImage, func() {}) })}wait.Wait()diff --git a/kernel/treenode/hpath_test.go b/kernel/treenode/hpath_test.goindex 93d23b5a5b..9390de7a83 100644--- a/kernel/treenode/hpath_test.go+++ b/kernel/treenode/hpath_test.go@@ -46,20 +46,20 @@ func TestHPathRefreshIndexMigration(t *testing.T) {t.Fatal(err)}defer rows.Close()- var plan string+ var plan strings.Builderfor rows.Next() {var id, parent, unused intvar detail stringif err = rows.Scan(&id, &parent, &unused, &detail); err != nil {t.Fatal(err)}- plan += detail + "\n"+ plan.WriteString(detail + "\n")}if err = rows.Err(); err != nil {t.Fatal(err)}- if !strings.Contains(plan, "root_id=? AND box_id=? AND rowid>?") || strings.Contains(plan, "TEMP B-TREE") {- t.Fatalf("batch scans beyond the document or sorts all rows: %s", plan)+ if !strings.Contains(plan.String(), "root_id=? AND box_id=? AND rowid>?") || strings.Contains(plan.String(), "TEMP B-TREE") {+ t.Fatalf("batch scans beyond the document or sorts all rows: %s", plan.String())}})}diff --git a/kernel/util/anthropic.go b/kernel/util/anthropic.goindex 18803b487f..46825538c7 100644--- a/kernel/util/anthropic.go+++ b/kernel/util/anthropic.go@@ -329,8 +329,8 @@ func anthropicMessageBlocks(message openai.ChatCompletionMessage) ([]json.RawMesreturn nil, errors.New("missing Anthropic image source")}source := map[string]string{"type": "url", "url": part.ImageURL.URL}- if strings.HasPrefix(part.ImageURL.URL, "data:") {- meta, data, ok := strings.Cut(strings.TrimPrefix(part.ImageURL.URL, "data:"), ";base64,")+ if after, ok := strings.CutPrefix(part.ImageURL.URL, "data:"); ok {+ meta, data, ok := strings.Cut(after, ";base64,")if !ok || data == "" || (meta != "image/png" && meta != "image/jpeg" && meta != "image/gif" && meta != "image/webp") {return nil, errors.New("unsupported Anthropic image data URL")}diff --git a/kernel/util/anthropic_stream.go b/kernel/util/anthropic_stream.goindex 0800e3f454..13ec6dfad5 100644--- a/kernel/util/anthropic_stream.go+++ b/kernel/util/anthropic_stream.go@@ -53,8 +53,8 @@ func (s *anthropicStream) readEvent() ([]byte, error) {if line == "" {return bytes.TrimSuffix(data.Bytes(), []byte("\n")), nil}- if strings.HasPrefix(line, "data:") {- data.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))+ if after, ok := strings.CutPrefix(line, "data:"); ok {+ data.WriteString(strings.TrimPrefix(after, " "))data.WriteByte('\n')if data.Len() > 32*1024*1024 {return nil, errors.New("Anthropic stream event is too large")diff --git a/kernel/util/anthropic_test.go b/kernel/util/anthropic_test.goindex c2542e8255..ea7c43a399 100644--- a/kernel/util/anthropic_test.go+++ b/kernel/util/anthropic_test.go@@ -62,7 +62,7 @@ func TestAnthropicContextWindowTruncation(t *testing.T) {t.Fatal(err)}defer stream.Close()- var text string+ var text strings.Buildervar finish openai.FinishReasonfor {part, err := stream.Recv()@@ -73,14 +73,14 @@ func TestAnthropicContextWindowTruncation(t *testing.T) {t.Fatal(err)}for _, choice := range part.Choices {- text += choice.Delta.Content+ text.WriteString(choice.Delta.Content)if choice.FinishReason != "" {finish = choice.FinishReason}}}- if text != "partial answer" || finish != openai.FinishReasonLength || stream.NativeContent() == nil {- t.Fatalf("context truncation lost streamed content: text=%q finish=%q", text, finish)+ if text.String() != "partial answer" || finish != openai.FinishReasonLength || stream.NativeContent() == nil {+ t.Fatalf("context truncation lost streamed content: text=%q finish=%q", text.String(), finish)}for _, reason := range []string{"pause_turn", "future_reason"} {if _, err := anthropicFinishReason(reason, false); err == nil {@@ -280,7 +280,7 @@ func TestAnthropicIncompleteStreams(t *testing.T) {t.Fatal(err)}defer stream.Close()- for i := 0; i < 100; i++ {+ for range 100 {_, err = stream.Recv()if err != nil {breakdiff --git a/kernel/util/builtin_skill.go b/kernel/util/builtin_skill.goindex 6482fba0dc..816bdf98fe 100644--- a/kernel/util/builtin_skill.go+++ b/kernel/util/builtin_skill.go@@ -9,6 +9,7 @@ import ("embed""fmt""io/fs"+ "slices""sort""strings""unicode/utf8"@@ -71,11 +72,8 @@ func BuiltinPluginSkill(disabled []string) (*BuiltinSkillInfo, error) {Description: frontmatter["description"], Source: "builtin",Version: BuiltinPluginSkillVersion, Digest: fmt.Sprintf("sha256:%x", hash.Sum(nil)), Enabled: true,}- for _, id := range disabled {- if id == info.ID {- info.Enabled = false- break- }+ if slices.Contains(disabled, info.ID) {+ info.Enabled = false}return info, nil}diff --git a/kernel/util/font.go b/kernel/util/font.goindex e94c3f3ecf..bc6e8e84af 100644--- a/kernel/util/font.go+++ b/kernel/util/font.go@@ -20,6 +20,7 @@ import ("encoding/binary""errors""os"+ "slices""sort""strconv""strings"@@ -227,7 +228,7 @@ func parseFontVariations(font *sfnt.Font, defaultFont *Font) (ret []*Font) {// 找到 wght 轴在实例坐标中的位置wghtAxisIndex := -1- for i := 0; i < axisCount; i++ {+ for i := range axisCount {base := axesArrayOffset + i*axisSizeif "wght" == string(buf[base:base+4]) {wghtAxisIndex = i@@ -248,7 +249,7 @@ func parseFontVariations(font *sfnt.Font, defaultFont *Font) (ret []*Font) {localizedFamily = defaultFont.Family}instancesBase := axesArrayOffset + axisCount*axisSize- for i := 0; i < instanceCount; i++ {+ for i := range instanceCount {base := instancesBase + i*instanceSizesubfamilyNameID := binary.BigEndian.Uint16(buf[base : base+2])// wght 坐标是 16.16 定点数,取整后即为 CSS font-weight@@ -379,7 +380,7 @@ func detectFontSpacingFromMetrics(font *sfnt.Font) string {}widths := make(map[uint16]struct{}, 3)- for i := 0; i < metricCount; i++ {+ for i := range metricCount {width := binary.BigEndian.Uint16(data[i*4 : i*4+2])if 0 == width {continue@@ -510,13 +511,7 @@ func fontNameValue(entry *sfnt.NameEntry) string {func collectFontAliases(entries []*sfnt.NameEntry, nameIDs ...sfnt.NameID) (ret []string) {for _, entry := range entries {- matched := false- for _, nameID := range nameIDs {- if entry.NameID == nameID {- matched = true- break- }- }+ matched := slices.Contains(nameIDs, entry.NameID)if !matched {continue}diff --git a/kernel/util/fontconfig.go b/kernel/util/fontconfig.goindex 6d2d2241ee..0624510de0 100644--- a/kernel/util/fontconfig.go+++ b/kernel/util/fontconfig.go@@ -44,7 +44,7 @@ type fontconfigLocalizedName struct {}func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {- for _, record := range bytes.Split(data, []byte(fontconfigRecordSeparator)) {+ for record := range bytes.SplitSeq(data, []byte(fontconfigRecordSeparator)) {if 0 == len(record) {continue}@@ -100,7 +100,7 @@ func parseFontconfigFonts(data []byte, lang string) (ret []*Font) {}func parseFontconfigLocalizedNames(value string) (ret []fontconfigLocalizedName) {- for _, item := range strings.Split(value, fontconfigValueSeparator) {+ for item := range strings.SplitSeq(value, fontconfigValueSeparator) {item = strings.TrimSpace(item)if "" == item {continue@@ -120,7 +120,7 @@ func parseFontconfigLocalizedNames(value string) (ret []fontconfigLocalizedName)}func parseFontconfigValues(value string) (ret []string) {- for _, item := range strings.Split(value, fontconfigValueSeparator) {+ for item := range strings.SplitSeq(value, fontconfigValueSeparator) {if item = strings.TrimSpace(item); "" != item {ret = append(ret, item)}@@ -152,8 +152,8 @@ func fontconfigLanguagesMatch(left, right string) bool {if "" == left || "" == right {return false}- leftPrimary := strings.SplitN(left, "-", 2)[0]- rightPrimary := strings.SplitN(right, "-", 2)[0]+ leftPrimary, _, _ := strings.Cut(left, "-")+ rightPrimary, _, _ := strings.Cut(right, "-")if leftPrimary != rightPrimary {return false}diff --git a/kernel/util/fontconfig_test.go b/kernel/util/fontconfig_test.goindex 624aede6c2..8a1203b287 100644--- a/kernel/util/fontconfig_test.go+++ b/kernel/util/fontconfig_test.go@@ -16,7 +16,10 @@package util-import "testing"+import (+ "slices"+ "testing"+)func TestParseFontconfigFonts(t *testing.T) {data := fontconfigValueSeparator + "LXGW WenKai" + fontconfigPairSeparator + "en" +@@ -98,10 +101,5 @@ func TestParseFontconfigSpacing(t *testing.T) {}func containsFontconfigAlias(aliases []string, expected string) bool {- for _, alias := range aliases {- if alias == expected {- return true- }- }- return false+ return slices.Contains(aliases, expected)}diff --git a/kernel/util/gemini_interactions.go b/kernel/util/gemini_interactions.goindex 357a66106d..0548d66676 100644--- a/kernel/util/gemini_interactions.go+++ b/kernel/util/gemini_interactions.go@@ -284,8 +284,8 @@ func geminiMessageContent(message openai.ChatCompletionMessage) ([]json.RawMessareturn nil, errors.New("missing Gemini image source")}image := map[string]string{"type": "image", "uri": part.ImageURL.URL}- if strings.HasPrefix(part.ImageURL.URL, "data:") {- mime, data, ok := strings.Cut(strings.TrimPrefix(part.ImageURL.URL, "data:"), ";base64,")+ if after, ok := strings.CutPrefix(part.ImageURL.URL, "data:"); ok {+ mime, data, ok := strings.Cut(after, ";base64,")if !ok || !strings.HasPrefix(mime, "image/") || data == "" {return nil, errors.New("unsupported Gemini image data URL")}diff --git a/kernel/util/gemini_interactions_stream.go b/kernel/util/gemini_interactions_stream.goindex 9b2c889f2e..0aaea7c9b9 100644--- a/kernel/util/gemini_interactions_stream.go+++ b/kernel/util/gemini_interactions_stream.go@@ -56,8 +56,8 @@ func (s *geminiInteractionsStream) readEvent() ([]byte, error) {if line == "" {return bytes.TrimSuffix(data.Bytes(), []byte("\n")), nil}- if strings.HasPrefix(line, "data:") {- data.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))+ if after, ok := strings.CutPrefix(line, "data:"); ok {+ data.WriteString(strings.TrimPrefix(after, " "))data.WriteByte('\n')if data.Len() > geminiResponseLimit {return nil, errors.New("Gemini stream event is too large")diff --git a/kernel/util/httprequest.go b/kernel/util/httprequest.goindex 93d0f0b5b3..ba97e75b66 100644--- a/kernel/util/httprequest.go+++ b/kernel/util/httprequest.go@@ -29,6 +29,7 @@ import ("net/url""os""path/filepath"+ "slices""strings""sync""time"@@ -51,11 +52,9 @@ func CheckHostSSRF(host string) error {if err != nil {return errors.New("failed to resolve host: " + err.Error())}- for _, ip := range ips {- // 与 SSRFSafeDialer 共用 isPrivateIP,覆盖 NAT64、6to4、Teredo 等 IPv6 过渡地址。- if isPrivateIP(ip) {- return errors.New("access to private/internal IP is prohibited")- }+ // 与 SSRFSafeDialer 共用 isPrivateIP,覆盖 NAT64、6to4、Teredo 等 IPv6 过渡地址。+ if slices.ContainsFunc(ips, isPrivateIP) {+ return errors.New("access to private/internal IP is prohibited")}return nil}diff --git a/kernel/util/lute_test.go b/kernel/util/lute_test.goindex e6790bbe87..014a73cc53 100644--- a/kernel/util/lute_test.go+++ b/kernel/util/lute_test.go@@ -32,7 +32,7 @@ func TestLuteTextMarkEscapedContentRoundTrip(t *testing.T) {engine := NewLute()const content = "<vitae> & &lt;literal&gt;"dom := `<div data-node-id="20260918120000-abcdefg" data-type="` + blockType + `" data-subtype="h1"><div contenteditable="true">before <span data-type="` + mark + `">` + content + `</span> after</div></div>`- for i := 0; i < 3; i++ {+ for i := range 3 {tree := engine.BlockDOM2Tree(dom)found := falseast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {diff --git a/kernel/util/openai_completion_test.go b/kernel/util/openai_completion_test.goindex b08b044a92..aa2468c8a4 100644--- a/kernel/util/openai_completion_test.go+++ b/kernel/util/openai_completion_test.go@@ -256,7 +256,7 @@ func TestOpenAIResponsesStreamRejectsIncompleteFunctionCall(t *testing.T) {t.Fatal(err)}defer stream.Close()- for i := 0; i < 2; i++ {+ for i := range 2 {if _, err = stream.Recv(); err != nil {t.Fatalf("receive partial function event %d: %v", i, err)}diff --git a/kernel/util/openai_gemini.go b/kernel/util/openai_gemini.goindex e847ff42ec..17b49e0718 100644--- a/kernel/util/openai_gemini.go+++ b/kernel/util/openai_gemini.go@@ -383,8 +383,8 @@ func (r *geminiThoughtSignatureReadCloser) captureLine(line []byte) {if len(line) == 0 {return}- if bytes.HasPrefix(line, []byte("data:")) {- line = bytes.TrimSpace(bytes.TrimPrefix(line, []byte("data:")))+ if after, ok := bytes.CutPrefix(line, []byte("data:")); ok {+ line = bytes.TrimSpace(after)}if len(line) == 0 || bytes.Equal(line, []byte("[DONE]")) {return@@ -452,6 +452,6 @@ type geminiChatToolCall struct {ExtraContent struct {Google struct {ThoughtSignature string `json:"thought_signature,omitempty"`- } `json:"google,omitempty"`- } `json:"extra_content,omitempty"`+ } `json:"google"`+ } `json:"extra_content"`}diff --git a/kernel/util/path.go b/kernel/util/path.goindex c662554ee5..bdf7427d5d 100644--- a/kernel/util/path.go+++ b/kernel/util/path.go@@ -556,10 +556,10 @@ func localAdminShareDrive(p string) (drive string, prefixLen int) {host := rest[:sep]rest = rest[sep+1:]- shareSep := strings.Index(rest, `\`)+ before, _, ok := strings.Cut(rest, `\`)share := rest- if 0 <= shareSep {- share = rest[:shareSep]+ if ok {+ share = before}if len(share) != 2 || share[1] != '$' || !isASCIILetter(share[0]) {return "", 0diff --git a/kernel/util/path_guard.go b/kernel/util/path_guard.goindex 0851e06895..53f4824ad5 100644--- a/kernel/util/path_guard.go+++ b/kernel/util/path_guard.go@@ -80,7 +80,7 @@ func IsForbiddenDataRelPath(rel string) bool {// 统一为斜杠并清理(path.Clean 使用斜杠语义,避免 Windows 上分隔符差异)rel = path.Clean("/" + filepath.ToSlash(rel))protectedRel := pluginDevelopmentLexicalPath(rel)- for _, component := range strings.Split(protectedRel, "/") {+ for component := range strings.SplitSeq(protectedRel, "/") {if strings.HasPrefix(component, ".siyuan-package-install-") {return true}diff --git a/kernel/util/plugin_development.go b/kernel/util/plugin_development.goindex f742e828c3..0aaa36f685 100644--- a/kernel/util/plugin_development.go+++ b/kernel/util/plugin_development.go@@ -152,7 +152,7 @@ func IsPluginDevelopmentRawPathForbidden(abs string, ancestors bool) bool {return true}}- for _, component := range strings.Split(pluginDevelopmentLexicalPath(candidate), "/") {+ for component := range strings.SplitSeq(pluginDevelopmentLexicalPath(candidate), "/") {if strings.HasPrefix(component, ".siyuan-package-install-") {return true}diff --git a/kernel/util/plugin_project.go b/kernel/util/plugin_project.goindex 7da26858c3..4401f6fb82 100644--- a/kernel/util/plugin_project.go+++ b/kernel/util/plugin_project.go@@ -14,6 +14,7 @@ import ("fmt""io""io/fs"+ "maps""os""path""path/filepath"@@ -103,7 +104,7 @@ func ValidatePluginProjectFile(name string) error {if err := validateManagedSkillPath(name); err != nil {return fmt.Errorf("invalid_path: %w", err)}- for _, part := range strings.Split(strings.ToLower(name), "/") {+ for part := range strings.SplitSeq(strings.ToLower(name), "/") {switch part {case "configs", "settings", "cache", "logs", "secrets", "credentials", "data.json", "settings.json", "token.json", "token.txt", "tokens.txt", "auth.json", "auth.txt", "credential.json", "credentials.txt", "secret.json", "secrets.json", "secrets.txt":return fmt.Errorf("invalid_path: credential or runtime material is not permitted: %s", name)@@ -173,7 +174,7 @@ func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error) {if rel == "." {return root, nil}- for _, part := range strings.Split(filepath.ToSlash(rel), "/") {+ for part := range strings.SplitSeq(filepath.ToSlash(rel), "/") {if part == "" || part == "." || part == ".." {root.Close()return nil, errors.New("invalid_path")@@ -832,9 +833,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)return errors.New("revision_conflict: current project revision changed")}known := map[string]string{}- for name, rev := range manifest.Current {- known[name] = rev- }+ maps.Copy(known, manifest.Current)for name, change := range manifest.Pending {actual := inventory[name]if actual == "" {diff --git a/kernel/util/plugin_project_test.go b/kernel/util/plugin_project_test.goindex ad12d2b8b4..3d75562e56 100644--- a/kernel/util/plugin_project_test.go+++ b/kernel/util/plugin_project_test.go@@ -326,7 +326,7 @@ func TestPluginProjectRepeatedMutationsKeepBoundedRecoveryState(t *testing.T) {t.Fatal(err)}previous := "initial"- for i := 0; i < 600; i++ {+ for i := range 600 {next := fmt.Sprintf("revision %d", i)err := WithPluginProjectSource(ctx, true, func(g *PluginDevelopmentGrant, root *os.Root) error {if err := BeginPluginProjectMutation(g, "index.js", PluginProjectDigest([]byte(previous)), PluginProjectDigest([]byte(next))); err != nil {@@ -389,7 +389,7 @@ func TestPluginProjectRepeatedReplansKeepOnlyCurrentCheckpoint(t *testing.T) {if err = os.WriteFile(unknown, []byte("keep"), 0600); err != nil {t.Fatal(err)}- for i := 0; i < 20; i++ {+ for i := range 20 {grant.PlanHash, grant.PlanVersion = fmt.Sprintf("plan %d", i), i+2status, err = PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision)if err != nil {diff --git a/kernel/util/publish_file.go b/kernel/util/publish_file.goindex 42f38a068f..914cd96eca 100644--- a/kernel/util/publish_file.go+++ b/kernel/util/publish_file.go@@ -11,7 +11,7 @@ func IsPublishRelativePath(name string) bool {if name == "" || strings.ContainsAny(name, "\\:%\x00") {return false}- for _, part := range strings.Split(name, "/") {+ for part := range strings.SplitSeq(name, "/") {if part == "" || part == "." || part == ".." || strings.TrimSpace(part) != part || strings.HasSuffix(part, ".") {return false}diff --git a/kernel/util/runtime.go b/kernel/util/runtime.goindex d7c7e1fe9f..c6628855a0 100644--- a/kernel/util/runtime.go+++ b/kernel/util/runtime.go@@ -25,6 +25,7 @@ import ("path/filepath""runtime""runtime/debug"+ "slices""strings""sync""sync/atomic"@@ -52,12 +53,7 @@ func DisableFeature(feature string) {// IsDisabledFeature 查询原生端启动时禁用的功能,不修改用户配置。func IsDisabledFeature(feature string) bool {- for _, disabled := range DisabledFeatures {- if disabled == feature {- return true- }- }- return false+ return slices.Contains(DisabledFeatures, feature)}const DefaultUseSingleLineSave = truediff --git a/kernel/util/session_test.go b/kernel/util/session_test.goindex 1773fc9497..2b16cb64c1 100644--- a/kernel/util/session_test.go+++ b/kernel/util/session_test.go@@ -45,7 +45,7 @@ func TestAuthCodeEquals(t *testing.T) {func TestAuthThrottleThreshold(t *testing.T) {key := "TestAuthThrottleThreshold"resetAuthThrottleForTest(key)- for i := 0; i < authThrottleMaxFail; i++ {+ for i := range authThrottleMaxFail {if retryAfter := AuthThrottleCheck(key); 0 < retryAfter {t.Fatalf("locked before reaching threshold at attempt %d", i+1)}@@ -61,11 +61,11 @@ func TestAuthThrottleThreshold(t *testing.T) {func TestAuthThrottleBackoff(t *testing.T) {key := "TestAuthThrottleBackoff"resetAuthThrottleForTest(key)- for i := 0; i < authThrottleMaxFail+1; i++ {+ for range authThrottleMaxFail + 1 {AuthThrottleFail(key)}firstLock := time.Until(authThrottles[key].LockUntil)- for i := 0; i < authThrottleMaxFail; i++ {+ for range authThrottleMaxFail {AuthThrottleFail(key)}extendedLock := time.Until(authThrottles[key].LockUntil)@@ -119,7 +119,7 @@ func TestAuthThrottleWindowReset(t *testing.T) {func TestAuthThrottleReset(t *testing.T) {key := "TestAuthThrottleReset"resetAuthThrottleForTest(key)- for i := 0; i < authThrottleMaxFail+1; i++ {+ for range authThrottleMaxFail + 1 {AuthThrottleFail(key)}if retryAfter := AuthThrottleCheck(key); 0 >= retryAfter {@@ -135,7 +135,7 @@ func TestAuthThrottleReset(t *testing.T) {func TestAuthThrottleExpiry(t *testing.T) {key := "TestAuthThrottleExpiry"resetAuthThrottleForTest(key)- for i := 0; i < authThrottleMaxFail+1; i++ {+ for range authThrottleMaxFail + 1 {AuthThrottleFail(key)}authThrottleLock.Lock()@@ -155,7 +155,7 @@ func TestAuthThrottleExpiry(t *testing.T) {// TestAuthThrottleSweep 验证定期清扫会删除窗口期已过的失败记录,即使 key 不再被访问。func TestAuthThrottleSweep(t *testing.T) {staleKeys := make([]string, 0, 64)- for i := 0; i < 64; i++ {+ for i := range 64 {key := fmt.Sprintf("TestAuthThrottleSweep-stale-%d", i)AuthThrottleFail(key)defer resetAuthThrottleForTest(key)@@ -186,7 +186,7 @@ func TestAuthThrottleSweepKeepsLocked(t *testing.T) {key := "TestAuthThrottleSweepKeepsLocked"resetAuthThrottleForTest(key)defer resetAuthThrottleForTest(key)- for i := 0; i < authThrottleMaxFail+1; i++ {+ for range authThrottleMaxFail + 1 {AuthThrottleFail(key)}authThrottleLock.Lock()@@ -213,7 +213,7 @@ func TestAuthThrottleMaxEntries(t *testing.T) {}authThrottleLock.Unlock()- for i := 0; i < authThrottleMaxEntries+50; i++ {+ for i := range authThrottleMaxEntries + 50 {AuthThrottleFail(fmt.Sprintf("TestAuthThrottleMaxEntries-%d", i))}authThrottleLock.Lock()diff --git a/kernel/util/shared_cache_test.go b/kernel/util/shared_cache_test.goindex 4c3d00b0cd..d5bf7325cb 100644--- a/kernel/util/shared_cache_test.go+++ b/kernel/util/shared_cache_test.go@@ -51,9 +51,9 @@ func TestNativeEmojiCacheReplacementAndConcurrentReads(t *testing.T) {}write(`[{"items":[{"unicode":"new"}]}]`)var group sync.WaitGroup- for i := 0; i < 8; i++ {+ for range 8 {group.Go(func() {- for j := 0; j < 50; j++ {+ for range 50 {InitEmojiChars()if !IsNativeEmoji("new") || IsNativeEmoji("old") {t.Error("concurrent refresh changed emoji membership")@@ -123,16 +123,16 @@ func TestRhyCacheSnapshotsAndConcurrentRefresh(t *testing.T) {fail.Store(false)var group sync.WaitGroupgroup.Go(func() {- for i := 0; i < 25; i++ {+ for range 25 {if _, err := getRhyResult0(ctx, server.URL); err != nil {t.Error(err)return}}})- for i := 0; i < 8; i++ {+ for range 8 {group.Go(func() {- for j := 0; j < 100; j++ {+ for range 100 {result, err := GetRhyResult(ctx, false)if err != nil || !strings.HasPrefix(result["bazaar"].(string), "hash-") {t.Errorf("invalid cached result: %#v err=%v", result, err)diff --git a/kernel/util/skill.go b/kernel/util/skill.goindex c47871702e..b49a960aad 100644--- a/kernel/util/skill.go+++ b/kernel/util/skill.go@@ -26,6 +26,7 @@ import ("path""path/filepath""regexp"+ "slices""sort""strings""unicode/utf8"@@ -232,10 +233,8 @@ func DiscoverUserSkills(enabledUserSkills []string) []UserSkillInfo {func findSkillRecord(records []skillRecord, name string) (skillRecord, bool) {key := skillKey(name)for _, record := range records {- for _, alias := range skillAliases(record) {- if alias == key {- return record, true- }+ if slices.Contains(skillAliases(record), key) {+ return record, true}}return skillRecord{}, falsediff --git a/kernel/util/skill_manage.go b/kernel/util/skill_manage.goindex a934199623..5bc7e82028 100644--- a/kernel/util/skill_manage.go+++ b/kernel/util/skill_manage.go@@ -58,7 +58,7 @@ func validateManagedSkillPath(p string) error {if p == "" || !fs.ValidPath(p) || strings.ContainsAny(p, "\\:") {return errors.New("invalid skill path")}- for _, part := range strings.Split(p, "/") {+ for part := range strings.SplitSeq(p, "/") {if strings.TrimSpace(part) != part || strings.HasSuffix(part, ".") ||strings.ContainsAny(part, "<>\"|?*~") || strings.ContainsFunc(part, unicode.IsControl) {return errors.New("invalid skill path component")diff --git a/kernel/util/skill_test.go b/kernel/util/skill_test.goindex df7fc54fa9..a70d77cb23 100644--- a/kernel/util/skill_test.go+++ b/kernel/util/skill_test.go@@ -306,7 +306,7 @@ func TestLoadSkillCapsManifestTraversal(t *testing.T) {workspaceRoot, _ := setSkillTestRoots(t)writeSkill(t, workspaceRoot, "many-dirs", "many-dirs", "description", "body")skillDir := filepath.Join(workspaceRoot, "many-dirs")- for i := 0; i < maxSkillResourceVisited; i++ {+ for i := range maxSkillResourceVisited {if err := os.Mkdir(filepath.Join(skillDir, fmt.Sprintf("empty-%04d", i)), 0755); err != nil {t.Fatal(err)}diff --git a/kernel/util/system_proxy.go b/kernel/util/system_proxy.goindex 7bbf5e70b4..fc5aef96cf 100644--- a/kernel/util/system_proxy.go+++ b/kernel/util/system_proxy.go@@ -49,7 +49,7 @@ func parseSystemNetworkProxy(proxyServer, proxyOverride string) (*systemNetworkP}proxies := map[string]string{}- for _, field := range strings.Split(proxyServer, ";") {+ for field := range strings.SplitSeq(proxyServer, ";") {parts := strings.SplitN(field, "=", 2)if 2 != len(parts) {continue@@ -119,7 +119,7 @@ func parseSystemNetworkProxyBypass(proxyOverride string) string {seen[entry] = true}}- for _, field := range strings.Split(proxyOverride, ";") {+ for field := range strings.SplitSeq(proxyOverride, ";") {field = strings.TrimSpace(field)if strings.EqualFold(field, "<local>") {add("localhost")diff --git a/kernel/util/text_file.go b/kernel/util/text_file.goindex 5633473eaf..514b732ff5 100644--- a/kernel/util/text_file.go+++ b/kernel/util/text_file.go@@ -34,13 +34,12 @@ func textFileError(code, message string) error {}func textFileBeforeCommitError(err error) error {- var failure *TextFileError- if errors.As(err, &failure) {+ if failure, ok := errors.AsType[*TextFileError](err); ok {return failure}for _, code := range []string{"revision_conflict", "invalid_path", "unsupported_encoding", "too_large", "backup_failed", "result_unknown"} {- if strings.HasPrefix(err.Error(), code+":") {- return textFileError(code, strings.TrimSpace(strings.TrimPrefix(err.Error(), code+":")))+ if after, ok := strings.CutPrefix(err.Error(), code+":"); ok {+ return textFileError(code, strings.TrimSpace(after))}}return textFileError("backup_failed", err.Error())diff --git a/kernel/util/tls_cert_manager_test.go b/kernel/util/tls_cert_manager_test.goindex 6d118c0f61..16b471e581 100644--- a/kernel/util/tls_cert_manager_test.go+++ b/kernel/util/tls_cert_manager_test.go@@ -182,7 +182,7 @@ func TestTLSCertManagerRefreshesCertificateOnceForConcurrentHandshakes(t *testinerrs := make([]error, handshakeCount)var waitGroup sync.WaitGroupwaitGroup.Add(handshakeCount)- for i := 0; i < handshakeCount; i++ {+ for i := range handshakeCount {go func(index int) {defer waitGroup.Done()certificates[index], errs[index] = manager.GetCertificate(&tls.ClientHelloInfo{diff --git a/kernel/util/webfetch.go b/kernel/util/webfetch.goindex d5fe66f84a..4fc2948b62 100644--- a/kernel/util/webfetch.go+++ b/kernel/util/webfetch.go@@ -162,7 +162,7 @@ func extractFilename(rawURL, contentType string) string {}func extByContentType(contentType string) string {- ct := strings.SplitN(contentType, ";", 2)[0]+ ct, _, _ := strings.Cut(contentType, ";")if exts, _ := mime.ExtensionsByType(ct); len(exts) > 0 {return exts[0]}