Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Enable structured document titles by default https://github.com/siyuan-note/siyuan/issues/19938

Daniel229af4abc114
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
index ee299be70a..42bcff4c2b 100644
--- a/.github/workflows/cd.yml
+++ b/.github/workflows/cd.yml
@@ -242,9 +242,9 @@ jobs:
env:
SIYUAN_OCR_TEST_ASSETS: ${{ github.workspace }}/app/stage/ocr/models
SIYUAN_OCR_TEST_LIBRARY: ${{ github.workspace }}/app/stage/ocr/runtime/linux-amd64/libonnxruntime.so
- - name: Test structured title migration behind the release gate
+ - name: Test default structured title migration
continue-on-error: true
- run: go test -tags "fts5 sqlcipher" -ldflags "-X github.com/siyuan-note/siyuan/kernel/documentaddressing.minimumReaderVersion=0.0.0-test" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1
+ run: go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1
working-directory: kernel
- name: Test path fixtures with custom temporary directories
id: test_path_fixtures_with_custom_temporary_directories
@@ -328,10 +328,10 @@ jobs:
CGO_ENABLED: 1
CC: gcc
- - name: Test Windows structured title migration behind the release gate
+ - name: Test Windows default structured title migration
continue-on-error: true
shell: msys2 {0}
- run: go test -tags "fts5 sqlcipher" -ldflags "-X github.com/siyuan-note/siyuan/kernel/documentaddressing.minimumReaderVersion=0.0.0-test" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1
+ run: go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1
working-directory: kernel
env:
CGO_ENABLED: 1
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
index 03760ca55d..ff90a0bafd 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy
@@ -6,7 +6,7 @@
"id": "20200924101225-k254i8g",
"title": "Content Block Type",
"type": "doc",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -1474,7 +1474,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104091538-a55chyw",
- "updated": "20261017174053"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3298,7 +3298,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20210104091538-clx67q4",
- "updated": "20251021230320"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3336,12 +3336,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261023112115-ewf6xvh",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Versions supporting structured document titles allow ASCII / in titles by default, without a setting to enable it. For example, A/B can be one document title and is different from a document B inside A. Existing titles and document links stay unchanged; / and %2F remain literal text."
+ "Data": "Document titles allow ASCII / by default, without a setting to enable it. For example, A/B can be one document title and is different from a document B inside A. Existing titles and document links stay unchanged; / and %2F remain literal text."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
index 9cf6a87473..fee72cb8fb 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-fqgskfj/20200905090211-2vixtlf.sy
@@ -6,7 +6,7 @@
"id": "20200905090211-2vixtlf",
"title": "内容块类型",
"type": "doc",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -1507,7 +1507,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20210104090624-9qgquxh",
- "updated": "20261017174053"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3380,7 +3380,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20210104090624-5abfwla",
- "updated": "20260425180524"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3418,12 +3418,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261023112115-3dui2fu",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
"Type": "NodeText",
- "Data": "支持结构化文档标题的版本默认允许标题包含半角斜杠 /,无需设置开关。例如,A/B 可以是一篇文档的标题,与 A 下的子文档 B 不同。已有标题和文档链接保持不变,/ 和 %2F 仍按原文字面显示。"
+ "Data": "文档标题默认允许包含半角斜杠 /,无需设置开关。例如,A/B 可以是一篇文档的标题,与 A 下的子文档 B 不同。已有标题和文档链接保持不变,/ 和 %2F 仍按原文字面显示。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
index e178ca8905..4e72423f7e 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226115825-mhcslw2/20211226120147-ib6yy3i.sy
@@ -6,7 +6,7 @@
"id": "20211226120147-ib6yy3i",
"title": "內容區塊類型",
"type": "doc",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -1503,7 +1503,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20211226120227-esm6f20",
- "updated": "20261017174053"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3298,7 +3298,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20211226120227-ub34qwj",
- "updated": "20260730184353"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3337,12 +3337,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261023112115-fwzt0ts",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
"Type": "NodeText",
- "Data": "支援結構化文檔標題的版本預設允許標題包含半形斜線 /,無需設定開關。例如,A/B 可以是一篇文檔的標題,與 A 下的子文檔 B 不同。既有標題和文檔連結保持不變,/ 和 %2F 仍按原文字面顯示。"
+ "Data": "文檔標題預設允許包含半形斜線 /,無需設定開關。例如,A/B 可以是一篇文檔的標題,與 A 下的子文檔 B 不同。既有標題和文檔連結保持不變,/ 和 %2F 仍按原文字面顯示。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
index bf6ebd8ac5..3aa6e340ff 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-gvtksyj/20240530101000-35bbvcx.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-35bbvcx",
"title": "コンテンツブロックの種類",
"type": "doc",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -1564,7 +1564,7 @@
"Properties": {
"ID": "20240530101000-rjjxxn8",
"id": "20240530101000-p035stn",
- "updated": "20261017174053"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3517,7 +3517,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20240530101000-gtx9sbs",
- "updated": "20250330192734"
+ "updated": "20261023133001"
},
"Children": [
{
@@ -3584,12 +3584,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261023112115-4rumyue",
- "updated": "20261023112115"
+ "updated": "20261023133001"
},
"Children": [
{
"Type": "NodeText",
- "Data": "構造化ドキュメントタイトルに対応するバージョンでは、設定の切り替えなしにタイトルで半角スラッシュ / を使用できます。例えば A/B は 1 つのドキュメントのタイトルにでき、A の中にある子ドキュメント B とは別です。既存のタイトルとドキュメントリンクは変わらず、/ と %2F も元の文字のまま扱われます。"
+ "Data": "ドキュメントタイトルでは、設定の切り替えなしに半角スラッシュ / を使用できます。例えば A/B は 1 つのドキュメントのタイトルにでき、A の中にある子ドキュメント B とは別です。既存のタイトルとドキュメントリンクは変わらず、/ と %2F も元の文字のまま扱われます。"
}
]
},
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 4923c94f0f..eac8df267b 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -6297,9 +6297,10 @@ export interface APIPOSTRoutes {
/**
* preserves existing configuration and permission filtering. Administrator
* responses also contain documentCapabilities: structuredPaths advertises the ID/segment APIs,
- * not permission to open a closed or locked notebook. The feature release migrates to mode 2
- * automatically without a user setting. literalSlash requires consistent mode records and ready
- * indexes; minimumReaderVersion remains null while protective-release verification is pending.
+ * not permission to open a closed or locked notebook. Ordinary builds migrate to mode 2
+ * automatically without a user setting or special build flags. literalSlash requires consistent
+ * mode records and ready indexes. minimumReaderVersion remains null while protective-release
+ * verification is pending; this informational field does not control feature activation.
* Revision covers configuration, confirmed capability and recovery records, not a document path.
* Malformed capability records fail the request; authentication, locking and network failures must
* never be interpreted as an absent capability object or as permission to retry a legacy write.
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index d1b7f2d49b..bf2f5e63eb 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -561,7 +561,7 @@ interface INotebook {
}
interface ISiyuan {
- /** 当前内核的只读文档标题能力,不持久化为用户设置。 */
+ /** 当前内核的只读文档标题能力,普通构建默认为 2,不持久化为用户设置。 */
documentAddressingVersion?: number;
zIndex: number
isReady?: boolean
diff --git a/docs/API.ja.md b/docs/API.ja.md
index 25ad21fe51..461e9f2a37 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -298,7 +298,7 @@ if (response.code === 0 && response.data) {
### ノートブック設定を取得
-管理者向けレスポンスには、読み取り専用の `documentCapabilities` オブジェクトが含まれる場合があります。アドレス指定モード、構造化 API、タイトル機能、インデックス状態、検証済みの最低読み取りバージョンを示します。機能リリースでは設定の切り替えなしに自動移行されます。`literalSlash` にはモード `2`、整合したモード記録、準備済みインデックスが必要です。保護リリースの検証が完了するまで `minimumReaderVersion` は `null` です。既存の権限によるフィルタリングは維持されます。
+管理者向けレスポンスには、読み取り専用の `documentCapabilities` オブジェクトが含まれる場合があります。アドレス指定モード、構造化 API、タイトル機能、インデックス状態、検証済みの最低読み取りバージョンを示します。通常のビルドでは、設定の切り替えや追加のビルド引数なしに、既定で自動移行されます。`literalSlash` にはモード `2`、整合したモード記録、準備済みインデックスが必要です。保護リリースの検証が完了するまで `minimumReaderVersion` は `null` ですが、新モードの既定の有効化には影響しません。既存の権限によるフィルタリングは維持されます。
* `/api/notebook/getNotebookConf`
* パラメータ
@@ -331,7 +331,7 @@ if (response.code === 0 && response.data) {
}
```
-管理者への応答には、読み取り専用の省略可能な `documentCapabilities` オブジェクトも含まれます。`structuredPaths` は ID とパス要素の API への対応を示し、閉じたノートブックやロック中のノートブックへのアクセス権限は付与しません。現在の `literalSlash` は `false` で、保護バージョンの検証が完了するまで `minimumReaderVersion` は `null` です。旧サーバーにこのオブジェクトがない場合とリクエストの失敗は区別し、失敗後に従来のパス API で書き込みを再試行しないでください。
+管理者への応答には、読み取り専用の省略可能な `documentCapabilities` オブジェクトも含まれます。`structuredPaths` は ID とパス要素の API への対応を示し、閉じたノートブックやロック中のノートブックへのアクセス権限は付与しません。`literalSlash` はモード `2` でモード記録が整合し、インデックスが準備済みの場合に `true` です。保護バージョンの検証が完了するまで `minimumReaderVersion` は `null` で、この値は機能の有効化を制御しません。旧サーバーにこのオブジェクトがない場合とリクエストの失敗は区別し、失敗後に従来のパス API で書き込みを再試行しないでください。
### ノートブック設定を保存
@@ -374,7 +374,7 @@ if (response.code === 0 && response.data) {
### Markdownでドキュメントを作成
-この旧名称パス API は互換モードでのみ利用できます。構造化タイトルに対応する機能リリースではノートブックが自動移行され、通常のタイトルや `parentID` を指定した場合も、ノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。`/api/filetree/createDocByParent` に親の識別情報とタイトルを別々に渡してください。以下の例は互換モードの動作を示します。
+この旧名称パス API は互換モードでのみ利用できます。通常のビルドでは既定でノートブックが構造化タイトルモードに自動移行され、通常のタイトルや `parentID` を指定した場合も、ノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。`/api/filetree/createDocByParent` に親の識別情報とタイトルを別々に渡してください。以下の例は互換モードの動作を示します。
* `/api/filetree/createDocWithMd`
* パラメータ
@@ -758,7 +758,7 @@ if (response.code === 0 && response.data) {
### 人間が読めるパスからIDを取得
-構造化タイトルに対応する機能リリースではノートブックが自動移行され、この旧 API はノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。既知のドキュメント ID はそのまま使用し、不明な場所は `/api/filetree/resolveDocPath` にタイトルの配列を渡して解決してください。表示パスだけでは、単一のタイトル `A/B` と 2 階層の `A`、`B` を区別できません。以下の例は互換モード用です。
+通常のビルドでは既定でノートブックが構造化タイトルモードに自動移行され、この旧 API はノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。既知のドキュメント ID はそのまま使用し、不明な場所は `/api/filetree/resolveDocPath` にタイトルの配列を渡して解決してください。表示パスだけでは、単一のタイトル `A/B` と 2 階層の `A`、`B` を区別できません。以下の例は互換モード用です。
* `/api/filetree/getIDsByHPath`
* パラメータ
diff --git a/docs/API.md b/docs/API.md
index 0820295bc3..724cb8f251 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -303,7 +303,7 @@ The close endpoint validates the notebook ID without trimming whitespace. Typed
### Get notebook configuration
-Administrator responses may also include the read-only `documentCapabilities` object. It reports addressing mode, structured API support, title capabilities, index state, and the verified minimum reader release. The feature release migrates notebooks automatically without an enable setting; `literalSlash` requires mode `2`, consistent records, and ready indexes. `minimumReaderVersion` remains `null` until the protective release is verified. Existing permission filtering still applies.
+Administrator responses may also include the read-only `documentCapabilities` object. It reports addressing mode, structured API support, title capabilities, index state, and the verified minimum reader release. Ordinary builds migrate notebooks automatically by default, without a user setting or extra build flags; `literalSlash` requires mode `2`, consistent records, and ready indexes. `minimumReaderVersion` remains `null` until the protective release is verified; it does not disable the default mode. Existing permission filtering still applies.
* `/api/notebook/getNotebookConf`
* Parameters
@@ -336,7 +336,7 @@ Administrator responses may also include the read-only `documentCapabilities` ob
}
```
-Administrator responses also include the optional read-only `documentCapabilities` object. `structuredPaths` advertises the ID and segment APIs; it does not grant access to closed or locked notebooks. `literalSlash` is currently `false`, and `minimumReaderVersion` is `null` until a protective release is verified. An absent object on an older server differs from a failed request; failures must not trigger a fallback write through legacy path APIs.
+Administrator responses also include the optional read-only `documentCapabilities` object. `structuredPaths` advertises the ID and segment APIs; it does not grant access to closed or locked notebooks. `literalSlash` is `true` in mode `2` with consistent mode records and ready indexes. `minimumReaderVersion` is `null` until a protective release is verified and does not control feature activation. An absent object on an older server differs from a failed request; failures must not trigger a fallback write through legacy path APIs.
### Save notebook configuration
@@ -379,7 +379,7 @@ Administrator responses also include the optional read-only `documentCapabilitie
### Create a document with Markdown
-This legacy name-path endpoint is available only in compatibility mode. In the structured-title feature release, notebooks migrate automatically and this endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook, even with ordinary titles or `parentID`. Use `/api/filetree/createDocByParent` with a separate parent identity and title. The examples below describe compatibility-mode behavior.
+This legacy name-path endpoint is available only in compatibility mode. In ordinary builds, notebooks migrate automatically to structured-title mode by default and this endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook, even with ordinary titles or `parentID`. Use `/api/filetree/createDocByParent` with a separate parent identity and title. The examples below describe compatibility-mode behavior.
* `/api/filetree/createDocWithMd`
* Parameters
@@ -763,7 +763,7 @@ Move documents by `id`:
### Get IDs based on human-readable path
-In the structured-title feature release, notebooks migrate automatically and this legacy endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook. Use known document IDs directly, or `/api/filetree/resolveDocPath` with explicit title segments. Displayed paths cannot distinguish a single title `A/B` from two levels `A`, `B`. The example below applies to compatibility mode.
+In ordinary builds, notebooks migrate automatically to structured-title mode by default and this legacy endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook. Use known document IDs directly, or `/api/filetree/resolveDocPath` with explicit title segments. Displayed paths cannot distinguish a single title `A/B` from two levels `A`, `B`. The example below applies to compatibility mode.
* `/api/filetree/getIDsByHPath`
* Parameters
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index bcac3a6f6f..4e430bb2de 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -303,7 +303,7 @@ if (response.code === 0 && response.data) {
### 获取笔记本配置
-管理员响应还可包含只读的 `documentCapabilities` 对象,用于报告寻址模式、结构化接口支持、标题能力、索引状态及已验证的最低读取版本。功能版本自动迁移笔记本,无需设置开关;`literalSlash` 要求模式 `2`、模式记录一致且索引就绪。保护版本尚未验证时,`minimumReaderVersion` 为 `null`。既有权限过滤保持不变。
+管理员响应还可包含只读的 `documentCapabilities` 对象,用于报告寻址模式、结构化接口支持、标题能力、索引状态及已验证的最低读取版本。普通构建默认自动迁移笔记本,无需设置开关或额外编译参数;`literalSlash` 要求模式 `2`、模式记录一致且索引就绪。保护版本尚未验证时,`minimumReaderVersion` 为 `null`,不影响新模式默认启用。既有权限过滤保持不变。
* `/api/notebook/getNotebookConf`
* 参数
@@ -336,7 +336,7 @@ if (response.code === 0 && response.data) {
}
```
-管理员响应还包含可选只读对象 `documentCapabilities`。`structuredPaths` 表示服务端支持 ID 与路径段接口,不授予关闭或锁定笔记本的访问权限。目前 `literalSlash` 为 `false`;保护版本验证完成前,`minimumReaderVersion` 为 `null`。旧服务端缺少此对象与请求失败含义不同,不能在请求失败后回退到旧路径接口继续写入。
+管理员响应还包含可选只读对象 `documentCapabilities`。`structuredPaths` 表示服务端支持 ID 与路径段接口,不授予关闭或锁定笔记本的访问权限。`literalSlash` 在模式 `2`、模式记录一致且索引就绪时为 `true`;保护版本验证完成前,`minimumReaderVersion` 为 `null`,该字段不控制功能启用。旧服务端缺少此对象与请求失败含义不同,不能在请求失败后回退到旧路径接口继续写入。
### 保存笔记本配置
@@ -379,7 +379,7 @@ if (response.code === 0 && response.data) {
### 通过 Markdown 创建文档
-这是仅在兼容模式可用的旧名称路径接口。结构化标题功能版本会自动迁移笔记本,该接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`,即使标题普通或提供了 `parentID`。请改用 `/api/filetree/createDocByParent`,分别传入父身份和标题。下面的示例描述兼容模式行为。
+这是仅在兼容模式可用的旧名称路径接口。普通构建默认自动迁移笔记本到结构化标题模式,该接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`,即使标题普通或提供了 `parentID`。请改用 `/api/filetree/createDocByParent`,分别传入父身份和标题。下面的示例描述兼容模式行为。
* `/api/filetree/createDocWithMd`
* 参数
@@ -763,7 +763,7 @@ if (response.code === 0 && response.data) {
### 根据人类可读路径获取 IDs
-结构化标题功能版本会自动迁移笔记本,该旧接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`。已知文档 ID 时直接使用;未知位置请通过 `/api/filetree/resolveDocPath` 传入明确的标题段。显示路径无法区分单标题 `A/B` 与两级 `A`、`B`。下面的示例适用于兼容模式。
+普通构建默认自动迁移笔记本到结构化标题模式,该旧接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`。已知文档 ID 时直接使用;未知位置请通过 `/api/filetree/resolveDocPath` 传入明确的标题段。显示路径无法区分单标题 `A/B` 与两级 `A`、`B`。下面的示例适用于兼容模式。
* `/api/filetree/getIDsByHPath`
* 参数
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.md
index 75f31b4b74..12004490cb 100644
--- a/docs/DOCUMENT-ADDRESSING.md
+++ b/docs/DOCUMENT-ADDRESSING.md
@@ -12,7 +12,7 @@ The development branch implements a shared title reader, document metadata organ
Creation plans retain fixed IDs and never recreate confirmed ancestors. Desktop and mobile share failure handling: an uncertain response or a failure after source commit retains the plan until the user approves an identity check and continuation. Closing or locking a notebook clears its title and template caches. Local shorthands keep a recovery record containing only identities and digests, verify block identities in the actual source before consuming the input, and preserve unresolved input without automatically replaying the operation.
-The structured-title feature release defaults to mode `2`, without a user setting or manual activation endpoint. The development branch implements automatic mode migration and interruption recovery, `DocumentTitleSpec = "6"`, literal slash reads and writes, and notebook-wide rejection of legacy string addressing. The frontend initializes title input rules from a read-only runtime capability. Ordinary builds remain at the protective stage: the verified minimum reader release has not yet been assigned, so they retain mode `1`; isolated tests exercise mode `2` through a test linker value. Actual protective-release, mixed-version, performance, and platform acceptance remain required before the feature release automatically adopts the new mode. Inline-title extension requirements remain unchanged.
+The structured-title feature release defaults to mode `2`, without a user setting or manual activation endpoint. The development branch implements automatic mode migration and interruption recovery, `DocumentTitleSpec = "6"`, literal slash reads and writes, and notebook-wide rejection of legacy string addressing. The frontend initializes title input rules from a read-only runtime capability. Ordinary builds default to mode `2` without additional build flags. `minimumReaderVersion` only reports a verified compatible release; leaving it unset does not disable the new mode. Actual protective-release, mixed-version, performance, and platform acceptance remain required release evidence and cannot be inferred from default activation. Inline-title extension requirements remain unchanged.
Administrator notebook configuration reads expose `documentCapabilities`, distinguishing structured APIs, the effective addressing mode, and index state. `minimumReaderVersion` stays `null` until a real protective release has been verified; malformed capability records return an error. Whole-notebook native import remaps notebook and anchor IDs in configured targets, while partial import preserves the destination configuration. Encrypted targets retain authenticated locked saves, password rewrapping, and backup recovery.
@@ -333,7 +333,7 @@ The caller submits each `createDocByParent` request in order, updating the next
### Capability discovery and automatic migration
-Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Administrator responses include this object; other roles retain existing configuration filtering. `minimumReaderVersion` is `null` until the actual protective release has been verified, then contains its version string. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.
+Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Administrator responses include this object; other roles retain existing configuration filtering. `minimumReaderVersion` is `null` until the actual protective release has been verified, then contains its version string. This field does not control feature activation. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.
`revision` summarizes mode records and recovery state. It is neither an individual document's path revision nor a user activation token. Capability declarations grant no access; closed or locked notebooks retain existing restrictions, and status reads expose neither titles nor protected template content. When an older server omits the object, plugins use only legacy capabilities. Authorization, locking, and network errors must not be interpreted as unsupported capabilities or trigger fallback writes.
@@ -374,7 +374,7 @@ Plugins migrate through capability discovery, reading known targets by ID, resol
Notebook configuration stores the internal compatibility marker `documentAddressingVersion`: an absent field or `1` denotes legacy records, and `2` denotes structured-title records. Effective mode also considers the capability floors and recovery records below. This is not a user setting, is independent of encryption-envelope versions, and must not reuse `BoxCrypt.Spec`. The feature release migrates records automatically without rewriting existing document titles or IDs in bulk.
-Even if `.sy` continues storing a string title, older clients can remove `/` or interpret title text as hierarchy. Release in two steps: first a protective version recognizing notebook capability and recovery markers and safely rejecting unsupported modes, then a feature version defaulting to mode `2`. The protective version rejects unsupported modes before mounting, indexing, repairing, editing, or applying sync changes; it must not modify data before requesting an upgrade.
+Even if `.sy` continues storing a string title, older clients can remove `/` or interpret title text as hierarchy. External release compatibility requires two steps: first a protective version recognizing notebook capability and recovery markers and safely rejecting unsupported modes, then a feature version defaulting to mode `2`. Ordinary development builds already default to mode `2`, independently of minimum-version metadata. The protective version rejects unsupported modes before mounting, indexing, repairing, editing, or applying sync changes; it must not modify data before requesting an upgrade.
Documents actually using new title capabilities adopt `DocumentTitleSpec = "6"`: normal writes raise `Spec` to at least `6` when the title contains ASCII `/`. Ordinary titles retain the specification required by their body features. A client upgrade, mode migration, or ordinary formatting must not raise every document to `6` or lower an existing version. Future rich representations also need explicit format versions; tolerant parsing must never overwrite unknown content.
@@ -386,7 +386,7 @@ Tree writes validate both the replacement and the current on-disk source. Authen
Raw file endpoints apply the same source-format checks to paths composed of notebook and document IDs; uploads, copies, and moves into those paths cannot bypass them. Validate the complete batch before creating destination directories or copying any files. Actual document copies use the validated source bytes and recheck the current destination under the file lock. Concurrent changes or I/O failures after preflight can leave completed copies; batch rollback is not promised. Files ending in `.sy` inside ordinary asset and plugin directories retain raw-file semantics, and encrypted notebooks remain inaccessible through raw file endpoints.
-Determine the minimum compatible version through read, write, and rejection tests against actual releases. Clients predating the protective release that ignore capability markers cannot be constrained automatically and are outside the safe mixed-version promise. Before using the feature release, all sync devices must run at least the protective release. Offline device state cannot be proven; release notes and user guides must explain this limit. If protection remains incomplete, retain the release gate rather than substituting documentation or a user switch for protection.
+Determine the minimum compatible version through read, write, and rejection tests against actual releases. Clients predating the protective release that ignore capability markers cannot be constrained automatically and are outside the safe mixed-version promise. Before using the feature release, all sync devices must run at least the protective release. Offline device state cannot be proven; release notes and user guides must explain this limit. Incomplete protection prevents a claim of release readiness or safe mixed-version use; documentation or a user switch cannot substitute for protection.
Automatic migration to mode `2` has no switch back to `1`. Even after current titles no longer contain `/`, history and backups can retain new formats. Older clients may use a verified compatible export copy or a complete pre-upgrade backup restored into a separate workspace; do not overwrite the original workspace with old configuration and continue syncing. Any future downgrade converter requires its own conversion manifest, conflict policy, and recovery design while preserving original data.
@@ -404,7 +404,7 @@ Deleting an entire notebook retains existing semantics; do not recreate it merel
Automatic migration first persists `{version: 1, notebook, phase: "records"}` in `conf/document-addressing-recovery/<notebookID>.json`, then writes the local floor, notebook floor, and configuration mode marker in that order, and finally removes the recovery record. After interruption, the next access continues the same migration without retracting a written requirement. The protective release also interprets valid recovery records as requiring at least mode `2`. Preserve unknown configuration fields and opaque encrypted payload values, without scanning or rewriting `.sy` files. Raw file APIs cannot overwrite the recovery directory.
-The feature release automatically repairs missing mode projections and outdated configuration without recreating deleted notebooks. Mode migration and index rebuilding remain separate: metadata migration needs no ready index and neither authenticates nor rewrites document ciphertext. Subsequent source reads and index construction must still authenticate source content under existing authorization and encrypted-notebook leases. Report `modeState: "structured"` only after records are consistent and indexes are ready.
+The feature release automatically repairs missing mode projections and outdated configuration without recreating deleted notebooks. Mode migration and index rebuilding remain separate: metadata migration needs no ready index and neither authenticates nor rewrites document ciphertext. Subsequent source reads and index construction must still authenticate source content under existing authorization and encrypted-notebook leases. Report `modeState: "structured"` only after records are consistent and indexes are ready. If an existing notebook has lost its configuration file, retain the confirmed mode without creating a replacement configuration. Encrypted backup recovery must still authenticate the original key and payload and cannot save the notebook as plaintext. Capabilities remain `recovering` until configuration is restored.
Record-recovery failures preserve the recovery record and return an error. Missing or rebuilding indexes report `recovering`, and structured writes await required metadata. Unknown source formats, corruption, or authentication failures preserve original files, keys, and pending tasks, stop affected operations, and report errors. Subsequent access or restart continues through existing recovery mechanisms without asking users to select a mode. Never downgrade, recreate a notebook, or bypass format validation to clear an error.
@@ -439,10 +439,10 @@ The versioned configuration-payload extension retains the existing authenticated
| A: Compatibility protection | Notebook capability floors and conflict detection, unknown-mode and source-version protection, existing behavior fixtures | Protective release shipped; modes checked before sync and snapshot application, unsupported modes safely refused at every write and repair entry point |
| B: Internal separation | Shared title access, document metadata, ID hierarchy calculations, path refresh, and recovery | Ordinary titles retain behavior; structure is no longer derived from display strings; encrypted indexes rebuild from authenticated sources |
| C: APIs and consumers | New read, resolve, and conditional-create APIs, version `2` templates and encrypted payloads, built-in workflow and platform migration | Name and configuration conditions and old/new contracts verified; partial failures and undo recoverable; daily-note and other business behavior retained |
-| D: New characters | Default structured mode and automatic recovery, legacy API rejection, plugin migration guidance, cross-mode operations, and import/export checks | Whole-subtree preflight, mode recovery, and all release gates pass before the feature release supports `/` by default |
+| D: New characters | Default structured mode and automatic recovery, legacy API rejection, plugin migration guidance, cross-mode operations, and import/export checks | Ordinary builds support `/` by default; whole-subtree preflight, mode recovery, and all release criteria must pass to complete external release acceptance |
| E: Inline titles | Separate source-format, editing, and rendering design | Retain this design's identity APIs and deliver separately after format and old-writer protection |
-Stages B and C may ship while retaining legacy title restrictions. New characters require all relevant conditions in A through D. Stage E is not a prerequisite for the foundational separation, but A through D must not reintroduce assumptions that titles will permanently have plain-text sources.
+Stages B and C may ship while retaining legacy title restrictions. The development branch enables new characters by default; external release acceptance still requires all relevant conditions in A through D. Stage E is not a prerequisite for the foundational separation, but A through D must not reintroduce assumptions that titles will permanently have plain-text sources.
Release gates include migrated built-in consumers, released replacement APIs and plugin guidance, verified minimum client versions and mixed-version rejection, interruptible ordinary and encrypted index migration, exports that do not overwrite files due to display-path collisions, consistent desktop/browser/mobile behavior, and user guides in all four bundled languages covering default behavior, plugin impact, and sync-device requirements.
@@ -496,7 +496,7 @@ Reports explain changes relative to the baseline. Duration depends on hardware,
Behavior tests enter existing frontend and kernel discovery; new Go contract tests retain `Contract` in their names. After API implementation, run `pnpm run api:generate --petal ../../petal`, `pnpm run api:check --petal ../../petal`, `pnpm run lint`, and relevant frontend tests from `app/`. From `kernel/`, run `go test ./apicontract/...` and regressions covering affected APIs, models, filesystem, block-tree, and SQL behavior. Before release, existing complete test entry points cover `pnpm test` and `go test -tags "fts5 sqlcipher" ./... -count=1`.
-While the release gate remains closed, CI additionally runs `go test -tags "fts5 sqlcipher" -ldflags "-X github.com/siyuan-note/siyuan/kernel/documentaddressing.minimumReaderVersion=0.0.0-test" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1` for automatic migration, structured source reads and writes, and actual HTTP contracts. This value is only for isolated tests, not a real minimum release; ordinary builds continue testing protective behavior. These complete acceptance requirements do not claim all checks have run. Documentation changes additionally verify bilingual consistency, examples, links, and diff formatting.
+CI runs `go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1` with ordinary build defaults for automatic migration, structured source reads and writes, and actual HTTP contracts, without injecting a test version. Explicit compatibility fixtures cover old-reader mode rejection, while ordinary builds continue verifying rejection of unknown future modes and source formats. These complete acceptance requirements do not claim all checks have run. Documentation changes additionally verify bilingual consistency, examples, links, and diff formatting.
## Related code
diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.md
index 4ee2dce4d8..0981645f65 100644
--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md
+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md
@@ -14,7 +14,7 @@
管理员读取笔记本配置时可获取 `documentCapabilities`,区分结构化接口、实际寻址模式和索引状态。未验证真实保护版本时,`minimumReaderVersion` 返回 `null`,不会伪造最低版本;能力记录损坏时明确报错。原生整本导入会同步重映射目标配置中的笔记本和锚点 ID,部分文档导入保留目标笔记本配置。加密目标载荷保持锁定保存、改密及备份恢复的认证边界。
-结构化标题功能版本默认采用模式 `2`,不提供用户开关或手动启用接口。开发分支已实现自动模式迁移与中断恢复、`DocumentTitleSpec = "6"`、标题斜杠读写及旧字符串接口的整本拒绝;前端通过只读运行时能力决定标题输入规则。当前普通构建仍处于保护阶段:发布门槛中的真实最低读取版本尚未填写,因此保持模式 `1`;隔离测试通过测试链接参数覆盖模式 `2`。发布前仍须完成真实保护版本、混合版本、性能及各端验收,之后功能版本自动采用新模式。行级标题扩展约束保持不变。
+结构化标题功能版本默认采用模式 `2`,不提供用户开关或手动启用接口。开发分支已实现自动模式迁移与中断恢复、`DocumentTitleSpec = "6"`、标题斜杠读写及旧字符串接口的整本拒绝;前端通过只读运行时能力决定标题输入规则。普通构建默认采用模式 `2`,无需额外编译参数。`minimumReaderVersion` 仅报告经验证的兼容版本,留空不阻止新模式启用。真实保护版本、混合版本、性能及各端验收仍是发布前需要补齐的证据,不能由默认启用推断已经完成。行级标题扩展约束保持不变。
## 目标与范围
@@ -333,7 +333,7 @@
### 能力探测与自动迁移
-在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`modeState`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`modeState` 为 `legacy`、`structured`、`conflict` 或 `recovering`;`structuredPaths` 表示服务端实现了新协议,`indexState` 表示派生索引状态,均不代替模式状态。管理员响应包含该对象,其他角色保持原有配置过滤。保护版本尚未验证时 `minimumReaderVersion` 为 `null`;确认真实最低版本后才返回版本字符串。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2`、`modeState: "structured"` 且索引就绪时为 `true`。
+在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`modeState`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`modeState` 为 `legacy`、`structured`、`conflict` 或 `recovering`;`structuredPaths` 表示服务端实现了新协议,`indexState` 表示派生索引状态,均不代替模式状态。管理员响应包含该对象,其他角色保持原有配置过滤。保护版本尚未验证时 `minimumReaderVersion` 为 `null`;确认真实最低版本后才返回版本字符串,该字段不控制功能是否启用。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2`、`modeState: "structured"` 且索引就绪时为 `true`。
`revision` 是模式记录及恢复状态的版本摘要,不等同于某篇文档的路径版本,也不用于用户启用流程。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。
@@ -374,7 +374,7 @@
笔记本配置保存内部兼容标记 `documentAddressingVersion`:字段缺省或 `1` 表示兼容记录,`2` 表示结构化标题记录;有效模式还须结合后文的能力下界与恢复记录,不能只读取这个字段。该标记不是用户配置项,与加密信封版本独立,不能复用 `BoxCrypt.Spec`。功能版本自动迁移记录,不批量改写已有文档标题或 ID。
-即使 `.sy` 仍保存字符串标题,旧客户端也可能移除 `/`,或把标题文字当作层级。发布分两步:先发布理解笔记本能力及恢复标记、能够安全拒绝未知模式的保护版本,再发布默认采用模式 `2` 的功能版本。保护版本在挂载、索引、修复、编辑及同步应用入口拒绝处理不支持的模式,不能先修改数据再提示升级。
+即使 `.sy` 仍保存字符串标题,旧客户端也可能移除 `/`,或把标题文字当作层级。对外发布的兼容要求分两步:先发布理解笔记本能力及恢复标记、能够安全拒绝未知模式的保护版本,再发布默认采用模式 `2` 的功能版本。开发分支普通构建已默认采用模式 `2`,这一默认值不依赖最低版本元数据。保护版本在挂载、索引、修复、编辑及同步应用入口拒绝处理不支持的模式,不能先修改数据再提示升级。
真正使用新标题能力的文档采用 `DocumentTitleSpec = "6"`:标题包含 ASCII `/` 时,正常写入将文档 `Spec` 至少提升到 `6`。普通标题仍按正文所需规格保存,不能因升级客户端、迁移模式或普通格式化而全部提升到 `6`,也不降低已有版本。未来富文本表示还需对应的明确格式版本,未知内容不得被容错解析后覆盖。
@@ -386,7 +386,7 @@
原始文件接口中的笔记本及文档 ID 路径同样受源格式检查保护,不能通过上传、复制或移入文件绕过。整批预检在创建目标目录及首次复制前完成,实际文档复制使用已经校验的读取字节,并在文件锁内重新检查目标源;检查后的并发变化或 I/O 失败仍可能留下已完成的复制,不承诺整批回滚。普通附件和插件目录下的 `.sy` 文件保持原始文件语义,加密笔记本仍禁止通过原始文件接口读写。
-最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。使用功能版本前要求所有同步设备至少升级到保护版本;系统无法证明离线设备状态,发布说明及用户指南须说明这一限制。如果保护仍存在缺口,继续保留发布门槛,不能以文档提示或用户开关代替必要保护。
+最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。使用功能版本前要求所有同步设备至少升级到保护版本;系统无法证明离线设备状态,发布说明及用户指南须说明这一限制。如果保护仍存在缺口,不能宣称已达到对外发布或安全混用条件,也不能以文档提示或用户开关代替必要保护。
自动迁移到模式 `2` 后不提供改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复升级前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。
@@ -404,7 +404,7 @@
自动迁移先在 `conf/document-addressing-recovery/<notebookID>.json` 持久化 `{version: 1, notebook, phase: "records"}`,再依次写入本机下界、笔记本下界及配置中的模式标记,最后删除该恢复记录。任一步骤中断后,下次访问继续同一迁移,不撤回已写入的模式要求;保护版本也必须将有效恢复记录视为至少需要模式 `2`。配置的未知字段及加密载荷原值保留,不扫描或批量重写 `.sy` 文件,原始文件接口不能覆盖该恢复目录。
-功能版本在已有模式记录缺失或配置落后时自动补齐,已删除的笔记本不能因恢复而重建。模式迁移与索引重建分开:元数据迁移不依赖就绪索引,也不认证或改写文档密文;后续源读取和索引构建仍必须在原授权及加密租约内先认证源内容。只有模式记录一致且索引就绪时才对外报告 `modeState: "structured"`。
+普通构建在已有模式记录缺失或配置落后时自动补齐,已删除的笔记本不能因恢复而重建。已有笔记本的配置文件缺失时,仅保留已确认模式,不生成替代配置;加密备份恢复仍须认证原密钥及载荷,不能保存为普通笔记本。配置恢复前能力状态保持 `recovering`。模式迁移与索引重建分开:元数据迁移不依赖就绪索引,也不认证或改写文档密文;后续源读取和索引构建仍必须在原授权及加密租约内先认证源内容。只有模式记录一致且索引就绪时才对外报告 `modeState: "structured"`。
模式记录恢复失败时保留恢复记录并报错;索引缺失或重建未完成时报告 `recovering`,结构化写入等待所需索引就绪。源格式未知、文件损坏或认证失败时保留原文件、密钥及待恢复任务,停止受影响操作并报告错误。再次访问或重新启动按既有恢复机制继续,不要求用户选择模式,也不能降级、重建笔记本或跳过格式校验来消除错误。
@@ -439,10 +439,10 @@
| A:兼容保护 | 笔记本能力下界及冲突识别、未知模式及源版本保护、旧行为回归样本 | 已发布保护版本;同步及快照应用前验证模式,所有写入与修复入口安全拒绝未知模式 |
| B:内部解耦 | 统一标题读取、文档元数据、ID 层级计算、路径刷新及恢复 | 普通标题行为不变;结构不再从显示字符串推导,加密索引可认证重建 |
| C:接口与调用方 | 新读取、解析、条件创建接口,版本 `2` 模板及加密载荷,内置业务及各端迁移 | 名称与配置并发条件、新旧契约通过验证,部分失败及撤销可恢复,日记等业务行为保持 |
-| D:开放新字符 | 默认采用新模式及自动恢复、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 完整子树预检、模式恢复和全部发布条件通过后,功能版本默认支持 `/` |
+| D:开放新字符 | 默认采用新模式及自动恢复、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 普通构建默认支持 `/`;完整子树预检、模式恢复及全部发布条件通过后才完成对外发布验收 |
| E:行级标题 | 独立的源格式、编辑及渲染设计 | 保持本方案身份接口,完成格式及旧写入保护后另行交付 |
-阶段 B、C 可以在保留旧标题限制时先行交付;新字符的开放必须等待 A 至 D 所需条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。
+阶段 B、C 可以在保留旧标题限制时先行交付;开发分支已默认开放新字符,对外发布验收仍要求 A 至 D 的相关条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。
开放条件包括:所有内置消费者已迁移;替代接口和插件适配文档已发布;已验证最低客户端版本及混合版本拒绝;普通与加密索引迁移可中断恢复;导入导出不会因显示路径冲突覆盖文件;桌面、浏览器和移动端行为一致;四种语言的用户指南说明默认行为、插件影响和同步设备要求。
@@ -496,7 +496,7 @@
行为测试进入现有前端及内核测试发现范围;新 Go 契约用例名称保留 `Contract`。实施 API 改动后,在 `app/` 执行 `pnpm run api:generate --petal ../../petal`、`pnpm run api:check --petal ../../petal`、`pnpm run lint` 及相关前端测试;在 `kernel/` 执行 `go test ./apicontract/...` 和覆盖受影响 API、模型、文件系统、块树及 SQL 的回归测试。发布前由现有完整测试入口覆盖 `pnpm test` 与 `go test -tags "fts5 sqlcipher" ./... -count=1`。
-发布门槛尚未打开时,持续集成另以 `go test -tags "fts5 sqlcipher" -ldflags "-X github.com/siyuan-note/siyuan/kernel/documentaddressing.minimumReaderVersion=0.0.0-test" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1` 覆盖自动迁移、新模式读写及真实 HTTP 契约。该值仅用于隔离测试,不是实际最低版本;默认构建继续验证保护行为。以上完整验收要求不等于已全部执行,文档修改另检查双语一致性、示例、链接及差异格式。
+持续集成直接以普通构建运行 `go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1`,覆盖自动迁移、新模式读写及真实 HTTP 契约,不再注入测试版本号。旧读取器的模式拒绝由显式兼容测试夹具覆盖,未知未来模式与源格式的拒绝继续在默认构建中验证。以上完整验收要求不等于已全部执行,文档修改另检查双语一致性、示例、链接及差异格式。
## 相关代码
diff --git a/kernel/api/contract_document_addressing_archive_test.go b/kernel/api/contract_document_addressing_archive_test.go
index deb3ab7dbe..11427330a1 100644
--- a/kernel/api/contract_document_addressing_archive_test.go
+++ b/kernel/api/contract_document_addressing_archive_test.go
@@ -42,7 +42,7 @@ func TestAPIContractDocumentAddressingArchives(t *testing.T) {
name := addressingAPIBox + "/" + document
for _, entries := range [][][2]string{
{{"first.txt", "first"}, {name, future}},
- {{"first.txt", "first"}, {addressingAPIBox + "/.siyuan/conf.json", `{"documentAddressingVersion":2}`}},
+ {{"first.txt", "first"}, {addressingAPIBox + "/.siyuan/conf.json", `{"documentAddressingVersion":3}`}},
{{"first.txt", "first"}, {name, future}, {name, ordinary}},
} {
write(entries)
diff --git a/kernel/api/contract_document_addressing_test.go b/kernel/api/contract_document_addressing_test.go
index 473f00e129..72c14f873a 100644
--- a/kernel/api/contract_document_addressing_test.go
+++ b/kernel/api/contract_document_addressing_test.go
@@ -97,7 +97,7 @@ func addressingAPIPut(t *testing.T, name, value string, directory bool) int {
func TestAPIContractDocumentAddressingRawWrites(t *testing.T) {
addressingAPIWorkspace(t)
confPath := filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json")
- addressingAPIWrite(t, confPath, `{"documentAddressingVersion":2}`)
+ addressingAPIWrite(t, confPath, `{"documentAddressingVersion":3}`)
name := "data/" + addressingAPIBox + "/original.sy"
abs := filepath.Join(util.WorkspaceDir, name)
addressingAPIWrite(t, abs, "future source")
@@ -160,7 +160,7 @@ func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
plain := filepath.Join(source, "first.txt")
future := filepath.Join(source, addressingAPIBox)
addressingAPIWrite(t, plain, "first")
- addressingAPIWrite(t, filepath.Join(future, ".siyuan", "conf.json"), `{"documentAddressingVersion":2}`)
+ addressingAPIWrite(t, filepath.Join(future, ".siyuan", "conf.json"), `{"documentAddressingVersion":3}`)
addressingAPIWrite(t, filepath.Join(future, "document.sy"), "future source")
if code := addressingAPIRequest(t, "globalCopyFiles", globalCopyFiles,
apicontract.CopyFilesRequest{Srcs: []string{plain, future}, DestDir: "data"}); code != -1 {
@@ -170,7 +170,7 @@ func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
if len(entries) != 0 {
t.Fatalf("batch wrote files before checking all notebooks: %v", entries)
}
- if code := addressingAPIPut(t, "data/20261022120000-rawbox2/.siyuan/conf.json", `{"documentAddressingVersion":2}`, false); code != -1 {
+ if code := addressingAPIPut(t, "data/20261022120000-rawbox2/.siyuan/conf.json", `{"documentAddressingVersion":3}`, false); code != -1 {
t.Fatalf("incoming mode accepted: %d", code)
}
entries, _ = os.ReadDir(util.DataDir)
@@ -314,7 +314,7 @@ func TestAPIContractDocumentAddressingDocumentCopies(t *testing.T) {
func TestAPIContractDocumentAddressingSettingsBackup(t *testing.T) {
addressingAPIWorkspace(t)
- addressingAPIWrite(t, filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json"), `{"documentAddressingVersion":2}`)
+ addressingAPIWrite(t, filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json"), `{"documentAddressingVersion":3}`)
_ = documentaddressing.CheckBox(util.DataDir, util.ConfDir, addressingAPIBox)
recorder := systemContractRequest(t, "POST", "exportConf", exportConf, nil)
var response struct {
diff --git a/kernel/api/contract_document_capabilities_test.go b/kernel/api/contract_document_capabilities_test.go
index 27f35e101f..b2f83e2086 100644
--- a/kernel/api/contract_document_capabilities_test.go
+++ b/kernel/api/contract_document_capabilities_test.go
@@ -41,22 +41,22 @@ func TestAPIContractDocumentCapabilities(t *testing.T) {
if bytes.Contains(public, []byte(`"documentCapabilities"`)) {
t.Fatal("configuration permissions were widened by capability discovery")
}
- if !capabilities.StructuredPaths || capabilities.LiteralSlash || capabilities.AddressingVersion != 1 ||
- capabilities.ModeState != "legacy" || capabilities.IndexState != "missing" || capabilities.MinimumReaderVersion != nil ||
+ if !capabilities.StructuredPaths || capabilities.LiteralSlash || capabilities.AddressingVersion != 2 ||
+ capabilities.ModeState != "recovering" || capabilities.IndexState != "missing" || capabilities.MinimumReaderVersion != nil ||
len(capabilities.TitleFormats) != 1 || capabilities.TitleFormats[0] != "plain" || capabilities.Revision == "" {
t.Fatalf("capabilities claimed an unimplemented or unverified feature: %+v", capabilities)
}
if err := treenode.SetDocumentMetadataState(boxID, "ready"); err != nil {
t.Fatal(err)
}
- if current := read(); current.IndexState != "ready" || current.LiteralSlash || current.Revision != capabilities.Revision {
- t.Fatalf("index readiness enabled new characters or changed the configuration revision: %+v", current)
+ if current := read(); current.IndexState != "ready" || !current.LiteralSlash || current.ModeState != "structured" || current.Revision != capabilities.Revision {
+ t.Fatalf("ready metadata did not enable structured titles or changed the configuration revision: %+v", current)
}
name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)
- if err := os.WriteFile(name, []byte(`{"version":1,"notebook":"`+boxID+`","minimumMode":2}`), 0600); err != nil {
+ if err := os.WriteFile(name, []byte(`{"version":1,"notebook":"`+boxID+`","minimumMode":3}`), 0600); err != nil {
t.Fatal(err)
}
- if current := read(); current.AddressingVersion != 2 || current.ModeState != "conflict" || current.LiteralSlash || current.Revision == capabilities.Revision {
+ if current := read(); current.AddressingVersion != 3 || current.ModeState != "conflict" || current.LiteralSlash || current.Revision == capabilities.Revision {
t.Fatalf("unsupported mode was reported as writable: %+v", current)
}
if err := os.WriteFile(name, []byte(`{"version":99}`), 0600); err != nil {
diff --git a/kernel/api/contract_document_target_test.go b/kernel/api/contract_document_target_test.go
index a5c80ceb89..589b56bfd8 100644
--- a/kernel/api/contract_document_target_test.go
+++ b/kernel/api/contract_document_target_test.go
@@ -2,6 +2,7 @@ package api
import (
"bytes"
+ "reflect"
"testing"
"github.com/gin-gonic/gin"
@@ -48,7 +49,7 @@ func TestAPIContractDocumentTargetPatchAndLegacyReads(t *testing.T) {
box.GetConf().DocCreateTarget != nil || box.GetConf().RefCreateTarget == nil {
t.Fatalf("explicit target removal did not stay scoped: %s", response)
}
- if response := patch(map[string]interface{}{"docCreateTarget": target}); !bytes.Contains(response, []byte(`"code":-1`)) {
- t.Fatalf("compatibility mode enabled a structured target: %s", response)
+ if response := patch(map[string]interface{}{"docCreateTarget": target}); !bytes.Contains(response, []byte(`"code":0`)) || !reflect.DeepEqual(box.GetConf().DocCreateTarget, target) {
+ t.Fatalf("default mode did not persist the structured target: %s", response)
}
}
diff --git a/kernel/api/contract_import_footnotes_test.go b/kernel/api/contract_import_footnotes_test.go
index b212efb998..1da157069f 100644
--- a/kernel/api/contract_import_footnotes_test.go
+++ b/kernel/api/contract_import_footnotes_test.go
@@ -16,11 +16,13 @@ import (
"github.com/88250/lute/ast"
"github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/internal/testutil"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -96,9 +98,9 @@ func TestAPIContractMarkdownFootnotes(t *testing.T) {
}
engine := gin.New()
engine.Use(boxLeaseMiddleware)
- engine.POST("/api/filetree/createDocWithMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocWithMd)
+ engine.POST("/api/filetree/createDocByParent", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createDocByParent)
engine.POST("/api/import/importStdMd", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importStdMd)
- post := func(route string, payload map[string]string, success bool) json.RawMessage {
+ post := func(route string, payload any, success bool) json.RawMessage {
t.Helper()
body, _ := json.Marshal(payload)
request := httptest.NewRequest(http.MethodPost, route, bytes.NewReader(body))
@@ -133,10 +135,20 @@ func TestAPIContractMarkdownFootnotes(t *testing.T) {
if _, err = model.Mount(boxID); err != nil {
t.Fatal(err)
}
- create := map[string]string{"notebook": boxID, "path": "/API footnotes", "markdown": markdown}
- var id string
- if err = json.Unmarshal(post("/api/filetree/createDocWithMd", create, true), &id); err != nil || id == "" {
- t.Fatalf("invalid document ID: %q, %v", id, err)
+ // 独立进程未启动后台任务,先执行挂载触发的真实索引再调用结构化创建接口。
+ deadline := time.Now().Add(20 * time.Second)
+ for treenode.DocumentMetadataState(boxID) != "ready" {
+ if state := treenode.DocumentMetadataState(boxID); state == "error" || time.Now().After(deadline) {
+ t.Fatal("notebook index did not become ready", state)
+ }
+ task.ExecTaskJob()
+ time.Sleep(time.Millisecond)
+ }
+ create := apicontract.CreateDocByParentRequest{Notebook: boxID, ID: ast.NewNodeID(),
+ Title: apicontract.DocumentCreateTitle{Format: "plain", Text: "API footnotes"}, Markdown: markdown}
+ var created apicontract.CreatedDocumentData
+ if err = json.Unmarshal(post("/api/filetree/createDocByParent", create, true), &created); err != nil || created.ID != create.ID {
+ t.Fatalf("invalid created document: %+v, %v", created, err)
}
importRequest := map[string]string{"notebook": boxID, "localPath": source, "toPath": "/"}
if data := post("/api/import/importStdMd", importRequest, true); string(data) != "null" {
@@ -190,7 +202,7 @@ func TestAPIContractMarkdownFootnotes(t *testing.T) {
}
if encrypted {
model.LockBox(boxID)
- post("/api/filetree/createDocWithMd", create, false)
+ post("/api/filetree/createDocByParent", create, false)
post("/api/import/importStdMd", importRequest, false)
}
}
diff --git a/kernel/api/contract_structured_titles_test.go b/kernel/api/contract_structured_titles_test.go
index 031ca631cf..4e41db6008 100644
--- a/kernel/api/contract_structured_titles_test.go
+++ b/kernel/api/contract_structured_titles_test.go
@@ -7,16 +7,12 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/treenode"
)
func TestStructuredTitlesAPIContracts(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
box := documentPathAPIWorkspace(t)
if err := filesys.CheckDocumentAddressing(box); err != nil {
t.Fatal(err)
@@ -52,7 +48,7 @@ func TestStructuredTitlesAPIContracts(t *testing.T) {
if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {
t.Fatal(err)
}
- if current := read(); current.ModeState != "structured" || !current.LiteralSlash || current.MinimumReaderVersion == nil {
+ if current := read(); current.ModeState != "structured" || !current.LiteralSlash || current.MinimumReaderVersion != nil {
t.Fatal("automatic mode was not available", current)
}
}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 402e559819..05804dec3d 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -134,9 +134,10 @@ var (
OpenNotebook = define[OpenNotebookRequest, Null]("openNotebook", "/api/notebook/openNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// GetNotebookConf preserves existing configuration and permission filtering. Administrator
// responses also contain documentCapabilities: structuredPaths advertises the ID/segment APIs,
- // not permission to open a closed or locked notebook. The feature release migrates to mode 2
- // automatically without a user setting. literalSlash requires consistent mode records and ready
- // indexes; minimumReaderVersion remains null while protective-release verification is pending.
+ // not permission to open a closed or locked notebook. Ordinary builds migrate to mode 2
+ // automatically without a user setting or special build flags. literalSlash requires consistent
+ // mode records and ready indexes. minimumReaderVersion remains null while protective-release
+ // verification is pending; this informational field does not control feature activation.
// Revision covers configuration, confirmed capability and recovery records, not a document path.
// Malformed capability records fail the request; authentication, locking and network failures must
// never be interpreted as an absent capability object or as permission to retry a legacy write.
diff --git a/kernel/apicontract/system.go b/kernel/apicontract/system.go
index e17b65d898..f2c381216c 100644
--- a/kernel/apicontract/system.go
+++ b/kernel/apicontract/system.go
@@ -53,7 +53,7 @@ type SystemMessageData struct {
Msg string `json:"msg"`
}
type SystemConfData struct {
- // DocumentAddressingVersion 是当前内核的只读能力,不是持久化配置或可写开关。
+ // DocumentAddressingVersion 是当前内核的只读能力,普通构建默认为 2,不是持久化配置或可写开关。
DocumentAddressingVersion int `json:"documentAddressingVersion"`
Conf *SystemAppConf `json:"conf"`
Start bool `json:"start"`
diff --git a/kernel/cli/cmd/document_test.go b/kernel/cli/cmd/document_test.go
index fcc580d55a..e9358da6bf 100644
--- a/kernel/cli/cmd/document_test.go
+++ b/kernel/cli/cmd/document_test.go
@@ -11,9 +11,6 @@ import (
)
func TestStructuredTitlesCLI(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
previousData, previousConf := util.DataDir, util.ConfDir
root := t.TempDir()
util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")
diff --git a/kernel/documentaddressing/capabilities_test.go b/kernel/documentaddressing/capabilities_test.go
index 8d3b52ffd2..d27206d03d 100644
--- a/kernel/documentaddressing/capabilities_test.go
+++ b/kernel/documentaddressing/capabilities_test.go
@@ -8,6 +8,7 @@ import (
)
func TestInspectBoxCapabilities(t *testing.T) {
+ readerModeForTest(t, 1)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
first, err := InspectBox(dataDir, confDir, testBox)
diff --git a/kernel/documentaddressing/migration.go b/kernel/documentaddressing/migration.go
index 7274d49f32..343716e07a 100644
--- a/kernel/documentaddressing/migration.go
+++ b/kernel/documentaddressing/migration.go
@@ -14,10 +14,11 @@ import (
"github.com/siyuan-note/filelock"
)
-// 保护版本验证并发布后填写。它是发布门槛,不是用户配置或笔记本开关。
-// 隔离测试使用链接参数提供测试版本,不修改产品二进制。
+// 最低读取版本只报告经过验证的兼容性信息,不控制标题功能是否启用。
var minimumReaderVersion string
+var defaultMode = 2
+
var ErrRecovering = errors.New("document addressing recovery is pending")
func MinimumReaderVersion() *string {
@@ -30,10 +31,7 @@ func MinimumReaderVersion() *string {
// DefaultMode 是当前发行版自动采用的内部模式,不暴露为用户可写配置。
func DefaultMode() int {
- if minimumReaderVersion != "" {
- return 2
- }
- return 1
+ return defaultMode
}
// migrationRecord 仅保存身份及阶段;源文件和认证密钥从不进入迁移记录。
diff --git a/kernel/documentaddressing/migration_test.go b/kernel/documentaddressing/migration_test.go
index 9586a14d40..3ea137eeaf 100644
--- a/kernel/documentaddressing/migration_test.go
+++ b/kernel/documentaddressing/migration_test.go
@@ -12,15 +12,26 @@ import (
"github.com/siyuan-note/filelock"
)
-func structuredReleaseForTest(t *testing.T) {
+func readerModeForTest(t *testing.T, mode int) {
t.Helper()
+ previous := defaultMode
+ defaultMode = mode
+ t.Cleanup(func() { defaultMode = previous })
+}
+
+func TestStructuredTitlesDefaultWithoutReaderRelease(t *testing.T) {
+ if DefaultMode() != 2 {
+ t.Fatal("ordinary builds must enable structured titles")
+ }
previous := minimumReaderVersion
- minimumReaderVersion = "0.0.0-test"
+ minimumReaderVersion = ""
t.Cleanup(func() { minimumReaderVersion = previous })
+ if DefaultMode() != 2 || MinimumReaderVersion() != nil {
+ t.Fatal("unverified reader release disabled titles or reported a fabricated version")
+ }
}
func TestStructuredTitlesAutomaticMigration(t *testing.T) {
- structuredReleaseForTest(t)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
boxDir := filepath.Join(dataDir, testBox)
@@ -71,7 +82,7 @@ func TestStructuredTitlesAutomaticMigration(t *testing.T) {
}
func TestStructuredTitlesMigrationInterruption(t *testing.T) {
- structuredReleaseForTest(t)
+ readerModeForTest(t, 2)
for stage := 1; stage <= 4; stage++ {
t.Run(fmt.Sprint(stage), func(t *testing.T) {
root := t.TempDir()
@@ -97,11 +108,11 @@ func TestStructuredTitlesMigrationInterruption(t *testing.T) {
t.Fatal("fault was not reached", err)
}
// 下界尚未写入时,保护读取器也必须识别迁移决定并拒绝访问。
- minimumReaderVersion = ""
+ defaultMode = 1
if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
t.Fatal(err)
}
- minimumReaderVersion = "0.0.0-test"
+ defaultMode = 2
if err = CheckBox(dataDir, confDir, testBox); err != nil {
t.Fatal(err)
}
@@ -114,7 +125,6 @@ func TestStructuredTitlesMigrationInterruption(t *testing.T) {
}
func TestStructuredTitlesMigrationRejectsUnknownAndDeleted(t *testing.T) {
- structuredReleaseForTest(t)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
boxDir := filepath.Join(dataDir, testBox)
@@ -136,3 +146,45 @@ func TestStructuredTitlesMigrationRejectsUnknownAndDeleted(t *testing.T) {
t.Fatal(err)
}
}
+
+func TestStructuredTitlesMissingConfigurationRetainsFloor(t *testing.T) {
+ readerModeForTest(t, 2)
+ root := t.TempDir()
+ dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
+ boxDir := filepath.Join(dataDir, testBox)
+ writeTestFile(t, boxDir, ConfigPath, `{}`)
+ if err := CheckBox(dataDir, confDir, testBox); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(filepath.Join(boxDir, ConfigPath)); err != nil {
+ t.Fatal(err)
+ }
+ floor, _ := os.ReadFile(filepath.Join(boxDir, FloorPath))
+ if mode, err := BoxMode(dataDir, confDir, testBox); err != nil || mode != 2 {
+ t.Fatal("missing configuration blocked recovery or lowered the floor", mode, err)
+ }
+ if _, err := os.Stat(filepath.Join(boxDir, ConfigPath)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("mode inspection created a replacement configuration", err)
+ }
+ if after, err := os.ReadFile(filepath.Join(boxDir, FloorPath)); err != nil || !bytes.Equal(after, floor) {
+ t.Fatal("mode inspection changed the source floor", err)
+ }
+ snapshot, err := InspectBox(dataDir, confDir, testBox)
+ if err != nil || snapshot.State != "recovering" || snapshot.RecordsConsistent {
+ t.Fatal("missing configuration was reported as ready", snapshot, err)
+ }
+ defaultMode = 1
+ if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
+ t.Fatal("missing configuration bypassed the old reader guard", err)
+ }
+ defaultMode = 2
+ if err = os.RemoveAll(boxDir); err != nil {
+ t.Fatal(err)
+ }
+ if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("deleted notebook was accepted for recovery", err)
+ }
+ if _, err = os.Stat(boxDir); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("mode inspection recreated a deleted notebook", err)
+ }
+}
diff --git a/kernel/documentaddressing/mode.go b/kernel/documentaddressing/mode.go
index f9d58868b3..8745f956e9 100644
--- a/kernel/documentaddressing/mode.go
+++ b/kernel/documentaddressing/mode.go
@@ -126,10 +126,21 @@ func BoxMode(dataDir, confDir, boxID string) (int, error) {
return 0, err
}
if DefaultMode() == 2 && (snapshot.Mode == 1 || snapshot.State == "recovering") {
- // 新笔记本尚未创建配置时不生成目录;恢复旧身份时也不能重建已删除的笔记本。
+ // 配置缺失时不自动创建配置,保留已确认模式供加密备份认证及配置恢复使用。
+ // 不能降低下界,也不能借本机记录重新创建已删除的笔记本。
_, statErr := os.Stat(filepath.Join(dataDir, boxID, ConfigPath))
- if errors.Is(statErr, os.ErrNotExist) && snapshot.Mode == 1 {
- return 1, nil
+ if errors.Is(statErr, os.ErrNotExist) {
+ if snapshot.Mode == 1 {
+ return 1, nil
+ }
+ info, dirErr := os.Lstat(filepath.Join(dataDir, boxID))
+ if dirErr != nil {
+ return 0, dirErr
+ }
+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
+ return 0, ErrInvalid
+ }
+ return snapshot.Mode, nil
}
if statErr != nil {
return 0, statErr
diff --git a/kernel/documentaddressing/mode_test.go b/kernel/documentaddressing/mode_test.go
index d5dac7eb8e..f9bfbfbe62 100644
--- a/kernel/documentaddressing/mode_test.go
+++ b/kernel/documentaddressing/mode_test.go
@@ -77,6 +77,7 @@ func TestReadMode(t *testing.T) {
}
func TestCheckBoxPreservesSourcesAndNeverLowersFloor(t *testing.T) {
+ readerModeForTest(t, 1)
for _, marker := range []string{"config", "floor"} {
t.Run(marker, func(t *testing.T) {
root := t.TempDir()
@@ -121,7 +122,8 @@ func TestCheckBoxPreservesSourcesAndNeverLowersFloor(t *testing.T) {
}
}
-func TestCheckBoxDoesNotMigrateLegacyData(t *testing.T) {
+func TestLegacyReaderDoesNotMigrateData(t *testing.T) {
+ readerModeForTest(t, 1)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
writeTestFile(t, dataDir, testBox+"/"+ConfigPath, `{"name":"legacy"}`)
@@ -159,6 +161,7 @@ func TestCheckBoxPreservesInvalidLocalFloor(t *testing.T) {
}
func TestCheckBatchUsesIncomingModeAndRetainsObservedFloor(t *testing.T) {
+ readerModeForTest(t, 1)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
config := testBox + "/" + ConfigPath
@@ -182,6 +185,7 @@ func TestCheckBatchUsesIncomingModeAndRetainsObservedFloor(t *testing.T) {
}
func TestCheckBatchAllowsOnlyWholeNotebookDeletion(t *testing.T) {
+ readerModeForTest(t, 1)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
config, doc := testBox+"/"+ConfigPath, testBox+"/document.sy"
@@ -210,6 +214,7 @@ func TestCheckBatchAllowsOnlyWholeNotebookDeletion(t *testing.T) {
}
func TestCheckBatchCannotEraseAnUnobservedFloor(t *testing.T) {
+ readerModeForTest(t, 1)
root := t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
config, floor := testBox+"/"+ConfigPath, testBox+"/"+FloorPath
@@ -233,6 +238,7 @@ func TestReadModePreservesIOErrors(t *testing.T) {
}
func TestCheckImportUsesConfirmedSourceFloorWithoutAdoptingNewIdentities(t *testing.T) {
+ readerModeForTest(t, 1)
root, source := t.TempDir(), t.TempDir()
dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
writeTestFile(t, source, ConfigPath, `{"documentAddressingVersion":2}`)
diff --git a/kernel/filesys/document_addressing_test.go b/kernel/filesys/document_addressing_test.go
index 0946f493c4..61076ab9cb 100644
--- a/kernel/filesys/document_addressing_test.go
+++ b/kernel/filesys/document_addressing_test.go
@@ -182,7 +182,7 @@ func TestDocumentAddressingPreservesPlainAndEncryptedSources(t *testing.T) {
t.Fatal(err)
}
absPath := writeStalePathFixture(t, boxID, document, source)
- writeStalePathFixture(t, boxID, documentaddressing.ConfigPath, []byte(`{"documentAddressingVersion":2}`))
+ writeStalePathFixture(t, boxID, documentaddressing.ConfigPath, []byte(`{"documentAddressingVersion":3}`))
readers := map[string]func() error{
"properties": func() error { _, err := DocIAL(absPath); return err },
"parent properties": func() error { _, err := readParentDocIAL(absPath); return err },
diff --git a/kernel/filesys/structured_titles_test.go b/kernel/filesys/structured_titles_test.go
index 1ba039b02f..d80d870630 100644
--- a/kernel/filesys/structured_titles_test.go
+++ b/kernel/filesys/structured_titles_test.go
@@ -13,9 +13,6 @@ import (
)
func TestStructuredTitlesSourceReaders(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
for _, encrypted := range []bool{false, true} {
t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
box, id, _, _ := setupStalePathTest(t)
diff --git a/kernel/filesys/tree_compare_write.go b/kernel/filesys/tree_compare_write.go
index c56b66a5e8..21c279df1a 100644
--- a/kernel/filesys/tree_compare_write.go
+++ b/kernel/filesys/tree_compare_write.go
@@ -20,6 +20,9 @@ import (
func WriteTreeIfUnchanged(tree *parse.Tree, original []byte) (size uint64, err error) {
unlock := lockDocumentSource()
defer unlock()
+ if err = validateTreePath(tree.Box, tree.Path); err != nil {
+ return 0, err
+ }
dek, _, release, err := acquireCryptoLease(tree.Box)
if err != nil {
return 0, err
diff --git a/kernel/filesys/tree_path_test.go b/kernel/filesys/tree_path_test.go
index 43ee823276..fd3b620e8b 100644
--- a/kernel/filesys/tree_path_test.go
+++ b/kernel/filesys/tree_path_test.go
@@ -34,6 +34,10 @@ func TestTreeIOPreservesNonDocumentFiles(t *testing.T) {
_, err := LoadTreeByData(original, box, p, luteEngine)
return err
},
+ "snapshot": func() error {
+ _, _, err := LoadTreeSnapshot(box, p, luteEngine)
+ return err
+ },
"cached load": func() error {
id := util.GetTreeID(p)
cache.SetTreeDataInBox(id, box, original)
diff --git a/kernel/model/attribute_view_relation_item_fts5_test.go b/kernel/model/attribute_view_relation_item_fts5_test.go
index 0f6e1b8bdb..132b25ecc4 100644
--- a/kernel/model/attribute_view_relation_item_fts5_test.go
+++ b/kernel/model/attribute_view_relation_item_fts5_test.go
@@ -97,7 +97,7 @@ func TestAttributeViewRelationItemCreation(t *testing.T) {
{"document", "Task document", "Task A", "Task document", av.NewItemTargetDocument, false},
{"input name", "Task from template", " Task A ", "Task A", av.NewItemTargetDetached, true},
{"document input name", "Task document", "Task A", "Task A", av.NewItemTargetDocument, true},
- {"normalized document input", "Task document", "Task /A", "Task A", av.NewItemTargetDocument, true},
+ {"literal slash document input", "Task document", "Task /A", "Task /A", av.NewItemTargetDocument, true},
} {
t.Run(test.name, func(t *testing.T) {
var template *av.NewItemTemplate
@@ -128,7 +128,7 @@ func TestAttributeViewRelationItemCreation(t *testing.T) {
}
wantInput := strings.TrimSpace(test.keyword)
if test.target == av.NewItemTargetDocument {
- wantInput = normalizeDocTitle(wantInput)
+ wantInput = normalizeDocumentTitle(wantInput)
}
if preview.InputPrimaryKey != wantInput {
t.Fatalf("input preview: got %q, want %q", preview.InputPrimaryKey, wantInput)
diff --git a/kernel/model/box_conf_crypto_test.go b/kernel/model/box_conf_crypto_test.go
index 8a8fc3a813..117c25b581 100644
--- a/kernel/model/box_conf_crypto_test.go
+++ b/kernel/model/box_conf_crypto_test.go
@@ -200,6 +200,15 @@ func TestDocumentTargetEncryptedMetadataRecovery(t *testing.T) {
if err = os.Remove(confPath); err != nil {
t.Fatal(err)
}
+ if _, _, err = decryptBoxCrypt(boxID, bytes.Repeat([]byte{0xff}, 32)); err == nil {
+ t.Fatal("missing configuration bypassed key authentication")
+ }
+ if err = box.SaveConf(conf.NewBoxConf()); err == nil {
+ t.Fatal("missing configuration allowed a plaintext replacement")
+ }
+ if _, err = os.Stat(confPath); !os.IsNotExist(err) {
+ t.Fatal("failed recovery created a replacement configuration", err)
+ }
// 删除配置后只能从已认证的备份恢复相同 DEK 和目标载荷。
check()
}
diff --git a/kernel/model/document_addressing_crypto_test.go b/kernel/model/document_addressing_crypto_test.go
index c35ef600fb..810af643c8 100644
--- a/kernel/model/document_addressing_crypto_test.go
+++ b/kernel/model/document_addressing_crypto_test.go
@@ -50,7 +50,7 @@ func TestDocumentAddressingEncryptedRecoveryPreservesKeys(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- setDocumentAddressingTestMode(t, filepath.Join(util.DataDir, boxID), 2)
+ setDocumentAddressingTestMode(t, filepath.Join(util.DataDir, boxID), 3)
original, err := archiveDirectoryFiles(util.DataDir)
if err != nil {
t.Fatal(err)
@@ -110,7 +110,7 @@ func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- setDocumentAddressingTestMode(t, filepath.Join(futureDirectory, "payload", "data", boxID), 2)
+ setDocumentAddressingTestMode(t, filepath.Join(futureDirectory, "payload", "data", boxID), 3)
if err = writeNotebookArchive(futureDirectory, manifest); err != nil {
t.Fatal(err)
}
@@ -125,7 +125,7 @@ func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
notebookArchiveTestWorkspace(t)
if test.remembered {
- backup := []byte(`{"documentAddressing":{"version":1,"notebooks":{"` + boxID + `":2}}}`)
+ backup := []byte(`{"documentAddressing":{"version":1,"notebooks":{"` + boxID + `":3}}}`)
if err := documentaddressing.RestoreBackup(util.ConfDir, backup); err != nil {
t.Fatal(err)
}
diff --git a/kernel/model/document_addressing_file_test.go b/kernel/model/document_addressing_file_test.go
index e23411bbe9..507d999c90 100644
--- a/kernel/model/document_addressing_file_test.go
+++ b/kernel/model/document_addressing_file_test.go
@@ -27,7 +27,7 @@ func TestDocumentAddressingSortRecoveryPreservesPendingWrite(t *testing.T) {
if err = os.WriteFile(confPath, partial, 0600); err != nil {
t.Fatal(err)
}
- if err = os.WriteFile(filepath.Join(filepath.Dir(confPath), "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0600); err != nil {
+ if err = os.WriteFile(filepath.Join(filepath.Dir(confPath), "conf.json"), []byte(`{"documentAddressingVersion":3}`), 0600); err != nil {
t.Fatal(err)
}
for _, operation := range []func() error{
@@ -71,7 +71,7 @@ func documentAddressingRawPathAliases(t *testing.T, linkDirectory func(string, s
if err := os.MkdirAll(filepath.Join(box, ".siyuan"), 0755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(box, ".siyuan", "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0600); err != nil {
+ if err := os.WriteFile(filepath.Join(box, ".siyuan", "conf.json"), []byte(`{"documentAddressingVersion":3}`), 0600); err != nil {
t.Fatal(err)
}
alias := filepath.Join(root, "alias")
diff --git a/kernel/model/document_addressing_fts5_test.go b/kernel/model/document_addressing_fts5_test.go
index 17f6464eea..c205c9fedb 100644
--- a/kernel/model/document_addressing_fts5_test.go
+++ b/kernel/model/document_addressing_fts5_test.go
@@ -23,7 +23,7 @@ func TestDocumentAddressingWholeNotebookDeletionRetainsRecoveryData(t *testing.T
setupNotebookDocumentImportDatabase(t)
boxID := fixture.box.ID
source := []byte("unparsed future source")
- config := []byte(`{"name":"future","closed":true,"documentAddressingVersion":2}`)
+ config := []byte(`{"name":"future","closed":true,"documentAddressingVersion":3}`)
if err := os.WriteFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath), config, 0644); err != nil {
t.Fatal(err)
}
diff --git a/kernel/model/document_addressing_test.go b/kernel/model/document_addressing_test.go
index a85ed89241..0fa694a5af 100644
--- a/kernel/model/document_addressing_test.go
+++ b/kernel/model/document_addressing_test.go
@@ -31,7 +31,7 @@ func TestDocumentAddressingImportTitlePreflight(t *testing.T) {
name, document string
err error
}{
- {"title", `{"Spec":"2","Properties":{"title":"A/B"}}`, documentaddressing.ErrModeConflict},
+ {"title", `{"Spec":"2","Properties":{"title":{"text":"Future"}}}`, documentaddressing.ErrInvalidTitle},
{"version", `{"Spec":"999","Spec":"2","Properties":{"title":"Legacy"}}`, treenode.ErrSpecTooNew},
} {
t.Run(sourceError.name+map[bool]string{false: "/documents", true: "/notebook"}[whole], func(t *testing.T) {
@@ -71,6 +71,10 @@ func TestDocumentAddressingImportTitlePreflight(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ beforeConf, err := archiveDirectoryFiles(util.ConfDir)
+ if err != nil {
+ t.Fatal(err)
+ }
created, err := importSY0(archive, fixture.box.ID, "/", whole, false, nil, false)
if created != "" || !errors.Is(err, sourceError.err) {
t.Fatalf("source preflight ran after adoption: %q, %v", created, err)
@@ -83,7 +87,7 @@ func TestDocumentAddressingImportTitlePreflight(t *testing.T) {
if err != nil || !bytes.Equal(original, retained) {
t.Fatal("rejected import changed the archive")
}
- if entries, err := os.ReadDir(util.ConfDir); err != nil || len(entries) != 0 {
+ if afterConf, err := archiveDirectoryFiles(util.ConfDir); err != nil || !reflect.DeepEqual(beforeConf, afterConf) {
t.Fatal("inspection of an unadopted source changed capability records")
}
})
@@ -108,7 +112,7 @@ func TestDocumentAddressingBlocksCachedAccessAndConfigRepair(t *testing.T) {
t.Fatal(err)
}
cache.PutDocIALInBox(fixture.sourcePath, boxID, map[string]string{"title": "cached"})
- data := []byte(`{"name":"future","closed":false,"documentAddressingVersion":2}`)
+ data := []byte(`{"name":"future","closed":false,"documentAddressingVersion":3}`)
if err = os.WriteFile(configPath, data, 0644); err != nil {
t.Fatal(err)
}
@@ -152,7 +156,7 @@ func TestDocumentAddressingBlocksCachedAccessAndConfigRepair(t *testing.T) {
}
}
-func TestDocumentAddressingRejectsConfigActivationBeforeWrite(t *testing.T) {
+func TestDocumentAddressingRejectsFutureConfigBeforeWrite(t *testing.T) {
fixture := setupFileOperationTest(t)
previousConfDir := util.ConfDir
util.ConfDir = t.TempDir()
@@ -162,7 +166,7 @@ func TestDocumentAddressingRejectsConfigActivationBeforeWrite(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if err = fixture.box.saveConf0([]byte(`{"documentAddressingVersion":2}`)); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err = fixture.box.saveConf0([]byte(`{"documentAddressingVersion":3}`)); !errors.Is(err, documentaddressing.ErrUnsupported) {
t.Fatal(err)
}
after, err := os.ReadFile(name)
@@ -204,10 +208,10 @@ func TestDocumentAddressingSnapshotPreflight(t *testing.T) {
t.Fatal(err)
}
}
- config := `{"documentAddressingVersion":2}`
+ config := `{"documentAddressingVersion":3}`
if marker == "floor" {
config = `{}`
- write(documentaddressing.FloorPath, `{"version":1,"notebook":"`+boxID+`","minimumMode":2}`, 10)
+ write(documentaddressing.FloorPath, `{"version":1,"notebook":"`+boxID+`","minimumMode":3}`, 10)
}
write(documentaddressing.ConfigPath, config, 10)
write("existing.sy", "future source", 10)
@@ -288,7 +292,7 @@ func TestDocumentAddressingSyncPreflightSurvivesTaskCleanup(t *testing.T) {
if _, _, err = partial.Sync(nil); err != nil {
t.Fatal(err)
}
- write(documentaddressing.ConfigPath, `{"documentAddressingVersion":2}`, 20)
+ write(documentaddressing.ConfigPath, `{"documentAddressingVersion":3}`, 20)
write("existing.sy", "future", 20)
write("new.sy", "future addition", 20)
if err = os.Remove(filepath.Join(fullData, boxID, "keep.sy")); err != nil {
@@ -351,7 +355,7 @@ func TestDocumentAddressingImportChecksBeforeRemapping(t *testing.T) {
if err := os.MkdirAll(metadata, 0755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(metadata, "conf.json"), []byte(`{"name":"future","documentAddressingVersion":2}`), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(metadata, "conf.json"), []byte(`{"name":"future","documentAddressingVersion":3}`), 0644); err != nil {
t.Fatal(err)
}
meta, err := json.Marshal(boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: sourceBox})
@@ -453,7 +457,7 @@ func TestDocumentAddressingDataImportRejectsBeforeAnyWrite(t *testing.T) {
if err := os.MkdirAll(metaDir, 0755); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(filepath.Join(metaDir, "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(metaDir, "conf.json"), []byte(`{"documentAddressingVersion":3}`), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(install, "ordinary.txt"), []byte("other batch content"), 0644); err != nil {
@@ -474,7 +478,7 @@ func TestDocumentAddressingNotebookHistoryPreservesSource(t *testing.T) {
util.ConfDir = t.TempDir()
t.Cleanup(func() { util.ConfDir = oldConfDir })
name := filepath.Join(util.WorkspaceDir, historyPath, documentaddressing.ConfigPath)
- source := []byte(`{"name":"future","documentAddressingVersion":2}`)
+ source := []byte(`{"name":"future","documentAddressingVersion":3}`)
if err := os.WriteFile(name, source, 0644); err != nil {
t.Fatal(err)
}
@@ -494,7 +498,7 @@ func TestDocumentAddressingNativeExportPreservesFloor(t *testing.T) {
const boxID = "20260101120000-abcdefg"
setupExportRelatedTest(t, boxID)
name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)
- source := []byte(`{"version":1,"notebook":"` + boxID + `","minimumMode":1}`)
+ source := []byte(`{"version":1,"notebook":"` + boxID + `","minimumMode":2}`)
if err := os.WriteFile(name, source, 0644); err != nil {
t.Fatal(err)
}
diff --git a/kernel/model/document_create_test.go b/kernel/model/document_create_test.go
index 9a9deac514..38e37d1bb6 100644
--- a/kernel/model/document_create_test.go
+++ b/kernel/model/document_create_test.go
@@ -43,7 +43,7 @@ func TestDocumentCreateByParent(t *testing.T) {
if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {
t.Fatal(err)
}
- parentPath, err := treenode.GetDocumentPath(box.ID, parent.ID, box.ID, 1)
+ parentPath, err := getDocumentPath(box.ID, parent.ID)
if err != nil {
t.Fatal(err)
}
@@ -81,7 +81,7 @@ func TestDocumentCreateByParent(t *testing.T) {
if err != nil || !document.Title.Empty || document.Title.Text == "" {
t.Fatalf("empty title lost its explicit marker: %+v, %v", document, err)
}
- request.ID, request.Title = ast.NewNodeID(), "Invalid/title"
+ request.ID, request.Title = ast.NewNodeID(), "Invalid\ntitle"
failure(request, "invalidTitle")
request.TitleFormat = "markdown"
failure(request, "unsupportedTitleFormat")
diff --git a/kernel/model/duplicate_doc_hpath_test.go b/kernel/model/duplicate_doc_hpath_test.go
index df86abbe40..4bb11b0a60 100644
--- a/kernel/model/duplicate_doc_hpath_test.go
+++ b/kernel/model/duplicate_doc_hpath_test.go
@@ -88,20 +88,28 @@ func TestDuplicateDocHPath(t *testing.T) {
if err != nil || hpath != wantHPath {
t.Fatalf("path by ID disagrees: %q, %v", hpath, err)
}
- ids, err := GetIDsByHPath(wantHPath, boxID)
- if err != nil || len(ids) != 1 || ids[0] != source.ID {
- t.Fatalf("duplicate is not addressable: %v, %v", ids, err)
+ if err = treenode.SetDocumentMetadataState(boxID, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ segments := []string{title}
+ if nested {
+ segments = append([]string{"Parent"}, segments...)
+ }
+ resolved, err := ResolveDocPath(boxID, "root", nil, segments)
+ if err != nil || resolved.Status != "resolved" || resolved.Resolved == nil || resolved.Resolved.ID != source.ID {
+ t.Fatalf("duplicate is not addressable: %+v, %v", resolved, err)
}
sql.FlushQueue()
block := sql.GetBlockInBox(source.ID, boxID)
if block == nil || block.Content != title || block.HPath != wantHPath {
t.Fatalf("SQL title and path disagree: %#v", block)
}
- childID, err := CreateWithMarkdown("", boxID, wantHPath+"/Child", "Child content", "", "", false, "", nil)
+ created, err := CreateDocByParent(DocumentCreateRequest{Notebook: boxID, ParentID: &source.ID, ID: ast.NewNodeID(),
+ TitleFormat: "plain", Title: "Child", Markdown: "Child content"})
if err != nil {
t.Fatal(err)
}
- child := treenode.GetBlockTreeInBox(childID, boxID)
+ child := treenode.GetBlockTreeInBox(created.ID, boxID)
if child == nil || path.Dir(child.Path) != strings.TrimSuffix(source.Path, ".sy") {
t.Fatalf("child created under a different parent: %#v", child)
}
diff --git a/kernel/model/file_index_test.go b/kernel/model/file_index_test.go
index 914b2b8f36..fbab497a9c 100644
--- a/kernel/model/file_index_test.go
+++ b/kernel/model/file_index_test.go
@@ -316,22 +316,23 @@ func TestDocumentTemplatesWaitForDatabaseIndex(t *testing.T) {
}
docID := "20260728000001-abcdefg"
- arg := map[string]any{"docCreateTemplatePath": "/indexed.md"}
- createdID, err := CreateWithMarkdown("", box.ID, "/Default template", "", "", docID, false, "", arg)
+ created, err := CreateDocByParent(DocumentCreateRequest{Notebook: box.ID, ID: docID,
+ TitleFormat: "plain", Title: "Default template", DocCreateTemplatePath: "/indexed.md"})
if nil != err {
t.Fatalf("create document with default template failed: %v", err)
}
- if docID != createdID {
- t.Fatalf("unexpected created document ID: got %s, want %s", createdID, docID)
+ if docID != created.ID {
+ t.Fatalf("unexpected created document ID: got %s, want %s", created.ID, docID)
}
assertTemplateOutputIndexed(t, docID)
attributeViewDocID := "20260728000002-abcdefg"
- createdID, err = CreateWithMarkdown("", box.ID, "/Attribute view template", "", "", attributeViewDocID, false, "", nil)
+ created, err = CreateDocByParent(DocumentCreateRequest{Notebook: box.ID, ID: attributeViewDocID,
+ TitleFormat: "plain", Title: "Attribute view template"})
if nil != err {
t.Fatalf("create attribute view item document failed: %v", err)
}
- if err = applyNewItemContentTemplate("/indexed.md", createdID); nil != err {
+ if err = applyNewItemContentTemplate("/indexed.md", created.ID); nil != err {
t.Fatalf("apply attribute view item content template failed: %v", err)
}
assertTemplateOutputIndexed(t, attributeViewDocID)
diff --git a/kernel/model/import_document_target_fts5_test.go b/kernel/model/import_document_target_fts5_test.go
index 261f42c7e1..5cb8de22fe 100644
--- a/kernel/model/import_document_target_fts5_test.go
+++ b/kernel/model/import_document_target_fts5_test.go
@@ -6,7 +6,6 @@ import (
"testing"
"github.com/siyuan-note/siyuan/kernel/conf"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -17,9 +16,6 @@ func TestImportNotebookDocumentTargets(t *testing.T) {
}
func TestStructuredTitlesNativeImport(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
testImportNotebookDocumentTargets(t, "Anchor/../literal")
}
diff --git a/kernel/model/import_markdown_batch_fts5_test.go b/kernel/model/import_markdown_batch_fts5_test.go
index 1854aff7c7..0f133dd887 100644
--- a/kernel/model/import_markdown_batch_fts5_test.go
+++ b/kernel/model/import_markdown_batch_fts5_test.go
@@ -14,7 +14,6 @@ import (
"github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/conf"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -26,9 +25,6 @@ func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {
}
func TestStructuredTitlesMarkdownImport(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
testMarkdownImportBatches(t, "Renamed/../parent%2F")
}
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index dd9be1b077..28329c5317 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -622,9 +622,10 @@ func mountBox(boxID string) (alreadyMount bool, err error) {
}
// 缓存根一级的文档树展开
- files, _, _ := ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, confFileTreeSnapshot.MaxListCount)
+ ListDocTree(box.ID, "/", util.SortModeUnassigned, false, false, confFileTreeSnapshot.MaxListCount)
box = Conf.Box(boxID)
- if 0 < len(files) || (nil != box && box.Exist(boxDocPath(box.ID))) {
+ // 空笔记本也须完成索引初始化,否则结构化创建接口会一直等待元数据就绪。
+ if nil != box {
box.Index()
}
if Conf.Box(boxID) != nil {
diff --git a/kernel/model/notebook_archive_test.go b/kernel/model/notebook_archive_test.go
index e0f71c41e1..0562de1ca1 100644
--- a/kernel/model/notebook_archive_test.go
+++ b/kernel/model/notebook_archive_test.go
@@ -11,7 +11,6 @@ import (
"testing"
"github.com/siyuan-note/siyuan/kernel/conf"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -189,19 +188,7 @@ func TestNotebookArchivePartialRemovalAndAuthenticatedRecovery(t *testing.T) {
})
}
-func TestNotebookArchiveRejectsChangedSourcesAndRollsBackInterruptedMove(t *testing.T) {
- testNotebookArchiveInterruptedMove(t)
-}
-
func TestStructuredTitlesArchiveInterruptedMove(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
- testNotebookArchiveInterruptedMove(t)
-}
-
-func testNotebookArchiveInterruptedMove(t *testing.T) {
- t.Helper()
notebookArchiveTestWorkspace(t)
if err := EnableEncryptedNotebook("archive-password"); err != nil {
t.Fatal(err)
diff --git a/kernel/model/search_test.go b/kernel/model/search_test.go
index 68d0614271..752263580e 100644
--- a/kernel/model/search_test.go
+++ b/kernel/model/search_test.go
@@ -19,6 +19,7 @@ package model
import (
"context"
gosql "database/sql"
+ "path/filepath"
"regexp"
"slices"
"strings"
@@ -28,6 +29,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -620,7 +622,23 @@ func TestTrimDocumentTitleHPath(t *testing.T) {
func TestFilterSelfHPathPreservesHighlight(t *testing.T) {
setSearchCaseSensitive(t, true)
+ previousPath := util.BlockTreeDBPath
+ util.BlockTreeDBPath = filepath.Join(t.TempDir(), "blocktree.db")
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ util.BlockTreeDBPath = previousPath
+ })
+ const boxID = "20260731120000-hpath00"
+ for id, title := range map[string]string{
+ "20260731120000-hpath01": "会员特权",
+ "20260731120001-hpath02": "会员特权",
+ "20260731120002-hpath03": "会员/特权",
+ } {
+ treenode.UpsertBlockTree(treenode.NewTree(boxID, "/"+id+".sy", "/"+title, title))
+ }
multipleKeywords := fromHPathSearchSQLBlock(&sql.Block{
+ Box: boxID,
ID: "20260731120000-hpath01",
RootID: "20260731120000-hpath01",
HPath: "/思源笔记用户指南/请/从这里开始/会员特权",
@@ -628,6 +646,7 @@ func TestFilterSelfHPathPreservesHighlight(t *testing.T) {
Type: "d",
}, "从这里"+search.TermSep+"会员", 36)
singleKeyword := fromHPathSearchSQLBlock(&sql.Block{
+ Box: boxID,
ID: "20260731120001-hpath02",
RootID: "20260731120001-hpath02",
HPath: "/会员特权",
@@ -641,6 +660,10 @@ func TestFilterSelfHPathPreservesHighlight(t *testing.T) {
Type: "NodeParagraph",
HPath: "/思源笔记用户指南/<mark>会员</mark>特权",
},
+ fromHPathSearchSQLBlock(&sql.Block{
+ Box: boxID, ID: "20260731120002-hpath03", RootID: "20260731120002-hpath03",
+ HPath: "/用户指南/会员/特权", Content: "会员/特权", Type: "d",
+ }, "会员", 36),
}
filterSelfHPath(blocks)
@@ -654,6 +677,9 @@ func TestFilterSelfHPathPreservesHighlight(t *testing.T) {
if expected := "/思源笔记用户指南/<mark>会员</mark>特权"; expected != blocks[2].HPath {
t.Fatalf("非文档块路径不应变化:got %q, want %q", blocks[2].HPath, expected)
}
+ if expected := "/用户指南/"; expected != blocks[3].HPath {
+ t.Fatalf("标题中的斜杠不应成为父路径:got %q, want %q", blocks[3].HPath, expected)
+ }
}
func TestBuildHPathSearchOrderBy(t *testing.T) {
diff --git a/kernel/model/structured_titles_test.go b/kernel/model/structured_titles_test.go
index b8a084e209..21ab572848 100644
--- a/kernel/model/structured_titles_test.go
+++ b/kernel/model/structured_titles_test.go
@@ -21,9 +21,6 @@ import (
)
func TestStructuredTitlesCreationAndIdentity(t *testing.T) {
- if documentaddressing.DefaultMode() != 2 {
- t.Skip("covered by the structured-title release-gate CI run")
- }
if os.Getenv("SIYUAN_TEST_STRUCTURED_TITLES") != "1" {
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
diff --git a/kernel/model/template_doc_tree_test.go b/kernel/model/template_doc_tree_test.go
index fd35eb086c..54146cca1e 100644
--- a/kernel/model/template_doc_tree_test.go
+++ b/kernel/model/template_doc_tree_test.go
@@ -107,7 +107,6 @@ func TestParseTemplateDocTreeDefinitionRejectsInvalidSchema(t *testing.T) {
{name: "missing title", definition: []any{map[string]any{}}},
{name: "non-string title", definition: []any{map[string]any{"title": true}}},
{name: "empty title", definition: []any{map[string]any{"title": " \t\r\n"}}},
- {name: "title empty after normalization", definition: []any{map[string]any{"title": "/"}}},
{name: "title is too long", definition: []any{map[string]any{"title": strings.Repeat("文", 513)}}},
{name: "unknown field", definition: []any{map[string]any{"title": "资料", "titel": "typo"}}},
{name: "non-string template", definition: []any{map[string]any{"title": "资料", "template": 1}}},
@@ -128,6 +127,15 @@ func TestParseTemplateDocTreeDefinitionRejectsInvalidSchema(t *testing.T) {
}
}
+func TestParseTemplateDocTreeDefinitionPreservesSlashes(t *testing.T) {
+ for _, title := range []string{"/", "Parent/Child"} {
+ nodes, err := parseTemplateDocTreeDefinition([]any{map[string]any{"title": title}})
+ if err != nil || len(nodes) != 1 || nodes[0].Title != title || nodes[0].Depth != 1 || len(nodes[0].Children) != 0 {
+ t.Fatalf("literal slash changed the title or hierarchy: %+v, %v", nodes, err)
+ }
+ }
+}
+
func TestParseTemplateDocTreeDefinitionLimitsDocumentCount(t *testing.T) {
definition := make([]any, maxTemplateDocTreeDocs)
for i := range definition {
diff --git a/kernel/treenode/document_source_test.go b/kernel/treenode/document_source_test.go
index 0787771fe7..be548c5eae 100644
--- a/kernel/treenode/document_source_test.go
+++ b/kernel/treenode/document_source_test.go
@@ -10,7 +10,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
)
-func TestDocumentAddressingSourceTitleConflict(t *testing.T) {
+func TestDocumentAddressingLegacySourceTitleConflict(t *testing.T) {
for _, source := range []string{
`{"Spec":"2","Properties":{"title":"A/B"}}`,
`{"Spec":"2","Properties":{"title":"A\u002fB"}}`,
@@ -20,7 +20,7 @@ func TestDocumentAddressingSourceTitleConflict(t *testing.T) {
`{"Spec":"999","Properties":{"title":"private/title"}}`,
`{"Properties":{"title":"private/title"},"Spec":"999"}`,
} {
- if err := CheckSpecJSON([]byte(source)); !errors.Is(err, documentaddressing.ErrModeConflict) {
+ if err := CheckSpecJSONForMode([]byte(source), 1); !errors.Is(err, documentaddressing.ErrModeConflict) {
t.Errorf("source title conflict was not retained: %v", err)
} else if strings.Contains(err.Error(), "private") {
t.Fatal("source title leaked into error")
@@ -29,7 +29,7 @@ func TestDocumentAddressingSourceTitleConflict(t *testing.T) {
for _, title := range []string{"A/B", "A&#47;B"} {
root := &ast.Node{Type: ast.NodeDocument, Spec: "2"}
root.KramdownIAL = [][]string{{"title", title}}
- if err := CheckSpec(&parse.Tree{Root: root}); !errors.Is(err, documentaddressing.ErrModeConflict) {
+ if err := CheckSpecForMode(&parse.Tree{Root: root}, 1); !errors.Is(err, documentaddressing.ErrModeConflict) {
t.Fatalf("in-memory source title was accepted: %v", err)
}
}