An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:fire: Move endpoint behavior into the contract declarations
Jeffrey Chenc01fbe7cf6b0
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex e83ce46aec..97e4e86f67 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -3063,6 +3063,14 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin"];};+ /**+ * 使用严格字符串字段,通过管理员和只读检查管理工作空间技能文件。相对路径标识实际目录,+ * 与文件头中的技能名称无关,允许普通的点开头名称。读写支持不超过 8 MiB 的 UTF-8 文本,+ * 不依赖扩展名并保留原文字节。目录和资源读取保留基于内容的版本;不支持编辑的内容省略 content,+ * 并增加可选的 readOnlyReason(binary、encoding 或 tooLarge)。+ * 修改已有文件时重新校验内容并要求当前版本,与旧技能修改接口和安装共享临界区,成功后通知同步。+ * 路径穿越、平台别名、链接、过期版本,以及单独修改不支持的内容或重命名、删除根 SKILL.md 均被拒绝。+ */"/api/ai/agent/manageSkills": {request: AISkillFileRequestInput;response: { "code": 0; "data": AISkillFileData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -3363,6 +3371,11 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 用固定的 TypeSafe System One 样例测试已保存的可选 ai.decision 配置,返回 {matched, msg?}。+ * 遵循全局人工智能禁用标记和请求取消,配置错误与供应商错误不会被转换为判断结果。+ * 省略决策配置时补齐默认关闭的配置,关闭后保留密钥,并沿用现有配置加密存储机制。+ */"/api/ai/testDecisionModel": {request: AIDecisionTestRequestInput;response: { "code": 0; "data": AIDecisionTestData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -3661,6 +3674,7 @@ export interface APIPOSTRoutes {};/*** 返回普通资源路径;已解锁的加密资源返回保留原始名称的受管临时明文副本路径。+ * 请求持有加密笔记本租约直至响应序列化完成,外部编辑不写回加密源数据。*/"/api/asset/resolveAssetPath": {request: AssetPathRequestInput;@@ -4835,6 +4849,11 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 要求管理员身份,保留只读保护及加密笔记本请求租约;请求必须提供文档 id 和 notebook。+ * 保存历史后在一次可撤销事务中转换能够完整解析的旧 mindmap 列表,返回 converted 数量与文档脑图的+ * 权威 blocks(id、dom)。重复请求返回当前块内容而不重复转换,不完整的原文保持不变。+ */"/api/block/migrateLegacyMindmaps": {request: MigrateLegacyMindmapsRequestInput;response: { "code": 0; "data": MigrateLegacyMindmapsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -4888,6 +4907,14 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 编辑器通过独立事务转换块引用:id 指定引用块,blockID 指定定义块,data 携带布尔选项 includeChildren+ * 和 originalToEmbed。内核在 retData 中返回受影响的文档 ID,并以受影响顶层块的私有内存快照生成逆向操作;+ * 快照不传给客户端,也不接受客户端提交。重放保留块 ID 和数据库绑定,内容或位置已改变时拒绝覆盖,+ * originalToEmbed 省略或为 false 时在原定义位置保留引用,为 true 时替换为查询已移动定义 ID 的嵌入块;+ * includeChildren 保留标题和列表行为。+ * 提交失败时补偿已写入的文档。撤销与重放期间为所有受影响文档持有笔记本租约,直至响应序列化完成。+ */"/api/block/swapBlockRef": {request: SwapBlockRefRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5487,7 +5514,10 @@ export interface APIPOSTRoutes {authorization?: readonly ["authenticated","admin","writable"];};/**- * evaluates block collection rules for every copied document and block, initializing only new rows.+ * 将单篇文档及全部子文档复制到同一笔记本的原父目录,返回副本根文档的 id、notebook、path 和 hPath。+ * 副本内部块引用、块链接和查询嵌入的显式块 ID 统一重映射,数据库定义与行绑定保持为共享镜像。+ * 源快照经过认证读取且不执行修复写回;运行期失败时清理新建文档并恢复排序,属运行时补偿,+ * 不保证进程崩溃时的事务原子性。*/"/api/filetree/duplicateDocTree": {request: FileTreeIDRequestInput;@@ -6684,6 +6714,9 @@ export interface APIPOSTRoutes {/*** sourceFilter.database 在父块合并前按来源块的数据库字段筛选,不修改原数据库视图。* 无条件仅筛数据库成员,失效字段不放宽结果;原来源筛选、排序及加密笔记本租约保持不变。+ * blockSort 为 0(默认)时保持正文顺序,1 按匹配引用的锚文本自然升序,2 为自然降序,其他值回退正文顺序。+ * 条目取首个匹配引用的锚文本并去除首尾空白;排序键相同时保持正文顺序,无锚文本的条目在两个方向均置后。+ * 来源文档内部把整篇文档条目展开为可独立排序的引用,恢复正文顺序时重新合并;排序模式参与上下文版本哈希。*/"/api/ref/getBacklinkDoc": {request: BacklinkDocumentRequestInput;@@ -6704,6 +6737,8 @@ export interface APIPOSTRoutes {};/*** 数据库条件与列表快照一致,不修改来源数据或原数据库视图。+ * 必需的 snapshot 与最多 20 个属于该快照的块 ids 返回可独立编辑的块正文,保留面包屑和数据库引用信息。+ * 返回前重新检查来源权限并持有加密笔记本请求租约;发布阅读者不能读取加密笔记本。*/"/api/ref/getGlobalBacklinkContexts": {request: GlobalBacklinkContextRequestInput;@@ -7978,6 +8013,11 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * completeAssets 为 true 时,在切换来源前从原提供商下载缺失的当前资源和历史快照内容;+ * 省略、null 与 false 保留只检查完整性的行为。补齐过程保留下载模式和恢复密钥,失败时保留原提供商。+ * 确认后的操作通过全局进度遮罩显示检查与补齐阶段,成功或失败均关闭遮罩。+ */"/api/sync/setSyncProvider": {request: SyncProviderRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -8241,6 +8281,11 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin"];};+ /**+ * 无需请求体,要求管理员权限并允许只读模式,返回 {text} 诊断摘要:内核版本、运行时、操作系统、+ * 逻辑 CPU 数量、当前系统与进程内存,以及检测到的工作空间存储类型。+ * 无法探测的内存或存储返回 unknown,不把移动端存储推断为 SSD;文本不含工作空间路径、主机名和账户标识。+ */"/api/system/getRuntimeInfo": {request: EmptyRequestInput;response: { "code": 0; "data": SystemRuntimeInfoData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 6f937ed494..4987f83286 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -38,59 +38,41 @@ Encrypted notebook lifecycle endpoints use typed requests and responses while re## Compatibility requirements-`POST /api/ai/testDecisionModel` tests the saved optional `ai.decision` configuration with a fixed TypeSafe System One sample. It requires administrator access, honors the global AI disable flag and request cancellation, and returns typed `{matched, msg?}` data; configuration and provider errors do not fabricate a judgment. Omitted decision configuration normalizes to disabled defaults and disabling preserves the API key using the existing encrypted configuration storage. `TestAPIContractAI*`, `TestAPIContractSetting*`, `TestAIDecisionConfiguration`, and `TestDecision*` cover contracts, configuration, sequential partial results, block reads, locked-notebook rejection, capability availability, confirmation, cancellation, and provider validation. They run in the full kernel CI suite. Run the focused checks with `go test -tags "fts5 sqlcipher" ./api ./conf ./util ./mcp/tools ./agent -run 'Test(APIContractAI|APIContractSetting|AIDecision|Decision)' -count=1` and `go test ./apicontract/...`.+Mobile distributions may call `DisableFeature("ai")` before kernel startup. All `/api/ai/` endpoints and `/api/setting/setAI` reject requests before body decoding while retaining route authentication and authorization. JSON endpoints return code `-1` with null data; the MCP OAuth callback returns HTTP 403 as plain text. Stored AI configuration is preserved. Embedding indexing, reranking, and outgoing MCP connections also honor the flag.-`POST /api/system/getRuntimeInfo` accepts no body and returns `{text: string}` in the standard success envelope. It requires authentication and administrator access, supports read-only mode, and reports kernel version, runtime, OS, logical CPU count, current system and process memory, and detected workspace storage type. Unsupported memory and storage probes report `unknown`; mobile storage is not inferred to be SSD. Diagnostic text excludes workspace paths, hostnames, and account identifiers. `TestAPIContractSystemRuntimeInfo` runs in the full kernel CI suite; run the focused checks with `go test -tags "fts5 sqlcipher" ./api -run TestAPIContractSystemRuntimeInfo -count=1` and `go test ./apicontract/...`.--Mobile distributions may call `DisableFeature("ai")` before kernel startup. All `/api/ai/` endpoints and `/api/setting/setAI` reject requests before body decoding while retaining route authentication and authorization. JSON endpoints return code `-1` with null data; the MCP OAuth callback returns HTTP 403 as plain text. Stored AI configuration is preserved. Embedding indexing, reranking, and outgoing MCP connections also honor the flag. `TestAPIContractAIDisabled`, `TestAIDisabledBackgroundFeatures`, and `TestAIDisabledMCPConnections` run in the full kernel CI suite. Run the affected checks with `go test -tags "fts5 sqlcipher" ./api ./model ./mcp/client -run 'Test(APIContractAI|AIDisabled)' -count=1` and `go test ./apicontract/...`.--Encrypted notebook system-lock endpoints preserve administrator authorization and read-only checks. The boolean preference is stored in system configuration, outside authenticated key backups. `TestAPIContractNotebookSystemLock` covers persistence, disabled behavior, independence from the idle timeout, multiple notebooks (including an unlocked but unmounted notebook), repeated locking, denied reads after locking, and authenticated reads of unchanged ciphertext after re-unlocking. It is included in the full kernel command below; run it separately with `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization)$' -count=1`. `TestNotebookSystemLockContract` covers strict boolean input and `TestRouteCoverage` checks registration and handler bindings.+Encrypted notebook system-lock endpoints preserve administrator authorization and read-only checks. The boolean preference is stored in system configuration, outside authenticated key backups.At migration completion on September 14, 2026, all 629 method/path registrations in `kernel/api/router.go` were contracted and the legacy list was empty. At that baseline, four `ANY` registrations expanded to 661 concrete method/path pairs in generated metadata. Use the generator and route coverage checks for current counts as endpoints are added. Static resources, the main application WebSocket, and other transport services registered by `kernel/server/serve.go` are outside this API route inventory.System contracts retain complete configuration, workspace management, uploads, authentication, OIDC response variants, boot streams, and empty or binary responses. Persisted layout and shortcut values are narrowed where the frontend consumes them, preserving existing default repair, obsolete-key cleanup, and binding filtering. Configuration export, import, and shutdown keep their existing lifecycle and encryption behavior.-The OIDC web callback returns HTTP 200 HTML after authentication, including repeated successful callbacks. It reuses the shared result page and starts a same-origin navigation with a meta refresh and a fallback link, ending the provider's cross-site HTTP redirect chain without relaxing session origin checks. Desktop and validation callbacks retain their result pages. `TestOIDCWebCallbackContract`, `TestOIDCRepeatedWebCallbackContractSession`, and `TestRenderOAuthRedirectPage` cover the response contract, target escaping, session cookies, and continued cross-site rejection; the full kernel CI suite includes them. Run focused checks with `go test -tags "fts5 sqlcipher" ./model ./util ./api -run 'Test(OIDC|WriteOIDC|RenderOAuth|IsSessionOriginAllowed|IsCrossSiteFetchSite|CheckAuthRemoteSessionOrigin|APIContractSystem|APIContractRouterCoverage)' -count=1` and `go test ./apicontract/...`.-Transaction contracts discriminate all 98 known operation actions and exclude those names from the explicit unknown-action compatibility branch. The frontend uses the same finite operation union. Private raw input preserves historical fields, ignored values, asynchronous model errors, and echoed payloads; schema declarations do not move model validation into HTTP admission. Undo, redo, heading operations, response leases, and transaction persistence formats retain their existing behavior.-The editor submits a standalone `swapBlockRef` transaction with the reference in `id`, the definition in `blockID`, and the boolean options `includeChildren` and `originalToEmbed` in `data`. The kernel returns affected document IDs in `retData` and records an inverse operation with a private in-memory snapshot of affected top-level blocks. Snapshots are never serialized to clients or accepted from requests. Replay preserves block IDs and database bindings, rejects changed content or positions, and compensates document writes after a commit failure. `TestBlockSwapTransaction` covers persisted undo/redo, cross-document history, conflict rejection, and write-failure recovery; it runs in the full kernel command below. Run it separately with `go test -tags "fts5 sqlcipher" ./model -run 'Test(SwapBlockRefNodes|BlockSwapTransaction)' -count=1`.--Block-swap undo and redo hold notebook leases for all affected documents through response serialization. `TestContractBlockSwapReplayNotebookResponseLease` verifies that locking waits for the response to finish and is included in the full kernel command.-Extension clipping retains first-value multipart handling, dynamically named uploaded files, partial results, original messages, and encrypted-notebook admission. Dynamic icons retain SVG bytes, security and cache headers, and empty failure responses. Broadcast streams declare raw SSE bytes with dynamic event names, IDs, and retry values, and raw WebSocket frames with their upgrade errors; payloads are not converted to JSON or Base64, and channel cleanup retains its original scope.Plugin private services declare their existing serialization modes, raw files, redirects, proxy responses, SSE events, and WebSocket frames. Plugin-defined payloads remain protocol extension data; branch-specific validation distinguishes serialized formats from arbitrary bytes. Request bodies, explicit response headers, admission failures, and cancellation retain the plugin service lifecycle.Network contracts retain request bytes, multipart fields, headers, URL and TLS diagnostics, including complete certificate public-key structures and large integers. Forward proxy options preserve validation order, numeric truncation, response encodings, and protocol-defined JSON payloads. HTTP, EventSource, and WebSocket proxies retain upstream statuses and bytes, repeated-header behavior, security headers, stream cancellation, and connection cleanup. Echo wildcard paths bind their own adapter while sharing the same handler behavior.-Attribute-view contracts declare table, gallery, and kanban result shapes and retain missing base fields, cell patches, and null values. The independent `list` layout uses the table-shaped `columns`/`rows`/`rowCount` payload and stores its layout settings under `list`; `viewType` identifies it as `list`. Known patch fields retain their supplied presence without populating omitted fields with zero values. Current, history, and snapshot rendering use their corresponding request types; callers handle error payloads before updating views. Row sorting, publish admission, encrypted-notebook leases, and fast JSON rendering preserve their existing behavior. Shared frontend and plugin declarations reflect the fields actually present in each view and cell. `TestAVContractListLayout` covers layout switching, default field visibility, subsequent rendering, and stored-layout mapping; run `go test -tags "fts5 sqlcipher" ./api -run 'TestAVContract' -count=1` and `go test ./apicontract/...`. These tests are included in the full kernel CI suite.+Attribute-view contracts declare table, gallery, and kanban result shapes and retain missing base fields, cell patches, and null values. The independent `list` layout uses the table-shaped `columns`/`rows`/`rowCount` payload and stores its layout settings under `list`; `viewType` identifies it as `list`. Known patch fields retain their supplied presence without populating omitted fields with zero values. Current, history, and snapshot rendering use their corresponding request types; callers handle error payloads before updating views. Row sorting, publish admission, encrypted-notebook leases, and fast JSON rendering preserve their existing behavior. Shared frontend and plugin declarations reflect the fields actually present in each view and cell. These tests are included in the full kernel CI suite.-Publish readers of attribute-view rendering endpoints use a non-persistent rendering path. Requests retain their existing schemas, carrier authorization, content filtering, and notebook leases; even `createIfNotExist: true` cannot create a missing database for a reader. Compatibility normalization, group generation, and missing-field corrections remain in memory. `TestAVContractPublishRenderDoesNotWrite` covers explicit view switching, unchanged database and carrier files, denied access, and missing databases. It runs in the full kernel CI suite; run the focused checks with `go test -tags "fts5 sqlcipher" ./api -run 'TestAVContract(PublishRenderDoesNotWrite|RenderWire)$' -count=1` and `go test ./apicontract/...`. Frontend session-state and DOM regressions run through `node --import tsx --test src/protyle/render/av/publishState.test.ts tests/publishReadonlyFold.test.js` and the full frontend CI suite.+Publish readers of attribute-view rendering endpoints use a non-persistent rendering path. Requests retain their existing schemas, carrier authorization, content filtering, and notebook leases; even `createIfNotExist: true` cannot create a missing database for a reader. Compatibility normalization, group generation, and missing-field corrections remain in memory. Frontend session-state and DOM regressions run through `node --import tsx --test src/protyle/render/av/publishState.test.ts tests/publishReadonlyFold.test.js` and the full frontend CI suite.AI contracts retain provider configuration, model discovery and matching, confirmation decisions, session extensions, and numeric and omission semantics. Editor and agent streams declare their actual SSE events; disconnection closes upstream requests, and stream lifetimes remain within the request. OAuth pages retain their media types, HTTP statuses, and security headers. Session permission notifications use `WithAfterWrite` to preserve response-before-broadcast ordering. Arbitrary JSON remains limited to protocol extension fields and tool results.-AI providers accept `anthropic-messages` alongside `openai` and `openai-responses`; omitted protocols retain the Chat Completions default. Native Messages calls cover model discovery, model tests, editor generation, agent tools, titles, and summary compaction. An automatic output limit uses 4096 tokens because Messages requires `max_tokens`. Assistant entries may carry `nativeContent` with a protocol, version, and opaque content blocks; version 1 preserves Anthropic thinking signatures and block ordering across runtime recovery and session commits. Other protocols project the visible conversation without sending these native blocks. Unknown native versions fail before sending a Messages request, retaining the original session. Stream usage is emitted once after `message_stop`, and incomplete tool responses cannot reach tool execution. `TestAnthropic*` and `TestAPIContractAnthropic*` run in the full kernel CI suite; run the affected subset with `go test -tags "fts5 sqlcipher" ./conf ./util ./agent ./api ./apicontract/... -run 'Test(Anthropic|APIContractAnthropic|APIContractAI|AIInput|AISession|RouteCoverage)' -count=1`, plus `go test ./apicontract/...`. The existing frontend test discovery includes `aiProviderPresets.test.ts`.--`/api/ai/agent/manageSkills` uses strict string fields and administrator/read-only admission for workspace skill files. Relative paths identify physical directories independently of frontmatter names, including ordinary dot-prefixed names. Reads and writes support UTF-8 text up to 8 MiB regardless of extension and preserve source bytes. Directory and resource reads retain content-based revisions; non-editable contents omit `content` and add an optional `readOnlyReason` (`binary`, `encoding`, or `tooLarge`). The read response, rather than a stale list entry, determines editor availability. Existing mutations revalidate content and require the current revision, share a critical section with legacy skill mutations and installation, and notify synchronization after success. Path traversal, platform aliases, links, stale revisions, and individual modification of unsupported contents or renaming/deletion of root `SKILL.md` are rejected. `TestAISkillManagementContract`, `TestAPIContractAISkillManagement`, and `TestSkillManagement` cover request types, actual HTTP responses, authorization, raw content, text classification, hidden paths, concurrent saves, and filesystem boundaries. Run `go test -tags "fts5 sqlcipher" ./apicontract/... ./api ./util -run 'Test(AISkillManagementContract|APIContractAISkillManagement|SkillManagement|RouteCoverage)' -count=1`; the full kernel CI suite below includes all of these regressions.+AI providers accept `anthropic-messages` alongside `openai` and `openai-responses`; omitted protocols retain the Chat Completions default. Native Messages calls cover model discovery, model tests, editor generation, agent tools, titles, and summary compaction. An automatic output limit uses 4096 tokens because Messages requires `max_tokens`. Assistant entries may carry `nativeContent` with a protocol, version, and opaque content blocks; version 1 preserves Anthropic thinking signatures and block ordering across runtime recovery and session commits. Other protocols project the visible conversation without sending these native blocks. Unknown native versions fail before sending a Messages request, retaining the original session. Stream usage is emitted once after `message_stop`, and incomplete tool responses cannot reach tool execution. The existing frontend test discovery includes `aiProviderPresets.test.ts`.Setting contracts retain partial configuration merging, existing defaults, case-insensitive struct fields, explicit null values, JSON number normalization, and parser error messages. Keyboard shortcuts and cloud authentication results declare their fixed fields while preserving their protocol-defined JSON extensions. Cloud-user admission still precedes body reads for non-administrators, and two-factor authentication keeps cloud error codes and extension fields. Frontend callers normalize persisted display settings at the same existing boundaries.Document-tree contracts retain conditional parameter validation, path and sorting semantics, omitted callbacks, pagination defaults, and document response variants. Publish authentication preserves HTTP 429 and `Retry-After` through explicitly declared additional error statuses. Publish and encrypted-notebook admission remain before deferred field validation, and document leases cover response serialization.-`POST /api/filetree/duplicateDocTree` copies one document and all descendants within the same notebook and parent. It accepts a document `id` and returns the new root's `id`, `notebook`, `path`, and `hPath`; the existing single-document endpoint remains unchanged. Internal block references, block links, and explicit block IDs in query embeds are remapped across the copied tree, while database definitions and row bindings remain shared mirrors. Source snapshots are authenticated without repair writes, and detected runtime failures remove new documents and restore sorting. This is runtime compensation, not a crash-atomic transaction. `TestDuplicateDocTree*` covers hierarchy, ordering, references, rich cells, mirrors, invalid sources, and rollback; `TestAPIContractDuplicateDocTree*` covers actual responses, authorization, encrypted source preservation, failed authentication, lock/unlock, and response leases. These tests are included in the full kernel CI command; run the focused checks with `go test -tags "fts5 sqlcipher" ./model ./api -run 'Test(DuplicateDocTree|APIContractDuplicateDocTree)' -count=1` and `go test ./apicontract/...`.--`TestAPIContractFileTreeMissingDocuments` tests actual HTTP responses for missing documents during path lookup, removal, renaming, duplication, and moving. It checks business errors and preserved `closeTimeout` values against the response contracts and runs in the full kernel command below. Run it separately with `go test -tags "fts5 sqlcipher" ./api -run TestAPIContractFileTreeMissingDocuments -count=1` from `kernel/`.-Asset contracts retain nullable result lists, per-file upload order and duplicate names, successful partial-upload messages, and local-insertion failure payloads. OCR columns remain string-valued. Annotation validation, published-file admission, encrypted reads and writes, deferred downloads, and upload target selection keep their existing behavior. The non-API upload entry uses the same typed model operation.-Unused-asset listing and cleanup return the standard `code: -1`, `data: null` error when document loading or reference-directory traversal fails, including unsupported document specs. Single-asset cleanup uses the same complete scan; bulk cleanup does not start history creation or deletion before scanning succeeds. Successful response shapes and encrypted-notebook exclusions remain unchanged. `TestAssetUnusedScanFailureContract`, `TestUnusedAssets*`, `TestHTMLAssetLinkDests`, `TestPagedPathsErrorModes`, `TestExportAssetEntityRename`, and `TestExportHTMLMultipleAssetReferences` cover HTTP errors, source preservation, HTML references, URL suffixes, legacy traversal behavior, and exported resources and links. They run in the full kernel CI selection; run the focused checks with `go test -tags "fts5 sqlcipher" ./model ./api -run 'Test(AssetUnusedScanFailureContract|UnusedAssets|HTMLAssetLinkDests|PagedPathsErrorModes|ExportAssetEntityRename|ExportHTMLMultipleAssetReferences)' -count=1` and `go test ./apicontract/...`.--`/api/asset/resolveAssetPath` preserves its path-string response and administrator authorization. Unlocked encrypted assets return an authenticated temporary plaintext copy with the original filename; ordinary assets retain their existing paths. The request holds the encrypted notebook lease through response serialization. External edits do not write back to the encrypted source. `TestAPIContractNotebookSystemLock` includes external-asset response validation, original-name preservation, source preservation, authentication-failure cleanup, locked rejection, and lock cleanup; it runs in the full kernel CI selection. Run `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(APIContractNotebookSystemLock|AssetAdminEndpointsRejectReader|MobileExportLease)' -count=1` and `go test ./apicontract/...` for the affected behavior and route coverage.+Unused-asset listing and cleanup return the standard `code: -1`, `data: null` error when document loading or reference-directory traversal fails, including unsupported document specs. Single-asset cleanup uses the same complete scan; bulk cleanup does not start history creation or deletion before scanning succeeds. Successful response shapes and encrypted-notebook exclusions remain unchanged.Asset-reference scans report missing attribute-view definitions and invalid definition IDs in the optional `unavailableAttributeViews` list without blocking queries, previews, or replacement. Each entry identifies the notebook ID/name, document ID/path/human-readable path, block ID, view ID, and reason. Existing unreadable or corrupt definitions remain errors. Missing-file snapshots are revalidated before writing so a definition restored during scanning cannot be silently omitted. Attribute-view definitions are not deferred assets under the current download-path policy; the regression suite checks this assumption. The unavailable-definition regressions run through the model and actual HTTP contracts, including closed notebooks and shared definitions.-Asset-reference query and replacement contracts preserve scalar requests and also accept batches. Batch results retain input order and report each mapping's status, reason, references, and changed-file count; the top-level count includes each shared file once. Empty batches, duplicate sources, and chained or cyclic mappings are rejected. Independent mappings may succeed when another mapping fails; a shared-file write failure belongs to every affected mapping. Scans allow editing and validate the workspace snapshot before saving; cancellation and unchanged retries preserve source data. `TestAssetRelink` regressions cover scalar compatibility, batch validation, shared document/database/OCR persistence, history, and concurrent edits and are included in the full kernel command below.+Asset-reference query and replacement contracts preserve scalar requests and also accept batches. Batch results retain input order and report each mapping's status, reason, references, and changed-file count; the top-level count includes each shared file once. Empty batches, duplicate sources, and chained or cyclic mappings are rejected. Independent mappings may succeed when another mapping fails; a shared-file write failure belongs to every affected mapping. Scans allow editing and validate the workspace snapshot before saving; cancellation and unchanged retries preserve source data.Export contracts retain Markdown option defaults and numeric truncation, notebook-list filtering, ignored title-option types, optional HTML folders, and file-upload field selection. Error responses preserve message durations and empty-string resource payloads. Publish filtering, encrypted-notebook admission, response-held leases, and temporary export cleanup remain in the existing lifecycle.@@ -100,17 +82,15 @@ Flashcard contracts retain numeric truncation, pagination defaults, optional revSync contracts retain numeric truncation, conditional direction validation in manual mode, configuration field matching and JSON numeric normalization, and message display durations. Provider imports require exactly one file and preserve encrypted package contents and recovery paths. Authorization and read-only checks still precede body decoding; synchronization and notebook encryption remain in the model layer.-`/api/sync/setSyncProvider` accepts optional, nullable `completeAssets`. Only `true` authorizes downloading missing current resources and historical snapshot content from the existing provider before changing the source; omission, `null`, and `false` retain the check-only behavior. Completion preserves the download mode and recovery keys, and failure keeps the original provider. The confirmed operation reports checking/completion through the existing global progress overlay and closes it on success or failure. Run `go test ./apicontract/...` and `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(APIContractSync|SyncProviderCompletion|AssetDownloadModePreservesHistoricalRecovery|AssetDownloadStateCorruption)' -count=1`; these tests are included in the full kernel CI suite. Frontend confirmation, cancellation, and overlay cleanup are covered by `src/config/tabs/syncRuntime.test.ts` in the existing frontend test selection.-Marketplace contracts retain required-field ordering, whitespace handling, theme mode dependencies, rating availability and rate-limit payloads, and local-package upload errors. Package and appearance responses declare their complete nested structures, including the fixed five-element rating distribution. Upload requests keep first-file selection and overwrite parsing. Installation, removal, authentication, and publish restrictions remain in the existing business handlers and middleware.Plugin information queries retain path, query-string, and JSON-body name precedence, including whitespace and business error codes 1 through 4. URL parameters skip body decoding, and list queries ignore the body. Plugin and RPC-method lists retain nullable arrays and entries. HTTP JSON-RPC has a separate contract for single and batch requests, success and error replies, and notification-only HTTP 204 responses. Plugin admission occurs before body reads, batch errors retain their order, and arbitrary JSON is limited to RPC parameters, results, and error details. RPC WebSocket routes declare HTTP 101 upgrades, HTTP 404 plugin admission errors, HTTP 400 text rejections, and separate incoming calls and outgoing replies or notifications. Origin authorization and connection cleanup remain in the existing upgrade lifecycle.-Plugin publishing contracts separate administrator-only grants and snapshot writes from authenticated public reads. Public data is limited to declared scalar fields; grants and snapshots use a local versioned store outside synced private plugin data. Static and file reads share plugin availability and secure file-opening rules, while publish loading excludes kernel code. `TestAPIContractPluginPublish`, `TestPluginPublishContracts`, `TestPluginPublish*`, and `TestPublishFile*` cover actual responses, admission, scope changes, revocation, reinstall, corruption, and path boundaries. They run in the full kernel suite; run the affected subset with `go test -tags "fts5 sqlcipher" ./api ./model ./server ./util ./apicontract -run 'Test(APIContractPluginPublish|PluginPublish|PublishFile|RouteCoverage)' -count=1`. The path-fixture CI selection also includes the model, static, and file-boundary regressions. See [Plugin publishing](PLUGIN-PUBLISH.md) for public API documentation and migration examples.+Plugin publishing contracts separate administrator-only grants and snapshot writes from authenticated public reads. Public data is limited to declared scalar fields; grants and snapshots use a local versioned store outside synced private plugin data. Static and file reads share plugin availability and secure file-opening rules, while publish loading excludes kernel code. The path-fixture CI selection also includes the model, static, and file-boundary regressions. See [Plugin publishing](PLUGIN-PUBLISH.md) for public API documentation and migration examples.Search contracts retain pagination defaults and numeric truncation, path validation and deduplication, ignored historical subtype filters, and null versus empty arrays. Reference search distinguishes correlation-only responses from block results and retains notebook admission before deferred parameter validation. SQL search authorization, publish filtering, encrypted notebook leases, cancellation responses, and read-only embed-update no-ops remain in their original order. Desktop and mobile callers share generated request types.-Custom block search uses the optional `customBlock` type filter. Explicit API type maps select only their enabled types; omitted type maps use search settings, which enable custom blocks by default. Saved criteria preserve omission separately from `false` so older frontend search configurations can inherit the setting. `TestCustomBlockSearch` regressions cover configuration compatibility, saved criteria, filtering, and FTS updates; `TestAPIContractSettingConfigCompatibility` and `TestAPIContractSettingCompletePayloads` cover the setting contract. All are included in the full kernel command below.+Custom block search uses the optional `customBlock` type filter. Explicit API type maps select only their enabled types; omitted type maps use search settings, which enable custom blocks by default. Saved criteria preserve omission separately from `false` so older frontend search configurations can inherit the setting. All are included in the full kernel command below.History contracts retain path trimming, optional highlight defaults, fractional history-type truncation, and null versus empty result arrays. Version comparison checks both reference objects before their fields and acquires notebook leases in sorted order. Content reads and document, asset, and attribute-view rollbacks retain their history-path lease checks; notebook rollback keeps its existing model-level recovery behavior.@@ -118,8 +98,6 @@ Import contracts preserve archive cleanup, first-upload selection, untrimmed MarBacklink contracts preserve untrimmed query fields, optional flag defaults, source-filter normalization, and revision hashes. Missing list IDs still return null; unchanged revisions retain the existing fields with null arrays. Candidate-definition failures retain their empty `refDefs` payload. Publish filtering, encrypted-notebook admission, and request-held leases remain in the handlers, and context payloads retain recursive block paths and attribute-view reference targets.-`/api/ref/getBacklinkDoc` accepts the optional integer `blockSort`: `0` (default) preserves document order, `1` sorts matching anchor text in natural ascending order, and `2` sorts it in natural descending order. Unknown integer modes preserve document order. The first matching reference in each displayed entry supplies the trimmed anchor text, including entries merged into a parent block. Equal keys preserve document order; entries without anchor text follow entries with text in both directions. Sorting preserves source-document groups, filtering, and mention order. Within a source document, a whole-document entry propagated from its first reference is expanded into independently sortable references; local list-item and heading context is retained. Returning to document order restores the whole-document entry. The mode participates in context revision hashes. The editor setting `backlinkBlockSort` persists the panel preference; omitted API `blockSort` remains independent of that preference. `TestBacklinkAnchorSort*`, `TestBacklinkDocumentBlockSort`, and the existing setting and published-encrypted-context contract tests cover ordering, compatibility, revision changes, and ordinary and encrypted notebook reads. These regressions run in the full kernel CI suite below; run the affected subset with `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(Backlink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`.-Graph contracts preserve partial configuration defaults, case-insensitive configuration fields, and numeric normalization. Query responses distinguish full graph data from correlation-only payloads, including errors and local queries without an ID; node and link arrays retain their original nullability. Configuration persistence still requires administrator access outside read-only mode. Publish filtering and encrypted-notebook rejection retain their existing order relative to configuration decoding.Template contracts retain path checks before mode and source validation, explicit-mode precedence over the legacy preview flag, database-mode defaults, and the code `1` overwrite prompt. File management keeps Go struct JSON binding and its fixed parse-error message, with separate list, source, revision, and null payloads. Revision checks, symlink restrictions, and sync invalidation remain in the existing model operations.@@ -152,9 +130,9 @@ Heading transaction queries return `BlockTransaction` with typed operations andAll `/api/block/` routes use contracts. Heading-level queries retain batch-ID precedence, deduplication, fractional-level truncation, document struct binding, and message display durations. Document conversion results include the six heading counts and typed transactions. Reference checks validate only the fields used by the selected scope, preserve ignored fields and notebook trimming rules, and retain boolean error payloads, publish filtering, and notebook leases through response serialization. These exceptional input rules use private, endpoint-specific typed decoders; ordinary endpoints continue to use field declarations. Recent-update results use a recursive `SearchBlock` payload, including nullable references, children, and card metadata.-HTML clipboard conversion preserves literal backslashes and marker characters while retaining HTML formatting when Markdown syntax is disabled. `TestHTML2BlockDOMContractEscapedText` covers both source-format modes, actual response schemas, editing round trips, HTML entities, and style/link boundaries. Run it with the related conversion regressions using `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(.*HTML.*|.*Clipboard.*|.*IFrame.*|SpinBlockDOM.*|WPSPresentation.*|NormalizeMSWord.*|NormalizeWPS.*)' -count=1`. The full kernel command below includes these tests, and `app/tests/luteHtmlEscapes.test.js` checks the generated Lute JavaScript through the full frontend suite. Lute source changes also require `go test ./...` in the Lute repository and regeneration of the bundled JavaScript.+HTML clipboard conversion preserves literal backslashes and marker characters while retaining HTML formatting when Markdown syntax is disabled. Lute source changes also require `go test ./...` in the Lute repository and regeneration of the bundled JavaScript.-`swapBlockRef` accepts the optional boolean `originalToEmbed`. Omission or `false` keeps the reference at the original definition position; `true` replaces it with an embed querying the moved definition ID. `includeChildren` retains its heading and list behavior. `TestSwapBlockRefContractCompatibility` and `TestSwapBlockRefNodes` cover request defaults, invalid options, and both replacement modes across document, heading, and list cases; they run in the full kernel command below.+`swapBlockRef` accepts the optional boolean `originalToEmbed`. Omission or `false` keeps the reference at the original definition position; `true` replaces it with an embed querying the moved definition ID. `includeChildren` retains its heading and list behavior.Storage contracts keep arbitrary JSON limited to storage values; keys, recent documents, search criteria, inline styles, and attribute-view palettes have structured types. Recent-document mutations retain their read-only no-op before parsing the body. An optional typed `beforeDecode` callback on `contractHandler` preserves this ordering and may return a response before decoding; route checks still require an explicit endpoint binding. Inline-style version 1 updates preserve existing built-in configuration, while version 2 and palette requests retain their struct-decoding compatibility.@@ -164,10 +142,6 @@ The global backlink endpoints use a separate flat list. `/api/ref/getGlobalBackl`/api/ref/getGlobalBacklinkContexts` takes the same query, its required `snapshot`, and up to 20 block `ids` from that snapshot. It renders independent editable blocks and preserves breadcrumb and attribute-view data. Both endpoints recheck source access before returning metadata or bodies and retain encrypted-notebook request leases. Published readers cannot access encrypted notebooks. The frontend loads 50 entries per page, retains a five-page window plus pages containing active editing sessions, and lazily mounts at most 16 editors. Recycling waits for pending transactions and preserves active composition, focus, drag, and attribute-view editing. Automatic refresh waits for editing to end and restores the visible block. The setting `backlinkGlobalSort` selects grouped mode (`0`, default) or global anchor order (`1`/`2`). `/api/ref/getBacklink2` accepts optional `includeBacklinks` (default `true`); `false` returns an empty backlink list and zero backlink count while preserving mentions, avoiding duplicate group loading. Existing callers and document-local `blockSort` keep their defaults.-`TestGlobalBacklink*`, `TestAPIContractGlobalBacklink`, `TestBacklinkAnchorSortContext`, and `TestBacklink2OptionalMentions` cover cross-document pagination, first-reference selection, snapshot stability after edits, reading-position lookup, ordinary and encrypted reads, source permissions, expiration, cache bounds, HTTP response contracts, and mention compatibility. They run in the full kernel CI command below; run the affected subset with `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`. Frontend regression files `globalBacklinkPaging.test.ts`, `globalBacklinkList.test.js`, and `backlinkSort.test.js` run in the existing full frontend CI selection and cover window bounds, stale responses, pending edits, and mode switching.--`TestGlobalBacklinkLargeDataset` creates 10,000 references across 100 real documents and indexes them in an isolated database. It checks natural order and absence of duplicate or missing entries across all 200 pages, then loads 16 editable contexts. It reports initial sorting, cached pagination, context loading, and snapshot size without imposing machine-dependent timing thresholds. Run it with `go test -tags "fts5 sqlcipher" ./model -run TestGlobalBacklinkLargeDataset -count=1 -v`; the existing `TestGlobalBacklink*` selection and full kernel CI include it. Frontend regressions also cover keeping the bottom-panel retry control visible after failure, restoring empty-state behavior after retry, and preserving the entire row height when recycling and recreating editors.-## File and streaming protocols`RawSSEOptions` and `RawWebSocketOptions` declare byte-oriented broadcast protocols. Use `ValidateRawSSEEvent` and `ValidateRawWebSocketFrame` to check their event and frame metadata independently; JSON event and RPC message declarations retain their existing validation. Raw WebSocket failures are written by the upgrader rather than `RejectWebSocket`.@@ -198,8 +172,6 @@ Dynamic multipart endpoints use `MultipartFields` to retain every text value andThe generator reads the leading comments on endpoint declarations in `kernel/apicontract/contracts.go` and emits them as JSDoc on the corresponding `APIGETRoutes` and `APIPOSTRoutes` entries in both the frontend and Petal declarations. Maintain endpoint behavior, defaults, constraints, and compatibility there; for a grouped `var` declaration, place the comment immediately before the individual endpoint. Group comments are not copied to every entry. Keep fetch helper comments focused on transport behavior and link to the route types for endpoint details; do not hand-edit generated declarations.-`/api/block/migrateLegacyMindmaps` is an authenticated administrator write endpoint with read-only protection and an encrypted-notebook request lease. It requires a document `id` and `notebook`, converts complete legacy `mindmap` lists in one undoable transaction after saving history, and returns `converted` and canonical `blocks` (`id`, `dom`) for the document's mind maps. Repeated requests return the current block content without reconverting lists; incomplete sources remain unchanged. Regression coverage runs with `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(LegacyMindmap|MigrateLegacyMindmaps|APIContractHeadingTransactions|APIContractRouterCoverage|RouteCoverage)' -count=1` and the frontend `listMindmap/migrate.test.ts` and `listMindmap/model.test.ts` suites. These tests use the existing CI discovery paths.-After contract changes, run generation and checks from `app/`. The commands below also show the full frontend suite; select regression coverage according to the affected behavior and risk rather than requiring the full suite for every task:```textdiff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdindex 3f64c3a3a9..761dc89be3 100644--- a/docs/API-CONTRACTS.zh-CN.md+++ b/docs/API-CONTRACTS.zh-CN.md@@ -38,59 +38,41 @@## 兼容要求-`POST /api/ai/testDecisionModel` 使用固定的 TypeSafe System One 样例测试已保存的可选 `ai.decision` 配置。接口要求管理员权限,遵循全局人工智能禁用标记和请求取消,返回具有类型声明的 `{matched, msg?}` 数据;配置错误和供应商错误不会被转换为判断结果。省略决策配置时补齐默认关闭的配置,关闭后保留密钥,并沿用现有配置加密存储机制。`TestAPIContractAI*`、`TestAPIContractSetting*`、`TestAIDecisionConfiguration` 和 `TestDecision*` 覆盖契约、配置、顺序批量调用的部分结果、区块读取、锁定笔记本拒绝访问、能力可用性、确认、取消及供应商响应校验,均纳入完整内核持续集成测试。可运行 `go test -tags "fts5 sqlcipher" ./api ./conf ./util ./mcp/tools ./agent -run 'Test(APIContractAI|APIContractSetting|AIDecision|Decision)' -count=1` 和 `go test ./apicontract/...` 进行针对性验证。+移动端发行版可在内核启动前调用 `DisableFeature("ai")`。全部 `/api/ai/` 接口及 `/api/setting/setAI` 在解码请求体前拒绝请求,同时保留路由认证和授权。JSON 接口返回错误码 `-1` 和空数据;MCP OAuth 回调返回 HTTP 403 纯文本。已存储的 AI 配置保持不变。嵌入索引、重排及传出的 MCP 连接也遵循此标记。-`POST /api/system/getRuntimeInfo` 不接受请求体,在标准成功信封中返回 `{text: string}`。接口要求认证和管理员权限,支持只读模式,报告内核版本、运行时、操作系统、逻辑 CPU 数量、当前系统与进程内存,以及检测到的工作空间存储类型。不支持的内存和存储探测返回 `unknown`;不推断移动端存储为 SSD。诊断文本不包含工作空间路径、主机名和账户标识。`TestAPIContractSystemRuntimeInfo` 纳入内核全量持续集成测试;可运行 `go test -tags "fts5 sqlcipher" ./api -run TestAPIContractSystemRuntimeInfo -count=1` 和 `go test ./apicontract/...` 单独验证。--移动端发行版可在内核启动前调用 `DisableFeature("ai")`。全部 `/api/ai/` 接口及 `/api/setting/setAI` 在解码请求体前拒绝请求,同时保留路由认证和授权。JSON 接口返回错误码 `-1` 和空数据;MCP OAuth 回调返回 HTTP 403 纯文本。已存储的 AI 配置保持不变。嵌入索引、重排及传出的 MCP 连接也遵循此标记。`TestAPIContractAIDisabled`、`TestAIDisabledBackgroundFeatures` 和 `TestAIDisabledMCPConnections` 纳入内核全量持续集成测试。可运行 `go test -tags "fts5 sqlcipher" ./api ./model ./mcp/client -run 'Test(APIContractAI|AIDisabled)' -count=1` 和 `go test ./apicontract/...` 验证受影响的行为。--加密笔记本系统锁屏接口保留管理员鉴权和只读检查。布尔开关保存在系统配置中,不进入密钥备份的认证数据。`TestAPIContractNotebookSystemLock` 覆盖配置持久化、关闭开关、独立于闲置时间、多笔记本(包括仅解锁未挂载的笔记本)、重复锁定、锁定后拒绝读取,以及重新解锁后认证读取未改变的密文。该测试已包含在下文的内核全量命令中,也可单独运行 `go test -tags "fts5 sqlcipher" ./api -run 'TestAPIContractNotebook(SystemLock|CryptoAuthorization)$' -count=1`。`TestNotebookSystemLockContract` 覆盖严格布尔输入,`TestRouteCoverage` 检查路由注册和处理器绑定。+加密笔记本系统锁屏接口保留管理员鉴权和只读检查。布尔开关保存在系统配置中,不进入密钥备份的认证数据。2026 年 9 月 14 日迁移完成时,`kernel/api/router.go` 中的 629 条方法和路径注册均已纳入契约,旧路由清单为空。该基线中的 4 条 `ANY` 注册在生成声明中展开为 661 条具体方法和路径。后续新增接口时,以生成器和路由覆盖检查的统计为准。由 `kernel/server/serve.go` 注册的静态资源、应用主 WebSocket 和其他传输服务不属于这份 API 路由清单。系统契约保留完整配置、工作空间管理、上传、认证、OIDC 响应分支、启动事件流以及空响应和二进制响应。前端在读取持久化布局和快捷键的位置缩小类型,保留原有默认值修复、废弃键清理和绑定过滤逻辑。配置导入、导出和退出保持原有生命周期及加密行为。-OIDC Web 回调在认证后返回 HTTP 200 HTML,重复成功的回调也使用相同响应。它复用共享结果页,通过 meta refresh 和备用链接发起同源导航,结束供应商的跨站 HTTP 重定向链,同时保留会话来源检查。桌面端和验证回调继续使用结果页。`TestOIDCWebCallbackContract`、`TestOIDCRepeatedWebCallbackContractSession` 和 `TestRenderOAuthRedirectPage` 覆盖响应契约、目标转义、会话 Cookie 及持续拒绝跨站请求,均包含在内核全量持续集成测试中。可运行 `go test -tags "fts5 sqlcipher" ./model ./util ./api -run 'Test(OIDC|WriteOIDC|RenderOAuth|IsSessionOriginAllowed|IsCrossSiteFetchSite|CheckAuthRemoteSessionOrigin|APIContractSystem|APIContractRouterCoverage)' -count=1` 和 `go test ./apicontract/...` 单独验证。-事务契约按动作区分全部 98 个已知操作,并在显式未知操作兼容分支中排除这些名称。前端使用同一组有限操作联合。私有原始输入保留历史字段、被忽略的值、模型异步错误和回传载荷,类型声明不把模型校验提前到 HTTP 准入阶段。撤销、重做、标题操作、响应租约及事务持久化格式保持原有行为。-编辑器通过独立的 `swapBlockRef` 事务转换块引用:`id` 指定引用块,`blockID` 指定定义块,`data` 包含布尔选项 `includeChildren` 和 `originalToEmbed`。内核在 `retData` 中返回受影响的文档 ID,并以受影响顶层块的私有内存快照生成逆向操作。快照不传给客户端,也不接受客户端提交。重放保留块 ID 和数据库绑定;内容或位置已改变时拒绝覆盖;提交失败时补偿已写入的文档。`TestBlockSwapTransaction` 覆盖落盘后的撤销和重做、跨文档历史、冲突拒绝及写入失败恢复,包含在下方完整内核测试命令中,也可在 `kernel/` 下运行 `go test -tags "fts5 sqlcipher" ./model -run 'Test(SwapBlockRefNodes|BlockSwapTransaction)' -count=1` 单独验证--块交换的撤销和重做为所有受影响文档持有笔记本租约,直到响应序列化完成。`TestContractBlockSwapReplayNotebookResponseLease` 验证锁定操作会等待响应结束,包含在完整内核测试命令中。-扩展剪藏保留多段表单首值处理、动态名称上传文件、部分结果、原有消息及加密笔记本准入。动态图标保留 SVG 字节、安全和缓存响应头以及空错误响应。广播流声明原始 SSE 字节、动态事件名、ID 和重试值,以及原始 WebSocket 帧和升级错误;载荷不转换为 JSON 或 Base64,频道清理保持原有作用范围。插件私有服务声明现有序列化模式、原始文件、重定向、代理响应、SSE 事件和 WebSocket 帧。插件自行定义的载荷保留为协议扩展数据,并按实际分支分别校验序列化格式与任意字节。请求体、显式响应头、准入错误和取消处理保持插件服务原有生命周期。网络契约保留请求字节、表单字段、请求头、URL 和 TLS 诊断信息,包括完整证书公钥结构与大整数。转发代理选项保留校验顺序、数字截断、响应编码及协议定义的 JSON 载荷。HTTP、EventSource 和 WebSocket 代理保留上游状态与字节、重复请求头行为、安全响应头、流取消和连接清理。回显通配路径绑定独立适配器,并共用相同业务处理。-数据库契约分别声明表格、画廊和看板的结果结构,保留基础字段缺失、单元格局部修改及 null 值。独立的 `list` 布局复用表格的 `columns`/`rows`/`rowCount` 载荷,布局配置保存在 `list` 下,`viewType` 标识为 `list`。已知修改字段保留传入状态,不以零值填充未提供的字段。当前、历史和快照渲染使用对应请求类型,调用端先处理错误载荷再更新视图。行排序、发布准入、加密笔记本租约和快速 JSON 渲染保留既有行为。前端和插件的共享声明按视图及单元格实际提供的字段同步。`TestAVContractListLayout` 覆盖布局切换、默认字段显隐、后续渲染和持久化布局映射;运行 `go test -tags "fts5 sqlcipher" ./api -run 'TestAVContract' -count=1` 和 `go test ./apicontract/...`。这些测试已包含在内核完整 CI 测试中。+数据库契约分别声明表格、画廊和看板的结果结构,保留基础字段缺失、单元格局部修改及 null 值。独立的 `list` 布局复用表格的 `columns`/`rows`/`rowCount` 载荷,布局配置保存在 `list` 下,`viewType` 标识为 `list`。已知修改字段保留传入状态,不以零值填充未提供的字段。当前、历史和快照渲染使用对应请求类型,调用端先处理错误载荷再更新视图。行排序、发布准入、加密笔记本租约和快速 JSON 渲染保留既有行为。前端和插件的共享声明按视图及单元格实际提供的字段同步。这些测试已包含在内核完整 CI 测试中。-数据库渲染接口对发布阅读者使用不落盘的渲染路径。请求保留现有模式、载体授权、内容过滤及笔记本租约;即使传入 `createIfNotExist: true`,也不能为阅读者创建缺失的数据库。兼容性归一化、分组生成和缺失字段修正均仅在内存中完成。`TestAVContractPublishRenderDoesNotWrite` 覆盖显式视图切换、数据库及载体文件保持不变、访问拒绝和数据库缺失,纳入内核全量持续集成测试;可运行 `go test -tags "fts5 sqlcipher" ./api -run 'TestAVContract(PublishRenderDoesNotWrite|RenderWire)$' -count=1` 和 `go test ./apicontract/...` 单独验证。前端会话状态和 DOM 回归通过 `node --import tsx --test src/protyle/render/av/publishState.test.ts tests/publishReadonlyFold.test.js` 及前端全量持续集成测试执行。+数据库渲染接口对发布阅读者使用不落盘的渲染路径。请求保留现有模式、载体授权、内容过滤及笔记本租约;即使传入 `createIfNotExist: true`,也不能为阅读者创建缺失的数据库。兼容性归一化、分组生成和缺失字段修正均仅在内存中完成。前端会话状态和 DOM 回归通过 `node --import tsx --test src/protyle/render/av/publishState.test.ts tests/publishReadonlyFold.test.js` 及前端全量持续集成测试执行。AI 契约保留供应商配置、模型发现与匹配、确认结果、会话扩展字段,以及数值和省略语义。编辑器和智能体流声明实际 SSE 事件,断开连接时关闭上游请求,流生命周期仍位于请求内部。OAuth 页面保留媒体类型、HTTP 状态和安全响应头。会话权限通知使用 `WithAfterWrite`,保留先响应再广播的顺序。任意 JSON 仅用于协议扩展字段和工具结果。-AI 供应商在 `openai` 和 `openai-responses` 之外支持 `anthropic-messages`;省略协议时保留 Chat Completions 默认值。原生 Messages 调用覆盖模型发现、模型测试、编辑器生成、智能体工具、标题和摘要压缩。由于 Messages 要求 `max_tokens`,自动输出上限使用 4096 个词元。助手条目可携带包含协议、版本和不透明内容块的 `nativeContent`;版本 1 在运行时恢复和会话提交期间保留 Anthropic 思考签名及块顺序。其他协议只投影可见对话,不发送这些原生内容块。未知原生版本在发送 Messages 请求前失败,并保留原始会话。流用量在 `message_stop` 后仅发送一次,不完整的工具响应不能进入工具执行。`TestAnthropic*` 和 `TestAPIContractAnthropic*` 纳入内核全量持续集成测试;可运行 `go test -tags "fts5 sqlcipher" ./conf ./util ./agent ./api ./apicontract/... -run 'Test(Anthropic|APIContractAnthropic|APIContractAI|AIInput|AISession|RouteCoverage)' -count=1` 和 `go test ./apicontract/...` 验证受影响的范围。现有前端测试发现规则已包含 `aiProviderPresets.test.ts`。--`/api/ai/agent/manageSkills` 使用严格字符串字段,并通过管理员和只读检查管理工作空间技能文件。相对路径标识实际目录,与文件头中的技能名称无关,允许普通的点开头名称。读写支持不超过 8 MiB 的 UTF-8 文本,不依赖扩展名并保留原文字节。目录和资源读取保留基于内容的版本;不支持编辑的内容省略 `content`,并增加可选的 `readOnlyReason`(`binary`、`encoding` 或 `tooLarge`)。编辑器以读取结果判断可编辑性,不依赖可能过期的列表项。修改已有文件时重新校验内容并要求当前版本,与旧技能修改接口和安装共享临界区,成功后通知同步。路径穿越、平台别名、链接、过期版本,以及单独修改不支持的内容或重命名、删除根 `SKILL.md` 的请求均被拒绝。`TestAISkillManagementContract`、`TestAPIContractAISkillManagement` 和 `TestSkillManagement` 覆盖请求类型、实际 HTTP 响应、权限、原文、文本判定、隐藏路径、并发保存和文件系统边界。运行 `go test -tags "fts5 sqlcipher" ./apicontract/... ./api ./util -run 'Test(AISkillManagementContract|APIContractAISkillManagement|SkillManagement|RouteCoverage)' -count=1`;下方完整内核 CI 测试包含这些回归用例。+AI 供应商在 `openai` 和 `openai-responses` 之外支持 `anthropic-messages`;省略协议时保留 Chat Completions 默认值。原生 Messages 调用覆盖模型发现、模型测试、编辑器生成、智能体工具、标题和摘要压缩。由于 Messages 要求 `max_tokens`,自动输出上限使用 4096 个词元。助手条目可携带包含协议、版本和不透明内容块的 `nativeContent`;版本 1 在运行时恢复和会话提交期间保留 Anthropic 思考签名及块顺序。其他协议只投影可见对话,不发送这些原生内容块。未知原生版本在发送 Messages 请求前失败,并保留原始会话。流用量在 `message_stop` 后仅发送一次,不完整的工具响应不能进入工具执行。现有前端测试发现规则已包含 `aiProviderPresets.test.ts`。设置契约保留局部配置合并、既有默认值、结构字段大小写兼容、显式 null、JSON 数字归一化及解析错误消息。快捷键与云端认证结果声明固定字段,同时保留协议定义的 JSON 扩展。非管理员查询云用户时仍先执行准入判断再读取请求体;双因素认证保留云端错误码与扩展字段。前端继续在既有边界规范化持久化的显示设置。文档树契约保留条件参数校验、路径与排序语义、回调省略规则、分页默认值及文档响应变体。发布认证通过显式声明的额外错误状态保留 HTTP 429 和 `Retry-After`。发布及加密笔记本准入仍先于延迟字段校验,文档租约覆盖响应序列化阶段。-`POST /api/filetree/duplicateDocTree` 将单篇文档及全部子文档复制到同一笔记本的原父目录。请求为文档 `id`,返回副本根文档的 `id`、`notebook`、`path` 和 `hPath`;原有单文档复制接口保持不变。副本中的内部块引用、块链接和查询嵌入的显式块 ID 统一重映射,数据库定义与行绑定保持为共享镜像。源快照经过认证读取,不执行修复写回;运行期间检测到失败时清理新建文档并恢复排序。这是运行时补偿,不保证进程崩溃时的事务原子性。`TestDuplicateDocTree*` 覆盖层级、排序、引用、富文本单元格、镜像、无效源及回滚;`TestAPIContractDuplicateDocTree*` 覆盖实际响应、授权、加密源数据保留、认证失败、锁定与解锁及响应租约。测试已纳入内核全量持续集成命令,可使用 `go test -tags "fts5 sqlcipher" ./model ./api -run 'Test(DuplicateDocTree|APIContractDuplicateDocTree)' -count=1` 和 `go test ./apicontract/...` 单独验证。--`TestAPIContractFileTreeMissingDocuments` 通过实际 HTTP 响应覆盖查询路径、删除、重命名、复制和移动不存在的文档,按响应契约检查业务错误及保留的 `closeTimeout`,已包含在下方的内核全量测试命令中。可在 `kernel/` 中执行 `go test -tags "fts5 sqlcipher" ./api -run TestAPIContractFileTreeMissingDocuments -count=1` 单独验证。-附件契约保留结果列表的空值、逐文件上传顺序与重名文件、部分上传成功时的提示及本地插入失败载荷。OCR 列保持字符串值。标注校验、发布文件准入、加密读写、延迟下载和上传目标选择保持既有行为。非 API 上传入口复用同一个有类型的模型操作。-未使用资源的列出和清理在文档加载或引用目录遍历失败时返回标准的 `code: -1`、`data: null` 错误,包括不支持的文档规范。单资源清理使用相同的完整扫描;批量清理在扫描成功前不会创建历史或开始删除。成功响应结构和加密笔记本排除规则保持不变。`TestAssetUnusedScanFailureContract`、`TestUnusedAssets*`、`TestHTMLAssetLinkDests`、`TestPagedPathsErrorModes`、`TestExportAssetEntityRename` 和 `TestExportHTMLMultipleAssetReferences` 覆盖 HTTP 错误、源数据保留、HTML 引用、URL 后缀、历史遍历行为,以及导出的资源和链接。它们纳入内核全量持续集成测试;可运行 `go test -tags "fts5 sqlcipher" ./model ./api -run 'Test(AssetUnusedScanFailureContract|UnusedAssets|HTMLAssetLinkDests|PagedPathsErrorModes|ExportAssetEntityRename|ExportHTMLMultipleAssetReferences)' -count=1` 和 `go test ./apicontract/...` 单独验证。--`/api/asset/resolveAssetPath` 保留路径字符串响应及管理员授权。已解锁的加密资源返回保留原文件名的已认证临时明文副本;普通资源保留现有路径。请求持有加密笔记本租约直至响应序列化完成。外部编辑不会写回加密源数据。`TestAPIContractNotebookSystemLock` 包含外部资源响应校验、原文件名保留、源数据保留、认证失败清理、锁定后拒绝访问及锁定清理,纳入内核全量持续集成测试。可运行 `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(APIContractNotebookSystemLock|AssetAdminEndpointsRejectReader|MobileExportLease)' -count=1` 和 `go test ./apicontract/...` 验证受影响的行为及路由覆盖。+未使用资源的列出和清理在文档加载或引用目录遍历失败时返回标准的 `code: -1`、`data: null` 错误,包括不支持的文档规范。单资源清理使用相同的完整扫描;批量清理在扫描成功前不会创建历史或开始删除。成功响应结构和加密笔记本排除规则保持不变。资源引用扫描将定义文件缺失或定义 ID 无效的数据库记录到可选的 `unavailableAttributeViews` 列表,不阻断查询、预演或替换。每项包含笔记本 ID 与名称、文档 ID 与路径及人类可读路径、块 ID、数据库 ID 和原因。已存在但无法读取或内容损坏的定义仍返回错误。保存前重新校验缺失文件快照,避免遗漏扫描期间恢复的定义。当前按需下载规则不包含数据库定义,回归测试会检查这一前提。缺失定义回归覆盖模型和实际 HTTP 契约,包括关闭的笔记本和共享定义。-资源引用查询和替换契约保留单资源请求,同时支持批量参数。批量结果按输入顺序返回每项状态、原因、引用和改动文件数;顶层计数对共享文件去重。空批次、重复源路径、链式和循环映射会被拒绝。独立映射可以在其他项失败时完成,共享文件写入失败归属所有受影响映射。扫描期间允许编辑,保存前校验工作区快照;取消和无变化重试保留源数据。`TestAssetRelink` 回归覆盖单资源兼容、批量校验、共享文档、数据库及 OCR 保存、历史和并发编辑,已包含在下方完整内核测试命令中。+资源引用查询和替换契约保留单资源请求,同时支持批量参数。批量结果按输入顺序返回每项状态、原因、引用和改动文件数;顶层计数对共享文件去重。空批次、重复源路径、链式和循环映射会被拒绝。独立映射可以在其他项失败时完成,共享文件写入失败归属所有受影响映射。扫描期间允许编辑,保存前校验工作区快照;取消和无变化重试保留源数据。导出契约保留 Markdown 选项默认值与数字截断、笔记本列表过滤、标题选项类型忽略规则、可省略的 HTML 目录字段及上传字段选择规则。错误响应保留消息显示时长与资源错误中的空字符串载荷。发布过滤、加密笔记本准入、覆盖响应阶段的租约及临时导出清理保持既有生命周期。@@ -100,17 +82,15 @@ AI 供应商在 `openai` 和 `openai-responses` 之外支持 `anthropic-messages同步契约保留数值截断、手动模式下的条件方向校验、配置字段匹配与 JSON 数字归一化,以及消息显示时长。同步配置导入要求恰好一个文件,并保留加密包内容与恢复路径。鉴权及只读检查仍先于请求体解码,同步和笔记本加密继续由模型层处理。-`/api/sync/setSyncProvider` 接受可选、可空的 `completeAssets`。只有 `true` 授权在切换来源前,从原提供商下载缺失的当前资源和历史快照内容;省略、`null` 和 `false` 保留只检查完整性的行为。补齐过程保留下载模式和恢复密钥,失败时保留原提供商。确认后的操作通过现有全局进度遮罩显示检查和补齐阶段,成功或失败均关闭遮罩。运行 `go test ./apicontract/...` 和 `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(APIContractSync|SyncProviderCompletion|AssetDownloadModePreservesHistoricalRecovery|AssetDownloadStateCorruption)' -count=1`;这些测试已包含在完整内核 CI 测试中。前端确认、取消和遮罩清理由现有前端测试范围内的 `src/config/tabs/syncRuntime.test.ts` 覆盖。-集市契约保留必填字段的校验顺序、空白处理、主题模式联动、评分可用性和限流载荷,以及本地包上传错误。包和外观响应声明完整嵌套结构,包括固定五项的评分分布。上传请求保留首文件选择及覆盖参数解析。安装、卸载、鉴权和发布限制仍由既有业务处理函数及中间件执行。插件信息查询保留路径参数、查询参数和 JSON 请求体中名称的优先级,包括空白及业务错误码 1 至 4。命中 URL 参数时不解析请求体,列表查询忽略请求体。插件列表与 RPC 方法列表保留数组及数组元素的空值语义。HTTP JSON-RPC 使用独立契约描述单次与批量请求、成功与错误回复,以及纯通知请求的 HTTP 204 响应。插件准入先于请求体读取,批量错误保留原有顺序,任意 JSON 仅用于 RPC 参数、返回值和错误详情。RPC WebSocket 路由声明 HTTP 101 升级、HTTP 404 插件准入错误、HTTP 400 文本拒绝,以及独立的入站调用和出站回复或通知。Origin 授权与连接清理保留在既有升级生命周期中。-插件发布契约将仅管理员可用的授权、快照写入与已认证访问者的公开读取分离。公开数据仅包含声明的标量字段,授权和快照使用独立于同步插件私有存储的本地版本化文件。静态路由与文件接口共用插件状态和安全文件打开规则,发布加载响应排除内核代码。`TestAPIContractPluginPublish`、`TestPluginPublishContracts`、`TestPluginPublish*` 和 `TestPublishFile*` 覆盖实际响应、准入、范围变化、撤销、重装、损坏及路径边界,均包含在完整内核测试中。可运行 `go test -tags "fts5 sqlcipher" ./api ./model ./server ./util ./apicontract -run 'Test(APIContractPluginPublish|PluginPublish|PublishFile|RouteCoverage)' -count=1` 单独验证。路径测试的 CI 筛选也包含模型、静态路由与文件边界回归。接口说明和迁移示例见[插件发布](PLUGIN-PUBLISH.zh-CN.md)。+插件发布契约将仅管理员可用的授权、快照写入与已认证访问者的公开读取分离。公开数据仅包含声明的标量字段,授权和快照使用独立于同步插件私有存储的本地版本化文件。静态路由与文件接口共用插件状态和安全文件打开规则,发布加载响应排除内核代码。路径测试的 CI 筛选也包含模型、静态路由与文件边界回归。接口说明和迁移示例见[插件发布](PLUGIN-PUBLISH.zh-CN.md)。搜索契约保留分页默认值与小数截断、路径校验与去重、历史子类型筛选的忽略规则,以及空值与空数组的区别。引用搜索区分仅回传请求标识和完整块结果,保留笔记本准入先于延迟参数校验的顺序。SQL 搜索权限、发布过滤、加密笔记本租约、取消请求的响应和只读嵌入块更新的空操作保持原有顺序。桌面端与移动端调用使用生成的请求类型。-自定义块搜索使用可选的 `customBlock` 类型筛选字段。API 显式传入类型映射时仅搜索其中启用的类型;省略类型映射时使用搜索设置,默认启用自定义块。保存的搜索条件区分字段缺失与 `false`,使旧版前端搜索配置能够继承设置。`TestCustomBlockSearch` 回归覆盖配置兼容、搜索条件保存、类型筛选和全文索引更新;`TestAPIContractSettingConfigCompatibility` 与 `TestAPIContractSettingCompletePayloads` 覆盖设置契约,均包含在下方完整内核测试命令中。+自定义块搜索使用可选的 `customBlock` 类型筛选字段。API 显式传入类型映射时仅搜索其中启用的类型;省略类型映射时使用搜索设置,默认启用自定义块。保存的搜索条件区分字段缺失与 `false`,使旧版前端搜索配置能够继承设置。历史契约保留路径去空白、可选高亮默认值、历史类型的小数截断,以及空值与空数组的区别。版本对比先检查两个引用对象,再检查对象字段,并按排序后的笔记本 ID 获取租约。内容读取及文档、资源和数据库回滚保留历史路径租约检查,笔记本回滚沿用模型层的恢复行为。@@ -118,8 +98,6 @@ AI 供应商在 `openai` 和 `openai-responses` 之外支持 `anthropic-messages反链契约保留查询字段的空白、可选开关默认值、来源过滤归一化和版本哈希。列表查询缺少 ID 时仍返回空值;版本未变化时保留既有字段和空值数组。候选定义查询失败时保留空的 `refDefs` 数组。发布过滤、加密笔记本准入和请求期间的租约仍由处理器维护,上下文载荷保留递归块路径和数据库引用位置。-`/api/ref/getBacklinkDoc` 接受可选整数 `blockSort`:`0`(默认)保持正文顺序,`1` 按匹配引用的锚文本自然升序排列,`2` 按自然降序排列,未知整数值保持正文顺序。每个展示条目取正文中首个匹配引用的锚文本并去除首尾空白,合并到父块的条目也遵循此规则。排序键相同时保持正文顺序,无锚文本的条目在两个方向中均置后。排序保留来源文档分组、过滤和提及顺序。在来源文档内部,由首段引用传递形成的整篇文档条目会展开为可独立排序的引用,并保留列表项和标题等局部上下文;恢复正文顺序时重新使用整篇文档条目。排序模式参与上下文版本哈希。编辑器设置 `backlinkBlockSort` 保存面板偏好,接口未提供 `blockSort` 时仍使用正文顺序。`TestBacklinkAnchorSort*`、`TestBacklinkDocumentBlockSort` 及已有设置和发布加密上下文契约测试覆盖排序、兼容性、版本变化以及普通和加密笔记本读取。这些回归包含在下方完整内核 CI 测试中,可单独运行 `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(Backlink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`。-图谱契约保留局部配置的默认值、配置字段不区分大小写和数值归一化行为。查询响应区分完整图数据和仅含请求标识的结果,后者包括错误及未提供 ID 的局部查询;节点和连线数组保留原有的空值语义。配置持久化仍要求管理员权限且不处于只读模式。发布过滤、加密笔记本拒绝访问与配置解码之间的执行顺序保持不变。模板契约保留路径先于模式和源内容校验、显式模式优先于旧预览开关、数据库模式默认值,以及代码 `1` 的覆盖提示。文件管理保留 Go 结构体 JSON 绑定及其固定解析错误消息,分别声明列表、源内容、版本号和空载荷。版本校验、符号链接限制和同步失效处理仍由现有模型操作执行。@@ -152,9 +130,9 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ全部 `/api/block/` 路由已使用契约。标题级别查询保留批量 ID 优先、去重、小数级别截断、文档结构体绑定和消息展示时长。文档转换结果包含六级标题计数和有类型的事务。引用检查仅校验所选范围使用的字段,保留忽略字段及笔记本参数去空白规则,并保留布尔错误载荷、发布过滤和持续到响应序列化完成的笔记本租约。这些特殊输入规则使用私有的入口专用类型解码函数,而普通接口继续通过字段声明解码。最近更新结果使用递归的 `SearchBlock` 载荷,包含可为空的引用、子块和卡片元数据。-HTML 剪贴板转换保留字面反斜杠和标记字符,并在关闭 Markdown 语法时保留 HTML 格式。`TestHTML2BlockDOMContractEscapedText` 覆盖两种源格式模式、实际响应模式校验、编辑往返、HTML 实体以及样式和链接边界。可使用 `go test -tags "fts5 sqlcipher" ./api ./model -run 'Test(.*HTML.*|.*Clipboard.*|.*IFrame.*|SpinBlockDOM.*|WPSPresentation.*|NormalizeMSWord.*|NormalizeWPS.*)' -count=1` 运行相关转换回归。下方内核全量命令已包含这些测试,`app/tests/luteHtmlEscapes.test.js` 通过前端全量测试检查生成的 Lute JavaScript。修改 Lute 源码后,还需在 Lute 仓库运行 `go test ./...` 并重新生成内置 JavaScript。+HTML 剪贴板转换保留字面反斜杠和标记字符,并在关闭 Markdown 语法时保留 HTML 格式。修改 Lute 源码后,需在 Lute 仓库运行 `go test ./...` 并重新生成内置 JavaScript。-`swapBlockRef` 接受可选布尔值 `originalToEmbed`。省略或传入 `false` 时,在原定义位置保留引用;传入 `true` 时,将其替换为查询已移动定义 ID 的嵌入块。`includeChildren` 保留标题和列表行为。`TestSwapBlockRefContractCompatibility` 和 `TestSwapBlockRefNodes` 覆盖请求默认值、无效选项,以及文档、标题和列表场景下的两种替换模式,包含在下方的内核全量命令中。+`swapBlockRef` 接受可选布尔值 `originalToEmbed`。省略或传入 `false` 时,在原定义位置保留引用;传入 `true` 时,将其替换为查询已移动定义 ID 的嵌入块。`includeChildren` 保留标题和列表行为。存储契约仅在存储值中允许任意 JSON,键、最近文档、搜索条件、行内样式和属性视图调色板均使用结构化类型。最近文档写入接口保留只读角色在解析请求体前直接返回成功的行为。`contractHandler` 可选的类型化 `beforeDecode` 回调用于保留这一执行顺序,允许在解码前返回响应;路由检查仍要求显式绑定端点。行内样式版本 1 的更新保留已有内置配置,版本 2 和调色板请求保留结构体解码的兼容行为。@@ -164,10 +142,6 @@ HTML 剪贴板转换保留字面反斜杠和标记字符,并在关闭 Markdown`/api/ref/getGlobalBacklinkContexts` 使用相同查询、必需的 `snapshot` 和最多 20 个属于该快照的块 `ids`,返回可独立编辑的块正文,并保留面包屑和数据库引用信息。两个接口在返回元数据或正文前重新检查来源权限,保留加密笔记本请求租约;发布阅读者不能读取加密笔记本。前端每页加载 50 条,保留视口附近 5 页及正在编辑的页,最多按需创建 16 个编辑器。回收等待未完成事务,保留输入法组合、焦点、拖动和数据库编辑会话。自动刷新等待编辑结束并恢复可见块的位置。配置 `backlinkGlobalSort` 的 `0`(默认)表示文档分组,`1`、`2` 表示全局锚文本升降序。`/api/ref/getBacklink2` 新增可选的 `includeBacklinks`(默认 `true`);设为 `false` 时返回空反链列表及零反链计数,保留提及行为,避免重复加载文档分组。已有调用方和文档内 `blockSort` 的默认行为保持不变。-`TestGlobalBacklink*`、`TestAPIContractGlobalBacklink`、`TestBacklinkAnchorSortContext` 和 `TestBacklink2OptionalMentions` 覆盖跨文档分页、首个引用取值、编辑后的快照稳定性、阅读定位、普通和加密读取、来源权限、过期、缓存上限、实际 HTTP 响应契约及提及兼容性。它们包含在下方内核全量 CI 命令中,可单独运行 `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(GlobalBacklink|Backlink|APIContractGlobalBacklink|APIContractBack|APIContractSetting|PublishReaderBack|PublishReaderSearchAndBacklink|RouteCoverage)' -count=1`。前端的 `globalBacklinkPaging.test.ts`、`globalBacklinkList.test.js` 和 `backlinkSort.test.js` 已由现有全量 CI 自动发现,覆盖页窗口上限、迟到响应、待提交编辑和模式切换。--`TestGlobalBacklinkLargeDataset` 在隔离数据库中创建并索引 100 篇真实文档、共 10,000 条引用,逐一检查全部 200 页的自然顺序及条目无重复、无遗漏,再加载 16 个可编辑上下文。测试报告首次排序、缓存分页、正文加载的耗时及快照大小,不设置依赖机器性能的时间阈值。可运行 `go test -tags "fts5 sqlcipher" ./model -run TestGlobalBacklinkLargeDataset -count=1 -v`;现有 `TestGlobalBacklink*` 筛选和内核全量 CI 均包含该测试。前端回归还覆盖底部面板请求失败后的重试入口、重试成功后的空状态恢复,以及编辑器回收与重建时整行高度保持稳定。-## 文件与流式协议`RawSSEOptions` 和 `RawWebSocketOptions` 声明以字节为载荷的广播协议,通过 `ValidateRawSSEEvent` 和 `ValidateRawWebSocketFrame` 单独校验事件及帧元数据;JSON 事件与 RPC 消息保留各自既有校验。原始 WebSocket 的错误由升级器写出,不使用 `RejectWebSocket`。@@ -198,8 +172,6 @@ JSON SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷生成器读取 `kernel/apicontract/contracts.go` 中接口声明的前置注释,并在前端和 Petal 声明中将其输出为对应 `APIGETRoutes`、`APIPOSTRoutes` 条目的 JSDoc。接口行为、默认值、约束和兼容性在该声明处维护;使用分组 `var` 声明时,将注释放在具体接口前,分组注释不会复制到每个条目。请求工具函数的注释只说明传输行为,并通过路由类型链接到接口详情;不要手工修改生成的声明。-`/api/block/migrateLegacyMindmaps` 是要求管理员身份的写入端点,保留只读保护及加密笔记本请求租约。请求必须提供文档 `id` 和 `notebook`;保存历史后,在一次可撤销事务中转换能够完整解析的旧 `mindmap` 列表,返回 `converted` 数量和文档脑图的权威 `blocks`(`id`、`dom`)。重复请求返回当前块内容,不重复转换;不完整的原文保持不变。回归命令为 `go test -tags "fts5 sqlcipher" ./model ./api ./apicontract/... -run 'Test(LegacyMindmap|MigrateLegacyMindmaps|APIContractHeadingTransactions|APIContractRouterCoverage|RouteCoverage)' -count=1`,前端覆盖位于 `listMindmap/migrate.test.ts` 和 `listMindmap/model.test.ts`,均由现有持续集成规则发现。-契约变更后,在 `app/` 下运行生成和检查。以下命令也列出了前端全量测试;根据受影响的行为和风险选择回归范围,不要求每个任务都运行全量测试:```textdiff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 4a9b379a26..4b8c7ff361 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -305,7 +305,10 @@ var (// 读取失败或扫描超时返回 code=-1、data=null;调用方应保留旧结果的时间标记,并允许用户重试。GetWorkspaceStorage = define[EmptyRequest, WorkspaceStorageData]("getWorkspaceStorage", "/api/system/getWorkspaceStorage", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")GetNetwork = define[EmptyRequest, NetworkData]("getNetwork", "/api/system/getNetwork", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")- GetRuntimeInfo = define[EmptyRequest, SystemRuntimeInfoData]("getRuntimeInfo", "/api/system/getRuntimeInfo", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")+ // 无需请求体,要求管理员权限并允许只读模式,返回 {text} 诊断摘要:内核版本、运行时、操作系统、+ // 逻辑 CPU 数量、当前系统与进程内存,以及检测到的工作空间存储类型。+ // 无法探测的内存或存储返回 unknown,不把移动端存储推断为 SSD;文本不含工作空间路径、主机名和账户标识。+ GetRuntimeInfo = define[EmptyRequest, SystemRuntimeInfoData]("getRuntimeInfo", "/api/system/getRuntimeInfo", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")// 无需参数,要求管理员权限并允许只读模式,以当前内核进程身份诊断 data 目录的遍历。// text 为 JSON Lines,比较标准库和原始目录项,不读取正文、不写入工作空间、不下载或解密资源。// 首行包含思源版本、容器和移动端提供的系统版本,便于关联 Android/SDK 及具体内核版本。@@ -427,6 +430,12 @@ var GetTreeStat = define[TreeStatRequest, TreeStatData]("getTreeStat", "/api/blovar TransferBlockRef = define[TransferBlockRefRequest, Null]("transferBlockRef", "/api/block/transferBlockRef", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+// 编辑器通过独立事务转换块引用:id 指定引用块,blockID 指定定义块,data 携带布尔选项 includeChildren+// 和 originalToEmbed。内核在 retData 中返回受影响的文档 ID,并以受影响顶层块的私有内存快照生成逆向操作;+// 快照不传给客户端,也不接受客户端提交。重放保留块 ID 和数据库绑定,内容或位置已改变时拒绝覆盖,+// originalToEmbed 省略或为 false 时在原定义位置保留引用,为 true 时替换为查询已移动定义 ID 的嵌入块;+// includeChildren 保留标题和列表行为。+// 提交失败时补偿已写入的文档。撤销与重放期间为所有受影响文档持有笔记本租约,直至响应序列化完成。var SwapBlockRef = define[SwapBlockRefRequest, Null]("swapBlockRef", "/api/block/swapBlockRef", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SetBlockReminder = define[BlockReminderRequest, Null]("setBlockReminder", "/api/block/setBlockReminder", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -483,6 +492,9 @@ var BatchInsertBlock = define[BatchInsertBlockRequest, []*BlockTransaction]("batvar UpdateBlock = define[UpdateBlockRequest, []*BlockTransaction]("updateBlock", "/api/block/updateBlock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+// 要求管理员身份,保留只读保护及加密笔记本请求租约;请求必须提供文档 id 和 notebook。+// 保存历史后在一次可撤销事务中转换能够完整解析的旧 mindmap 列表,返回 converted 数量与文档脑图的+// 权威 blocks(id、dom)。重复请求返回当前块内容而不重复转换,不完整的原文保持不变。var MigrateLegacyMindmaps = define[MigrateLegacyMindmapsRequest, MigrateLegacyMindmapsData]("migrateLegacyMindmaps", "/api/block/migrateLegacyMindmaps", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var BatchUpdateBlock = define[BatchUpdateBlockRequest, []*BlockTransaction]("batchUpdateBlock", "/api/block/batchUpdateBlock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -713,6 +725,9 @@ var GetBackmentionDoc = define[BackmentionDocumentRequest, BacklinkContextData](// sourceFilter.database 在父块合并前按来源块的数据库字段筛选,不修改原数据库视图。// 无条件仅筛数据库成员,失效字段不放宽结果;原来源筛选、排序及加密笔记本租约保持不变。+// blockSort 为 0(默认)时保持正文顺序,1 按匹配引用的锚文本自然升序,2 为自然降序,其他值回退正文顺序。+// 条目取首个匹配引用的锚文本并去除首尾空白;排序键相同时保持正文顺序,无锚文本的条目在两个方向均置后。+// 来源文档内部把整篇文档条目展开为可独立排序的引用,恢复正文顺序时重新合并;排序模式参与上下文版本哈希。var GetBacklinkDoc = define[BacklinkDocumentRequest, BacklinkContextData]("getBacklinkDoc", "/api/ref/getBacklinkDoc", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")// 提及数量提示使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,发布读者不发送提示。@@ -727,6 +742,8 @@ var GetBacklinkDatabases = define[BacklinkDatabasesRequest, []*BacklinkDatabase]var GetGlobalBacklinks = define[GlobalBacklinkListRequest, GlobalBacklinkListData]("getGlobalBacklinks", "/api/ref/getGlobalBacklinks", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")// 数据库条件与列表快照一致,不修改来源数据或原数据库视图。+// 必需的 snapshot 与最多 20 个属于该快照的块 ids 返回可独立编辑的块正文,保留面包屑和数据库引用信息。+// 返回前重新检查来源权限并持有加密笔记本请求租约;发布阅读者不能读取加密笔记本。var GetGlobalBacklinkContexts = define[GlobalBacklinkContextRequest, GlobalBacklinkContextData]("getGlobalBacklinkContexts", "/api/ref/getGlobalBacklinkContexts", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")var ContinueImportSY = define[ContinueImportSYRequest, ImportDocumentData]("continueImportSY", "/api/import/continueImportSY", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -947,6 +964,10 @@ var SetSyncLAN = define[SyncLANRequest, SyncLANStatus]("setSyncLAN", "/api/sync/var GetSyncLANStatus = define[EmptyRequest, SyncLANStatus]("getSyncLANStatus", "/api/sync/getSyncLANStatus", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var SetSyncGenerateConflictDoc = define[SyncEnabledRequest, Null]("setSyncGenerateConflictDoc", "/api/sync/setSyncGenerateConflictDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")var SetSyncMode = define[SyncModeRequest, Null]("setSyncMode", "/api/sync/setSyncMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")++// completeAssets 为 true 时,在切换来源前从原提供商下载缺失的当前资源和历史快照内容;+// 省略、null 与 false 保留只检查完整性的行为。补齐过程保留下载模式和恢复密钥,失败时保留原提供商。+// 确认后的操作通过全局进度遮罩显示检查与补齐阶段,成功或失败均关闭遮罩。var SetSyncProvider = define[SyncProviderRequest, Null]("setSyncProvider", "/api/sync/setSyncProvider", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")var SetSyncProviderS3 = define[SetSyncS3Request, SyncS3Data]("setSyncProviderS3", "/api/sync/setSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "sync"}}, "POST")@@ -1163,7 +1184,10 @@ var RenameDocByID = define[FileTreeRenameIDRequest, Null]("renameDocByID", "/api// DuplicateDoc evaluates block collection rules for the new document and its blocks, initializing only new rows.var DuplicateDoc = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDoc", "/api/filetree/duplicateDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-// DuplicateDocTree evaluates block collection rules for every copied document and block, initializing only new rows.+// 将单篇文档及全部子文档复制到同一笔记本的原父目录,返回副本根文档的 id、notebook、path 和 hPath。+// 副本内部块引用、块链接和查询嵌入的显式块 ID 统一重映射,数据库定义与行绑定保持为共享镜像。+// 源快照经过认证读取且不执行修复写回;运行期失败时清理新建文档并恢复排序,属运行时补偿,+// 不保证进程崩溃时的事务原子性。var DuplicateDocTree = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDocTree", "/api/filetree/duplicateDocTree", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -1367,6 +1391,7 @@ var RemoveUnusedEncryptedBoxAssets = define[RemoveEncryptedBoxAssetsRequest, Assvar GetMissingAssets = define[EmptyRequest, []*AssetUnusedItem]("getMissingAssets", "/api/asset/getMissingAssets", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")// ResolveAssetPath 返回普通资源路径;已解锁的加密资源返回保留原始名称的受管临时明文副本路径。+// 请求持有加密笔记本租约直至响应序列化完成,外部编辑不写回加密源数据。var ResolveAssetPath = define[AssetPathRequest, string]("resolveAssetPath", "/api/asset/resolveAssetPath", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")// 上传提示生命周期使用可选请求头 X-SiYuan-App-ID 定向;无标识时广播,状态栏仍全局更新。@@ -1582,6 +1607,10 @@ var AIRemoveEditorAction = define[AIEditorActionIDRequest, Null]("removeAIEditorvar AITestModel = define[AIModelRequest, AIModelTestData]("testModel", "/api/ai/testModel", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")var AITestEmbeddingModel = define[EmptyRequest, AIEmbeddingTestData]("testEmbeddingModel", "/api/ai/testEmbeddingModel", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")var AITestRerankModel = define[EmptyRequest, AIRerankTestData]("testRerankModel", "/api/ai/testRerankModel", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")++// 用固定的 TypeSafe System One 样例测试已保存的可选 ai.decision 配置,返回 {matched, msg?}。+// 遵循全局人工智能禁用标记和请求取消,配置错误与供应商错误不会被转换为判断结果。+// 省略决策配置时补齐默认关闭的配置,关闭后保留密钥,并沿用现有配置加密存储机制。var AITestDecisionModel = define[AIDecisionTestRequest, AIDecisionTestData]("testDecisionModel", "/api/ai/testDecisionModel", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")// 按提供商协议读取模型及上下文上限;gemini-interactions 使用原生模型清单并去除 models/ 前缀。@@ -1653,6 +1682,13 @@ var AIGetSkill = define[AISkillNameRequest, AISkillData]("getSkill", "/api/ai/agvar AISaveSkill = define[AISkillSaveRequest, Null]("saveSkill", "/api/ai/agent/saveSkill", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")var AIRemoveSkill = define[AISkillNameRequest, Null]("removeSkill", "/api/ai/agent/removeSkill", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")var AIRenameSkill = define[AISkillRenameRequest, Null]("renameSkill", "/api/ai/agent/renameSkill", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{}, "POST")++// 使用严格字符串字段,通过管理员和只读检查管理工作空间技能文件。相对路径标识实际目录,+// 与文件头中的技能名称无关,允许普通的点开头名称。读写支持不超过 8 MiB 的 UTF-8 文本,+// 不依赖扩展名并保留原文字节。目录和资源读取保留基于内容的版本;不支持编辑的内容省略 content,+// 并增加可选的 readOnlyReason(binary、encoding 或 tooLarge)。+// 修改已有文件时重新校验内容并要求当前版本,与旧技能修改接口和安装共享临界区,成功后通知同步。+// 路径穿越、平台别名、链接、过期版本,以及单独修改不支持的内容或重命名、删除根 SKILL.md 均被拒绝。var AIManageSkills = define[AISkillFileRequest, AISkillFileData]("manageSkills", "/api/ai/agent/manageSkills", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var AIEditorChat = define[AIEditorChatRequest, Null]("aiEditorChat", "/api/ai/editor/chat", AuthenticatedAccess|AdminAccess, StructJSONBody, aiEditorSSEOptions(), "POST")