An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add automatic structured title migration https://github.com/siyuan-note/siyuan/issues/19938
Daniel7442811dc278
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.ymlindex 6f9f4d2620..ee299be70a 100644--- a/.github/workflows/cd.yml+++ b/.github/workflows/cd.yml@@ -242,6 +242,10 @@ jobs:env:SIYUAN_OCR_TEST_ASSETS: ${{ github.workspace }}/app/stage/ocr/modelsSIYUAN_OCR_TEST_LIBRARY: ${{ github.workspace }}/app/stage/ocr/runtime/linux-amd64/libonnxruntime.so+ - name: Test structured title migration behind the release gate+ 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+ working-directory: kernel- name: Test path fixtures with custom temporary directoriesid: test_path_fixtures_with_custom_temporary_directories# 测试失败只记录结果,不阻塞后续发布构建。@@ -324,6 +328,15 @@ jobs:CGO_ENABLED: 1CC: gcc+ - name: Test Windows structured title migration behind the release gate+ 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+ working-directory: kernel+ env:+ CGO_ENABLED: 1+ CC: gcc+- name: Upload kernel test logsif: always()uses: actions/upload-artifact@v7diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-6yi0dv5/20200924101225-k254i8g.syindex 41b9691d55..03760ca55d 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": "20261017174053"+ "updated": "20261023112115"},"Children": [{@@ -3331,6 +3331,48 @@}]},+ {+ "ID": "20261023112115-ewf6xvh",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-ewf6xvh",+ "updated": "20261023112115"+ },+ "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."+ }+ ]+ },+ {+ "ID": "20261023112115-ntigpv2",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-ntigpv2",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "A displayed path is for reading. Use document links or block references to navigate to the intended document. Plugins that locate documents by splitting title paths need to support structured addressing."+ }+ ]+ },+ {+ "ID": "20261023112115-9dsprn2",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-9dsprn2",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Before using this title capability, upgrade all sync devices to supported versions and check plugin compatibility. Migration runs automatically and resumes after interruption. Do not reopen the same workspace with an older version that lacks compatibility protection."+ }+ ]+ },{"ID": "20200925102736-x94e40g","Type": "NodeHeading",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.syindex bdb113e48a..9cf6a87473 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": "20261017174053"+ "updated": "20261023112115"},"Children": [{@@ -3413,6 +3413,48 @@}]},+ {+ "ID": "20261023112115-3dui2fu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-3dui2fu",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "支持结构化文档标题的版本默认允许标题包含半角斜杠 /,无需设置开关。例如,A/B 可以是一篇文档的标题,与 A 下的子文档 B 不同。已有标题和文档链接保持不变,/ 和 %2F 仍按原文字面显示。"+ }+ ]+ },+ {+ "ID": "20261023112115-qkbgw0v",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-qkbgw0v",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "显示路径用于阅读;需要定位某篇文档时,请使用文档链接或块引用。依赖拆分标题路径定位文档的插件需要适配结构化寻址。"+ }+ ]+ },+ {+ "ID": "20261023112115-q33vi92",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-q33vi92",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "使用新标题能力前,请将所有同步设备升级到受支持版本,并确认插件兼容。迁移自动完成,中断后会继续恢复。请勿使用缺少兼容保护的旧版本重新打开同一工作空间。"+ }+ ]+ },{"ID": "20200925095848-aon4lem","Type": "NodeHeading",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.syindex e845791f1d..e178ca8905 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": "20261017174053"+ "updated": "20261023112115"},"Children": [{@@ -3332,6 +3332,48 @@}]},+ {+ "ID": "20261023112115-fwzt0ts",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-fwzt0ts",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "支援結構化文檔標題的版本預設允許標題包含半形斜線 /,無需設定開關。例如,A/B 可以是一篇文檔的標題,與 A 下的子文檔 B 不同。既有標題和文檔連結保持不變,/ 和 %2F 仍按原文字面顯示。"+ }+ ]+ },+ {+ "ID": "20261023112115-2wpc8r5",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-2wpc8r5",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "顯示路徑用於閱讀;需要定位某篇文檔時,請使用文檔連結或區塊引用。依賴拆分標題路徑定位文檔的外掛需要支援結構化定址。"+ }+ ]+ },+ {+ "ID": "20261023112115-6k97ybe",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-6k97ybe",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "使用新標題功能前,請將所有同步裝置升級至受支援版本,並確認外掛相容。移轉自動完成,中斷後會繼續復原。請勿使用缺少相容保護的舊版本重新開啟同一工作空間。"+ }+ ]+ },{"ID": "20211226120227-3jdgfm5","Type": "NodeHeading",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.syindex dda36dee6f..bf6ebd8ac5 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": "20261017174053"+ "updated": "20261023112115"},"Children": [{@@ -3579,6 +3579,48 @@}]},+ {+ "ID": "20261023112115-4rumyue",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-4rumyue",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "構造化ドキュメントタイトルに対応するバージョンでは、設定の切り替えなしにタイトルで半角スラッシュ / を使用できます。例えば A/B は 1 つのドキュメントのタイトルにでき、A の中にある子ドキュメント B とは別です。既存のタイトルとドキュメントリンクは変わらず、/ と %2F も元の文字のまま扱われます。"+ }+ ]+ },+ {+ "ID": "20261023112115-31enzcv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-31enzcv",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "表示パスは閲覧用です。特定のドキュメントに移動するには、ドキュメントリンクまたはブロック参照を使用してください。タイトルのパスを分割してドキュメントを探すプラグインは、構造化されたアドレス指定に対応する必要があります。"+ }+ ]+ },+ {+ "ID": "20261023112115-sb4a5iu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261023112115-sb4a5iu",+ "updated": "20261023112115"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "新しいタイトル機能を使用する前に、すべての同期端末を対応バージョンに更新し、プラグインの互換性を確認してください。移行は自動で行われ、中断後も復旧を継続します。互換性保護のない古いバージョンで同じワークスペースを開かないでください。"+ }+ ]+ },{"ID": "20240530101000-yy3nfa8","Type": "NodeHeading",diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex 6ba13e9250..82ddabf04f 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -173,6 +173,7 @@ const initialize = async () => {return;}window.siyuan.config = systemConfig(response.data.conf);+ window.siyuan.documentAddressingVersion = response.data.documentAddressingVersion;window.siyuan.isPublish = response.data.isPublish;await loadDesktopHostConnection();if (!isActive()) return;diff --git a/app/src/editor/rename.test.ts b/app/src/editor/rename.test.tsindex 063b3c843d..017ec7fcf5 100644--- a/app/src/editor/rename.test.ts+++ b/app/src/editor/rename.test.ts@@ -4,6 +4,29 @@ import * as path from "node:path";import {test} from "node:test";import {ScriptTarget, transpileModule} from "typescript";+test("document titles preserve slash characters while notebook and file names retain their rules", () => {+ const source = transpileModule(readFileSync(path.resolve(__dirname, "rename.ts"), "utf8")+ .replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText;+ const runtime = {siyuan: {documentAddressingVersion: 2,+ languages: {fileNameRule: "Invalid filename", _kernel: {106: "Title too long"}}}};+ let messages = 0;+ const methods = new Function("window", "Constants", "showMessage", source + "\nreturn {normalizeDocumentTitle, replaceFileName, validateName};")(+ runtime, {SIZE_TITLE: 512}, () => messages++);+ for (const title of ["A/B", "../Title/", "A/B/%2F", "**text**/`code`", "&/literal"]) {+ assert.equal(methods.normalizeDocumentTitle(title), title);+ }+ assert.equal(messages, 0);+ assert.equal(methods.replaceFileName("Notebook/name"), "Notebook/name");+ assert.equal(methods.normalizeDocumentTitle("First\nSecond/third"), "FirstSecond/third");+ assert.equal(methods.normalizeDocumentTitle("😀".repeat(513)), "😀".repeat(512));+ assert.equal(methods.validateName("😀".repeat(512), undefined, true), true);+ assert.equal(methods.validateName("😀".repeat(513), undefined, true), false);+ assert.equal(methods.validateName("😀".repeat(512)), false);+ runtime.siyuan.documentAddressingVersion = 1;+ assert.equal(methods.normalizeDocumentTitle("Old/server"), "Old/server");+});+test("failed asset rename keeps the dialog open and does not update or reload editors", async () => {const source = transpileModule(readFileSync(path.resolve(__dirname, "rename.ts"), "utf8").replace(/^import [\s\S]*?;\r?\n/gm, "").replace(/^export /gm, ""),diff --git a/app/src/editor/rename.ts b/app/src/editor/rename.tsindex dd2ec7b35a..118a4745e5 100644--- a/app/src/editor/rename.ts+++ b/app/src/editor/rename.ts@@ -13,7 +13,7 @@ import {getAllModels} from "../layout/getAll";/// #endifimport {getAllEditor} from "../layout/getAll";-export const validateName = (name: string, targetElement?: HTMLElement) => {+export const validateName = (name: string, targetElement?: HTMLElement, documentTitle = false) => {if (/\r\n|\r|\n|\u2028|\u2029|\t/.test(name)) {if (targetElement) {showTooltip(window.siyuan.languages.fileNameRule, targetElement, "error");@@ -22,7 +22,8 @@ export const validateName = (name: string, targetElement?: HTMLElement) => {}return false;}- if (name.length > Constants.SIZE_TITLE) {+ const length = documentTitle && window.siyuan.documentAddressingVersion === 2 ? Array.from(name).length : name.length;+ if (length > Constants.SIZE_TITLE) {if (targetElement) {showTooltip(window.siyuan.languages["_kernel"]["106"], targetElement, "error");} else {@@ -41,6 +42,14 @@ export const replaceFileName = (name: string) => {return name.replace(/\r\n|\r|\n|\u2028|\u2029|\t|/g, "").substring(0, Constants.SIZE_TITLE);};+// 文档标题与文件名分开处理;旧内核保留既有输入规则。+export const normalizeDocumentTitle = (name: string) => {+ if (window.siyuan.documentAddressingVersion !== 2) {+ return replaceFileName(name);+ }+ return Array.from(name.replace(/\r\n|\r|\n|\u2028|\u2029|\t/g, "")).slice(0, Constants.SIZE_TITLE).join("");+};+export const replaceLocalPath = (name: string) => {return name.replace(/\\\\|\/|"|:|\*|\?|\\|'|<|>|\|/g, "");};@@ -66,7 +75,7 @@ export const rename = (options: {}},onConfirm: (value, dialog) => {- if (!validateName(value)) {+ if (!validateName(value, undefined, options.type === "file")) {return;}let name = value.trim();@@ -74,7 +83,7 @@ export const rename = (options: {dialog.destroy();return;}- name = replaceFileName(name);+ name = options.type === "notebook" ? replaceFileName(name) : normalizeDocumentTitle(name);if (options.type === "notebook") {if (!name) {name = window.siyuan.languages.untitled;@@ -165,7 +174,7 @@ export const newFileContentBySelect = (protyle: IProtyle) => {if (fileNameShort.length > 10) {fileNameShort = fileNameShort.substr(0, 10) + "...";}- fileNameShort = replaceFileName(fileNameShort);+ fileNameShort = normalizeDocumentTitle(fileNameShort);fetchPost("/api/filetree/createDocByParent", documentCreateRequest(protyle.notebookId, protyle.path,Lute.NewNodeID(), fileNameShort, protyle.lute.BlockDOM2StdMd(html)));};diff --git a/app/src/index.ts b/app/src/index.tsindex 0957f1fc1d..eee72de919 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -339,6 +339,7 @@ export class App {await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = systemConfig(response.data.conf, () => structuredClone(Constants.SIYUAN_EMPTY_LAYOUT));+ window.siyuan.documentAddressingVersion = response.data.documentAddressingVersion;await loadDesktopHostConnection();ensureUILayout();window.siyuan.isPublish = response.data.isPublish;diff --git a/app/src/layout/dock/Inbox.test.ts b/app/src/layout/dock/Inbox.test.tsindex 300b53c274..d49413e997 100644--- a/app/src/layout/dock/Inbox.test.ts+++ b/app/src/layout/dock/Inbox.test.ts@@ -106,7 +106,7 @@ const loadMoveInbox = (fetchEntry: (id: string) => Promise<void> = async () => {created.push(input.id);options.onCreated();}},- "../../editor/rename": {replaceFileName: (value: string) => value},+ "../../editor/rename": {normalizeDocumentTitle: (value: string) => value},"../../util/escape": {escapeHtml: (value: string) => value},"../../dialog/message": {showMessage() {}},})[name] || {},diff --git a/app/src/layout/dock/Inbox.ts b/app/src/layout/dock/Inbox.tsindex 616bfe4ff5..81f5a351dd 100644--- a/app/src/layout/dock/Inbox.ts+++ b/app/src/layout/dock/Inbox.ts@@ -11,7 +11,7 @@ import {Model} from "../Model";import {needSubscribe} from "../../util/needSubscribe";import {MenuItem} from "../../menus/Menu";import {confirmDialog} from "../../dialog/confirmDialog";-import {replaceFileName} from "../../editor/rename";+import {normalizeDocumentTitle} from "../../editor/rename";import {movePathTo} from "../../util/pathName";import {documentCreateRequest} from "../../util/documentCreate";import {createConfiguredDocument} from "../../util/configuredDocument";@@ -436,7 +436,7 @@ ${data.shorthandContent}this.moveTargets.set(idItem, target);}const request = documentCreateRequest(target.notebook, target.path, target.id,- replaceFileName(response.data.shorthandTitle), md);+ normalizeDocumentTitle(response.data.shorthandTitle), md);let completed = false;await createConfiguredDocument({notebook: target.notebook, contextID: request.parentID, purpose: "document",diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 8903bf3b30..9b8ca027d9 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -222,6 +222,7 @@ class App {await ensureLute({reloadOnFailure: false});addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = systemConfig(confResponse.data.conf);+ window.siyuan.documentAddressingVersion = confResponse.data.documentAddressingVersion;window.siyuan.isPublish = confResponse.data.isPublish;applyPlatformClasses();correctHotkey(siyuanApp);diff --git a/app/src/protyle/header/Title.ts b/app/src/protyle/header/Title.tsindex 837463d5d4..f79a49a559 100644--- a/app/src/protyle/header/Title.ts+++ b/app/src/protyle/header/Title.ts@@ -6,7 +6,7 @@ import {} from "../util/selection";import {focusByRange, getSelectionOffset} from "../util/selectionOffsets";import {fetchPost} from "../../util/fetch";-import {replaceFileName, validateName} from "../../editor/rename";+import {normalizeDocumentTitle, validateName} from "../../editor/rename";import {MenuItem} from "../../menus/Menu";import {openFileAttr,} from "../../menus/commonMenuItem";import {Constants} from "../../constants";@@ -72,7 +72,7 @@ export class Title {}// 阻止右键复制菜单报错setTimeout(function () {- document.execCommand("insertText", false, replaceFileName(text));+ document.execCommand("insertText", false, normalizeDocumentTitle(text));}, 0);this.rename(protyle);});@@ -124,7 +124,7 @@ export class Title {restoreLuteMarkdownSyntax(protyle);// 移除 ;;;lt;;; 和 ;;;gt;;; 转义及其包裹的内容content = content.replace(/;;;lt;;;[^;]+;;;gt;;;/g, "");- document.execCommand("insertText", false, replaceFileName(content));+ document.execCommand("insertText", false, normalizeDocumentTitle(content));this.rename(protyle);}return;@@ -284,7 +284,7 @@ export class Title {} else {try {const text = await readText() || "";- document.execCommand("insertText", false, replaceFileName(text));+ document.execCommand("insertText", false, normalizeDocumentTitle(text));this.rename(protyle);} catch (e) {console.log(e);@@ -306,7 +306,7 @@ export class Title {restoreLuteMarkdownSyntax(protyle);// 移除 ;;;lt;;; 和 ;;;gt;;; 转义及其包裹的内容content = content.replace(/;;;lt;;;[^;]+;;;gt;;;/g, "");- document.execCommand("insertText", false, replaceFileName(content));+ document.execCommand("insertText", false, normalizeDocumentTitle(content));this.rename(protyle);}}).element);@@ -347,7 +347,7 @@ export class Title {private rename(protyle: IProtyle) {clearTimeout(this.timeout);this.pendingRename = undefined;- if (!validateName(this.editElement.textContent, this.editElement)) {+ if (!validateName(this.editElement.textContent, this.editElement, true)) {// 字数过长会导致滚动const offset = getSelectionOffset(this.editElement);this.setTitle(this.editElement.textContent.substring(0, Constants.SIZE_TITLE));@@ -358,7 +358,7 @@ export class Title {this.pendingRename = () => {this.pendingRename = undefined;this.timeout = undefined;- const fileName = replaceFileName(this.editElement.textContent);+ const fileName = normalizeDocumentTitle(this.editElement.textContent);fetchPost("/api/filetree/renameDoc", {notebook: protyle.notebookId,path: protyle.path,diff --git a/app/src/protyle/util/editorSave.test.ts b/app/src/protyle/util/editorSave.test.tsindex 64ac9fd9bf..df7c18fc13 100644--- a/app/src/protyle/util/editorSave.test.ts+++ b/app/src/protyle/util/editorSave.test.ts@@ -303,7 +303,7 @@ test("Title flushes debounce once, captures composition, and can cancel pendingexports,require: (name: string) => {if (name === "../../util/fetch") return {fetchPost: (_url: string, data: unknown) => requests.push(data)};- if (name === "../../editor/rename") return {validateName: () => true, replaceFileName: (name: string) => name};+ if (name === "../../editor/rename") return {validateName: () => true, normalizeDocumentTitle: (name: string) => name};if (name === "../../dialog/tooltip") return {hideTooltip: () => {}};if (name === "../../constants") return {Constants: {TIMEOUT_INPUT: 400}};return {};diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.tsindex 36c194b80b..828f40c826 100644--- a/app/src/protyle/wysiwyg/keydown.ts+++ b/app/src/protyle/wysiwyg/keydown.ts@@ -108,7 +108,7 @@ import {shouldIgnoreListShortcut,type TListSubtype} from "./listContext";-import {newFileContentBySelect, rename, replaceFileName} from "../../editor/rename";+import {newFileContentBySelect, rename, normalizeDocumentTitle} from "../../editor/rename";import {cancelSB, insertEmptyBlock, insertEmptySuperBlockColumn, jumpToParent} from "../../block/util";import {isEncryptedBox, isLocalPath} from "../../util/pathName";/// #if !MOBILE@@ -1817,7 +1817,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {fetchPost("/api/filetree/renameDoc", {notebook: protyle.notebookId,path: protyle.path,- title: replaceFileName(selectText),+ title: normalizeDocumentTitle(selectText),});}event.preventDefault();diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 14786c8dc8..f6c0736f38 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1486,6 +1486,12 @@ export type KernelPetal = { "existed": boolean; "incompatible": boolean; "js": sexport type LegacyDocumentTarget = { "notebook": string; "path": string; "version": 1; };+export type LegacyPathDocumentResult = string | LegacyPathUnsupported;++export type LegacyPathIDsResult = Array<string> | null | LegacyPathUnsupported;++export type LegacyPathUnsupported = { "reason": "legacyPathUnsupported"; };+export type ListNotebooksData = { "boxDocEnabled": boolean; "notebooks": Array<Notebook | null> | null; };export type ListNotebooksRequestInput = { "flashcard"?: boolean | null; };@@ -2394,7 +2400,7 @@ export type SystemChangelogRequestInput = { "force"?: boolean | null; };export type SystemCheckUpdateRequestInput = { "showMsg": boolean; };-export type SystemConfData = { "conf": SystemAppConf | null; "isPublish": boolean; "revision": number; "settingTasks"?: SettingTaskState; "start": boolean; };+export type SystemConfData = { "conf": SystemAppConf | null; "documentAddressingVersion": number; "isPublish": boolean; "revision": number; "settingTasks"?: SettingTaskState; "start": boolean; };export type SystemCustomEmojiRequestInput = { "file"?: Blob; "name"?: string; "url"?: string; };@@ -5400,7 +5406,8 @@ export interface APIPOSTRoutes {* 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。* ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。* 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。- * 当前兼容阶段仍不允许标题包含 /,不提升已有文档 Spec;加密笔记本使用原有认证写入与响应租约。+ * 功能版本默认保留标题中的 /,该文档写入 Spec 6;普通文档不因迁移统一升级,保护版本仍拒绝 /。+ * 加密笔记本使用原有认证写入与响应租约;自动模式迁移不改变密文格式或密钥材料。*/"/api/filetree/createDocByParent": {request: CreateDocByParentRequestInput;@@ -5412,10 +5419,11 @@ export interface APIPOSTRoutes {/*** 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。* 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。+ * 模式 2 对整个笔记本返回 legacyPathUnsupported,即使提供 parentID;改用 createDocByParent。*/"/api/filetree/createDocWithMd": {request: FileTreeCreateMarkdownRequestInput;- response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": LegacyPathDocumentResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | LegacyPathDocumentResult; "msg": string; };body: "json";/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];@@ -5518,9 +5526,12 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 在兼容模式保留旧名称路径查询;模式 2 整本返回 legacyPathUnsupported,改用 resolveDocPath。+ */"/api/filetree/getIDsByHPath": {request: FileTreeOptionalPathRequestInput;- response: { "code": 0; "data": Array<string> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": LegacyPathIDsResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | LegacyPathIDsResult; "msg": string; };body: "json";/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];@@ -5681,7 +5692,7 @@ export interface APIPOSTRoutes {* 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。* candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。* 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。- * 索引未就绪返回 indexUnavailable;普通标题仍遵守兼容模式限制,不隐式启用新字符。+ * 索引未就绪返回 indexUnavailable;功能版本默认保留段内 /,保护版本仍遵守兼容模式限制。*/"/api/filetree/resolveDocPath": {request: ResolveDocPathRequestInput;@@ -6286,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. literalSlash remains false until structured- * title mode is implemented and enabled; minimumReaderVersion is null until a protective release- * is verified. Revision covers configuration and confirmed capability records, not a document path.+ * 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.+ * 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.tsindex c6bb0ed61c..d1b7f2d49b 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -561,6 +561,8 @@ interface INotebook {}interface ISiyuan {+ /** 当前内核的只读文档标题能力,不持久化为用户设置。 */+ documentAddressingVersion?: number;zIndex: numberisReady?: booleanstorage?: {diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.tsindex b325601f77..e8e8adb88a 100644--- a/app/src/util/newFile.ts+++ b/app/src/util/newFile.ts@@ -9,7 +9,7 @@ import {getActiveTab, getDockByType} from "../layout/tabUtil";import {fetchPost, fetchSyncPost} from "./fetch";import {getOpenNotebookCount, isMoveTargetAllowed, movePathTo} from "./pathName";import {Constants} from "../constants";-import {replaceFileName, validateName} from "../editor/rename";+import {normalizeDocumentTitle, validateName} from "../editor/rename";import {hideElements} from "../protyle/ui/hideElements";import {openMobileFileById} from "../mobile/editor";import type {App} from "../index";@@ -68,7 +68,7 @@ export const newFile = (app: App, name?: string) => {notebookId,currentPath,hasFocusTarget,- name: replaceFileName(name.trim()),+ name: normalizeDocumentTitle(name.trim()),onCreated: () => hideElements(["dialog"]),});}@@ -168,7 +168,7 @@ export const newFileBySelectRange = (protyle: IProtyle, range: Range, target: "s}const fileName = name === undefined ? (selectText.trim() ||protyle.lute.BlockDOM2Content(nodeElement.outerHTML).replace(/\n/g, "").trim()) : name.trim();- const newFileName = replaceFileName(fileName);+ const newFileName = normalizeDocumentTitle(fileName);newFileBySelect(protyle, newFileName, selectionContext, target === "subDoc" ? "child" : "configured", refSubtype);hideElements(["toolbar"], protyle);};@@ -282,7 +282,7 @@ export const newFileByRefHint = () => {void createConfiguredDocument({notebook: protyle.notebookId, contextID: documentParentID(protyle.path), purpose: "reference",- title: replaceFileName(name.trim()), id: presetId,+ title: normalizeDocumentTitle(name.trim()), id: presetId,}, {onCreated: (id, title) => onCreated?.(id, title)});};@@ -314,8 +314,8 @@ export const newFileAtPath = (options: {restoreFocus?: () => void;onCreated: (id: string, title: string) => void;}) => {- const title = replaceFileName(options.name.trim());- if (!options.isValid() || (title && !validateName(title))) {+ const title = normalizeDocumentTitle(options.name.trim());+ if (!options.isValid() || (title && !validateName(title, undefined, true))) {return;}let submitted = false;@@ -357,7 +357,7 @@ export const newSubDocByRefHint = () => {createRefDocAsSubDoc({kind: "subDoc", targetNotebookId: protyle.notebookId, parentPath: protyle.path,- title: replaceFileName(name.trim()),+ title: normalizeDocumentTitle(name.trim()),}, onCreated, presetId);};diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 2992c01cbf..9fa8eeb07f 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -244,6 +244,7 @@ class App {await addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");window.siyuan.config = systemConfig(response.data.conf, () => structuredClone(Constants.SIYUAN_EMPTY_LAYOUT));+ window.siyuan.documentAddressingVersion = response.data.documentAddressingVersion;await loadDesktopHostConnection();ensureUILayout();setBodyHighlight();diff --git a/docs/API.ja.md b/docs/API.ja.mdindex b054ec7103..63f1018c96 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -298,6 +298,8 @@ if (response.code === 0 && response.data) {### ノートブック設定を取得+管理者向けレスポンスには、読み取り専用の `documentCapabilities` オブジェクトが含まれる場合があります。アドレス指定モード、構造化 API、タイトル機能、インデックス状態、検証済みの最低読み取りバージョンを示します。機能リリースでは設定の切り替えなしに自動移行されます。`literalSlash` にはモード `2`、整合したモード記録、準備済みインデックスが必要です。保護リリースの検証が完了するまで `minimumReaderVersion` は `null` です。既存の権限によるフィルタリングは維持されます。+* `/api/notebook/getNotebookConf`* パラメータ@@ -372,6 +374,8 @@ if (response.code === 0 && response.data) {### Markdownでドキュメントを作成+この旧名称パス API は互換モードでのみ利用できます。構造化タイトルに対応する機能リリースではノートブックが自動移行され、通常のタイトルや `parentID` を指定した場合も、ノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。`/api/filetree/createDocByParent` に親の識別情報とタイトルを別々に渡してください。以下の例は互換モードの動作を示します。+* `/api/filetree/createDocWithMd`* パラメータ@@ -754,6 +758,8 @@ if (response.code === 0 && response.data) {### 人間が読めるパスからIDを取得+構造化タイトルに対応する機能リリースではノートブックが自動移行され、この旧 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.mdindex 1352613bea..aa4f5a8154 100644--- a/docs/API.md+++ b/docs/API.md@@ -303,6 +303,8 @@ 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.+* `/api/notebook/getNotebookConf`* Parameters@@ -377,6 +379,8 @@ 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.+* `/api/filetree/createDocWithMd`* Parameters@@ -759,6 +763,8 @@ 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.+* `/api/filetree/getIDsByHPath`* Parametersdiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 3703821e61..ba0984a609 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -303,6 +303,8 @@ if (response.code === 0 && response.data) {### 获取笔记本配置+管理员响应还可包含只读的 `documentCapabilities` 对象,用于报告寻址模式、结构化接口支持、标题能力、索引状态及已验证的最低读取版本。功能版本自动迁移笔记本,无需设置开关;`literalSlash` 要求模式 `2`、模式记录一致且索引就绪。保护版本尚未验证时,`minimumReaderVersion` 为 `null`。既有权限过滤保持不变。+* `/api/notebook/getNotebookConf`* 参数@@ -377,6 +379,8 @@ if (response.code === 0 && response.data) {### 通过 Markdown 创建文档+这是仅在兼容模式可用的旧名称路径接口。结构化标题功能版本会自动迁移笔记本,该接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`,即使标题普通或提供了 `parentID`。请改用 `/api/filetree/createDocByParent`,分别传入父身份和标题。下面的示例描述兼容模式行为。+* `/api/filetree/createDocWithMd`* 参数@@ -759,6 +763,8 @@ if (response.code === 0 && response.data) {### 根据人类可读路径获取 IDs+结构化标题功能版本会自动迁移笔记本,该旧接口对整个笔记本返回 `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.mdindex 2f30b17547..75f31b4b74 100644--- a/docs/DOCUMENT-ADDRESSING.md+++ b/docs/DOCUMENT-ADDRESSING.md@@ -4,7 +4,7 @@Related issues: [Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938), [Improve content preservation when converting headings to documents](https://github.com/siyuan-note/siyuan/issues/19235)-This is an implementation design draft defining document titles, hierarchy addressing, readable paths, APIs, and migration behavior. The new fields, endpoints, and version mechanisms below are proposed contracts, not capabilities already supported by the current release. See [Document rename and path indexes](DOCUMENT-HPATH.md) (Chinese) for the current rename and index update mechanism.+This document defines document titles, hierarchy addressing, readable paths, APIs, and migration behavior. Development implementation and release requirements are described separately; development capabilities do not establish availability in a released version. See [Document rename and path indexes](DOCUMENT-HPATH.md) (Chinese) for the current rename and index update mechanism.### Current implementation scope@@ -12,7 +12,7 @@ The development branch implements a shared title reader, document metadata organCreation 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.-Only compatibility mode `1` is currently available. ASCII `/` remains prohibited in document titles, and public writes of version `2` target configurations remain gated by the notebook mode. Explicit enablement, mode `2` source formats and conflict recovery, notebook-wide rejection of legacy string addressing, and the enablement UI have not shipped; this work must not be described as merely waiting for a release switch. Stage D must also determine the minimum reader version and `DocumentTitleSpec` from actual protective-release verification and complete mixed-version, performance, and platform acceptance before activation. The 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 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.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.@@ -29,7 +29,7 @@ The design covers desktop, browser, mobile, kernel APIs, and plugin-visible data| Area | Selected approach || --- | --- || Document addressing | Notebook and document IDs; creation takes a parent identity and a separate title |-| Compatibility modes | Explicitly enable structured title mode per notebook; existing notebooks default to compatibility mode |+| Compatibility modes | The feature release defaults to structured titles and automatically migrates existing notebooks; mode records are internal compatibility markers, not user settings || Plugins | Accept adaptation of plugins that depend on legacy `hPath` rules; deliver replacement APIs and migration guidance before enabling new characters || Legacy string addressing | Preserve existing behavior in compatibility mode; reject legacy string lookup and creation in structured title mode || Readable paths | Join original ancestor title text for display; do not encode `/` or decode `/` or `%2F` |@@ -179,9 +179,9 @@ Legacy string save paths retain their current interpretation, including absoluteThe compatibility compiler evaluates legacy templates using their original grammar and produces structured creation plans. A separately supplied new title remains separate and is not joined back into a path string. Relative anchors and upward navigation use the current document ID and parent relationships, never a split of its display path into legacy segments. This internal adapter does not call public string-addressing endpoints disabled by the new mode, so existing daily-note configurations still work. A `/` produced by a variable within a legacy template continues to create a level; it remains one segment only after an explicit switch to the new template format.-Legacy workflows and string templates in mode `1` retain existing duplicate-name selection and `parentID` fallback behavior. Internal identity-based implementations must pass legacy regressions rather than silently returning ambiguity errors because they share a strict resolver. New structured APIs apply strict ambiguity checks in both modes. Built-in mode `2` workflows use strict plans even for legacy templates and never select an arbitrary same-named parent; disclose that behavior change at explicit activation. A cross-notebook target used through the new protocol remains strict even when the destination uses mode `1`.+Legacy workflows and string templates in mode `1` retain existing duplicate-name selection and `parentID` fallback behavior. Internal identity-based implementations must pass legacy regressions rather than silently returning ambiguity errors because they share a strict resolver. New structured APIs apply strict ambiguity checks in both modes. Built-in mode `2` workflows use strict plans even for legacy templates and never select an arbitrary same-named parent; describe that behavior change in feature-release migration guidance. A cross-notebook target used through the new protocol remains strict even when the destination uses mode `1`.-New configuration uses `docCreateTarget`, `refCreateTarget`, and `dailyNoteTarget` alongside the original string save-path fields. Initially, these objects are available only in the configuration of notebooks with mode `2` enabled. Global settings retain legacy string templates and existing inheritance rules, avoiding configuration unknown to old clients before notebook activation. Each object requires `version: 2`, specifying the destination notebook, anchor, number of upward steps, ancestor segments, final title, and missing-parent policy. Each segment reuses the existing save-path template evaluator. The example's `{{now | date ...}}` syntax is for save-path templates and must not be confused with body-template syntax.+New configuration uses `docCreateTarget`, `refCreateTarget`, and `dailyNoteTarget` alongside the original string save-path fields. These objects are available in the configuration of notebooks automatically migrated to mode `2` by the feature release. Global settings retain legacy string templates and existing inheritance rules, keeping global configuration compatible with the protective release. Each object requires `version: 2`, specifying the destination notebook, anchor, number of upward steps, ancestor segments, final title, and missing-parent policy. Each segment reuses the existing save-path template evaluator. The example's `{{now | date ...}}` syntax is for save-path templates and must not be confused with body-template syntax.```json{@@ -234,9 +234,9 @@ Renames still invalidate display paths, ancestor text search data, and related c### Cross-mode moves and recovery-Cross-notebook moves, copies, native imports, and history restoration preflight the entire operation set before the first write, including every descendant of each root document. Check destination mode, title formats and original text, source-format readability, destination depth, and existing encryption boundaries, not just top-level titles. If any document requires a title capability not enabled at the destination, reject the entire operation with `targetModeUnsupported`, returning conflicting document IDs only within authorized scope. Do not move directories, rewrite titles, delete sources, or automatically enable the destination mode.+Cross-notebook moves, copies, native imports, and historical recovery preflight the complete operation set before the first source write, including every descendant of each root. Check destination capabilities, title format and content, readable source versions, destination depth, and existing encryption boundaries rather than only root titles. The feature release automatically completes destination mode records. If the destination reader still lacks a required capability, return `targetModeUnsupported` for the entire operation with authorized conflicting document IDs, without moving directories, rewriting titles, or deleting sources.-After the user explicitly enables the destination mode and recovery completes, replan and revalidate the operation. Imports creating a notebook also obtain an explicit mode choice before committing documents. Required title capabilities derive from the title representation and actual content. The `.sy` version expresses source-reader requirements; not every version higher than `DocumentTitleSpec` implies mode `2`, and source versions must not be lowered to pass checks. Ordinary titles satisfying destination rules may move from a mode `2` notebook into mode `1`.+After upgrading the destination client and completing automatic recovery, replan and revalidate. Imports creating a notebook use the current release's default capabilities without asking the user to select a mode. Required title capabilities depend on the title format and actual content. A `.sy` version describes source-reading requirements; versions above `DocumentTitleSpec` do not all imply mode `2`, and versions must not be lowered to pass preflight. Ordinary titles may be exported to compatible readers that support their source format.Ready metadata may support whole-subtree preflight; imports and history use their authenticated source snapshots. Recover missing or stale indexes rather than inferring capabilities from old `hPath` values. Preflight records identities, membership, and title and location revisions for the whole operation set; revalidate under mutation coordination to catch descendant renames or additions before commit. Reject predictable incompatibilities before any write. Actual I/O failures follow partial-commit recording and recovery rules without claiming atomic multi-file moves. Existing isolation between ordinary and encrypted notebooks, and between different encrypted notebooks, remains unchanged.@@ -315,7 +315,7 @@ Business errors use `code: -1` with a stable `data.reason`. `msg` is for human r| `legacyPathUnsupported` | Legacy string addressing is disabled for the notebook; use the new API || `indexUnavailable` | Structured metadata is not ready; wait for recovery without falling back to display paths || `unsupportedTitleFormat` | Client or endpoint cannot handle the title format; upgrade or use an endpoint supporting that format |-| `targetModeUnsupported` | The complete move, copy, import, or recovery set exceeds destination mode capabilities; explicitly enable the destination before replanning |+| `targetModeUnsupported` | The complete move, copy, import, or recovery set exceeds destination capabilities; upgrade the destination and complete automatic recovery before replanning || `modeConflict` | Notebook mode records conflict with source title capabilities; enter controlled recovery instead of continuing compatibility-mode writes || `writeFailed` | A write or later processing failed; recover using `commitState` and the reported stage |@@ -331,13 +331,13 @@ Legacy `/api/filetree/getDocCreateSavePath` and `/api/filetree/getRefCreateSavePThe caller submits each `createDocByParent` request in order, updating the next step's parent revision from the previous successful response. The returned identity is authoritative after submission. Failures follow their reported commit state; callers must not allocate a fresh set of IDs and blindly replay. A plan is not a transaction across multiple files, and successful planning does not replace validation at each commit.-### Capability discovery and activation+### Capability discovery and automatic migrationAdd 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.-`revision` is the configuration revision relevant to activation, not an individual document's path revision. 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.+`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.-`/api/notebook/enableStructuredTitles` accepts `notebook` and `expectedRevision`. Normal activation from compatibility mode checks the configuration revision, ready index, and local client compatibility before persisting mode `2`. Mode conflicts use the dedicated recovery flow below, without first requiring a ready index in the conflicting state. The endpoint returns current `documentCapabilities`; `recovering` means only that the activation decision is durable, while writes still await recovery. If already enabled with a matching revision, it may return the current state. The endpoint cannot prove that every offline sync client has upgraded; the activation UI explains the minimum version and plugin adaptation requirements, and the user explicitly enables the mode. General configuration updates cannot bypass this activation flow, and old requests omitting new fields cannot reset the mode to `1`.+There is no manual activation endpoint or setting. Before accessing notebook sources, the feature release automatically confirms the mode and completes its persistent records, using the same flow for normal migration and interruption recovery without requiring a previously ready index. `recovering` means mode records are inconsistent or indexes are not ready; it does not promise that structured writes are available. General configuration updates cannot lower the internal mode, and old requests omitting new fields cannot reset it to `1`. The read-only `documentAddressingVersion` in `getConf` declares the release's default capability for desktop, browser, and mobile input initialization; it is not persisted as a user setting. Actual notebook availability still comes from `documentCapabilities`.### Contract and declaration maintenance@@ -345,7 +345,7 @@ Implementation follows [Kernel API type contracts](API-CONTRACTS.md): define dec## API and plugin compatibility-Mode `1` is compatibility mode; mode `2` is explicitly enabled structured title mode. An old notebook with neither the field nor a higher capability record reads as `1`; a missing field cannot override an established capability floor. The mode determines availability of legacy protocols, not a guess based on whether a particular request happens to contain `/`.+Mode `1` is the protective release's compatibility mode; mode `2` is the structured title mode automatically adopted by the feature release. Old notebook records without a higher requirement read as `1`, then migrate automatically to `2` before source access in the feature release. Missing fields cannot lower an established capability floor. The mode determines availability of legacy protocols, not a guess based on whether a particular request contains `/`.| Use case | Compatibility mode `1` | Structured title mode `2` | Plugin migration || --- | --- | --- | --- |@@ -372,13 +372,13 @@ Plugins migrate through capability discovery, reading known targets by ID, resol### Mixed-version access-Notebook configuration adds `documentAddressingVersion`: an absent field or `1` denotes compatibility mode, and `2` denotes structured title mode. Effective mode also considers the capability floor records below instead of relying only on this field. This is independent of encryption-envelope versions and must not reuse `BoxCrypt.Spec`. Enabling the mode does not rewrite existing document titles or IDs in bulk; it changes subsequent operation eligibility and representation rules for new content.+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 that recognizes notebook capability markers and safely rejects unsupported modes, then a feature version that allows enabling 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. 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.-Documents actually using new title capabilities adopt a new `DocumentTitleSpec`. Allocate its numeric value against the `.sy` versions in use at implementation time, rather than reserving a number in this draft. Enabling a notebook does not rewrite every document that does not use the capability. Future rich representations also need explicit format versions, and tolerant parsing must never overwrite unknown content.+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.-Version protection covers full reads, attribute-only reads, read-only path recovery, import, history, backups, and sync. Both strict and non-strict `readDocIAL` branches validate the source version. Streaming `DocIAL` reads must not stop at properties and skip a later `Spec`, and version errors must not enter corrupt-file repair. Checking only ordinary editor loads does not establish complete protection. If the source title format or actual content requires mode `2` while the notebook's effective mode is `1`, return `modeConflict` first. Import continues only after explicit activation, never by silently cleaning titles to fit the old mode. Other newer body features do not automatically require structured title mode.+Version protection covers full reads, attribute-only reads, read-only path recovery, import, history, backups, and sync. Both strict and non-strict `readDocIAL` branches validate source versions. Streaming `DocIAL` reads must not stop at properties and skip a later `Spec`, and version errors must not enter corrupt-file repair. Readers supporting only mode `1` reject titles requiring mode `2`; the feature release completes automatic mode migration before processing supported sources. Never silently clean titles to fit an older mode. Other newer body features do not automatically require structured title mode.In compatibility mode, inspect the decoded root title for ASCII `/` before tolerant parsing, normalization, or repair. Decode stored attribute escaping exactly once; preserve literal HTML entities, `/`, `%2F`, and Markdown syntax. Repeated root properties or version fields cannot hide an earlier incompatible value. Unknown title representations retain a source-format error rather than entering property repair. Check every document in a native import before installing resources, creating a notebook, or remapping IDs. A conflict alone does not activate the mode or create a confirmed capability floor.@@ -386,13 +386,13 @@ Tree writes validate both the replacement and the current on-disk source. AuthenRaw 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 by new fields and are outside the safe mixed-version promise. All sync devices must upgrade before activation. Offline device state cannot be proven and must be explained. If a supported version still has a path that rewrites data, keep the capability disabled rather than substituting documentation for necessary 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. If protection remains incomplete, retain the release gate rather than substituting documentation or a user switch for protection.-Mode `2` has no direct 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-activation 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.+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.### Mode records and conflict recovery-Activation writes a separate capability floor record `{version: 1, notebook, minimumMode: 2}` to the notebook's `.siyuan/document-addressing.json`. It contains only identity and version information and accompanies native notebook exports, backups, and sync. The workspace also retains confirmed minimum modes keyed by notebook ID in `conf/document-addressing.json`; include it in workspace configuration backups without storing titles or keys there. The effective mode is the strictest requirement from valid notebook configuration, the capability floor record, and the local confirmed record. A record is not proof of ciphertext authentication. Unknown record versions, invalid fields, or mismatched identities preserve the original files and refuse processing rather than defaulting to mode `1`.+Automatic migration writes a separate capability floor record `{version: 1, notebook, minimumMode: 2}` to the notebook's `.siyuan/document-addressing.json`. It contains only identity and version information and accompanies native notebook exports, backups, and sync. The workspace retains confirmed minimum modes keyed by notebook ID in `conf/document-addressing.json`. Effective mode is the strictest requirement from valid configuration, notebook and local floors, and valid recovery records. Records do not authenticate ciphertext. Unknown versions, invalid fields, or mismatched identities preserve original files and refuse processing rather than defaulting to mode `1`.The local record uses `{version: 1, notebooks: {"<notebookID>": 2}}`, omitting notebooks with no higher requirement. Reading ordinary compatibility-mode data creates no record and rewrites no source data. Replace the record atomically and merge by taking the maximum for each identity, never by overwriting it with an older record. Once a local read or sync or snapshot preflight has observed a valid higher requirement, retain it even if insufficient capability rejects that batch, so the next read of older local configuration cannot resume ordinary writes. Remembering a capability requirement does not activate structured titles. Inspecting a standalone native notebook import does not record a source identity that has not been adopted into the workspace.@@ -402,11 +402,11 @@ The protective release recognizes both configuration and capability floor recordDeleting an entire notebook retains existing semantics; do not recreate it merely to restore a capability record. Keep the locally confirmed floor for that identity and apply it when the same identity is restored. Native imports of whole notebooks validate the source identity and capability record before allocating or reusing the destination identity under existing import rules, then bind the floor to that destination identity. Identity remapping must not lower the source notebook's confirmed mode. Importing selected documents into an existing notebook instead checks the complete operation set described above without copying the source notebook's mode configuration.-Normal activation coordinates the local floor, notebook floor, and configuration writes through a durable record containing only identity and stage information. After interruption, complete the confirmed activation decision without retracting a mode requirement already written. Enter `modeState: "structured"` only once indexes and records are consistent. The configuration revision covers these activation states and records rather than just ordinary configuration modification time.+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.-If a valid activation record exists but configuration lags, recovery may proceed automatically under the confirmed mode. Without a valid activation record, finding source titles that require mode `2` enters `modeState: "conflict"` and rejects ordinary writes. Under authorization and encrypted-notebook leases, administrators can inspect source formats and required capabilities through an independent read-only scan. That scan does not depend on derived indexes, modify source files, or tolerate unknown formats or unauthenticated ciphertext.+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.-After the user explicitly chooses recovery to mode `2`, `enableStructuredTitles` validates the latest `expectedRevision`, local compatibility, and source inspection results. It first persists the activation decision, then enters `modeState: "recovering"` to build indexes; this recovery path does not require the original index to be `ready`. Success enters `structured`. Scan, authentication, or build failure preserves source files, keys, and recovery records, blocks ordinary writes, and reports the error. Retrying continues the same recovery decision instead of downgrading or recreating the notebook. Unknown source formats still require a reader upgrade; explicit activation never bypasses format validation.+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.### Index and task recovery@@ -432,21 +432,21 @@ Derived indexes can be rebuilt only after authenticating source ciphertext and vThe versioned configuration-payload extension retains the existing authenticated container, `siyuan/box-metadata` subkey purpose, and notebook-bound AAD without changing encryption envelopes, AAD semantics, or key derivation. Any later change to those formats requires a separate explicit version, authenticated migration, and interruption recovery design that retains matching keys and backup material. Never regenerate `MasterSalt`, discard keys, or require users to recreate existing encrypted notebooks to avoid incompatibility. Supported formats in documents, history, backups, and sync snapshots must remain recoverable.-## Implementation stages and activation gates+## Implementation stages and release gates| Stage | Deliverables | Completion criteria || --- | --- | --- || 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 | Mode activation and conflict recovery, legacy API rejection, plugin migration guidance, cross-mode operations, and import/export checks | Whole-subtree preflight, mode recovery, and all activation gates pass before explicit user activation of `/` |+| 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 || 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.-Activation 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 activation, plugin impact, and sync-device requirements.+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.-Implementation still needs actual release version numbers, an available `.sy` version allocation, performance measurements, and compatibility test results. These are release evidence, not unresolved decisions about identity, templates, plugin boundaries, or failure semantics. Proposed endpoints and fields must become verifiable contracts; finishing this document or rebuilding an index once is not feature acceptance.+The implementation allocates `.sy` specification `6`. Release still requires the actual protective release number, performance measurements, and compatibility results. These are release evidence, not unresolved decisions about identity, templates, plugin boundaries, or failure semantics. Completing documentation, passing isolated tests, or rebuilding an index once does not establish full feature acceptance.## Verification and acceptance@@ -474,9 +474,9 @@ Create a root document `A/B`, a root document `A` with child `B`, a root documenHave two requests resolve the same missing ancestor and submit the same absence condition; exactly one succeeds and the other returns `planChanged`, while ordinary same-named final documents can still be created separately. A second same-named candidate invalidates a previously unique ancestor condition. Changing the destination notebook, inherited configuration, or body-template path after preview must reject submission even with the same parent path revision. Cover rename and configuration-update races between final validation and commit.-Build a subtree with an ordinary root title but descendants containing `/` or a new title representation. Moves, copies, imports, and recovery into mode `1` all fail before the first write, and descendant changes after preflight are detected. Retry successfully after explicit destination activation without relaxing encryption boundaries. Documents with other newer body features but compatible titles must not be misclassified as requiring mode `2`.+Build a subtree with an ordinary root title but descendants containing `/` or a new title representation. Using a reader without the required capabilities, moves, copies, imports, and recovery all fail before the first source write; descendant changes after preflight are detected. Retry successfully after upgrading the destination and completing automatic recovery without relaxing encryption boundaries. Documents with other newer body features but compatible titles must not be misclassified as requiring mode `2`.-Simulate old-configuration replacement, missing or corrupt capability records, interrupted sync, and source documents already requiring mode `2` while indexes remain unavailable. Verify that effective mode never decreases, unknown formats preserve original data, explicit activation can enter independent recovery, and restart resumes the original recovery decision. Cover deletion followed by restoration of the same notebook identity, and preservation of capability floors when whole-notebook imports remap identities. Inspect new configuration payload persistence and locked responses and caches for absence of plaintext target objects, and verify old payload reads and recovery after backups and password changes.+Simulate old-configuration replacement, missing or corrupt capability records, interrupted sync, and source documents already requiring mode `2` while indexes remain unavailable. Verify that effective mode never decreases, unknown formats preserve original data, automatic migration works without a setting or ready index, and restart continues the same recovery task. Inject failures at every migration write, cover deletion and restoration of the same notebook identity, and preserve capability floors when imports remap identities. Inspect new payload persistence and locked responses and caches for absence of plaintext target objects, and verify old payload reads and recovery after backups and password changes.Retain `TestHeadingDocParagraph` and `TestHeadingDocParagraphTextMark` so foundational separation continues covering images, links, and original heading content preserved in the body. Stage E additionally verifies supported nodes in title sources and both conversion directions without deleting user paragraphs based on equal plain text. Template document trees cover grouped undo and redo, partial commits, name or ID conflicts on redo, and user edits after creation, not just successful creation.@@ -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`.-Change CI filters or maintenance guides only if existing discovery would miss new tests. These are implementation acceptance requirements, not functional tests already executed for this design document. Documentation changes themselves verify bilingual consistency, examples, links, and diff formatting.+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.## Related codediff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.mdindex e7540597e6..4ee2dce4d8 100644--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md@@ -4,7 +4,7 @@关联问题:[Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938)、[Improve content preservation when converting headings to documents](https://github.com/siyuan-note/siyuan/issues/19235)-本文为实施设计草案,规定文档标题、层级定位、可读路径、接口及迁移的目标行为。下文新增的字段、接口和版本机制均为拟实现契约,不表示当前版本已经支持。当前重命名与路径索引的更新机制见 [文档重命名与路径索引](DOCUMENT-HPATH.md)。+本文规定文档标题、层级定位、可读路径、接口及迁移的目标行为。当前开发实现和发布条件分别说明,不能将开发分支能力视为已发布能力。当前重命名与路径索引的更新机制见 [文档重命名与路径索引](DOCUMENT-HPATH.md)。### 当前实现范围@@ -14,7 +14,7 @@管理员读取笔记本配置时可获取 `documentCapabilities`,区分结构化接口、实际寻址模式和索引状态。未验证真实保护版本时,`minimumReaderVersion` 返回 `null`,不会伪造最低版本;能力记录损坏时明确报错。原生整本导入会同步重映射目标配置中的笔记本和锚点 ID,部分文档导入保留目标笔记本配置。加密目标载荷保持锁定保存、改密及备份恢复的认证边界。-目前只开放兼容模式 `1`,仍拒绝标题中的 ASCII `/`,版本 `2` 目标配置的公开写入仍受模式门槛限制。显式启用入口、模式 `2` 的源格式与冲突恢复、旧字符串接口的整本拒绝以及相应启用界面尚未交付;不能把这些工作视为仅待发布开关。阶段 D 还需结合真实保护版本的验证结果确定最低读取版本和 `DocumentTitleSpec`,完成混合版本、性能及各端验收后开放。行级标题扩展约束保持不变。+结构化标题功能版本默认采用模式 `2`,不提供用户开关或手动启用接口。开发分支已实现自动模式迁移与中断恢复、`DocumentTitleSpec = "6"`、标题斜杠读写及旧字符串接口的整本拒绝;前端通过只读运行时能力决定标题输入规则。当前普通构建仍处于保护阶段:发布门槛中的真实最低读取版本尚未填写,因此保持模式 `1`;隔离测试通过测试链接参数覆盖模式 `2`。发布前仍须完成真实保护版本、混合版本、性能及各端验收,之后功能版本自动采用新模式。行级标题扩展约束保持不变。## 目标与范围@@ -29,7 +29,7 @@| 项目 | 采用的方案 || --- | --- || 文档定位 | 笔记本 ID 与文档 ID;创建使用独立的父文档身份与标题 |-| 新旧模式 | 按笔记本显式启用结构化标题模式;已有笔记本默认保持兼容模式 |+| 新旧模式 | 功能版本默认采用结构化标题模式,自动迁移已有笔记本;模式记录只用于内部兼容保护,不提供开关 || 插件兼容 | 接受依赖旧 `hPath` 规则的插件适配;先交付替代接口及迁移说明,再启用新字符 || 旧字符串寻址 | 兼容模式保留原有行为;结构化标题模式明确拒绝旧字符串定位与创建入口 || 可读路径 | 保留标题原文并按层级拼接展示;不编码 `/`,不把 `/` 或 `%2F` 解码 |@@ -179,9 +179,9 @@旧模板由兼容编译器按原语法求值,再输出结构化创建计划;另行传入的新标题保持独立,不重新拼入路径字符串。相对起点和向上导航使用当前文档 ID 及父关系,不能先把当前文档的显示路径拆成旧模板段。该内部适配不调用被新模式禁用的公开字符串寻址接口,因此已有日记等配置仍可工作。旧模板内变量产生 `/` 时继续按旧语法分层,只有显式改用新模板后才保留为单段。-模式 `1` 的旧业务入口及旧字符串模板保留既有同名选择和 `parentID` 回退行为;内部实现改用身份后仍须通过旧行为回归,不能因共享严格解析器而悄悄改成歧义错误。新结构化接口在两个模式中均执行严格歧义检查。模式 `2` 的内置业务使用严格计划,即使输入来自旧模板也不得任取同名父文档;这是显式启用时需要说明的行为变化。跨笔记本目标使用新协议时同样保持严格规则,不因目标为模式 `1` 而恢复任取行为。+模式 `1` 的旧业务入口及旧字符串模板保留既有同名选择和 `parentID` 回退行为;内部实现改用身份后仍须通过旧行为回归,不能因共享严格解析器而悄悄改成歧义错误。新结构化接口在两个模式中均执行严格歧义检查。模式 `2` 的内置业务使用严格计划,即使输入来自旧模板也不得任取同名父文档;功能版本的迁移说明须说明这一行为变化。跨笔记本目标使用新协议时同样保持严格规则,不因目标为模式 `1` 而恢复任取行为。-新配置分别使用 `docCreateTarget`、`refCreateTarget`、`dailyNoteTarget`,与原保存路径字符串字段并存。首版仅在已启用模式 `2` 的笔记本配置中开放这三个对象,全局配置继续保留旧字符串模板及现有继承规则,避免未经笔记本启用便引入旧客户端无法识别的配置。对象必须带 `version: 2`,指定目标笔记本、起点、向上层数、祖先段、最终标题和缺失祖先策略;各段继续复用现有保存路径模板求值器。示例中的 `{{now | date ...}}` 是保存路径模板语法,不能与正文模板语法混淆。+新配置分别使用 `docCreateTarget`、`refCreateTarget`、`dailyNoteTarget`,与原保存路径字符串字段并存。功能版本在自动迁移为模式 `2` 的笔记本配置中开放这三个对象,全局配置继续保留旧字符串模板及现有继承规则,保持与保护版本兼容。对象必须带 `version: 2`,指定目标笔记本、起点、向上层数、祖先段、最终标题和缺失祖先策略;各段继续复用现有保存路径模板求值器。示例中的 `{{now | date ...}}` 是保存路径模板语法,不能与正文模板语法混淆。```json{@@ -234,9 +234,9 @@### 跨模式移动与恢复-跨笔记本移动、复制、原生导入及历史恢复在首次写入前检查完整操作集合,包括每个根文档的所有后代。检查目标模式、标题格式和原文、源格式可读性、目标深度及既有加密边界;不能仅检查顶层标题。只要任一文档需要目标尚未启用的标题能力,整次操作返回 `targetModeUnsupported`,并提供授权范围内的冲突文档 ID;不移动目录、不改写标题、不删除来源,也不自动启用目标模式。+跨笔记本移动、复制、原生导入及历史恢复在首次写入前检查完整操作集合,包括每个根文档的所有后代。检查目标版本支持的能力、标题格式和原文、源格式可读性、目标深度及既有加密边界;不能仅检查顶层标题。功能版本自动补齐目标模式记录;若目标读取器仍不支持所需能力,整次操作返回 `targetModeUnsupported`,并提供授权范围内的冲突文档 ID,不移动目录、不改写标题、不删除来源。-用户明确启用目标模式并完成恢复后,重新规划和校验操作。新建目标笔记本的导入流程也先取得明确的模式选择,再提交文档。需要的标题能力由标题格式及实际内容决定;`.sy` 版本表示源格式的读取要求,不把所有高于 `DocumentTitleSpec` 的版本都等同于需要模式 `2`,也不为通过检查而降低源版本。符合目标规则的普通标题可以从模式 `2` 的笔记本进入模式 `1`。+目标客户端升级并完成自动恢复后,重新规划和校验操作。新建目标笔记本采用当前版本的默认能力,不要求用户选择模式。需要的标题能力由标题格式及实际内容决定;`.sy` 版本表示源格式的读取要求,不把所有高于 `DocumentTitleSpec` 的版本都等同于需要模式 `2`,也不为通过检查而降低源版本。符合目标规则的普通标题可以导出给支持其源格式的兼容读取器。已就绪元数据可用于检查完整子树,导入和历史使用对应的已认证源快照;缺失或过期索引先恢复,不用旧 `hPath` 推断能力。预检记录整个操作集合的身份、成员及标题和位置版本,提交在变更协调范围内复核,防止预检后后代改名或新增。可预知的不兼容必须在任何写入前拒绝;实际 I/O 失败沿用部分提交记录及恢复规则,不承诺跨文件原子移动。普通与加密笔记本之间、不同加密笔记本之间的既有隔离规则保持不变。@@ -315,7 +315,7 @@| `legacyPathUnsupported` | 目标笔记本禁用旧字符串寻址,改用新接口 || `indexUnavailable` | 结构化元数据未就绪,等待恢复,不回退到显示路径 || `unsupportedTitleFormat` | 客户端或接口不能处理标题格式,升级或改用对应格式接口 |-| `targetModeUnsupported` | 移动、复制、导入或恢复的完整操作集合超出目标模式;明确启用目标后重新规划 |+| `targetModeUnsupported` | 移动、复制、导入或恢复的完整操作集合超出目标支持能力;升级目标并完成自动恢复后重新规划 || `modeConflict` | 笔记本模式记录与源标题能力不一致,进入受控恢复,不按兼容模式继续写入 || `writeFailed` | 写入或后续处理失败,依据 `commitState` 及阶段恢复 |@@ -331,13 +331,13 @@调用方依次提交每个 `createDocByParent` 请求,用上一项成功响应的路径版本更新下一项的父版本。提交后以返回 ID 为准;错误按提交状态处理,不能重新生成一组 ID 并盲目重放。单次计划不是跨文件事务,计划期间的成功校验也不代替每次提交时的复核。-### 能力探测与启用+### 能力探测与自动迁移在 `/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` 是启用流程相关的配置版本;它不等同于某篇文档的路径版本。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。+`revision` 是模式记录及恢复状态的版本摘要,不等同于某篇文档的路径版本,也不用于用户启用流程。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。-`/api/notebook/enableStructuredTitles` 接收 `notebook` 与 `expectedRevision`。正常从兼容模式启用时,先核查当前配置版本、就绪索引及客户端本地兼容能力,再持久化模式 `2`;模式冲突恢复按后文专门流程执行,不要求冲突状态下先有就绪索引。接口返回最新 `documentCapabilities`,`recovering` 只表示启用决定已持久化,写入仍等待恢复完成。已经启用且版本匹配时可直接返回当前状态。此接口不能证明所有离线同步客户端都已升级;启用界面需要说明最低版本和插件适配要求,由用户明确启用。通用配置更新不能绕过此流程切换模式,省略新字段的旧请求也不能将模式重置为 `1`。+不提供手动启用接口或设置项。功能版本在访问笔记本源数据前自动确认模式并补齐持久化记录,正常迁移与中断恢复使用同一流程;此过程不要求旧索引预先就绪。`recovering` 表示模式记录尚未一致或索引尚未就绪,不能据此宣称结构化写入已经可用。通用配置更新不能降低内部模式,旧请求省略新字段也不能将模式重置为 `1`。`getConf` 的 `documentAddressingVersion` 只读字段声明当前发行版的默认能力,供桌面、浏览器和移动端初始化输入规则,不保存为用户设置;笔记本实际可用性仍以 `documentCapabilities` 为准。### 契约及声明维护@@ -345,7 +345,7 @@## 接口与插件兼容-模式 `1` 为兼容模式;模式 `2` 为显式启用的结构化标题模式。没有模式字段且没有更高能力记录的旧笔记本按 `1` 读取;已有能力下界不能被缺省字段覆盖。模式决定旧协议是否可用,不根据某一次请求是否恰好包含 `/` 猜测。+模式 `1` 为保护版本使用的兼容模式;模式 `2` 为功能版本自动采用的结构化标题模式。旧笔记本记录缺失且没有更高能力记录时,其源记录按 `1` 解释,功能版本在源访问前自动迁移到 `2`;缺省字段不能覆盖已有能力下界。模式决定旧协议是否可用,不根据某一次请求是否恰好包含 `/` 猜测。| 使用场景 | 兼容模式 `1` | 结构化标题模式 `2` | 插件迁移方式 || --- | --- | --- | --- |@@ -372,13 +372,13 @@### 混合版本访问-笔记本配置新增 `documentAddressingVersion`,字段缺省或 `1` 表示兼容模式,`2` 表示结构化标题模式;有效模式还须结合后文的能力下界记录,不能只读取这个字段。该字段与加密信封版本独立,不能复用 `BoxCrypt.Spec`。新旧模式不批量改写已有文档标题或 ID;开启能力只改变后续操作准入和新内容的表示规则。+笔记本配置保存内部兼容标记 `documentAddressingVersion`:字段缺省或 `1` 表示兼容记录,`2` 表示结构化标题记录;有效模式还须结合后文的能力下界与恢复记录,不能只读取这个字段。该标记不是用户配置项,与加密信封版本独立,不能复用 `BoxCrypt.Spec`。功能版本自动迁移记录,不批量改写已有文档标题或 ID。-即使 `.sy` 仍保存字符串标题,旧客户端也可能移除 `/`,或把标题文字当作层级。发布分两步:先发布理解笔记本能力标记、能够安全拒绝未知模式的保护版本,再发布允许启用模式 `2` 的功能版本。保护版本在挂载、索引、修复、编辑及同步应用入口拒绝处理不支持的模式,不能先修改数据再提示升级。+即使 `.sy` 仍保存字符串标题,旧客户端也可能移除 `/`,或把标题文字当作层级。发布分两步:先发布理解笔记本能力及恢复标记、能够安全拒绝未知模式的保护版本,再发布默认采用模式 `2` 的功能版本。保护版本在挂载、索引、修复、编辑及同步应用入口拒绝处理不支持的模式,不能先修改数据再提示升级。-真正使用新标题能力的文档采用新的 `DocumentTitleSpec`;具体数值在实现时按当时已使用的 `.sy` 版本分配,不在草案中预占某个数字。未使用新能力的文档不因笔记本启用而全部改写。未来富文本表示还需对应的明确格式版本,未知内容不得被容错解析后覆盖。+真正使用新标题能力的文档采用 `DocumentTitleSpec = "6"`:标题包含 ASCII `/` 时,正常写入将文档 `Spec` 至少提升到 `6`。普通标题仍按正文所需规格保存,不能因升级客户端、迁移模式或普通格式化而全部提升到 `6`,也不降低已有版本。未来富文本表示还需对应的明确格式版本,未知内容不得被容错解析后覆盖。-版本保护必须覆盖完整读取、仅属性读取、只读路径恢复、导入、历史、备份及同步。`readDocIAL` 的严格与非严格分支均须验证源版本;流式 `DocIAL` 读取不能因先遇到属性就跳过其后的 `Spec`,版本错误也不能进入损坏文件修复。仅在普通编辑加载处添加检查不能证明完整受保护。源标题格式或实际内容要求模式 `2` 而笔记本有效模式仍为 `1` 时,先返回 `modeConflict`;导入只能在明确选择启用后继续,不能偷偷清理标题以适配旧模式。版本较新的其他正文功能不自动要求结构化标题模式。+版本保护必须覆盖完整读取、仅属性读取、只读路径恢复、导入、历史、备份及同步。`readDocIAL` 的严格与非严格分支均须验证源版本;流式 `DocIAL` 读取不能因先遇到属性就跳过其后的 `Spec`,版本错误也不能进入损坏文件修复。源标题需要模式 `2` 而当前读取器只支持模式 `1` 时拒绝访问;功能版本先完成自动模式迁移再处理受支持源格式。不能偷偷清理标题以适配旧模式,版本较新的其他正文功能也不自动要求结构化标题模式。兼容模式在容错解析、规范化及修复前检查解码后的根标题是否包含 ASCII `/`。存储属性的转义只解码一次,保留 HTML 实体、`/`、`%2F` 和 Markdown 的字面内容;重复的根属性或版本字段不能遮盖此前遇到的不兼容值。未知标题表示保留源格式错误,不进入属性修复。原生导入在安装资源、创建笔记本或重新分配 ID 前检查全部源文档;仅发现冲突不会启用模式或生成已确认的能力下界。@@ -386,13 +386,13 @@原始文件接口中的笔记本及文档 ID 路径同样受源格式检查保护,不能通过上传、复制或移入文件绕过。整批预检在创建目标目录及首次复制前完成,实际文档复制使用已经校验的读取字节,并在文件锁内重新检查目标源;检查后的并发变化或 I/O 失败仍可能留下已完成的复制,不承诺整批回滚。普通附件和插件目录下的 `.sy` 文件保持原始文件语义,加密笔记本仍禁止通过原始文件接口读写。-最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。启用前要求所有同步设备升级;系统无法证明离线设备状态,应明确说明这一限制。如果已支持版本仍存在会改写数据的路径,保持新能力关闭,不能以文档提示代替必要保护。+最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。使用功能版本前要求所有同步设备至少升级到保护版本;系统无法证明离线设备状态,发布说明及用户指南须说明这一限制。如果保护仍存在缺口,继续保留发布门槛,不能以文档提示或用户开关代替必要保护。-模式 `2` 启用后不提供直接改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复启用前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。+自动迁移到模式 `2` 后不提供改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复升级前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。### 模式记录与冲突恢复-启用时在笔记本 `.siyuan/document-addressing.json` 写入独立的能力下界记录 `{version: 1, notebook, minimumMode: 2}`,只含身份及版本,随原生笔记本导出、备份和同步保存。本机另在工作空间 `conf/document-addressing.json` 保留按笔记本 ID 索引的已确认最低模式;它参与工作空间配置备份,不作为标题或密钥的存储位置。有效模式取合法笔记本配置、能力下界记录和本机已确认记录中最严格的要求。记录不是密文认证凭据;未知记录版本、无效字段或身份不匹配必须保留原文件并拒绝处理,不能按缺省模式 `1` 继续。+自动迁移在笔记本 `.siyuan/document-addressing.json` 写入独立的能力下界记录 `{version: 1, notebook, minimumMode: 2}`,只含身份及版本,随原生笔记本导出、备份和同步保存。本机另在工作空间 `conf/document-addressing.json` 保留按笔记本 ID 索引的已确认最低模式。有效模式取合法笔记本配置、笔记本下界、本机下界及有效恢复记录中最严格的要求。记录不是密文认证凭据;未知版本、无效字段或身份不匹配必须保留原文件并拒绝处理,不能按缺省模式 `1` 继续。本机记录采用 `{version: 1, notebooks: {"<notebookID>": 2}}`,省略尚无较高要求的笔记本;普通兼容模式读取不创建记录或改写源数据。记录写入必须原子替换,合并时逐个身份取最大值,不能用较旧记录整体覆盖。本机或同步、快照预检已经读到合法的较高要求时,即使本次批次因能力不足被拒绝,也保留该要求,防止下一次读取旧的本地配置时恢复普通写入;记住能力要求不等于启用结构化标题。导入时尚未采用的独立原生笔记本身份不因此写入本机记录。@@ -402,11 +402,11 @@删除整个笔记本仍按现有语义执行,不为补齐能力记录而重新创建已删除的笔记本;本机保留该身份的已确认下界,恢复同一身份时继续生效。完整笔记本的原生导入先校验源身份与能力记录,再按既有导入规则分配或复用目标身份,并将能力下界绑定到目标身份;不得借身份重映射降低源笔记本已确认的模式。向既有笔记本导入部分文档则按前述完整操作集合检查,不直接复制源笔记本的模式配置。-正常启用通过仅含身份和阶段的持久化记录协调本机下界、笔记本下界及配置写入;任一步骤中断后继续完成已确认的启用决定,不撤回已经写入的模式要求。索引完成、记录一致后才进入 `modeState: "structured"`。配置版本覆盖这些启用状态及记录,不能仅取普通配置的修改时间。+自动迁移先在 `conf/document-addressing-recovery/<notebookID>.json` 持久化 `{version: 1, notebook, phase: "records"}`,再依次写入本机下界、笔记本下界及配置中的模式标记,最后删除该恢复记录。任一步骤中断后,下次访问继续同一迁移,不撤回已写入的模式要求;保护版本也必须将有效恢复记录视为至少需要模式 `2`。配置的未知字段及加密载荷原值保留,不扫描或批量重写 `.sy` 文件,原始文件接口不能覆盖该恢复目录。-已有有效启用记录而配置落后时,可以按已确认的模式自动恢复。没有有效启用记录、但发现源标题需要模式 `2` 时,进入 `modeState: "conflict"`,拒绝普通写入。管理员可在授权和加密租约内通过独立只读扫描检查源格式及所需能力;该扫描不依赖派生索引,不更改源文件,也不容错接受未知格式或未认证密文。+功能版本在已有模式记录缺失或配置落后时自动补齐,已删除的笔记本不能因恢复而重建。模式迁移与索引重建分开:元数据迁移不依赖就绪索引,也不认证或改写文档密文;后续源读取和索引构建仍必须在原授权及加密租约内先认证源内容。只有模式记录一致且索引就绪时才对外报告 `modeState: "structured"`。-用户明确选择恢复为模式 `2` 后,通过 `enableStructuredTitles` 校验最新 `expectedRevision`、本地兼容能力和源检查结果,先持久化启用决定,再进入 `modeState: "recovering"` 构建索引;这条恢复路径不以原索引 `ready` 为前置条件。成功后进入 `structured`;扫描、认证或构建失败时保留源文件、密钥和恢复记录,停止普通写入并报告错误。重试继续同一恢复决定,不能为了消除错误而降级或重建笔记本。未知源格式仍须升级读取器,明确启用不等于允许跳过格式检查。+模式记录恢复失败时保留恢复记录并报错;索引缺失或重建未完成时报告 `recovering`,结构化写入等待所需索引就绪。源格式未知、文件损坏或认证失败时保留原文件、密钥及待恢复任务,停止受影响操作并报告错误。再次访问或重新启动按既有恢复机制继续,不要求用户选择模式,也不能降级、重建笔记本或跳过格式校验来消除错误。### 索引与任务恢复@@ -439,14 +439,14 @@| A:兼容保护 | 笔记本能力下界及冲突识别、未知模式及源版本保护、旧行为回归样本 | 已发布保护版本;同步及快照应用前验证模式,所有写入与修复入口安全拒绝未知模式 || B:内部解耦 | 统一标题读取、文档元数据、ID 层级计算、路径刷新及恢复 | 普通标题行为不变;结构不再从显示字符串推导,加密索引可认证重建 || C:接口与调用方 | 新读取、解析、条件创建接口,版本 `2` 模板及加密载荷,内置业务及各端迁移 | 名称与配置并发条件、新旧契约通过验证,部分失败及撤销可恢复,日记等业务行为保持 |-| D:开放新字符 | 模式启用与冲突恢复入口、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 完整子树预检、模式恢复和全部开放条件满足后才允许用户显式启用 `/` |+| D:开放新字符 | 默认采用新模式及自动恢复、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 完整子树预检、模式恢复和全部发布条件通过后,功能版本默认支持 `/` || E:行级标题 | 独立的源格式、编辑及渲染设计 | 保持本方案身份接口,完成格式及旧写入保护后另行交付 |阶段 B、C 可以在保留旧标题限制时先行交付;新字符的开放必须等待 A 至 D 所需条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。-开放条件包括:所有内置消费者已迁移;替代接口和插件适配文档已发布;已验证最低客户端版本及混合版本拒绝;普通与加密索引迁移可中断恢复;导入导出不会因显示路径冲突覆盖文件;桌面、浏览器和移动端行为一致;四种语言的用户指南说明启用方式、插件影响和同步设备要求。+开放条件包括:所有内置消费者已迁移;替代接口和插件适配文档已发布;已验证最低客户端版本及混合版本拒绝;普通与加密索引迁移可中断恢复;导入导出不会因显示路径冲突覆盖文件;桌面、浏览器和移动端行为一致;四种语言的用户指南说明默认行为、插件影响和同步设备要求。-实施时还需登记实际发布版本号、分配未冲突的 `.sy` 版本号,并附上性能测量与兼容测试结果。这些是发布证据,不是重新悬置身份、模板、插件边界或失败语义的决策。本文中的接口和字段需落实为可验证契约,不能以完成文档或一次索引重建代替功能验收。+实施已分配 `.sy` 规格 `6`;发布前仍需登记实际保护版本号,并附上性能测量与兼容测试结果。这些是发布证据,不是重新悬置身份、模板、插件边界或失败语义的决策。不能以完成文档、通过隔离测试或一次索引重建代替全部功能验收。## 验证与验收@@ -474,9 +474,9 @@两个请求同时解析缺失祖先并提交同一不存在条件,验证只成功一次,另一次返回 `planChanged`;普通同名最终文档仍可分别创建。已匹配祖先出现第二个同名文档时,唯一身份条件失败。配置预览后改变目标笔记本、继承配置或正文模板路径,即使父路径版本相同也须拒绝;重命名与配置更新发生在最后校验和提交之间的竞争也需覆盖。-构造标题普通但后代包含 `/` 或新标题格式的子树,向模式 `1` 移动、复制、导入和恢复均在首次写入前拒绝;预检后后代变化也须被发现。目标明确启用后重新执行成功,既有加密边界不放宽。仅使用其他新版正文功能而标题仍兼容的文档不得被误判为需要模式 `2`。+构造标题普通但后代包含 `/` 或新标题格式的子树,使用不支持相应能力的读取器移动、复制、导入和恢复,均在首次源写入前拒绝;预检后后代变化也须被发现。目标升级并完成自动恢复后重新执行成功,既有加密边界不放宽。仅使用其他新版正文功能而标题仍兼容的文档不得被误判为需要模式 `2`。-模拟旧配置覆盖、能力记录缺失或损坏、同步中断,以及源文档已经需要模式 `2` 但索引尚不可用的场景。验证有效模式不下降、未知格式保留原数据、明确启用可进入独立恢复流程、重启继续原恢复决定。覆盖整本删除后按同一身份恢复,以及完整导入重映射笔记本身份时保留能力下界。对新配置载荷检查磁盘及锁定后的接口和缓存均无新目标对象明文,并验证旧载荷读取及备份、改密后的恢复。+模拟旧配置覆盖、能力记录缺失或损坏、同步中断,以及源文档已经需要模式 `2` 但索引尚不可用的场景。验证有效模式不下降、未知格式保留原数据、无开关的自动迁移可在索引未就绪时进行、重启继续同一恢复任务。覆盖迁移每一步的写入故障、整本删除后按同一身份恢复,以及完整导入重映射笔记本身份时保留能力下界。对新配置载荷检查磁盘及锁定后的接口和缓存均无新目标对象明文,并验证旧载荷读取及备份、改密后的恢复。保留 `TestHeadingDocParagraph` 与 `TestHeadingDocParagraphTextMark`,基础解耦继续覆盖图片、链接和原标题内容进入正文的行为;阶段 E 再验证支持的节点进入标题源内容及双向转换,不按纯文本相等删除用户段落。模板文档树覆盖整组撤销和重做、部分提交、重做时的名称或 ID 冲突及创建后用户编辑,不能只测试新建成功。@@ -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 契约。该值仅用于隔离测试,不是实际最低版本;默认构建继续验证保护行为。以上完整验收要求不等于已全部执行,文档修改另检查双语一致性、示例、链接及差异格式。## 相关代码diff --git a/docs/SY-FORMAT.md b/docs/SY-FORMAT.mdindex 1877c9680d..fa74bdb19e 100644--- a/docs/SY-FORMAT.md+++ b/docs/SY-FORMAT.md@@ -2,7 +2,7 @@[中文](SY-FORMAT.zh-CN.md)-> Canonical Spec baseline: `2` for ordinary documents, `3` for documents containing tabs, `4` for documents using table-cell rich text, `5` for documents containing mind map nodes; compatible readers may upgrade older or missing versions.+> Canonical Spec baseline: `2` for ordinary documents, `3` for documents containing tabs, `4` for documents using table-cell rich text, `5` for documents containing mind map nodes, and `6` for document titles containing ASCII `/`; compatible readers may upgrade older or missing versions.> Verified against samples: `20200825162036-4dx365o.sy` (formatting elements), `20200905090211-2vixtlf.sy` (block types).> All conclusions are based on real samples and the current Lute / SiYuan kernel source. The cited samples contain a few known legacy artifacts; canonical write rules follow the current source when a sample differs.> This guide describes plaintext `.sy` JSON in an ordinary notebook, or the decrypted AST of an unlocked encrypted notebook. An encrypted notebook's on-disk `.sy` file is ciphertext and must not be edited as JSON.@@ -73,11 +73,13 @@ Division of labor among the four paths:| Top-level key | Required | Meaning ||---|---|---|| `ID` | ✅ | Document block ID. **Equals the filename without `.sy`** |-| `Spec` | ✅ | `"2"` for ordinary documents, `"3"` for tabs documents, `"4"` for documents using table-cell rich text, `"5"` for documents containing mind map nodes; older or missing values are compatible input and may be upgraded |+| `Spec` | ✅ | `"2"` for ordinary documents, `"3"` for tabs, `"4"` for table-cell rich text, `"5"` for mind map nodes, `"6"` for titles containing ASCII `/`; use at least the highest required feature version and never lower an existing version || `Type` | ✅ | `"NodeDocument"` || `Properties` | ✅ | Document-level IAL — see §8 || `Children` | ✅ | Array of body child blocks; canonical files contain at least one block |+Spec `6` retains the ordinary `Properties.title` string representation and requires structured document addressing when the title contains ASCII `/`. The feature release adopts that addressing mode automatically; it does not rewrite old document sources just to migrate notebook records. Existing `/`, `%2F`, Markdown-like text, and HTML entity text retain their literal meaning. This specification does not enable inline formatting in titles. Encrypted notebooks authenticate the existing ciphertext envelope before interpreting the same JSON; key derivation, AAD, and recovery material remain unchanged. See [Document titles and addressing](DOCUMENT-ADDRESSING.md) for release protection and migration requirements.+> ⚠️ The file path strictly corresponds to the root ID: `data/<box>/<...>/<rootID>.sy`. Changing the root ID means renaming the file — don't change it casually. For the full file-system layout see [`WORKSPACE.md`](./WORKSPACE.md).> A compatible reader inserts an empty paragraph when `Children` is missing or empty, but new writers should emit that paragraph themselves.@@ -344,7 +346,7 @@ The table lists the five built-in types and their defaults. However, custom `Cal`NodeTabs.Properties["tabs-task"] = "true"` enables task status for every direct tab item; items without an explicit marker default to incomplete. `NodeTabItem.Properties["tabs-task"]` optionally preserves the original task-list marker. Without the group setting, absence means an ordinary tab. One ASCII space means incomplete, and other supported single-character task markers (including `X`, `/`, and `?`) retain their exact values. Task status is independent of title content and active-tab selection. Markdown export preserves the group setting in the group IAL and item states in an item IAL immediately after the `@tab` title line, for example `{: tabs-task="/"}`. Attribute values must use the same escaping as other IAL values. Conversion back to a task list restores the current marker; conversion to an ordinary list removes the task attribute. Existing item-only task states and mixed groups remain supported.-Documents containing either tab node require at least `Spec: "3"`; documents using table-cell rich text use Spec 4, and documents containing mind map nodes use Spec 5. Ordinary documents remain on Spec 2. Never lower the version after removing a feature. Check the raw root `Spec` before passing JSON to a tolerant parser, because unknown node types can otherwise cause their children to be lost. Unsupported versions must not be repaired and written back.+Documents containing either tab node require at least `Spec: "3"`; table-cell rich text requires Spec 4, mind map nodes require Spec 5, and document titles containing ASCII `/` require Spec 6. Ordinary documents remain on Spec 2. Never lower the version after removing a feature. Check the raw root `Spec` before passing JSON to a tolerant parser, because unknown node types can otherwise cause their children to be lost. Unsupported versions must not be repaired and written back.The internal Markdown syntax uses `::: tabs` to open a group and `@tab <inline title>` to start each item; `@tab:active <inline title>` identifies the selected item. The opening fence requires at least three colons and whitespace (spaces or tabs) before `tabs`; canonical output uses one space. Items have no closing marker; the group closes with a standalone fence containing the same number of colons as its opening fence. Outer fences must be longer than nested fences. Indentation is optional, and canonical output computes fence lengths from nesting depth without adding indentation to tab bodies. Old `:::tabs` and `:::tab` syntax is not recognized; existing `.sy` tab nodes retain the same structure.@@ -645,7 +647,7 @@ Canonical writers must not generate the following syntax or node families. MostWhen generating or compatibly editing a `.sy` that SiYuan can load cleanly, verify item by item:-1. ☐ Root `Type` = `"NodeDocument"`, `Spec` = `"2"`, `"3"` (tabs), `"4"` (table-cell rich text), or `"5"` (mind map nodes), without lowering an existing version; root `ID` = filename (without `.sy`) and equals `Properties.id`+1. ☐ Root `Type` = `"NodeDocument"`, `Spec` = `"2"`, `"3"` (tabs), `"4"` (table-cell rich text), `"5"` (mind map nodes), or `"6"` (ASCII `/` in document titles), without lowering an existing version; root `ID` = filename (without `.sy`) and equals `Properties.id`2. ☐ Root `Properties` contains `id`/`title`/`type:"doc"`/`updated`3. ☐ Every newly generated ID is fresh and workspace-wide unique; every canonical block has a 22-char `ID`, matching `Properties.id`, and a valid 14-digit `Properties.updated`4. ☐ Determine block status from `Type`, not from `ID`; do not add IDs to new inline/marker nodes, and only remove historical non-block IDs as field normalization without deleting the nodediff --git a/docs/SY-FORMAT.zh-CN.md b/docs/SY-FORMAT.zh-CN.mdindex f9e5f70864..35c1a9f22d 100644--- a/docs/SY-FORMAT.zh-CN.md+++ b/docs/SY-FORMAT.zh-CN.md@@ -2,7 +2,7 @@[English](SY-FORMAT.md)-> 规范写入基准:普通文档为 Spec `2`,包含页签的文档为 Spec `3`,使用表格单元格富文本的文档为 Spec `4`,包含思维导图节点的文档为 Spec `5`;兼容读取器可以升级旧版或缺少 `Spec` 的数据。+> 规范写入基准:普通文档为 Spec `2`,包含页签的文档为 Spec `3`,使用表格单元格富文本的文档为 Spec `4`,包含思维导图节点的文档为 Spec `5`,文档标题包含 ASCII `/` 时为 Spec `6`;兼容读取器可以升级旧版或缺少 `Spec` 的数据。> 核验样本:`20200825162036-4dx365o.sy`(排版元素)、`20200905090211-2vixtlf.sy`(内容块类型)。> 本文档所有结论均基于真实样本及当前 Lute / 思源内核源码核验。上述样本包含少量已知的历史遗留数据;样本与当前源码不一致时,规范写入规则以当前源码为准。> 本指南描述普通笔记本中的明文 `.sy` JSON,或已解锁加密笔记本的解密后 AST。但加密笔记本磁盘上的 `.sy` 文件是密文,不能当作 JSON 直接编辑。@@ -73,11 +73,13 @@| 顶层键 | 必有 | 说明 ||---|---|---|| `ID` | ✅ | 文档块 ID,**等于去掉 `.sy` 后的文件名** |-| `Spec` | ✅ | 普通文档为 `"2"`,页签文档为 `"3"`,使用表格单元格富文本的文档为 `"4"`,包含思维导图节点的文档为 `"5"`;旧值或缺失值属于兼容输入,可以升级 |+| `Spec` | ✅ | 普通文档为 `"2"`,页签为 `"3"`,表格单元格富文本为 `"4"`,思维导图节点为 `"5"`,标题包含 ASCII `/` 时为 `"6"`;至少采用所用功能要求的最高版本,不降低已有版本 || `Type` | ✅ | `"NodeDocument"` || `Properties` | ✅ | 文档级 IAL,见 §8 || `Children` | ✅ | 正文子块数组;规范文件至少包含一个块 |+Spec `6` 保留普通 `Properties.title` 字符串表示;标题包含 ASCII `/` 时要求结构化文档寻址。功能版本自动采用该寻址模式,不为迁移笔记本记录而改写旧文档源文件。已有 `/`、`%2F`、Markdown 样式文字和 HTML 实体文字保留字面含义,此规格不启用标题的行级格式。加密笔记本先认证现有密文封装,再解释相同 JSON,密钥派生、AAD 和恢复材料均不改变。发布保护与迁移要求见 [文档标题与寻址](DOCUMENT-ADDRESSING.zh-CN.md)。+> ⚠️ 文件路径与根 ID 严格对应:`data/<box>/<...>/<根ID>.sy`。改根 ID 等于改文件名,AI 不要随意改根 ID。文件系统的完整布局见 [`WORKSPACE.zh-CN.md`](./WORKSPACE.zh-CN.md)。> 兼容读取器会在 `Children` 缺失或为空时插入空段落,但新写入器应自行写出该段落。@@ -342,7 +344,7 @@ NodeList NodeList`TabItemTitle` 是可省略的行级 Markdown,使用与 `CalloutTitle` 相同的行级文本标记表示,不作为独立子块持久化。允许空标题和重名。子节点数组决定顺序。`tabs-active-id` 指向直属页签项 ID,缺失或失效时回退到第一页。`tabs-position` 仅接受 `top`(默认)和 `left`。两项属性均保存并同步,仅切换选中项不改变正文修改时间。重建块 ID 时,也必须映射选中项 ID 及标题中的内部引用。-包含页签节点的文档必须至少使用 `Spec: "3"`;使用表格单元格富文本的文档为 Spec 4,包含思维导图节点的文档为 Spec 5,普通文档保持 Spec 2。移除功能后不降低版本。向容错解析器传递 JSON 之前,先读取根的原始 `Spec`,避免未知节点的子内容被清空;不得修复并写回不支持的版本。+包含页签节点的文档必须至少使用 `Spec: "3"`;表格单元格富文本至少要求 Spec 4,思维导图节点至少要求 Spec 5,文档标题包含 ASCII `/` 时至少要求 Spec 6,普通文档保持 Spec 2。移除功能后不降低版本。向容错解析器传递 JSON 之前,先读取根的原始 `Spec`,避免未知节点的子内容被清空;不得修复并写回不支持的版本。内部 Markdown 使用 `::: tabs` 开始一组页签,`@tab <行级标题>` 开始一个页签项,`@tab:active <行级标题>` 标识选中项。开始围栏至少包含三个冒号,冒号与 `tabs` 之间需要空格或制表符,规范输出使用一个空格。页签项没有单独的结束标记;整组以独占一行、与开始围栏冒号数量相同的结束围栏闭合。外层围栏必须比内层长,缩进可选;规范输出根据嵌套深度计算围栏长度,不额外缩进页签正文。旧的 `:::tabs`、`:::tab` 语法不再识别,但既有 `.sy` 页签节点结构保持不变。@@ -644,7 +646,7 @@ NodeList NodeList生成或兼容编辑一份能被思源正常加载的 `.sy` 时,应逐条核对:-1. ☐ 根 `Type` = `"NodeDocument"`、`Spec` = `"2"`、`"3"`(页签)、`"4"`(表格单元格富文本)或 `"5"`(思维导图节点),且不降低已有版本;根 `ID` 等于去掉 `.sy` 后的文件名,并等于 `Properties.id`+1. ☐ 根 `Type` = `"NodeDocument"`、`Spec` = `"2"`、`"3"`(页签)、`"4"`(表格单元格富文本)、`"5"`(思维导图节点)或 `"6"`(文档标题包含 ASCII `/`),且不降低已有版本;根 `ID` 等于去掉 `.sy` 后的文件名,并等于 `Properties.id`2. ☐ 根 `Properties` 包含 `id` / `title` / `type:"doc"` / `updated`3. ☐ 每个新生成的 ID 都是新值且在整个工作区中唯一;每个规范块都有 22 字符 `ID`、与之匹配的 `Properties.id`,以及合法的 14 位 `Properties.updated`4. ☐ 根据 `Type` 而不是 `ID` 判断块;不要为新内联或标记节点添加 ID,只能将历史非块 ID 作为字段规范化清理,不能删除节点本身diff --git a/kernel/api/contract_notebook_test.go b/kernel/api/contract_notebook_test.goindex 61278e982a..2ecb989ff3 100644--- a/kernel/api/contract_notebook_test.go+++ b/kernel/api/contract_notebook_test.go@@ -17,8 +17,11 @@ import (func TestAPIContractNotebookConfConversion(t *testing.T) {for _, bytes := range [][]byte{nil, {}, {0, 1, 254, 255}} {value := conf.NewBoxConf()+ value.DocumentAddressingVersion = 2value.BoxCrypt = &conf.BoxEncryption{Spec: 2, WrappedDEK: bytes, WrapNonce: bytes, Metadata: bytes, CreatedAt: 1234567890}- before, err := json.Marshal(value)+ publicFields := *value+ publicFields.DocumentAddressingVersion = 0 // 内部格式标记仅通过只读能力声明,不作为可写配置返回。+ before, err := json.Marshal(&publicFields)if err != nil {t.Fatal(err)}@@ -28,7 +31,9 @@ func TestAPIContractNotebookConfConversion(t *testing.T) {}}value := conf.NewBoxConf()- before, _ := json.Marshal(value)+ publicFields := *value+ publicFields.DocumentAddressingVersion = 0+ before, _ := json.Marshal(&publicFields)after, err := json.Marshal(notebookConfContract(value))if err != nil || string(before) != string(after) {t.Fatalf("unencrypted configuration serialization changed: %v", err)diff --git a/kernel/api/contract_structured_titles_test.go b/kernel/api/contract_structured_titles_test.gonew file mode 100644index 0000000000..031ca631cf--- /dev/null+++ b/kernel/api/contract_structured_titles_test.go@@ -0,0 +1,58 @@+package api++import (+ "bytes"+ "encoding/json"+ "testing"++ "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)+ }+ for _, path := range []string{"/", "/Plain", "/A/B"} {+ data := documentPathAPIRequest(t, "/api/filetree/getIDsByHPath", getIDsByHPath, map[string]string{"notebook": box, "path": path})+ if !bytes.Contains(data, []byte(`"reason":"legacyPathUnsupported"`)) {+ t.Fatal(string(data))+ }+ data = documentPathAPIRequest(t, "/api/filetree/createDocWithMd", createDocWithMd,+ map[string]string{"notebook": box, "path": path, "markdown": "", "parentID": box})+ if !bytes.Contains(data, []byte(`"reason":"legacyPathUnsupported"`)) {+ t.Fatal(string(data))+ }+ }+ read := func() *apicontract.DocumentCapabilities {+ data := documentPathAPIRequest(t, "/api/notebook/getNotebookConf", func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleAdministrator)+ getNotebookConf(c)+ }, map[string]string{"notebook": box})+ var response struct {+ Code int+ Data apicontract.NotebookConfData+ }+ if err := json.Unmarshal(data, &response); err != nil || response.Code != 0 {+ t.Fatal(string(data), err)+ }+ return response.Data.DocumentCapabilities+ }+ if current := read(); current.AddressingVersion != 2 || current.ModeState != "recovering" || current.LiteralSlash {+ t.Fatal("missing index was advertised as ready", current)+ }+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {+ t.Fatal(err)+ }+ if current := read(); current.ModeState != "structured" || !current.LiteralSlash || current.MinimumReaderVersion == nil {+ t.Fatal("automatic mode was not available", current)+ }+}diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 1ddd40f87c..3853a7f4c5 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -32,6 +32,7 @@ import ("github.com/88250/lute/ast""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"@@ -444,19 +445,26 @@ func getFullHPathByIDContract(c *gin.Context, request apicontract.FileTreeOptionvar getIDsByHPath = contractHandler(apicontract.GetIDsByHPath, getIDsByHPathContract)-func getIDsByHPathContract(c *gin.Context, request apicontract.FileTreeOptionalPathRequest) apicontract.Response[[]string] {+func getIDsByHPathContract(c *gin.Context, request apicontract.FileTreeOptionalPathRequest) apicontract.Response[apicontract.LegacyPathIDsResult] {ret := gulu.Ret.NewResult()if request.Path == nil {- return contractFailure[[]string](ret)+ return contractFailure[apicontract.LegacyPathIDsResult](ret)}if request.Notebook == nil {- return contractFailure[[]string](ret)+ return contractFailure[apicontract.LegacyPathIDsResult](ret)}notebook := *request.Notebookif util.InvalidIDPattern(notebook, ret) {- return contractFailure[[]string](ret)+ return contractFailure[apicontract.LegacyPathIDsResult](ret)+ }++ if err := model.CheckLegacyDocumentPath(notebook); err != nil {+ if errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ return apicontract.GetIDsByHPath.FailureWithData(-1, err.Error(), apicontract.UnsupportedLegacyPathIDs())+ }+ return apicontract.Failure[apicontract.LegacyPathIDsResult](-1, err.Error())}p := *request.Path@@ -464,10 +472,10 @@ func getIDsByHPathContract(c *gin.Context, request apicontract.FileTreeOptionalPif err != nil {ret.Code = -1ret.Msg = err.Error()- return contractFailure[[]string](ret)+ return contractFailure[apicontract.LegacyPathIDsResult](ret)}ids = filterFileTreeBlockIDsByPublishDiscoverability(c, ids, notebook)- return apicontract.Success(ids)+ return apicontract.Success(apicontract.NewLegacyPathIDs(ids))}func filterFileTreePathsByPublishMetadataAccess(c *gin.Context, paths []string) (ret []string) {@@ -821,12 +829,19 @@ func createDailyNoteContract(c *gin.Context, request apicontract.FileTreeDailyNovar createDocWithMd = contractHandler(apicontract.CreateDocWithMd, createDocWithMdContract)-func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateMarkdownRequest) apicontract.Response[string] {+func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateMarkdownRequest) apicontract.Response[apicontract.LegacyPathDocumentResult] {ret := gulu.Ret.NewResult()notebook := request.Notebookif util.InvalidIDPattern(notebook, ret) {- return contractFailure[string](ret)+ return contractFailure[apicontract.LegacyPathDocumentResult](ret)+ }++ if err := model.CheckLegacyDocumentPath(notebook); err != nil {+ if errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ return apicontract.CreateDocWithMd.FailureWithData(-1, err.Error(), apicontract.UnsupportedLegacyPathDocument())+ }+ return apicontract.Failure[apicontract.LegacyPathDocumentResult](-1, err.Error())}tags, parentID := request.Tags, request.ParentID@@ -855,9 +870,9 @@ func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateMif err != nil {ret.Code = -1ret.Msg = err.Error()- return contractFailure[string](ret)+ return contractFailure[apicontract.LegacyPathDocumentResult](ret)}- return apicontract.Success(id)+ return apicontract.Success(apicontract.NewLegacyPathDocument(id))}var getDocCreateSavePath = contractHandler(apicontract.GetDocCreateSavePath, getDocCreateSavePathContract)diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 71809809b5..d2712b693d 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -322,13 +322,14 @@ var getNotebookConf = contractHandler(apicontract.GetNotebookConf, func(c *gin.Cif err != nil {return apicontract.Failure[apicontract.NotebookConfData](-1, err.Error())}- modeState := "legacy"- if snapshot.Mode != 1 {- modeState = "conflict"+ modeState := snapshot.State+ indexState := treenode.DocumentMetadataState(notebook)+ if modeState == "structured" && indexState != "ready" {+ modeState = "recovering"}capabilities = &apicontract.DocumentCapabilities{AddressingVersion: snapshot.Mode,- ModeState: modeState, StructuredPaths: true, LiteralSlash: false, TitleFormats: []string{"plain"},- IndexState: treenode.DocumentMetadataState(notebook), Revision: snapshot.Revision}+ ModeState: modeState, StructuredPaths: true, LiteralSlash: modeState == "structured", TitleFormats: []string{"plain"},+ IndexState: indexState, MinimumReaderVersion: documentaddressing.MinimumReaderVersion(), Revision: snapshot.Revision}}return apicontract.Success(apicontract.NotebookConfData{Box: box.ID, Name: box.Name,diff --git a/kernel/api/system.go b/kernel/api/system.goindex c6261ebd26..945f753d55 100644--- a/kernel/api/system.go+++ b/kernel/api/system.go@@ -831,7 +831,7 @@ var getConf = contractHandler(apicontract.SystemGetConf, func(c *gin.Context, rereturn apicontract.Failure[apicontract.SystemConfData](-1, "get conf failed: "+err.Error())}ret = apicontract.Success(apicontract.SystemConfData{Conf: config, Start: !util.IsUILoaded.Load(), IsPublish: isPublish,- SettingTasks: activeSettingTasks(), Revision: revision})+ SettingTasks: activeSettingTasks(), Revision: revision, DocumentAddressingVersion: documentaddressing.DefaultMode()})return})diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 4e9cd79713..1fdda566fa 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. literalSlash remains false until structured- // title mode is implemented and enabled; minimumReaderVersion is null until a protective release- // is verified. Revision covers configuration and confirmed capability records, not a document path.+ // 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.+ // 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.GetNotebookConf = define[CloseNotebookRequest, NotebookConfData]("getNotebookConf", "/api/notebook/getNotebookConf", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")@@ -1068,7 +1069,7 @@ var GetDocPaths = define[GetDocPathsRequest, DocumentPathsResult]("getDocPaths",// 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。// candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。// 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。-// 索引未就绪返回 indexUnavailable;普通标题仍遵守兼容模式限制,不隐式启用新字符。+// 索引未就绪返回 indexUnavailable;功能版本默认保留段内 /,保护版本仍遵守兼容模式限制。var ResolveDocPath = define[ResolveDocPathRequest, ResolveDocPathResult]("resolveDocPath", "/api/filetree/resolveDocPath", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")// CreateDocByParent 在显式父文档 ID 或 null 根位置创建固定 ID 文档,不接收 path/hPath 或名称回退。@@ -1076,7 +1077,8 @@ var ResolveDocPath = define[ResolveDocPathRequest, ResolveDocPathResult]("resolv// 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。// ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。// 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。-// 当前兼容阶段仍不允许标题包含 /,不提升已有文档 Spec;加密笔记本使用原有认证写入与响应租约。+// 功能版本默认保留标题中的 /,该文档写入 Spec 6;普通文档不因迁移统一升级,保护版本仍拒绝 /。+// 加密笔记本使用原有认证写入与响应租约;自动模式迁移不改变密文格式或密钥材料。var CreateDocByParent = define[CreateDocByParentRequest, CreateDocByParentResult]("createDocByParent", "/api/filetree/createDocByParent", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")// GetDocCreateTarget 返回指定用途的有效目标及正文模板,不渲染模板、不猜测上下文或日期。@@ -1092,7 +1094,9 @@ var GetDocCreateTarget = define[GetDocCreateTargetRequest, DocumentCreateTargetDvar PlanDocCreate = define[PlanDocCreateRequest, DocumentCreatePlan]("planDocCreate", "/api/filetree/planDocCreate", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")var GetPathByID = define[FileTreeTrimIDRequest, FileTreeDocPathData]("getPathByID", "/api/filetree/getPathByID", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetFullHPathByID = define[FileTreeOptionalIDRequest, *string]("getFullHPathByID", "/api/filetree/getFullHPathByID", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")-var GetIDsByHPath = define[FileTreeOptionalPathRequest, []string]("getIDsByHPath", "/api/filetree/getIDsByHPath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")++// GetIDsByHPath 在兼容模式保留旧名称路径查询;模式 2 整本返回 legacyPathUnsupported,改用 resolveDocPath。+var GetIDsByHPath = define[FileTreeOptionalPathRequest, LegacyPathIDsResult]("getIDsByHPath", "/api/filetree/getIDsByHPath", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")var MoveDocs = define[FileTreeMoveRequest, Null]("moveDocs", "/api/filetree/moveDocs", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var MoveDocsByID = define[FileTreeMoveIDsRequest, Null]("moveDocsByID", "/api/filetree/moveDocsByID", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RemoveDoc = define[FileTreePathRequest, Null]("removeDoc", "/api/filetree/removeDoc", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")@@ -1109,7 +1113,8 @@ var GetDailyNoteInfo = define[DailyNoteInfoRequest, *DailyNoteInfo]("getDailyNot// 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。// 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。-var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+// 模式 2 对整个笔记本返回 legacyPathUnsupported,即使提供 parentID;改用 createDocByParent。+var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, LegacyPathDocumentResult]("createDocWithMd", "/api/filetree/createDocWithMd", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")// 旧模板保持既有渲染及回退;对应的新目标对象生效时返回 structuredTemplateRequired,不读取历史路径。var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathResult]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")diff --git a/kernel/apicontract/document_addressing.go b/kernel/apicontract/document_addressing.goindex 140f6f1fe7..87fe680147 100644--- a/kernel/apicontract/document_addressing.go+++ b/kernel/apicontract/document_addressing.go@@ -274,6 +274,10 @@ func documentAddressingSchema(b *schemaBuilder, t reflect.Type, input bool) (*Scvar valueType reflect.TypefailureType := reflect.TypeFor[DocumentAddressingFailure]()switch t {+ case reflect.TypeFor[LegacyPathIDsResult]():+ valueType, failureType = reflect.TypeFor[[]string](), reflect.TypeFor[LegacyPathUnsupported]()+ case reflect.TypeFor[LegacyPathDocumentResult]():+ valueType, failureType = reflect.TypeFor[string](), reflect.TypeFor[LegacyPathUnsupported]()case reflect.TypeFor[FileTreeCreateSavePathResult]():valueType, failureType = reflect.TypeFor[FileTreeCreateSavePathData](), reflect.TypeFor[StructuredTemplateRequired]()case reflect.TypeFor[FileTreeSavePathResult]():diff --git a/kernel/apicontract/document_legacy.go b/kernel/apicontract/document_legacy.goindex 4df4c760ca..fd32bee481 100644--- a/kernel/apicontract/document_legacy.go+++ b/kernel/apicontract/document_legacy.go@@ -9,6 +9,44 @@ type StructuredTemplateRequired struct {Reason string `json:"reason" api:"enum=structuredTemplateRequired"`}+type LegacyPathUnsupported struct {+ Reason string `json:"reason" api:"enum=legacyPathUnsupported"`+}++type LegacyPathIDsResult struct {+ value []string+ failure *LegacyPathUnsupported+}++func NewLegacyPathIDs(value []string) LegacyPathIDsResult { return LegacyPathIDsResult{value: value} }+func UnsupportedLegacyPathIDs() LegacyPathIDsResult {+ return LegacyPathIDsResult{failure: &LegacyPathUnsupported{Reason: "legacyPathUnsupported"}}+}+func (result LegacyPathIDsResult) MarshalJSON() ([]byte, error) {+ if result.failure != nil {+ return json.Marshal(result.failure)+ }+ return json.Marshal(result.value)+}++type LegacyPathDocumentResult struct {+ value string+ failure *LegacyPathUnsupported+}++func NewLegacyPathDocument(value string) LegacyPathDocumentResult {+ return LegacyPathDocumentResult{value: value}+}+func UnsupportedLegacyPathDocument() LegacyPathDocumentResult {+ return LegacyPathDocumentResult{failure: &LegacyPathUnsupported{Reason: "legacyPathUnsupported"}}+}+func (result LegacyPathDocumentResult) MarshalJSON() ([]byte, error) {+ if result.failure != nil {+ return json.Marshal(result.failure)+ }+ return json.Marshal(result.value)+}+type FileTreeCreateSavePathResult struct {value *FileTreeCreateSavePathDatafailure *StructuredTemplateRequireddiff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex e4084abc7f..590a1a1a65 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -32147,6 +32147,51 @@],"additionalProperties": false},+ "LegacyPathDocumentResult": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "$ref": "#/$defs/LegacyPathUnsupported"+ }+ ]+ },+ "LegacyPathIDsResult": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ {+ "$ref": "#/$defs/LegacyPathUnsupported"+ }+ ]+ },+ "LegacyPathUnsupported": {+ "type": "object",+ "properties": {+ "reason": {+ "type": "string",+ "enum": [+ "legacyPathUnsupported"+ ]+ }+ },+ "required": [+ "reason"+ ],+ "additionalProperties": false+ },"ListNotebooksData": {"type": "object","properties": {@@ -53640,6 +53685,9 @@}]},+ "documentAddressingVersion": {+ "type": "integer"+ },"isPublish": {"type": "boolean"},@@ -53655,6 +53703,7 @@},"required": ["conf",+ "documentAddressingVersion","isPublish","revision","start"@@ -148016,7 +148065,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/LegacyPathDocumentResult"},"msg": {"type": "string"@@ -148054,6 +148103,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/LegacyPathDocumentResult"}]},@@ -149072,17 +149124,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/LegacyPathIDsResult"},"msg": {"type": "string"@@ -149120,6 +149162,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/LegacyPathIDsResult"}]},diff --git a/kernel/apicontract/system.go b/kernel/apicontract/system.goindex 7152d21cc4..e17b65d898 100644--- a/kernel/apicontract/system.go+++ b/kernel/apicontract/system.go@@ -53,9 +53,11 @@ type SystemMessageData struct {Msg string `json:"msg"`}type SystemConfData struct {- Conf *SystemAppConf `json:"conf"`- Start bool `json:"start"`- IsPublish bool `json:"isPublish"`+ // DocumentAddressingVersion 是当前内核的只读能力,不是持久化配置或可写开关。+ DocumentAddressingVersion int `json:"documentAddressingVersion"`+ Conf *SystemAppConf `json:"conf"`+ Start bool `json:"start"`+ IsPublish bool `json:"isPublish"`// SettingTasks 为当前仍执行的设置维护任务,前端初始化和重连时恢复任务阻塞。SettingTasks *SettingTaskState `json:"settingTasks,omitempty"`// Revision 是读取开始前的配置提交序号,客户端据此丢弃已包含在本次读取中的通知。diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex 9800def33c..98d8605a26 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -297,6 +297,11 @@ var documentInfoCmd = &cobra.Command{}func resolvePath(boxID, userPath, hpath string) (string, error) {+ if userPath == "" && hpath != "" {+ if err := model.CheckLegacyDocumentPath(boxID); err != nil {+ return "", err+ }+ }return resolvePathWithLookup(userPath, hpath, func(targetHPath string) (string, bool) {bt := treenode.GetBlockTreeRootByHPath(boxID, targetHPath)if nil == bt {@@ -325,6 +330,11 @@ func resolvePathWithLookup(userPath, hpath string, lookup func(string) (string,}func resolveDocumentMovePath(boxID, userPath, hpath, sourceTitle string) (string, error) {+ if userPath == "" && hpath != "" {+ if err := model.CheckLegacyDocumentPath(boxID); err != nil {+ return "", err+ }+ }return resolveDocumentMovePathWithLookup(userPath, hpath, sourceTitle, func(targetHPath string) (string, bool) {bt := treenode.GetBlockTreeRootByHPath(boxID, targetHPath)if nil == bt {diff --git a/kernel/cli/cmd/document_test.go b/kernel/cli/cmd/document_test.gonew file mode 100644index 0000000000..fcc580d55a--- /dev/null+++ b/kernel/cli/cmd/document_test.go@@ -0,0 +1,44 @@+package cmd++import (+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/util"+)++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")+ t.Cleanup(func() { util.DataDir, util.ConfDir = previousData, previousConf })+ const boxID = "20261023000000-cli0001"+ name := filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath)+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(name, []byte(`{"name":"Existing"}`), 0644); err != nil {+ t.Fatal(err)+ }+ for _, hpath := range []string{"/", "/Plain", "/A/B"} {+ if _, err := resolvePath(boxID, "", hpath); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ t.Fatalf("legacy read path %q accepted: %v", hpath, err)+ }+ if _, err := resolveDocumentMovePath(boxID, "", hpath, "A/B"); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ t.Fatalf("legacy move path %q accepted: %v", hpath, err)+ }+ }+ const idPath = "/20261023000001-documen.sy"+ if got, err := resolvePath(boxID, idPath, "/ignored"); err != nil || got != idPath {+ t.Fatal("explicit identity path changed", got, err)+ }+ if got, err := resolvePath(boxID, "", ""); err != nil || got != "/" {+ t.Fatal("default root changed", got, err)+ }+}diff --git a/kernel/conf/box.go b/kernel/conf/box.goindex afd664e4d6..73990384be 100644--- a/kernel/conf/box.go+++ b/kernel/conf/box.go@@ -16,28 +16,32 @@package conf-import "github.com/siyuan-note/siyuan/kernel/util"+import (+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/util"+)// BoxConf 维护 .siyuan/conf.json 笔记本配置。type BoxConf struct {- DocCreateTarget *DocumentTarget `json:"docCreateTarget,omitempty"`- RefCreateTarget *DocumentTarget `json:"refCreateTarget,omitempty"`- DailyNoteTarget *DocumentTarget `json:"dailyNoteTarget,omitempty"`- MetadataVersion int `json:"-"` // 已认证配置载荷版本,只在内存中保存- Name string `json:"name"` // 笔记本名称- Sort int `json:"sort"` // 排序字段- Icon string `json:"icon"` // 图标- Closed bool `json:"closed"` // 是否处于关闭状态- RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本- RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径- DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本- DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径- DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径- DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径- DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径- SortMode int `json:"sortMode"` // 排序方式- Encrypted bool `json:"encrypted"` // 是否为加密笔记本- BoxCrypt *BoxEncryption `json:"boxCrypt"` // 笔记本加密参数,仅 Encrypted=true 时有值+ DocumentAddressingVersion int `json:"documentAddressingVersion,omitempty"` // 内部格式标记,不是用户开关+ DocCreateTarget *DocumentTarget `json:"docCreateTarget,omitempty"`+ RefCreateTarget *DocumentTarget `json:"refCreateTarget,omitempty"`+ DailyNoteTarget *DocumentTarget `json:"dailyNoteTarget,omitempty"`+ MetadataVersion int `json:"-"` // 已认证配置载荷版本,只在内存中保存+ Name string `json:"name"` // 笔记本名称+ Sort int `json:"sort"` // 排序字段+ Icon string `json:"icon"` // 图标+ Closed bool `json:"closed"` // 是否处于关闭状态+ RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本+ RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径+ DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本+ DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径+ DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径+ DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径+ DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径+ SortMode int `json:"sortMode"` // 排序方式+ Encrypted bool `json:"encrypted"` // 是否为加密笔记本+ BoxCrypt *BoxEncryption `json:"boxCrypt"` // 笔记本加密参数,仅 Encrypted=true 时有值}// BoxEncryption 维护单个加密笔记本的密钥包络参数。WrappedDEK 是用全局 KEK 加密后的 DEK,本身可落盘。@@ -51,11 +55,12 @@ type BoxEncryption struct {func NewBoxConf() *BoxConf {return &BoxConf{- Name: "Untitled",- Closed: true,- DailyNoteSavePath: "/daily note/{{now | date \"2006/01\"}}/{{now | date \"2006-01-02\"}}",- DailyNoteTemplatePath: "",- SortMode: util.SortModeFileTree,- Encrypted: false,+ DocumentAddressingVersion: documentaddressing.DefaultMode(),+ Name: "Untitled",+ Closed: true,+ DailyNoteSavePath: "/daily note/{{now | date \"2006/01\"}}/{{now | date \"2006-01-02\"}}",+ DailyNoteTemplatePath: "",+ SortMode: util.SortModeFileTree,+ Encrypted: false,}}diff --git a/kernel/documentaddressing/capabilities.go b/kernel/documentaddressing/capabilities.goindex e7e63491d9..5b4c5feb52 100644--- a/kernel/documentaddressing/capabilities.go+++ b/kernel/documentaddressing/capabilities.go@@ -8,7 +8,9 @@ import ("crypto/sha256""encoding/hex""encoding/json"+ "errors""fmt"+ "os""path/filepath""github.com/88250/lute/ast"@@ -16,43 +18,85 @@ import (// ModeSnapshot 描述经过校验的能力要求,不代表当前读取器可以处理该模式。type ModeSnapshot struct {- Mode int- Revision string+ Mode int+ Revision string+ State string+ Phase string+ RecordsConsistent bool}// InspectBox 不读取文档或派生索引。合法的高模式与 CheckBox 一样记入本机下界,// 配置损坏则返回错误,不向调用方伪装成旧服务端或兼容模式。func InspectBox(dataDir, confDir, boxID string) (*ModeSnapshot, error) {- if !ast.IsNodeIDPattern(boxID) {- return nil, ErrInvalid- }storeLock.Lock()defer storeLock.Unlock()+ snapshot, _, err := inspectBox(dataDir, confDir, boxID)+ return snapshot, err+}++func inspectBox(dataDir, confDir, boxID string) (*ModeSnapshot, *localStore, error) {+ if !ast.IsNodeIDPattern(boxID) {+ return nil, nil, ErrInvalid+ }store, err := loadStore(dataDir, confDir)if err != nil {- return nil, err+ return nil, nil, err}read := directoryReader(filepath.Join(dataDir, boxID))sources := map[string]string{}+ consistent := truemode, err := ReadMode(boxID, func(name string) ([]byte, error) {data, readErr := read(name)if readErr == nil {digest := sha256.Sum256(data)sources[name] = hex.EncodeToString(digest[:])+ fields, parseErr := object(data, name == ConfigPath)+ key := "minimumMode"+ if name == ConfigPath {+ key = "documentaddressingversion"+ }+ value, valueErr := positiveInt(fields[key])+ consistent = consistent && parseErr == nil && valueErr == nil && value == 2+ } else if errors.Is(readErr, os.ErrNotExist) {+ consistent = false}return data, readErr})if err != nil {- return nil, fmt.Errorf("notebook [%s]: %w", boxID, err)+ return nil, nil, fmt.Errorf("notebook [%s]: %w", boxID, err)}mode = store.confirm(boxID, mode)if err = store.save(); err != nil {- return nil, err+ return nil, nil, err+ }+ record, err := readMigration(store, boxID)+ if err != nil {+ return nil, nil, err+ }+ snapshot := &ModeSnapshot{Mode: mode, State: "legacy", RecordsConsistent: consistent}+ if record != nil {+ snapshot.Phase = record.Phase+ snapshot.Mode = max(snapshot.Mode, 2)+ snapshot.State = "recovering"+ store.confirm(boxID, snapshot.Mode)+ if err = store.save(); err != nil {+ return nil, nil, err+ }+ }+ if snapshot.Mode > 1 {+ snapshot.State = "structured"+ if record != nil || !consistent {+ snapshot.State = "recovering"+ }+ if snapshot.Mode > DefaultMode() {+ snapshot.State = "conflict"+ }}- data, err := json.Marshal([]interface{}{1, boxID, mode, sources})+ data, err := json.Marshal([]interface{}{2, boxID, snapshot.Mode, sources, record})if err != nil {- return nil, err+ return nil, nil, err}digest := sha256.Sum256(data)- return &ModeSnapshot{Mode: mode, Revision: "1:" + hex.EncodeToString(digest[:])}, nil+ snapshot.Revision = "2:" + hex.EncodeToString(digest[:])+ return snapshot, store, nil}diff --git a/kernel/documentaddressing/migration.go b/kernel/documentaddressing/migration.gonew file mode 100644index 0000000000..7274d49f32--- /dev/null+++ b/kernel/documentaddressing/migration.go@@ -0,0 +1,124 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package documentaddressing++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"++ "github.com/siyuan-note/filelock"+)++// 保护版本验证并发布后填写。它是发布门槛,不是用户配置或笔记本开关。+// 隔离测试使用链接参数提供测试版本,不修改产品二进制。+var minimumReaderVersion string++var ErrRecovering = errors.New("document addressing recovery is pending")++func MinimumReaderVersion() *string {+ if minimumReaderVersion == "" {+ return nil+ }+ version := minimumReaderVersion+ return &version+}++// DefaultMode 是当前发行版自动采用的内部模式,不暴露为用户可写配置。+func DefaultMode() int {+ if minimumReaderVersion != "" {+ return 2+ }+ return 1+}++// migrationRecord 仅保存身份及阶段;源文件和认证密钥从不进入迁移记录。+type migrationRecord struct {+ Version int `json:"version"`+ Notebook string `json:"notebook"`+ Phase string `json:"phase"`+}++func migrationPath(store *localStore, boxID string) string {+ return filepath.Join(filepath.Dir(store.path), "document-addressing-recovery", boxID+".json")+}++func readMigration(store *localStore, boxID string) (*migrationRecord, error) {+ data, err := filelock.ReadFile(migrationPath(store, boxID))+ if errors.Is(err, os.ErrNotExist) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ fields, err := versionedObject(data)+ if err != nil || len(fields) != 3 {+ return nil, ErrInvalid+ }+ var record migrationRecord+ if json.Unmarshal(data, &record) != nil || record.Notebook != boxID || record.Phase != "records" {+ return nil, ErrInvalid+ }+ return &record, nil+}++// migrateBoxRecords 在源访问之前自动补齐模式投影。每次只写元数据,不批量读取或重写文档。+// 调用方持有 storeLock;决定先落盘,失败后下次访问继续,已经写入的下界只升不降。+func migrateBoxRecords(dataDir, boxID string, store *localStore, write func(string, []byte) error) error {+ directory := filepath.Join(dataDir, boxID)+ info, err := os.Lstat(directory)+ if err != nil {+ return err+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return ErrInvalid+ }+ name := filepath.Join(directory, ConfigPath)+ data, err := filelock.ReadFile(name)+ if err != nil {+ return err+ }+ // 既有配置已由 ReadMode 严格验证;保留未知字段及密文载荷的原始值。+ fields, err := object(data, false)+ if err != nil {+ return err+ }+ recordPath := migrationPath(store, boxID)+ if err = os.MkdirAll(filepath.Dir(recordPath), 0755); err != nil {+ return err+ }+ decision, _ := json.Marshal(migrationRecord{1, boxID, "records"})+ if err = write(recordPath, decision); err != nil {+ return err+ }+ store.confirm(boxID, 2)+ if err = store.saveUsing(write); err != nil {+ return err+ }+ floor, _ := json.Marshal(struct {+ Version int `json:"version"`+ Notebook string `json:"notebook"`+ MinimumMode int `json:"minimumMode"`+ }{1, boxID, 2})+ if err = write(filepath.Join(directory, FloorPath), floor); err != nil {+ return err+ }+ for key := range fields {+ if strings.EqualFold(key, "documentAddressingVersion") {+ delete(fields, key)+ }+ }+ fields["documentAddressingVersion"] = json.RawMessage("2")+ data, err = json.MarshalIndent(fields, "", " ")+ if err != nil {+ return err+ }+ if err = write(name, data); err != nil {+ return err+ }+ return os.Remove(recordPath)+}diff --git a/kernel/documentaddressing/migration_test.go b/kernel/documentaddressing/migration_test.gonew file mode 100644index 0000000000..9586a14d40--- /dev/null+++ b/kernel/documentaddressing/migration_test.go@@ -0,0 +1,138 @@+package documentaddressing++import (+ "bytes"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/filelock"+)++func structuredReleaseForTest(t *testing.T) {+ t.Helper()+ previous := minimumReaderVersion+ minimumReaderVersion = "0.0.0-test"+ t.Cleanup(func() { minimumReaderVersion = previous })+}++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)+ original := `{"name":"private title","boxCrypt":{"metadata":"opaque-authenticated-data","wrappedDEK":"original-key"},"future":{"keep":true}}`+ writeTestFile(t, boxDir, ConfigPath, original)+ writeTestFile(t, boxDir, "20261023000001-abcdefg.sy", `{"Spec":"2","Properties":{"title":"existing"}}`)+ before, _ := os.ReadFile(filepath.Join(boxDir, "20261023000001-abcdefg.sy"))+ if err := CheckBox(dataDir, confDir, testBox); err != nil {+ t.Fatal(err)+ }+ snapshot, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || snapshot.Mode != 2 || snapshot.State != "structured" || !snapshot.RecordsConsistent {+ t.Fatal(snapshot, err)+ }+ after, _ := os.ReadFile(filepath.Join(boxDir, "20261023000001-abcdefg.sy"))+ if !bytes.Equal(before, after) {+ t.Fatal("migration rewrote a source document")+ }+ data, _ := os.ReadFile(filepath.Join(boxDir, ConfigPath))+ var got, want map[string]json.RawMessage+ _ = json.Unmarshal(data, &got)+ _ = json.Unmarshal([]byte(original), &want)+ delete(got, "documentAddressingVersion")+ for key, value := range want {+ var a, b bytes.Buffer+ _ = json.Compact(&a, value)+ _ = json.Compact(&b, got[key])+ if !bytes.Equal(a.Bytes(), b.Bytes()) {+ t.Fatalf("changed protected configuration field %s", key)+ }+ }+ store, _ := loadStore(dataDir, confDir)+ if _, err = os.Stat(migrationPath(store, testBox)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("completed migration retained an active journal", err)+ }+ // 旧设备覆盖配置和移除笔记本下界后,本机记录自动恢复投影,不降级也不重写源。+ writeTestFile(t, boxDir, ConfigPath, original)+ if err = os.Remove(filepath.Join(boxDir, FloorPath)); err != nil {+ t.Fatal(err)+ }+ if err = CheckBox(dataDir, confDir, testBox); err != nil {+ t.Fatal(err)+ }+ snapshot, err = InspectBox(dataDir, confDir, testBox)+ if err != nil || snapshot.State != "structured" || !snapshot.RecordsConsistent {+ t.Fatal(snapshot, err)+ }+}++func TestStructuredTitlesMigrationInterruption(t *testing.T) {+ structuredReleaseForTest(t)+ for stage := 1; stage <= 4; stage++ {+ t.Run(fmt.Sprint(stage), func(t *testing.T) {+ root := t.TempDir()+ dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")+ writeTestFile(t, filepath.Join(dataDir, testBox), ConfigPath, `{"name":"unchanged"}`)+ store, err := loadStore(dataDir, confDir)+ if err != nil {+ t.Fatal(err)+ }+ calls := 0+ injected := errors.New("interrupted after durable write")+ err = migrateBoxRecords(dataDir, testBox, store, func(name string, data []byte) error {+ if err := filelock.WriteFile(name, data); err != nil {+ return err+ }+ calls+++ if calls == stage {+ return injected+ }+ return nil+ })+ if !errors.Is(err, injected) {+ t.Fatal("fault was not reached", err)+ }+ // 下界尚未写入时,保护读取器也必须识别迁移决定并拒绝访问。+ minimumReaderVersion = ""+ if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {+ t.Fatal(err)+ }+ minimumReaderVersion = "0.0.0-test"+ if err = CheckBox(dataDir, confDir, testBox); err != nil {+ t.Fatal(err)+ }+ snapshot, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || snapshot.Mode != 2 || snapshot.State != "structured" {+ t.Fatal(snapshot, err)+ }+ })+ }+}++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)+ for _, source := range []string{`{"documentAddressingVersion":9}`, `{"documentAddressingVersion":1,"DocumentAddressingVersion":2}`} {+ writeTestFile(t, boxDir, ConfigPath, source)+ if err := CheckBox(dataDir, confDir, testBox); err == nil {+ t.Fatal("unknown or duplicate mode accepted")+ }+ after, _ := os.ReadFile(filepath.Join(boxDir, ConfigPath))+ if string(after) != source {+ t.Fatal("invalid source was overwritten")+ }+ }+ missing := "20261023000009-missing"+ if err := CheckBox(dataDir, confDir, missing); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(dataDir, missing)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal(err)+ }+}diff --git a/kernel/documentaddressing/mode.go b/kernel/documentaddressing/mode.goindex ba79fd690a..f9d58868b3 100644--- a/kernel/documentaddressing/mode.go+++ b/kernel/documentaddressing/mode.go@@ -22,9 +22,8 @@ import ()const (- ConfigPath = ".siyuan/conf.json"- FloorPath = ".siyuan/document-addressing.json"- supportedMode = 1+ ConfigPath = ".siyuan/conf.json"+ FloorPath = ".siyuan/document-addressing.json")var (@@ -97,29 +96,56 @@ func CheckImport(dataDir, confDir, boxID, directory string) error {if err != nil {return err}+ if ast.IsNodeIDPattern(boxID) {+ record, readErr := readMigration(store, boxID)+ if readErr != nil {+ return readErr+ }+ if record != nil {+ mode = max(mode, 2)+ }+ }return checkSupported(boxID, max(mode, store.Notebooks[boxID]))}// CheckBox 在任何源数据修复、索引和读写前确认能力下界。合法的较高要求只升不降。func CheckBox(dataDir, confDir, boxID string) error {- if !ast.IsNodeIDPattern(boxID) {- return ErrInvalid- }+ _, err := BoxMode(dataDir, confDir, boxID)+ return err+}++// BoxMode 在确认能力下界和完成自动迁移后返回可用模式,避免调用者重复读取元数据。+func BoxMode(dataDir, confDir, boxID string) (int, error) {storeLock.Lock()defer storeLock.Unlock()- store, err := loadStore(dataDir, confDir)+ snapshot, store, err := inspectBox(dataDir, confDir, boxID)if err != nil {- return err+ return 0, err}- mode, err := ReadMode(boxID, directoryReader(filepath.Join(dataDir, boxID)))- if err != nil {- return fmt.Errorf("notebook [%s]: %w", boxID, err)+ if err = checkSupported(boxID, snapshot.Mode); err != nil {+ return 0, err}- mode = store.confirm(boxID, mode)- if err = store.save(); err != nil {- return 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 statErr != nil {+ return 0, statErr+ }+ if err = migrateBoxRecords(dataDir, boxID, store, filelock.WriteFile); err != nil {+ return 0, err+ }+ return 2, nil}- return checkSupported(boxID, mode)+ if snapshot.State == "conflict" {+ return 0, ErrModeConflict+ }+ if snapshot.State == "recovering" {+ return 0, ErrRecovering+ }+ return snapshot.Mode, nil}// CheckBatch 校验一次同步或恢复的完整替换计划;调用者必须在任何源文件变动前调用。@@ -165,6 +191,11 @@ func CheckBatch(dataDir, confDir string, upserts, removes []string, read Reader)for _, boxID := range ids {current := directoryReader(filepath.Join(dataDir, boxID))mode, currentErr := ReadMode(boxID, current)+ record, recoveryErr := readMigration(store, boxID)+ if record != nil {+ mode = max(mode, 2)+ }+ currentErr = errors.Join(currentErr, recoveryErr)if currentErr == nil {mode = store.confirm(boxID, mode)}@@ -203,7 +234,7 @@ func CheckBatch(dataDir, confDir string, upserts, removes []string, read Reader)}func checkSupported(boxID string, mode int) error {- if mode > supportedMode {+ if mode > DefaultMode() {return fmt.Errorf("%w [%s, mode=%d]", ErrUnsupported, boxID, mode)}return nil@@ -369,6 +400,10 @@ func (store *localStore) confirm(boxID string, mode int) int {}func (store *localStore) save() error {+ return store.saveUsing(filelock.WriteFile)+}++func (store *localStore) saveUsing(write func(string, []byte) error) error {if !store.dirty {return nil}@@ -379,5 +414,5 @@ func (store *localStore) save() error {if err = os.MkdirAll(filepath.Dir(store.path), 0755); err != nil {return err}- return filelock.WriteFile(store.path, data)+ return write(store.path, data)}diff --git a/kernel/documentaddressing/title.go b/kernel/documentaddressing/title.goindex 2031307de3..9ac5052c6d 100644--- a/kernel/documentaddressing/title.go+++ b/kernel/documentaddressing/title.go@@ -11,8 +11,9 @@ import ()var (- ErrModeConflict = errors.New("document title requires structured addressing")- ErrInvalidTitle = errors.New("invalid document title source")+ ErrModeConflict = errors.New("document title requires structured addressing")+ ErrInvalidTitle = errors.New("invalid document title source")+ ErrLegacyPathUnsupported = errors.New("legacy document paths are unsupported; use structured document addressing"))// CheckLegacyTitle 检查已经解码的兼容模式标题,不清洗内容,也不将冲突视为已确认的模式启用。@@ -26,6 +27,11 @@ func CheckLegacyTitle(title string) error {// CheckLegacyTitleProperties 在属性解码和修复前检查每个标题值,重复字段不能遮盖冲突源。func CheckLegacyTitleProperties(data []byte) error {+ return CheckTitleProperties(data, 1)+}++// CheckTitleProperties 保留原始字符;模式只决定是否允许新字符,不能清洗冲突源。+func CheckTitleProperties(data []byte, mode int) error {if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {return nil}@@ -52,7 +58,7 @@ func CheckLegacyTitleProperties(data []byte) error {if titleErr == nil {titleErr = ErrInvalidTitle}- } else if err = CheckLegacyTitle(html.UnescapeAttrVal(title)); err != nil {+ } else if err = CheckLegacyTitle(html.UnescapeAttrVal(title)); mode < 2 && err != nil {titleErr = err}}diff --git a/kernel/filesys/document_addressing.go b/kernel/filesys/document_addressing.goindex f2bd6f4056..2adf0d73c8 100644--- a/kernel/filesys/document_addressing.go+++ b/kernel/filesys/document_addressing.go@@ -1,7 +1,11 @@package filesysimport (+ "bytes"++ "github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -9,3 +13,26 @@ import (func CheckDocumentAddressing(boxID string) error {return documentaddressing.CheckBox(util.DataDir, util.ConfDir, boxID)}++func DocumentAddressingMode(boxID string) (int, error) {+ if boxID == "" {+ return 1, nil+ }+ return documentaddressing.BoxMode(util.DataDir, util.ConfDir, boxID)+}++func CheckDocumentSpecJSON(boxID string, data []byte) error {+ mode, err := DocumentAddressingMode(boxID)+ if err != nil {+ return err+ }+ return treenode.CheckSpecJSONForMode(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")), mode)+}++func checkDocumentTreeSpec(tree *parse.Tree) error {+ mode, err := DocumentAddressingMode(tree.Box)+ if err != nil {+ return err+ }+ return treenode.CheckSpecForMode(tree, mode)+}diff --git a/kernel/filesys/structured_titles_test.go b/kernel/filesys/structured_titles_test.gonew file mode 100644index 0000000000..1ba039b02f--- /dev/null+++ b/kernel/filesys/structured_titles_test.go@@ -0,0 +1,89 @@+package filesys++import (+ "bytes"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++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)+ oldConf, oldProvider, oldAcquire, oldRelease := util.ConfDir, DEKProvider, DEKLockAcquire, DEKLockRelease+ util.ConfDir = t.TempDir()+ DEKLockAcquire, DEKLockRelease = nil, nil+ t.Cleanup(func() {+ util.ConfDir, DEKProvider, DEKLockAcquire, DEKLockRelease = oldConf, oldProvider, oldAcquire, oldRelease+ })+ var key []byte+ if encrypted {+ key = bytes.Repeat([]byte{27}, 32)+ }+ DEKProvider = func(string) ([]byte, error) { return bytes.Clone(key), nil }+ configPath := filepath.Join(util.DataDir, box, documentaddressing.ConfigPath)+ if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(configPath, []byte(`{"name":"Old notebook"}`), 0600); err != nil {+ t.Fatal(err)+ }+ p := "/" + id + ".sy"+ for _, title := range []string{"A/B", "../literal/", "A/B/C", "**bold**/`code`", "A/B/C"} {+ tree := treenode.NewTree(box, p, "/"+title, title)+ if _, err := WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ if tree.Root.Spec != treenode.DocumentTitleSpec {+ t.Fatal("new title missing source spec")+ }+ cache.RemoveTreeDataInBox(tree.ID, box)+ loaded, err := LoadTree(box, p, util.NewLute())+ if err != nil || loaded.Root.IALAttr("title") != title {+ t.Fatal("load changed title", err)+ }+ properties, err := DocIAL(filepath.Join(util.DataDir, box, p))+ if err != nil || properties["title"] != title {+ t.Fatal("streaming IAL changed title", err)+ }+ if header, err := readParentDocIAL(filepath.Join(util.DataDir, box, p)); err != nil || header["title"] != title {+ t.Fatal("strict properties changed title", err)+ }+ if snapshot, _, err := LoadTreeSnapshot(box, p, util.NewLute()); err != nil || snapshot.Root.IALAttr("title") != title {+ t.Fatal("snapshot changed title", err)+ }+ }+ if encrypted {+ name := filepath.Join(util.DataDir, box, p)+ data, err := os.ReadFile(name)+ if err != nil || !util.IsCiphertext(data) {+ t.Fatal("source lost encryption", err)+ }+ data[len(data)-1] ^= 1+ if err = os.WriteFile(name, data, 0600); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(id, box)+ if _, err = DocIAL(name); err == nil {+ t.Fatal("unauthenticated title accepted")+ }+ if _, _, err = LoadTreeSnapshot(box, p, util.NewLute()); err == nil {+ t.Fatal("unauthenticated snapshot accepted")+ }+ after, _ := os.ReadFile(name)+ if !bytes.Equal(data, after) {+ t.Fatal("damaged ciphertext was overwritten")+ }+ }+ })+ }+}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 26d933c42f..5c75516ea5 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -251,7 +251,7 @@ func NormalizeTreeForRead(tree *parse.Tree) (err error) {if nil == tree || nil == tree.Root {return errors.New("tree is empty")}- if err = treenode.CheckSpec(tree); nil != err {+ if err = checkDocumentTreeSpec(tree); nil != err {return}if err = treenode.RefreshTableCellRichProjection(tree.Root); nil != err {@@ -394,7 +394,7 @@ func readDocumentHeader(absPath string, strict bool) (*documentHeader, error) {return nil, err}data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))- if err = treenode.CheckSpecJSON(data); err != nil {+ if err = CheckDocumentSpecJSON(boxID, data); err != nil {return nil, err}var doc documentHeader@@ -419,10 +419,9 @@ func DocIAL(absPath string) (ret map[string]string, err error) {// 加密笔记本的 .sy 是密文,流式 jsoniter 解析无法处理,需先整体读+解密。// 反推 boxID:路径形如 <DataDir>/<boxID>/...;非加密笔记本走原流式逻辑。boxID := docIALBoxID(absPath)- if boxID != "" {- if err = CheckDocumentAddressing(boxID); err != nil {- return nil, err- }+ mode, err := DocumentAddressingMode(boxID)+ if err != nil {+ return nil, err}if boxID != "" && DEKProvider != nil {dek, encrypted, releaseCryptoLease, leaseErr := acquireCryptoLease(boxID)@@ -447,7 +446,7 @@ func DocIAL(absPath string) (ret map[string]string, err error) {logging.LogErrorf("decrypt doc [%s] for IAL failed: %s", absPath, decErr)return nil, decErr}- return parseDocIAL(bytes.NewReader(plain))+ return parseDocIALForMode(bytes.NewReader(plain), mode)}}@@ -461,7 +460,7 @@ func DocIAL(absPath string) (ret map[string]string, err error) {return nil, err}defer file.Close()- return parseDocIAL(file)+ return parseDocIALForMode(file, mode)}// docIALReader 保留底层读取错误,避免将临时 I/O 失败当成 JSON 损坏。@@ -479,6 +478,10 @@ func (r *docIALReader) Read(p []byte) (int, error) {}func parseDocIAL(reader io.Reader) (ret map[string]string, err error) {+ return parseDocIALForMode(reader, 1)+}++func parseDocIALForMode(reader io.Reader, mode int) (ret map[string]string, err error) {r := &docIALReader{Reader: reader}buffered := bufio.NewReaderSize(r, 512)if prefix, _ := buffered.Peek(3); bytes.Equal(prefix, []byte("\xef\xbb\xbf")) {@@ -499,7 +502,7 @@ func parseDocIAL(reader io.Reader) (ret map[string]string, err error) {}case field == "Properties":properties = iter.SkipAndReturnBytes()- if checkErr := documentaddressing.CheckLegacyTitleProperties(properties); checkErr != nil &&+ if checkErr := documentaddressing.CheckTitleProperties(properties, mode); checkErr != nil &&(titleErr == nil || errors.Is(checkErr, documentaddressing.ErrModeConflict)) {titleErr = checkErr}@@ -617,7 +620,7 @@ func WriteTreeWithPreflight(tree *parse.Tree, preflight func() error) (size uintif validatedSource != nil && bytes.Equal(plain, validatedSource) {return nil}- return treenode.CheckSpecJSON(bytes.TrimPrefix(plain, []byte("\xef\xbb\xbf")))+ return CheckDocumentSpecJSON(tree.Box, plain)})if err != nil {return@@ -643,7 +646,7 @@ func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err errorif err = treenode.SyncTableCellRichInlineChanges(tree.Root); nil != err {return}- if err = treenode.CheckSpec(tree); nil != err {+ if err = checkDocumentTreeSpec(tree); nil != err {return}luteEngine := util.NewLute() // 不关注用户的自定义解析渲染选项@@ -745,7 +748,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, dewithoutBOM := bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))needFix = len(withoutBOM) != len(jsonData)jsonData = withoutBOM- if err = treenode.CheckSpecJSON(jsonData); nil != err {+ if err = CheckDocumentSpecJSON(boxID, jsonData); nil != err {return}jsonData, removedNull := removeUnescapedUnicodeNull(jsonData)@@ -763,7 +766,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, deret.Box = boxIDret.Path = p- if err = treenode.CheckSpec(ret); nil != err {+ if err = checkDocumentTreeSpec(ret); nil != err {return}if err = treenode.RefreshTableCellRichProjection(ret.Root); nil != err {@@ -849,7 +852,7 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute, defunc parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (ret *parse.Tree, err error) {jsonData = bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))- if err = treenode.CheckSpecJSON(jsonData); nil != err {+ if err = CheckDocumentSpecJSON(boxID, jsonData); nil != err {return}ret, _, err = dataparser.ParseJSON(jsonData, luteEngine.ParseOptions)@@ -862,7 +865,7 @@ func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (reret.Box = boxIDret.Path = p- if err = treenode.CheckSpec(ret); nil != err {+ if err = checkDocumentTreeSpec(ret); nil != err {return}err = treenode.RefreshTableCellRichProjection(ret.Root)diff --git a/kernel/filesys/tree_compare_write.go b/kernel/filesys/tree_compare_write.goindex 416d79b6bc..c56b66a5e8 100644--- a/kernel/filesys/tree_compare_write.go+++ b/kernel/filesys/tree_compare_write.go@@ -5,7 +5,6 @@package filesysimport (- "bytes""path/filepath""github.com/88250/lute"@@ -30,7 +29,7 @@ func WriteTreeIfUnchanged(tree *parse.Tree, original []byte) (size uint64, err eif err != nil {return 0, err}- if err = treenode.CheckSpecJSON(bytes.TrimPrefix(plain, []byte("\xef\xbb\xbf"))); err != nil {+ if err = CheckDocumentSpecJSON(tree.Box, plain); err != nil {return 0, err}data, filePath, err := prepareWriteTree(tree)diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.goindex 28d1165851..3a19156888 100644--- a/kernel/model/attribute_view_new_item.go+++ b/kernel/model/attribute_view_new_item.go@@ -468,7 +468,7 @@ func resolveAttributeViewItemDocument(blockID, primary string, itemTemplate *av.if nil == blockTree {return nil, ErrBlockNotFound}- primary = normalizeDocTitle(primary)+ primary = normalizeDocumentTitle(primary)target, err := resolveNewItemDocumentTarget(blockTree.BoxID, itemTemplate.SaveLocation)if err != nil {diff --git a/kernel/model/box.go b/kernel/model/box.goindex 912423d1fb..f8f7a074f2 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -40,6 +40,7 @@ import ("github.com/siyuan-note/logging""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/heif""github.com/siyuan-note/siyuan/kernel/sql"@@ -358,6 +359,11 @@ func (box *Box) saveConf(conf *conf.BoxConf, syncChange bool) error {if err != nil {return fmt.Errorf("prepare box conf [%s] failed: %w", confPath, err)}+ mode, err := filesys.DocumentAddressingMode(box.ID)+ if err != nil {+ return err+ }+ persisted.DocumentAddressingVersion = max(mode, documentaddressing.DefaultMode())newData, err := gulu.JSON.MarshalIndentJSON(persisted, "", " ")if err != nil {return fmt.Errorf("marshal box conf [%s] failed: %w", confPath, err)diff --git a/kernel/model/document_addressing_file.go b/kernel/model/document_addressing_file.goindex ab0434fd67..1c3803e025 100644--- a/kernel/model/document_addressing_file.go+++ b/kernel/model/document_addressing_file.go@@ -87,13 +87,15 @@ func checkDocumentAddressingLocalFile(absPath string, ancestors bool) error {if !filepath.IsAbs(confDir) {return nil}- record := util.NormalizeAndResolve(util.ResolveLongestExistingParent(filepath.Join(confDir, "document-addressing.json")))name := util.NormalizeAndResolve(util.ResolveLongestExistingParent(absPath))- if _, inside := dataRelativePath(record, name); inside {- return documentaddressing.ErrInvalid- }- if _, ancestor := dataRelativePath(name, record); ancestors && ancestor {- return documentaddressing.ErrInvalid+ for _, relative := range []string{"document-addressing.json", "document-addressing-recovery"} {+ record := util.NormalizeAndResolve(util.ResolveLongestExistingParent(filepath.Join(confDir, relative)))+ if _, inside := dataRelativePath(record, name); inside {+ return documentaddressing.ErrInvalid+ }+ if _, ancestor := dataRelativePath(name, record); ancestors && ancestor {+ return documentaddressing.ErrInvalid+ }}return nil}diff --git a/kernel/model/document_addressing_source.go b/kernel/model/document_addressing_source.goindex cb612445e8..0a9385e7fe 100644--- a/kernel/model/document_addressing_source.go+++ b/kernel/model/document_addressing_source.go@@ -1,7 +1,6 @@package modelimport (- "bytes""errors""io/fs""os"@@ -38,13 +37,22 @@ func isDocumentAddressingSource(paths []string) bool {return false}-func checkDocumentAddressingSource(data []byte) error {- return treenode.CheckSpecJSON(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")))+func checkDocumentAddressingSource(absPath string, data []byte) error {+ paths, err := documentAddressingDataPaths(absPath)+ if err != nil {+ return err+ }+ for _, doc := range documentSourcesFromPaths(paths) {+ if err = filesys.CheckDocumentSpecJSON(doc.BoxID, data); err != nil {+ return err+ }+ }+ return nil}// checkDocumentAddressingSourceOverwrite 在创建目录及写入批次前检查新旧文档;不修改原始字节。func checkDocumentAddressingSourceOverwrite(absPath string, data []byte) error {- if err := checkDocumentAddressingSource(data); err != nil {+ if err := checkDocumentAddressingSource(absPath, data); err != nil {return err}current, err := filelock.ReadFile(absPath)@@ -54,7 +62,7 @@ func checkDocumentAddressingSourceOverwrite(absPath string, data []byte) error {if err != nil {return err}- return checkDocumentAddressingSource(current)+ return checkDocumentAddressingSource(absPath, current)}// WriteFileWithDocumentAddressing 在文件锁内重新检查当前文档,再原样写入已验证的请求内容。@@ -75,7 +83,7 @@ func WriteFileWithDocumentAddressing(absPath string, data []byte) error {if current == nil {return nil}- return checkDocumentAddressingSource(current)+ return checkDocumentAddressingSource(absPath, current)})})}diff --git a/kernel/model/document_create.go b/kernel/model/document_create.goindex 2f24d539e2..68b8a9af0f 100644--- a/kernel/model/document_create.go+++ b/kernel/model/document_create.go@@ -81,7 +81,7 @@ func documentCreateParent(request *DocumentCreateRequest) (folder, revision strierr = documentAddressingError("parentUnavailable", errors.New("invalid parent document ID"))return}- parent, readErr := treenode.GetDocumentPath(request.Notebook, parentID, request.Notebook, 1)+ parent, readErr := getDocumentPath(request.Notebook, parentID)if readErr != nil {err = documentAddressingError("parentUnavailable", readErr)return@@ -283,7 +283,7 @@ func createDocByParent(request DocumentCreateRequest, creationLocked bool) (docu}return err}- document, err = treenode.GetDocumentPath(tree.Box, tree.ID, tree.Box, 1)+ document, err = getDocumentPath(tree.Box, tree.ID)return err}()if err != nil {diff --git a/kernel/model/document_move.go b/kernel/model/document_move.goindex 56fae2ea52..8eac19c3b8 100644--- a/kernel/model/document_move.go+++ b/kernel/model/document_move.go@@ -42,6 +42,13 @@ func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenodeif err != nil {return nil, err}+ mode, modeErr := filesys.DocumentAddressingMode(toBox)+ if modeErr != nil {+ return nil, modeErr+ }+ if err = treenode.CheckSpecForMode(tree, mode); err != nil {+ return nil, documentAddressingError("targetModeUnsupported", err)+ }relative := strings.TrimPrefix(sourcePath, path.Dir(fromPath)+"/")if path.Dir(fromPath) == "/" {relative = strings.TrimPrefix(sourcePath, "/")diff --git a/kernel/model/document_path.go b/kernel/model/document_path.goindex b551643342..552e7ffd01 100644--- a/kernel/model/document_path.go+++ b/kernel/model/document_path.go@@ -12,6 +12,7 @@ import ("unicode/utf8""github.com/88250/lute/ast"+ "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"@@ -75,6 +76,10 @@ func GetDocPaths(boxID string, ids []string) (documents []*treenode.DocumentPathreturn}defer ReleaseEncryptedBoxOperation(boxID)+ mode, modeErr := filesys.DocumentAddressingMode(boxID)+ if modeErr != nil {+ return nil, nil, modeErr+ }documents, missing = []*treenode.DocumentPath{}, []string{}seen := map[string]bool{}for _, id := range ids {@@ -82,7 +87,7 @@ func GetDocPaths(boxID string, ids []string) (documents []*treenode.DocumentPathcontinue}seen[id] = true- document, readErr := treenode.GetDocumentPath(boxID, id, boxID, 1)+ document, readErr := treenode.GetDocumentPath(boxID, id, boxID, mode)if errors.Is(readErr, sql.ErrNoRows) {missing = append(missing, id)continue@@ -96,7 +101,53 @@ func GetDocPaths(boxID string, ids []string) (documents []*treenode.DocumentPath}func documentRootRevision(boxID string) string {- return treenode.DocumentRevision([]interface{}{1, boxID, 1, IsBoxDocEnabled()})+ return treenode.DocumentRevision([]interface{}{1, boxID, documentaddressing.DefaultMode(), IsBoxDocEnabled()})+}++func getDocumentPath(boxID, id string) (*treenode.DocumentPath, error) {+ mode, err := filesys.DocumentAddressingMode(boxID)+ if err != nil {+ return nil, err+ }+ return treenode.GetDocumentPath(boxID, id, boxID, mode)+}++func resolveDocumentPath(boxID string, parentID *string, segments []string) (*treenode.ResolvedDocumentPath, error) {+ mode, err := filesys.DocumentAddressingMode(boxID)+ if err != nil {+ return nil, err+ }+ return treenode.ResolveDocumentPath(boxID, parentID, segments, boxID, documentRootRevision(boxID), mode)+}++func normalizeDocumentTitle(title string) string {+ if documentaddressing.DefaultMode() == 1 {+ return normalizeDocTitle(title)+ }+ return normalizeTitleText(title)+}++// appendDocumentHPath 只拼接显示文字,不对标题中的斜杠、点段或尾部字符做路径规范化。+func appendDocumentHPath(parent, title string) string {+ if parent == "/" {+ parent = ""+ }+ if title == "" {+ return parent+ }+ return parent + "/" + title+}++// CheckLegacyDocumentPath 按整本模式拒绝旧名称寻址,不根据某个请求是否包含斜杠放行。+func CheckLegacyDocumentPath(boxID string) error {+ mode, err := filesys.DocumentAddressingMode(boxID)+ if err != nil {+ return err+ }+ if mode > 1 {+ return documentaddressing.ErrLegacyPathUnsupported+ }+ return nil}// ValidateDocumentTitle 校验新协议的完整输入,不通过截断、修剪或字符替换悄悄改变标题。@@ -104,7 +155,7 @@ func ValidateDocumentTitle(format, text string) error {if format != "plain" {return documentAddressingError("unsupportedTitleFormat", errors.New("unsupported document title format"))}- if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 512 || text != normalizeDocTitle(text) || text == "." || text == ".." {+ if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 512 || text != normalizeDocumentTitle(text) || text == "." || text == ".." {return documentAddressingError("invalidTitle", errors.New("invalid document title"))}return nil@@ -143,7 +194,7 @@ func ResolveDocPath(boxID, startKind string, startID *string, segments []string)}startID = nil}- ret, err := treenode.ResolveDocumentPath(boxID, startID, segments, boxID, documentRootRevision(boxID), 1)+ ret, err := resolveDocumentPath(boxID, startID, segments)if errors.Is(err, sql.ErrNoRows) {return nil, documentAddressingError("parentUnavailable", fmt.Errorf("parent document is unavailable in notebook [%s]", boxID))}diff --git a/kernel/model/document_plan.go b/kernel/model/document_plan.goindex 4023520dc2..ba86b0b96a 100644--- a/kernel/model/document_plan.go+++ b/kernel/model/document_plan.go@@ -10,6 +10,7 @@ import ("time""github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -48,7 +49,7 @@ func documentParentLocation(boxID string, id *string) (*string, error) {if id == nil || IsBoxDoc(boxID, *id) {return nil, nil}- document, err := treenode.GetDocumentPath(boxID, *id, boxID, 1)+ document, err := getDocumentPath(boxID, *id)if err != nil {return nil, documentAddressingError("parentUnavailable", err)}@@ -57,7 +58,7 @@ func documentParentLocation(boxID string, id *string) (*string, error) {// renderDocumentTarget 只对旧模板拆分渲染结果;版本 2 的每一段在同一时间快照独立求值。func renderDocumentTarget(target *EffectiveDocumentTarget, request DocumentPlanRequest) (ret renderedDocumentTarget, err error) {- ret.missing, ret.legacy = "create", target.Structured == nil+ ret.missing, ret.legacy = "create", target.Structured == nil && documentaddressing.DefaultMode() == 1if request.Now.IsZero() {request.Now = time.Now()}@@ -127,7 +128,7 @@ func renderDocumentTarget(target *EffectiveDocumentTarget, request DocumentPlanRif request.Title != nil {ret.title = *request.Title}- ret.title = normalizeDocTitle(ret.title)+ ret.title = normalizeDocumentTitle(ret.title)if request.Placement == "child" {ret.parentID, ret.parents = request.ContextID, nilreturn@@ -149,7 +150,7 @@ func renderDocumentTarget(target *EffectiveDocumentTarget, request DocumentPlanR}// 兼容旧 parentID 优先规则:相同展示位置仍使用调用方的实际父身份。if ret.legacy && request.ContextID != nil && target.Notebook == request.Notebook && ret.parentID == nil {- if current, readErr := treenode.GetDocumentPath(target.Notebook, *request.ContextID, target.Notebook, 1); readErr == nil &&+ if current, readErr := getDocumentPath(target.Notebook, *request.ContextID); readErr == nil &¤t.DisplayPath == "/"+strings.Join(ret.parents, "/") {ret.parentID, ret.parents = request.ContextID, nil}@@ -216,7 +217,7 @@ func PlanDocumentCreation(request DocumentPlanRequest) (*DocumentCreatePlan, errparentID, revision, depth := rendered.parentID, documentRootRevision(target.Notebook), 0displayParents := []string{}if parentID != nil {- parent, readErr := treenode.GetDocumentPath(target.Notebook, *parentID, target.Notebook, 1)+ parent, readErr := getDocumentPath(target.Notebook, *parentID)if readErr != nil {return nil, documentAddressingError("parentUnavailable", readErr)}@@ -249,7 +250,7 @@ func PlanDocumentCreation(request DocumentPlanRequest) (*DocumentCreatePlan, errfor _, title := range rendered.parents {depth++if !missing {- resolved, resolveErr := treenode.ResolveDocumentPath(target.Notebook, parentID, []string{title}, target.Notebook, documentRootRevision(target.Notebook), 1)+ resolved, resolveErr := resolveDocumentPath(target.Notebook, parentID, []string{title})if resolveErr != nil {return nil, resolveErr}@@ -281,7 +282,7 @@ func PlanDocumentCreation(request DocumentPlanRequest) (*DocumentCreatePlan, errreturn nil, errors.New(Conf.Language(118))}if request.Reuse && !missing && rendered.title != "" {- resolved, resolveErr := treenode.ResolveDocumentPath(target.Notebook, parentID, []string{rendered.title}, target.Notebook, documentRootRevision(target.Notebook), 1)+ resolved, resolveErr := resolveDocumentPath(target.Notebook, parentID, []string{rendered.title})if resolveErr != nil {return nil, resolveErr}@@ -351,7 +352,7 @@ func legacyDocumentCandidate(boxID string, candidates []*treenode.DocumentPath)// executeDocumentCreationPlan 保留已完成文档,下一步使用实际提交后的父版本,不重放正文副作用。func executeDocumentCreationPlan(plan *DocumentCreatePlan, creationLocked bool) (*treenode.DocumentPath, error) {if plan.ExistingID != "" {- return treenode.GetDocumentPath(plan.Notebook, plan.ExistingID, plan.Notebook, 1)+ return getDocumentPath(plan.Notebook, plan.ExistingID)}var last *treenode.DocumentPathfor _, step := range plan.Steps {diff --git a/kernel/model/document_target.go b/kernel/model/document_target.goindex 33f9e7b17c..6d7edecbe9 100644--- a/kernel/model/document_target.go+++ b/kernel/model/document_target.go@@ -2,16 +2,12 @@ package modelimport ("errors"- "path/filepath""strings""github.com/88250/lute/ast"- "github.com/siyuan-note/filelock""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")type DocumentTargetRevision struct {@@ -35,14 +31,12 @@ func ValidateNotebookDocumentTarget(boxID string, target *conf.DocumentTarget) eif err := target.Validate(); err != nil || target == nil {return err}- mode, err := documentaddressing.ReadMode(boxID, func(name string) ([]byte, error) {- return filelock.ReadFile(filepath.Join(util.DataDir, boxID, name))- })+ mode, err := filesys.DocumentAddressingMode(boxID)if err != nil {return err}if mode != 2 {- return errors.New("structured document targets require an enabled notebook")+ return errors.New("structured document targets are unavailable in this release")}return filesys.CheckDocumentAddressing(boxID)}diff --git a/kernel/model/file.go b/kernel/model/file.goindex 490042ccf9..ed9a03eddb 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -1373,6 +1373,9 @@ func createDocByMd(boxID, p, title, md string, sorts []string, arg map[string]an}func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bool, clippingHref string, arg map[string]any) (retID string, err error) {+ if err = CheckLegacyDocumentPath(boxID); err != nil {+ return+ }createDocLock.Lock()defer createDocLock.Unlock()@@ -1625,6 +1628,9 @@ func GetFullHPathByID(id string) (hPath string, err error) {}func GetIDsByHPath(hpath, boxID string) (ret []string, err error) {+ if err = CheckLegacyDocumentPath(boxID); err != nil {+ return+ }ret = []string{}if IsBoxDocEnabled() && "/" == hpath {if box := Conf.Box(boxID); nil != box {@@ -2323,7 +2329,7 @@ func renameDoc0(boxID, p, title string) (err error) {// 规范化标题及空标题标记,由调用方选择普通写入或基于扫描源的条件写入。func prepareDocRename(tree *parse.Tree, title string) (titleChanged, emptyAttrUpdated bool, err error) {- title = normalizeDocTitle(title)+ title = normalizeDocumentTitle(title)if 512 < utf8.RuneCountInString(title) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299err = errors.New(Conf.Language(106))@@ -2407,7 +2413,7 @@ func ValidateCreateDoc(boxID, p, title string) error {func validateCreateDoc(boxID, p, title string, titleEmpty bool) (ret *createDocValidation, err error) {p = normalizeBoxDocPath(boxID, p)- title = normalizeDocTitle(title)+ title = normalizeDocumentTitle(title)if 512 < utf8.RuneCountInString(title) {// 限制笔记本名和文档名最大长度为 `512` https://github.com/siyuan-note/siyuan/issues/6299return nil, errors.New(Conf.Language(106))@@ -2448,7 +2454,7 @@ func validateCreateDoc(boxID, p, title string, titleEmpty bool) (ret *createDocVlogging.LogErrorf("parent tree [%s] does not match box [%s] and folder [%s]", parentID, boxID, folder)return nil, ErrBlockNotFound}- hPath = path.Join(parentTree.HPath, title)+ hPath = parentTree.HPath + "/" + title}if depth := strings.Count(p, "/"); 7 < depth && !Conf.FileTree.Load().AllowCreateDeeper {@@ -2588,6 +2594,10 @@ func performCreateDocTransaction(tree *parse.Tree, syncWrite bool) (err error) {func normalizeDocTitle(title string) string {title = strings.ReplaceAll(title, "/", "")+ return normalizeTitleText(title)+}++func normalizeTitleText(title string) string {// 不要踢掉 零宽连字符,否则有的 Emoji 会变形 https://github.com/siyuan-note/siyuan/issues/11480title = strings.ReplaceAll(title, string(gulu.ZWJ), "__@ZWJ@__")title = util.RemoveInvalid(title)diff --git a/kernel/model/format.go b/kernel/model/format.goindex 70ee6dbdac..2f5de474fc 100644--- a/kernel/model/format.go+++ b/kernel/model/format.go@@ -24,7 +24,6 @@ import ("github.com/88250/lute/parse""github.com/88250/lute/render""github.com/siyuan-note/logging"- "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")@@ -92,14 +91,14 @@ func autoSpaceTree(tree *parse.Tree) *parse.Tree {md := formatRenderer.Render()newTree := parseKTree(md)restoreMindmapTypes(newTree)- newTree.Root.Spec = treenode.CurrentSpec+ newTree.Root.Spec = tree.Root.Spec// 第二次格式化启用自动空格luteEngine.SetAutoSpace(true)formatRenderer = render.NewFormatRenderer(newTree, luteEngine.RenderOptions, luteEngine.ParseOptions)md = formatRenderer.Render()newTree = parseKTree(md)restoreMindmapTypes(newTree)- newTree.Root.Spec = treenode.CurrentSpec+ newTree.Root.Spec = tree.Root.SpecnewTree.Root.ID = tree.IDnewTree.Root.KramdownIAL = rootIALnewTree.ID = tree.IDdiff --git a/kernel/model/heading.go b/kernel/model/heading.goindex 9699aa5f68..93bdea8a67 100644--- a/kernel/model/heading.go+++ b/kernel/model/heading.go@@ -28,6 +28,7 @@ import ("github.com/88250/lute/parse""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -367,13 +368,15 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTbox := Conf.Box(targetBoxID)headingText := getNodeRefText0(headingNode, Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen, true)- if strings.Contains(headingText, "/") {+ if documentaddressing.DefaultMode() == 2 {+ headingText = normalizeDocumentTitle(headingText)+ } else if strings.Contains(headingText, "/") {headingText = strings.ReplaceAll(headingText, "/", "_")util.PushMsg(Conf.language(246), 7000)}moveToRoot := "/" == targetPath- toHP := path.Join("/", headingText)+ toHP := "/" + headingTexttoFolder := "/"if "" != previousPath {previousDoc := treenode.GetBlockTreeRootByPath(targetBoxID, previousPath)@@ -389,7 +392,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTerr = ErrBlockNotFoundreturn}- toHP = path.Join(parentDoc.HPath, headingText)+ toHP = parentDoc.HPath + "/" + headingTexttoFolder = path.Join(path.Dir(parentPath), parentDoc.ID)}} else {@@ -399,7 +402,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTerr = ErrBlockNotFoundreturn}- toHP = path.Join(parentDoc.HPath, headingText)+ toHP = parentDoc.HPath + "/" + headingTexttoFolder = path.Join(path.Dir(targetPath), parentDoc.ID)}}@@ -461,7 +464,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toTnewTree.Box, newTree.Path = targetBoxID, newTargetPathnewTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())- newTree.Root.Spec = treenode.CurrentSpec+ newTree.Root.Spec = treenode.BaseSpecif "" != previousPath {box.addSort(previousPath, newTree.ID)} else if toTop {diff --git a/kernel/model/heading_doc_test.go b/kernel/model/heading_doc_test.goindex 0554034b59..760fef00dd 100644--- a/kernel/model/heading_doc_test.go+++ b/kernel/model/heading_doc_test.go@@ -37,6 +37,7 @@ func TestHeadingDocParagraph(t *testing.T) {{"plain", "Test", "Test", false},{"escaped text", "A & B", "A & B", false},{"slash", "A/B", "A_B", true},+ {"literal slash retained in title", "A/B", "A/B", false},{"truncated", strings.Repeat("标题", 20), "标题...", true},{"image", "Test ", "Test image", true},{"image only", "", "image", true},diff --git a/kernel/model/history.go b/kernel/model/history.goindex e3c505e419..3963aa1807 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -479,7 +479,7 @@ func RollbackDocHistory(historyPath string) (err error) {ReloadFiletree()ReloadProtyle(rootID)- msg := fmt.Sprintf(Conf.Language(286), path.Join(box.Name, tree.HPath))+ msg := fmt.Sprintf(Conf.Language(286), box.Name+tree.HPath)util.PushMsg(msg, 7000)IncSync()diff --git a/kernel/model/import.go b/kernel/model/import.goindex 9820710ae4..89e6adfee1 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -53,6 +53,7 @@ import ("github.com/siyuan-note/siyuan/kernel/av""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/task"@@ -1494,8 +1495,8 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)}defer spool.close()stagedCount, stagedBytes := 0, 0- stageTree := func(tree *parse.Tree) error {- if err := spool.add(tree); err != nil {+ stageTree := func(tree *parse.Tree, sourcePath string) error {+ if err := spool.addSource(tree, sourcePath); err != nil {return err}stagedCount++@@ -1571,11 +1572,11 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)if skipRoot {hPathRoot = ""}- hPath := path.Join(baseHPath, hPathRoot, filepath.ToSlash(strings.TrimPrefix(currentPath, localPath)))- hPath = strings.TrimSuffix(hPath, ext)+ externalPath := strings.TrimSuffix(path.Join("/", hPathRoot, filepath.ToSlash(strings.TrimPrefix(currentPath, localPath))), ext)+ hPath := appendDocumentHPath(baseHPath, strings.TrimPrefix(externalPath, "/"))if "" == curRelPath {curRelPath = "/"- hPath = path.Join(baseHPath, title)+ hPath = appendDocumentHPath(baseHPath, title)} else {dirPath := targetPaths[path.Dir(curRelPath)]targetPath = path.Join(dirPath, id)@@ -1608,7 +1609,7 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)}tree = treenode.NewTree(boxID, targetPath, hPath, title)- if err := stageTree(tree); err != nil {+ if err := stageTree(tree, externalPath); err != nil {return err}return nil@@ -1636,11 +1637,16 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)if "" != yfmTitle {title = yfmTitle}- unescapedTitle, unescapeErr := url.PathUnescape(title)- if nil == unescapeErr {- title = unescapedTitle+ if documentaddressing.DefaultMode() == 1 {+ if unescapedTitle, unescapeErr := url.PathUnescape(title); unescapeErr == nil {+ title = unescapedTitle+ }}- hPath = path.Join(path.Dir(hPath), title)+ parentDisplay := baseHPath+ if curRelPath != "/" {+ parentDisplay = appendDocumentHPath(baseHPath, strings.TrimPrefix(path.Dir(externalPath), "/"))+ }+ hPath = appendDocumentHPath(parentDisplay, title)updated := yfmUpdatedfname := path.Base(targetPath)targetPath = strings.ReplaceAll(targetPath, fname, id+".sy")@@ -1655,7 +1661,8 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)tree.Path = targetPathtargetPaths[curRelPath] = targetPathtree.HPath = hPath- tree.Root.Spec = treenode.CurrentSpec+ tree.Root.Spec = treenode.BaseSpec+ treenode.UpgradeSpec(tree)currentDir := filepath.Dir(currentPath)ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {@@ -1744,11 +1751,11 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)})reassignIDUpdated(tree, id, updated)- if err := stageTree(tree); err != nil {+ if err := stageTree(tree, externalPath); err != nil {return err}- hPathsIDs[tree.HPath] = tree.ID+ hPathsIDs[externalPath] = tree.IDidPaths[tree.ID] = tree.Pathcount++@@ -1788,9 +1795,10 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)if "" != yfmTitle {title = yfmTitle}- unescapedTitle, unescapeErr := url.PathUnescape(title)- if nil == unescapeErr {- title = unescapedTitle+ if documentaddressing.DefaultMode() == 1 {+ if unescapedTitle, unescapeErr := url.PathUnescape(title); unescapeErr == nil {+ title = unescapedTitle+ }}updated := yfmUpdatedfname := path.Base(targetPath)@@ -1802,8 +1810,9 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)tree.Root.SetIALAttr("title", title)tree.Box = boxIDtree.Path = targetPath- tree.HPath = path.Join(baseHPath, title)- tree.Root.Spec = treenode.CurrentSpec+ tree.HPath = appendDocumentHPath(baseHPath, title)+ tree.Root.Spec = treenode.BaseSpec+ treenode.UpgradeSpec(tree)localPathParentDir := filepath.Dir(localPath)ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {@@ -1886,7 +1895,7 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)reassignIDUpdated(tree, id, updated)// 兜底校验:禁止跨加密边界块引(导入的 Markdown 可能含跨边界引用)degradeCrossBoundaryBlockRefs(tree.Root, tree.Box)- if err := stageTree(tree); err != nil {+ if err := stageTree(tree, "/"+strings.TrimSuffix(fileName, util.Ext(fileName))); err != nil {return err}}@@ -1894,6 +1903,9 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)var importedRootIDs []stringif len(spool.entries) > 0 {spool.movePaths(moveIDs)+ if err = spool.refreshDisplayPaths(baseTargetPath, baseHPath); err != nil {+ return err+ }for _, entry := range spool.entries {if _, ok := idPaths[entry.id]; ok {idPaths[entry.id] = entry.pathdiff --git a/kernel/model/import_document_target_fts5_test.go b/kernel/model/import_document_target_fts5_test.goindex 90121b506e..261f42c7e1 100644--- a/kernel/model/import_document_target_fts5_test.go+++ b/kernel/model/import_document_target_fts5_test.go@@ -6,10 +6,25 @@ 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")func TestImportNotebookDocumentTargets(t *testing.T) {+ testImportNotebookDocumentTargets(t, "Anchor")+}++func TestStructuredTitlesNativeImport(t *testing.T) {+ if documentaddressing.DefaultMode() != 2 {+ t.Skip("covered by the structured-title release-gate CI run")+ }+ testImportNotebookDocumentTargets(t, "Anchor/../literal")+}++func testImportNotebookDocumentTargets(t *testing.T, title string) {+ t.Helper()const sourceBoxID, targetBoxID = "20261023092000-source1", "20261023092001-target1"const docID = "20261023092002-documen"setupExportRelatedTest(t, sourceBoxID, targetBoxID)@@ -22,7 +37,9 @@ func TestImportNotebookDocumentTargets(t *testing.T) {if err := source.SaveConf(sourceConf); err != nil {t.Fatal(err)}- writeExportRelatedTestTree(t, treenode.NewTree(sourceBoxID, "/"+docID+".sy", "/Anchor", "Anchor"))+ tree := treenode.NewTree(sourceBoxID, "/"+docID+".sy", "/"+title, title)+ treenode.UpgradeSpec(tree)+ writeExportRelatedTestTree(t, tree)if err := writeBoxDocID(sourceBoxID); err != nil {t.Fatal(err)}@@ -35,6 +52,10 @@ func TestImportNotebookDocumentTargets(t *testing.T) {t.Fatal(err)}imported := (&Box{ID: targetBoxID}).GetConf()+ loaded, err := filesys.LoadTree(targetBoxID, "/"+ids[docID]+".sy", util.NewLute())+ if err != nil || treenode.ReadDocumentTitle(loaded.Root).Text != title || loaded.Root.Spec != tree.Root.Spec {+ t.Fatal("native import changed the title or source specification", err)+ }for _, target := range []*conf.DocumentTarget{imported.DocCreateTarget, imported.RefCreateTarget, imported.DailyNoteTarget} {if target == nil || target.Notebook != targetBoxID || target.Anchor.ID != ids[docID] || target.Anchor.ID == docID ||target.Title != "Literal template" {diff --git a/kernel/model/import_markdown.go b/kernel/model/import_markdown.goindex 2cb0a863bb..73e7f8f9a4 100644--- a/kernel/model/import_markdown.go+++ b/kernel/model/import_markdown.go@@ -29,6 +29,7 @@ const markdownImportBatchBytes = 8 * 1024 * 1024type markdownImportEntry struct {id, box, path, hpath string+ sourcePath, title stringrootType stringhasRootType booloffset int64@@ -71,6 +72,11 @@ func markdownImportAAD(index int) []byte {}func (spool *markdownImportSpool) add(tree *parse.Tree) error {+ return spool.addSource(tree, tree.HPath)+}++// addSource 将外部链接位置与文档显示标题分开,标题中的斜杠不参与相对文件定位。+func (spool *markdownImportSpool) addSource(tree *parse.Tree, sourcePath string) error {if err := treenode.SyncTableCellRichInlineChanges(tree.Root); err != nil {return err}@@ -82,8 +88,9 @@ func (spool *markdownImportSpool) add(tree *parse.Tree) error {spool.singleTree = treespool.entries = append(spool.entries, markdownImportEntry{id: tree.ID, box: tree.Box, path: tree.Path, hpath: tree.HPath,+ sourcePath: sourcePath, title: treenode.ReadDocumentTitle(tree.Root).Text,})- addImportSearchLinks(tree, spool.searchLinks)+ spool.addSourceLinks(tree, sourcePath)return nil}luteEngine := util.NewLute()@@ -103,6 +110,7 @@ func (spool *markdownImportSpool) add(tree *parse.Tree) error {}entry := markdownImportEntry{id: tree.ID, box: tree.Box, path: tree.Path, hpath: tree.HPath,+ sourcePath: sourcePath, title: treenode.ReadDocumentTitle(tree.Root).Text,offset: offset, size: len(ciphertext), rawSize: len(raw),}for _, attribute := range tree.Root.KramdownIAL {@@ -112,7 +120,49 @@ func (spool *markdownImportSpool) add(tree *parse.Tree) error {}}spool.entries = append(spool.entries, entry)- addImportSearchLinks(tree, spool.searchLinks)+ spool.addSourceLinks(tree, sourcePath)+ return nil+}++func (spool *markdownImportSpool) addSourceLinks(tree *parse.Tree, sourcePath string) {+ view := *tree+ view.HPath = sourcePath+ addImportSearchLinks(&view, spool.searchLinks)+}++// refreshDisplayPaths 使用暂存身份关系修正前置元数据标题,不从显示文本拆分父级。+func (spool *markdownImportSpool) refreshDisplayPaths(basePath, baseHPath string) error {+ entries := map[string]*markdownImportEntry{}+ for i := range spool.entries {+ entry := &spool.entries[i]+ entries[strings.TrimSuffix(entry.path, ".sy")] = entry+ }+ resolved := map[string]string{basePath: baseHPath}+ var resolve func(string) (string, error)+ resolve = func(idPath string) (string, error) {+ if display, ok := resolved[idPath]; ok {+ return display, nil+ }+ entry := entries[idPath]+ if entry == nil {+ return "", fmt.Errorf("Markdown import parent identity is missing: %s", idPath)+ }+ parent, err := resolve(path.Dir(idPath))+ if err != nil {+ return "", err+ }+ entry.hpath = appendDocumentHPath(parent, entry.title)+ resolved[idPath] = entry.hpath+ return entry.hpath, nil+ }+ for idPath := range entries {+ if _, err := resolve(idPath); err != nil {+ return err+ }+ }+ if spool.singleTree != nil {+ spool.singleTree.HPath = spool.entries[0].hpath+ }return nil}@@ -180,7 +230,12 @@ func (spool *markdownImportSpool) finish(write func(*parse.Tree) error, flush fuif err != nil {return fmt.Errorf("read Markdown import staging entry %d: %w", i, err)}- if err = convertMarkdownImportTree(tree, spool.searchLinks, luteEngine); err != nil {+ // 链接转换只借用外部文件位置;恢复显示路径后才交给文档写入器。+ displayPath := tree.HPath+ tree.HPath = entry.sourcePath+ err = convertMarkdownImportTree(tree, spool.searchLinks, luteEngine)+ tree.HPath = displayPath+ if err != nil {return err}if err = write(tree); err != nil {diff --git a/kernel/model/import_markdown_batch_fts5_test.go b/kernel/model/import_markdown_batch_fts5_test.goindex 7eb42c0102..1854aff7c7 100644--- a/kernel/model/import_markdown_batch_fts5_test.go+++ b/kernel/model/import_markdown_batch_fts5_test.go@@ -14,6 +14,7 @@ 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"@@ -21,6 +22,18 @@ import ()func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {+ testMarkdownImportBatches(t, "Renamed parent")+}++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")+}++func testMarkdownImportBatches(t *testing.T, parentTitle string) {+ t.Helper()for _, encrypted := range []bool{false, true} {t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {const boxID = "20261010000000-batch01"@@ -80,7 +93,7 @@ func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {if err := os.MkdirAll(filepath.Join(source, "parent"), 0755); err != nil {t.Fatal(err)}- if err := os.WriteFile(filepath.Join(source, "parent.md"), []byte("---\ndate: 2020-01-02\ntitle: Renamed parent\n---\n\n[[parent/child|child]]"), 0600); err != nil {+ if err := os.WriteFile(filepath.Join(source, "parent.md"), []byte(fmt.Sprintf("---\ndate: 2020-01-02\ntitle: %s\n---\n\n[[parent/child|child]]", parentTitle)), 0600); err != nil {t.Fatal(err)}if err := os.WriteFile(filepath.Join(source, "parent", "child.markdown"), []byte("child content"), 0600); err != nil {@@ -141,11 +154,14 @@ func TestMarkdownImportBatchesPreserveReferencesAndEncryption(t *testing.T) {t.Fatal("encrypted import wrote a plaintext document")}}- parent := treenode.GetBlockTreeRootByHPath(boxID, "/Renamed parent")- child := treenode.GetBlockTreeRootByHPath(boxID, "/parent/child")+ parent := treenode.GetBlockTreeRootByHPath(boxID, "/"+parentTitle)+ child := treenode.GetBlockTreeRootByHPath(boxID, "/"+parentTitle+"/child")if parent == nil || child == nil || !strings.HasPrefix(child.Path, "/"+parent.ID+"/") {t.Fatal("front matter root ID did not relocate child documents")}+ if old := treenode.GetBlockTreeRootByHPath(boxID, "/parent/child"); old != nil {+ t.Fatal("child display path retained the external filename instead of the parent title")+ }if _, err := os.Stat(filepath.Join(source, "doc-000.md")); err != nil {t.Fatal("import altered source Markdown")}diff --git a/kernel/model/import_markdown_spool_test.go b/kernel/model/import_markdown_spool_test.goindex 42972b873b..4fc3afdf12 100644--- a/kernel/model/import_markdown_spool_test.go+++ b/kernel/model/import_markdown_spool_test.go@@ -110,6 +110,54 @@ func TestMarkdownImportSpoolPreservesConversion(t *testing.T) {}}+func TestMarkdownImportSpoolSeparatesFilePathsFromTitles(t *testing.T) {+ setupMarkdownSpoolTest(t)+ spool, err := newMarkdownImportSpool()+ if err != nil {+ t.Fatal(err)+ }+ defer spool.close()+ parent := markdownSpoolFixture("[[folder/child|child]]", "Parent/../title", 1)+ child := markdownSpoolFixture("[[../folder|parent]]", "Child//title", 2)+ child.Path = "/" + parent.ID + "/" + child.ID + ".sy"+ for _, fixture := range []struct {+ tree *parse.Tree+ source string+ }{+ {parent, "/folder"}, {child, "/folder/child"},+ } {+ if err = spool.addSource(fixture.tree, fixture.source); err != nil {+ t.Fatal(err)+ }+ }+ if err = spool.refreshDisplayPaths("/", "/"); err != nil {+ t.Fatal(err)+ }+ expected := map[string]string{parent.ID: child.ID, child.ID: parent.ID}+ if err = spool.finish(func(tree *parse.Tree) error {+ got := ""+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && treenode.IsBlockRef(n) {+ got = n.TextMarkBlockRefID+ }+ return ast.WalkContinue+ })+ if got != expected[tree.ID] {+ t.Fatalf("file link resolved through title: %s => %s", tree.ID, got)+ }+ wantPath := "/Parent/../title"+ if tree.ID == child.ID {+ wantPath += "/Child//title"+ }+ if tree.HPath != wantPath {+ t.Fatalf("display path: %q", tree.HPath)+ }+ return nil+ }, func() {}); err != nil {+ t.Fatal(err)+ }+}+func TestMarkdownImportSpoolBoundsQueuedTrees(t *testing.T) {setupMarkdownSpoolTest(t)spool, err := newMarkdownImportSpool()diff --git a/kernel/model/import_obsidian.go b/kernel/model/import_obsidian.goindex 129f06b575..6dfdb75dae 100644--- a/kernel/model/import_obsidian.go+++ b/kernel/model/import_obsidian.go@@ -772,7 +772,7 @@ func planObsidianDocuments(ctx context.Context, vault *obsidianVaultContext) errdirDoc := dirDocs[obsidianPathKey(dir)]dirDoc.Title = uniqueObsidianTitle(parentTarget, dirDoc.Title, titleUses, vault.Analysis)dirDoc.TargetPath = path.Join(parentTarget, dirDoc.ID+".sy")- dirDoc.HPath = path.Join(parentHPath, dirDoc.Title)+ dirDoc.HPath = appendDocumentHPath(parentHPath, dirDoc.Title)contentTarget = path.Join(parentTarget, dirDoc.ID)contentHPath = dirDoc.HPath}@@ -797,7 +797,7 @@ func planObsidianDocuments(ctx context.Context, vault *obsidianVaultContext) errfor _, doc := range directDocs {doc.Title = uniqueObsidianTitle(contentTarget, doc.Title, titleUses, vault.Analysis)doc.TargetPath = path.Join(contentTarget, doc.ID+".sy")- doc.HPath = path.Join(contentHPath, doc.Title)+ doc.HPath = appendDocumentHPath(contentHPath, doc.Title)}var childDirs []string@@ -2344,7 +2344,8 @@ func assignObsidianTreeIDs(tree *parse.Tree, doc *obsidianDocPlan, reservedIDs mtree.HPath = doc.HPathtree.Root.Box = ""tree.Root.Path = doc.TargetPath- tree.Root.Spec = treenode.CurrentSpec+ tree.Root.Spec = treenode.BaseSpec+ treenode.UpgradeSpec(tree)tree.Root.SetIALAttr("id", doc.ID)tree.Root.SetIALAttr("title", doc.Title)tree.Root.SetIALAttr("updated", util.TimeFromID(doc.ID))diff --git a/kernel/model/listitem.go b/kernel/model/listitem.goindex 530ae387cf..8a4ca14763 100644--- a/kernel/model/listitem.go+++ b/kernel/model/listitem.go@@ -22,6 +22,7 @@ import ("github.com/88250/lute/ast""github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -46,10 +47,14 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, tbox := Conf.Box(targetBoxID)listItemText := sql.GetContainerText(listItemNode)- listItemText = util.FilterFileName(listItemText)+ if documentaddressing.DefaultMode() == 2 {+ listItemText = normalizeDocumentTitle(listItemText)+ } else {+ listItemText = util.FilterFileName(listItemText)+ }moveToRoot := "/" == targetPath- toHP := path.Join("/", listItemText)+ toHP := "/" + listItemTexttoFolder := "/"if "" != previousPath {@@ -66,7 +71,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, terr = ErrBlockNotFoundreturn}- toHP = path.Join(parentDoc.HPath, listItemText)+ toHP = parentDoc.HPath + "/" + listItemTexttoFolder = path.Join(path.Dir(parentPath), parentDoc.ID)}} else {@@ -76,7 +81,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, terr = ErrBlockNotFoundreturn}- toHP = path.Join(parentDoc.HPath, listItemText)+ toHP = parentDoc.HPath + "/" + listItemTexttoFolder = path.Join(path.Dir(targetPath), parentDoc.ID)}}@@ -104,7 +109,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, tnewTree.Box, newTree.Path = targetBoxID, newTargetPathnewTree.Root.SetIALAttr("updated", util.CurrentTimeSecondsStr())- newTree.Root.Spec = treenode.CurrentSpec+ newTree.Root.Spec = treenode.BaseSpecif "" != previousPath {box.addSort(previousPath, newTree.ID)} else if toTop {diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 267abc3b7b..e3f77cd08a 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -356,7 +356,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {ReloadFiletree()ReloadProtyle(rootID)- msg := fmt.Sprintf(Conf.Language(286), path.Join(box.Name, tree.HPath))+ msg := fmt.Sprintf(Conf.Language(286), box.Name+tree.HPath)util.PushMsg(msg, 7000)} else {to := filepath.Join(util.DataDir, file.Path)diff --git a/kernel/model/search.go b/kernel/model/search.goindex d4e644ed4f..3c416cea95 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -46,6 +46,7 @@ import ("github.com/jinzhu/copier""github.com/siyuan-note/logging""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/search""github.com/siyuan-note/siyuan/kernel/sql"@@ -574,8 +575,14 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBracif !isDatabase {// 如果非数据库中搜索块引,则不允许新建重名文档if block := treenode.GetBlockTreeInBox(id, boxID); nil != block {- p := path.Join(block.HPath, keyword)- newDoc = nil == treenode.GetBlockTreeRootByHPath(block.BoxID, p)+ if documentaddressing.DefaultMode() == 2 {+ parentID := block.RootID+ resolved, resolveErr := ResolveDocPath(block.BoxID, "document", &parentID, []string{keyword})+ newDoc = resolveErr == nil && resolved.Status == "missing"+ } else {+ p := path.Join(block.HPath, keyword)+ newDoc = nil == treenode.GetBlockTreeRootByHPath(block.BoxID, p)+ }}} else { // 如果是数据库中搜索绑定块,则允许新建重名文档 https://github.com/siyuan-note/siyuan/issues/11713newDoc = true@@ -592,14 +599,24 @@ func filterSelfHPath(blocks []*Block) {for _, b := range blocks {if b.IsDoc() {- b.HPath = trimSelfHPath(b.HPath)+ if documentaddressing.DefaultMode() == 2 {+ if metadata, err := treenode.GetDocumentMetadata(b.Box, b.RootID); err == nil {+ b.HPath = trimDocumentTitleHPath(b.HPath, metadata.Title.Text)+ }+ } else {+ b.HPath = trimSelfHPath(b.HPath)+ }}}}func trimSelfHPath(hPath string) string {+ return trimDocumentTitleHPath(hPath, "")+}++func trimDocumentTitleHPath(hPath, title string) string {inTag := false- lastSlash := -1+ var separators []intfor i, r := range hPath {switch r {case '<':@@ -608,14 +625,19 @@ func trimSelfHPath(hPath string) string {inTag = falsecase '/':if !inTag {- lastSlash = i+ separators = append(separators, i)}}}- if 0 > lastSlash {+ position := len(separators) - strings.Count(title, "/") - 1+ if position < 0 {return hPath}- return hPath[:lastSlash+1]+ prefix := hPath[:separators[position]+1]+ if strings.Count(prefix, "<mark>") > strings.Count(prefix, "</mark>") {+ prefix += "</mark>"+ }+ return prefix}func prependNotebookNameInHPath(blocks []*Block) {diff --git a/kernel/model/search_test.go b/kernel/model/search_test.goindex b728baf333..68d0614271 100644--- a/kernel/model/search_test.go+++ b/kernel/model/search_test.go@@ -604,6 +604,20 @@ func TestFromFTSAndHPathMatchSQLBlockMarksMatchSource(t *testing.T) {}}+func TestTrimDocumentTitleHPath(t *testing.T) {+ for _, test := range []struct{ path, title, want string }{+ {"Notebook/A/B", "A/B", "Notebook/"},+ {"Notebook/Parent//A//B/", "A//B/", "Notebook/Parent//"},+ {"Notebook/<mark>Parent/A</mark>/B", "A/B", "Notebook/<mark>Parent/</mark>"},+ {"Notebook/<mark>Parent</mark>/A/<mark>B</mark>", "A/B", "Notebook/<mark>Parent</mark>/"},+ {"Notebook/Parent/A&B/<C>", "A&B/<C>", "Notebook/Parent/"},+ } {+ if got := trimDocumentTitleHPath(test.path, test.title); got != test.want {+ t.Errorf("%q with %q: got %q, want %q", test.path, test.title, got, test.want)+ }+ }+}+func TestFilterSelfHPathPreservesHighlight(t *testing.T) {setSearchCaseSensitive(t, true)multipleKeywords := fromHPathSearchSQLBlock(&sql.Block{diff --git a/kernel/model/structured_titles_test.go b/kernel/model/structured_titles_test.gonew file mode 100644index 0000000000..b8a084e209--- /dev/null+++ b/kernel/model/structured_titles_test.go@@ -0,0 +1,154 @@+//go:build fts5++package model++import (+ "bytes"+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "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"+)++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()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStructuredTitlesCreationAndIdentity$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_STRUCTURED_TITLES=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("structured titles: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ t.Cleanup(backgroundRefreshWaitGroup.Wait)+ box := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Titles", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ ordinary := newHPathTestDoc(t, box.ID, "/", "Existing", 1)+ oldSource, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, ordinary.Path))+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ create := func(parent *string, title string) *treenode.DocumentPath {+ t.Helper()+ ret, err := CreateDocByParent(DocumentCreateRequest{Notebook: box.ID, ParentID: parent, ID: ast.NewNodeID(),+ TitleFormat: "plain", Title: title, Markdown: "body"})+ if err != nil || ret.Title.Text != title || ret.AddressingVersion != 2 {+ t.Fatalf("create %q: %+v %v", title, ret, err)+ }+ return ret+ }+ literal := create(nil, "A/B")+ parent := create(nil, "A")+ child := create(&parent.ID, "B")+ if literal.DisplayPath != child.DisplayPath || literal.Depth != 1 || child.Depth != 2 {+ t.Fatal("display path changed identity")+ }+ for _, item := range []struct {+ segments []string+ id string+ }{{[]string{"A/B"}, literal.ID}, {[]string{"A", "B"}, child.ID}} {+ resolved, err := ResolveDocPath(box.ID, "root", nil, item.segments)+ if err != nil || resolved.Resolved == nil || resolved.Resolved.ID != item.id {+ t.Fatal(resolved, err)+ }+ }+ leaf := create(&literal.ID, "C/../D & **literal**")+ loaded, err := filesys.LoadTree(box.ID, leaf.Path, util.NewLute())+ if err != nil || loaded.Root.Spec != treenode.DocumentTitleSpec {+ t.Fatal("title spec not recorded", err)+ }+ leafBefore, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, leaf.Path))+ if err = RenameDoc(box.ID, literal.Path, "Parent/renamed"); err != nil {+ t.Fatal(err)+ }+ leafAfter, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, leaf.Path))+ if !bytes.Equal(leafBefore, leafAfter) {+ t.Fatal("parent rename rewrote descendant source")+ }+ paths, missing, err := GetDocPaths(box.ID, []string{leaf.ID})+ if err != nil || len(missing) != 0 || paths[0].Depth != 2 || paths[0].Segments[0].Text != "Parent/renamed" ||+ paths[0].Title.Text != leaf.Title.Text {+ t.Fatal(paths, missing, err)+ }+ if _, err = GetIDsByHPath("/A/B", box.ID); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ t.Fatal(err)+ }+ if _, err = CreateWithMarkdown("", box.ID, "/Plain", "", parent.ID, ast.NewNodeID(), false, "", nil); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {+ t.Fatal(err)+ }+ newSource, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, ordinary.Path))+ if !bytes.Equal(oldSource, newSource) || ordinary.Root.Spec != treenode.BaseSpec {+ t.Fatal("unused title capability upgraded an existing source")+ }++ for _, test := range []struct {+ markdown, title string+ typeOf ast.NodeType+ convert func(string, string, string, string, bool) (string, string, error)+ }{+ {"# Heading/part\n\nBody", "Heading/part", ast.NodeHeading, Heading2Doc},+ {"- Item/part", "Item/part", ast.NodeListItem, ListItem2Doc},+ } {+ source, createErr := CreateDocByParent(DocumentCreateRequest{Notebook: box.ID, ID: ast.NewNodeID(),+ TitleFormat: "plain", Title: "Conversion source", Markdown: test.markdown})+ if createErr != nil {+ t.Fatal(createErr)+ }+ tree, loadErr := filesys.LoadTree(box.ID, source.Path, util.NewLute())+ if loadErr != nil {+ t.Fatal(loadErr)+ }+ blockID := ""+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {+ if entering && n.Type == test.typeOf {+ blockID = n.ID+ return ast.WalkStop+ }+ return ast.WalkContinue+ })+ _, convertedPath, convertErr := test.convert(blockID, box.ID, "/", "", false)+ if convertErr != nil {+ t.Fatal(convertErr)+ }+ converted, loadErr := filesys.LoadTree(box.ID, convertedPath, util.NewLute())+ if loadErr != nil || treenode.ReadDocumentTitle(converted.Root).Text != test.title ||+ converted.Root.Spec != treenode.DocumentTitleSpec {+ t.Fatal("conversion changed literal title or source spec", test.title, loadErr)+ }+ }++ // 新模式的旧模板也拒绝同名祖先,不任取匹配项;显式标题中的斜杠保持原文。+ create(nil, "A")+ boxConf.DocCreateSavePath = "/A/Leaf"+ if err = box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if _, err = PlanDocumentCreation(DocumentPlanRequest{Notebook: box.ID, Purpose: "document", ID: ast.NewNodeID()}); err == nil {+ t.Fatal("ambiguous legacy template selected an arbitrary ancestor")+ }+ title := "Literal/final"+ plan, err := PlanDocumentCreation(DocumentPlanRequest{Notebook: box.ID, Purpose: "document", ID: ast.NewNodeID(),+ ContextID: &literal.ID, Placement: "child", Title: &title})+ if err != nil || len(plan.Steps) != 1 || plan.Title != title {+ t.Fatal(plan, err)+ }+}diff --git a/kernel/model/template.go b/kernel/model/template.goindex 3c4c909644..ad61573f13 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -1039,7 +1039,7 @@ func renderTemplateSourceAt(p, id string, mode TemplateRenderMode, content *strireturn}var location *treenode.DocumentPath- location, err = treenode.GetDocumentPath(sourceTree.Box, sourceTree.ID, sourceTree.Box, 1)+ location, err = getDocumentPath(sourceTree.Box, sourceTree.ID)if err != nil {return}diff --git a/kernel/model/template_doc_tree.go b/kernel/model/template_doc_tree.goindex ca645b6604..5e49824491 100644--- a/kernel/model/template_doc_tree.go+++ b/kernel/model/template_doc_tree.go@@ -154,7 +154,7 @@ func (state *templateDocTreeParseState) parseNodes(value any, depth int) ([]*Temif !ok {return nil, errors.New("createDocTree document title must be a string")}- title = normalizeDocTitle(title)+ title = normalizeDocumentTitle(title)if "" == title {return nil, errors.New("createDocTree document title must not be empty")}@@ -235,7 +235,7 @@ func (collector *templateDocTreeCollector) bindNodes(nodes []*TemplateDocTreeNodfor _, node := range nodes {node.ParentID = parentIDnode.path = strings.TrimSuffix(parentPath, ".sy") + "/" + node.ID + ".sy"- node.HPath = strings.TrimRight(parentHPath, "/") + "/" + node.Title+ node.HPath = parentHPath + "/" + node.Titlecollector.bindNodes(node.Children, node.ID, node.path, node.HPath)}}@@ -322,7 +322,7 @@ func (collector *templateDocTreeCollector) buildTree(node *TemplateDocTreeNode,renderedTree.HPath = node.HPathrenderedTree.ID = node.IDrenderedTree.Root.ID = node.ID- renderedTree.Root.Spec = treenode.CurrentSpec+ renderedTree.Root.Spec = treenode.BaseSpectemplateIALs := parse.IAL2Map(renderedTree.Root.KramdownIAL)renderedTree.Root.KramdownIAL = [][]string{{"id", node.ID},@@ -509,7 +509,7 @@ func AttachTemplateDocTreePlans(transactions []*Transaction) (attached bool, errplan.rootRevision == "" {return false, errors.New("the document used to render the template has changed")}- location, locationErr := treenode.GetDocumentPath(plan.boxID, plan.rootID, plan.boxID, 1)+ location, locationErr := getDocumentPath(plan.boxID, plan.rootID)if locationErr != nil || location.Revision != plan.rootRevision {return false, errors.New("the document used to render the template has changed")}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 51b332e415..b302b672a8 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2900,7 +2900,7 @@ func (tx *Transaction) begin() (err error) {return errors.New("the document used to render the template has changed")}if expectedTemplateDocTreeRevision != "" {- location, err := treenode.GetDocumentPath(snapshot.Box, snapshot.ID, snapshot.Box, 1)+ location, err := getDocumentPath(snapshot.Box, snapshot.ID)if err != nil || location.Revision != expectedTemplateDocTreeRevision {return errors.New("the document used to render the template has changed")}@@ -3026,7 +3026,7 @@ func (tx *Transaction) commit() (err error) {if root == nil {return errors.New("template document tree parent snapshot is missing")}- location, err := treenode.GetDocumentPath(root.Box, root.ID, root.Box, 1)+ location, err := getDocumentPath(root.Box, root.ID)if err != nil || location.Revision != tx.templateDocTreeCommitRevision {return errors.New("the document used to render the template has changed")}diff --git a/kernel/treenode/document_source.go b/kernel/treenode/document_source.goindex ddaca1de37..f27886d6fd 100644--- a/kernel/treenode/document_source.go+++ b/kernel/treenode/document_source.go@@ -11,7 +11,7 @@ import ()// checkDocumentSourceJSON 保留重复字段中遇到的兼容错误,在容错解析前确定标题和源版本能否处理。-func checkDocumentSourceJSON(data []byte) (string, error) {+func checkDocumentSourceJSON(data []byte, mode int) (string, error) {if !bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) {return "", errors.New("invalid document source")}@@ -19,6 +19,7 @@ func checkDocumentSourceJSON(data []byte) (string, error) {Spec documentSourceSpecProperties documentSourceProperties}+ root.Properties.mode = modeif err := json.Unmarshal(data, &root); err != nil {return "", err}@@ -52,11 +53,12 @@ func (spec *documentSourceSpec) UnmarshalJSON(data []byte) error {}type documentSourceProperties struct {- err error+ err error+ mode int}func (properties *documentSourceProperties) UnmarshalJSON(data []byte) error {- if err := documentaddressing.CheckLegacyTitleProperties(data); err != nil {+ if err := documentaddressing.CheckTitleProperties(data, properties.mode); err != nil {if properties.err == nil || errors.Is(err, documentaddressing.ErrModeConflict) {properties.err = err}diff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.goindex 1942b8e096..5b28989077 100644--- a/kernel/treenode/tree.go+++ b/kernel/treenode/tree.go@@ -152,13 +152,20 @@ func ContainOnlyDefaultIAL(tree *parse.Tree) bool {const BaseSpec = "2"-var CurrentSpec = "5"+const DocumentTitleSpec = "6"++var CurrentSpec = DocumentTitleSpecvar ErrSpecTooNew = fmt.Errorf("the document spec is too new")-// CheckSpecJSON 在解析节点之前检查文档规范,避免未知节点被容错解析后覆盖原始内容。+// CheckSpecJSON 按当前发行版能力校验独立源(如导入和历史),不能代替笔记本模式与授权预检。+// 在解析节点之前检查,避免未知节点被容错解析后覆盖原始内容。func CheckSpecJSON(data []byte) error {- spec, err := checkDocumentSourceJSON(data)+ return CheckSpecJSONForMode(data, documentaddressing.DefaultMode())+}++func CheckSpecJSONForMode(data []byte, mode int) error {+ spec, err := checkDocumentSourceJSON(data, mode)if err != nil {return err}@@ -166,9 +173,14 @@ func CheckSpecJSON(data []byte) error {}func CheckSpec(tree *parse.Tree) (err error) {- if err = documentaddressing.CheckLegacyTitle(tree.Root.IALAttr("title")); err != nil {+ return CheckSpecForMode(tree, documentaddressing.DefaultMode())+}++func CheckSpecForMode(tree *parse.Tree, mode int) (err error) {+ if err = documentaddressing.CheckLegacyTitle(tree.Root.IALAttr("title")); mode < 2 && err != nil {return}+ err = nilif err = ValidateTableCellRich(tree.Root); nil != err {return}@@ -224,6 +236,10 @@ func UpgradeSpec(tree *parse.Tree) (upgraded bool) {return ast.WalkContinue})}+ if version, err := strconv.Atoi(tree.Root.Spec); err == nil && version < 6 &&+ strings.Contains(tree.Root.IALAttr("title"), "/") {+ tree.Root.Spec = DocumentTitleSpec+ }return oldSpec != tree.Root.Spec}