Skip to content

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

:recycle: Retire mode 1 and validate legacy document paths https://github.com/siyuan-note/siyuan/issues/20892

Daniele12c24379bb1
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index dd688ef27c..2bf1d8f9d6 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1006,7 +1006,7 @@ export type DocVersionRefInput = { "id"?: string | null; "path"?: string | null;
export type DocsInfoRequestInput = { "av": boolean; "ids": Array<string>; "refCount": boolean; };
-export type DocumentAddressingFailure = { "reason": "invalidTitle" | "parentUnavailable" | "planChanged" | "documentIDConflict" | "legacyPathUnsupported" | "indexUnavailable" | "unsupportedTitleFormat" | "targetModeUnsupported" | "modeConflict" | "writeFailed"; };
+export type DocumentAddressingFailure = { "reason": "invalidTitle" | "parentUnavailable" | "planChanged" | "documentIDConflict" | "legacyPathUnsupported" | "pathAmbiguous" | "indexUnavailable" | "unsupportedTitleFormat" | "targetModeUnsupported" | "modeConflict" | "writeFailed"; };
export type DocumentCapabilities = { "addressingVersion": number; "indexState": "missing" | "building" | "ready" | "error"; "literalSlash": boolean; "minimumReaderVersion": string | null; "modeState": "legacy" | "structured" | "conflict" | "recovering"; "revision": string; "structuredPaths": boolean; "titleFormats": Array<string> | null; };
@@ -1490,7 +1490,7 @@ export type LegacyPathDocumentResult = string | LegacyPathUnsupported;
export type LegacyPathIDsResult = Array<string> | null | LegacyPathUnsupported;
-export type LegacyPathUnsupported = { "reason": "legacyPathUnsupported"; };
+export type LegacyPathUnsupported = { "cleanIDs"?: Array<string>; "reason": "legacyPathUnsupported" | "pathAmbiguous" | "indexUnavailable"; "unsupportedIDs"?: Array<string>; };
export type ListNotebooksData = { "boxDocEnabled": boolean; "notebooks": Array<Notebook | null> | null; };
@@ -5297,7 +5297,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
+ * 在写入前检查文档源格式及规范路径,预检失败返回 -1。
* 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。
* 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有源的读取和恢复不受此写入检查影响。
* 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
@@ -5325,10 +5325,10 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin"];
};
/**
- * 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+ * 在创建目标目录及复制前预检整批规范路径和文档源;预检不兼容时返回 -1,不写入目标。
* 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
* 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
- * 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+ * 原有敏感路径、加密笔记本和符号链接限制继续生效。
*/
"/api/file/globalCopyFiles": {
request: CopyFilesRequestInput;
@@ -5338,7 +5338,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
+ * 在创建目录、写入内容及更新时间前校验文档源格式与规范路径;不兼容时返回 -1。
* 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。
* 新传入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有低 Spec 源仍可读取并由合法内容替换。
* 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。
@@ -5359,8 +5359,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin"];
};
/**
- * 对不支持寻址模式的笔记本拒绝部分删除,返回 -1;整本删除保留已确认的本机能力下界。
- * 不能删除本机 conf/document-addressing.json 或其父目录,既有加密笔记本删除限制不变。
+ * 保留既有敏感路径和加密边界检查;整本删除不读取已撤销的寻址模式记录。
*/
"/api/file/removeFile": {
request: RemoveFileRequestInput;
@@ -5370,10 +5369,9 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
+ * 在创建目标父目录或移动源文件前预检文档源格式与规范路径,失败返回 -1。
* 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。
* 新移入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
- * 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。
*/
"/api/file/renameFile": {
request: RenameFileRequestInput;
@@ -5383,10 +5381,10 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+ * 在创建目标目录及复制前预检整批规范路径和文档源;预检不兼容时返回 -1,不写入目标。
* 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
* 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
- * 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+ * 原有敏感路径、加密笔记本和符号链接限制继续生效。
*/
"/api/file/workspaceCopyFiles": {
request: CopyFilesRequestInput;
@@ -5430,8 +5428,8 @@ export interface APIPOSTRoutes {
* 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。
* ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。
* 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。
- * 普通构建默认保留标题中的 /,该文档写入 Spec 6;普通文档不因迁移统一升级,内部兼容模式 1 仍拒绝 /。
- * 加密笔记本使用原有认证写入与响应租约;自动模式迁移不改变密文格式或密钥材料。
+ * 保留标题中的 /,新写入含斜杠标题使用 Spec 6;普通文档不统一升级规格。
+ * 加密笔记本使用原有认证写入与响应租约;寻址规则不改变密文格式或密钥材料。
*/
"/api/filetree/createDocByParent": {
request: CreateDocByParentRequestInput;
@@ -5443,7 +5441,10 @@ export interface APIPOSTRoutes {
/**
* 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。
* 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。
- * 模式 2 对整个笔记本返回 legacyPathUnsupported,即使提供 parentID;改用 createDocByParent。
+ * Every parent prefix is checked before writing; slash/empty-title candidates return pathAmbiguous.
+ * Multiple clean parents also return pathAmbiguous unless a valid matching parentID selects their
+ * real ancestor chain. An ID cannot bypass unsupported candidates. Unready or inconsistent metadata
+ * returns indexUnavailable. Prefer createDocByParent with a separate parent identity and title.
*/
"/api/filetree/createDocWithMd": {
request: FileTreeCreateMarkdownRequestInput;
@@ -5551,7 +5552,12 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated"];
};
/**
- * 在兼容模式保留旧名称路径查询;模式 2 整本返回 legacyPathUnsupported,改用 resolveDocPath。
+ * queries exact legacy display paths and verifies each candidate's real ancestor chain.
+ * Clean candidates have nonempty titles without ASCII / and no empty-title flag at every level.
+ * Returns every clean ID, an empty array for no matches, pathAmbiguous for mixed candidates,
+ * or legacyPathUnsupported for unsupported candidates only. Error data may include cleanIDs and
+ * unsupportedIDs, filtered by existing access restrictions. Missing, pending, inconsistent or failed
+ * metadata returns indexUnavailable. Prefer resolveDocPath with independent title segments.
*/
"/api/filetree/getIDsByHPath": {
request: FileTreeOptionalPathRequestInput;
@@ -5716,7 +5722,7 @@ export interface APIPOSTRoutes {
* 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。
* candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。
* 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。
- * 索引未就绪返回 indexUnavailable;普通构建默认保留段内 /,内部兼容模式 1 仍遵守原有标题限制。
+ * 索引未就绪返回 indexUnavailable;标题段保留字面 /,不按笔记本选择不同的寻址模式。
*/
"/api/filetree/resolveDocPath": {
request: ResolveDocPathRequestInput;
@@ -6234,7 +6240,7 @@ export interface APIPOSTRoutes {
proxy: {"kind":"http","contentType":"application/octet-stream","upstreamStatuses":true};
};
/**
- * 在改密恢复、密钥切换及迁移记录写入前预检全部现存加密笔记本,不支持的寻址模式返回 -1。
+ * 改密恢复和密钥切换保留现存加密笔记本的认证、信封格式及中断恢复检查。
*/
"/api/notebook/changeMasterPassword": {
request: ChangeMasterPasswordRequestInput;
@@ -6260,7 +6266,7 @@ export interface APIPOSTRoutes {
/**
* 移出已导出的加密笔记本,要求管理员权限并禁止只读模式;saved: true 表示用户确认已保存归档。
* 提交前重新检查源文件,内容变化需重新导出;重复提交同一归档不会重复移出,未选择的笔记本不受影响。
- * 移出前重新检查笔记本寻址能力,不支持的模式返回 -1,保留原归档及源目录。
+ * 移出前保留归档及源目录检查,失败时保留原归档和密钥材料。
*/
"/api/notebook/commitNotebookArchive": {
request: CommitNotebookArchiveRequestInput;
@@ -6321,12 +6327,11 @@ 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. Ordinary builds migrate to mode 2
- * automatically without a user setting or special build flags. literalSlash requires consistent
- * mode records and ready indexes. minimumReaderVersion stays null until the minimum compatible
+ * not permission to open a closed or locked notebook. All notebooks use addressing version 2
+ * without a user setting or special build flags. literalSlash requires ready indexes. minimumReaderVersion stays null until the minimum compatible
* feature release is verified; it neither controls activation nor permits mixing with older clients.
- * Revision covers configuration, confirmed capability and recovery records, not a document path.
- * Malformed capability records fail the request; authentication, locking and network failures must
+ * Revision identifies the fixed capability declaration, not a document path or retired record.
+ * Authentication, locking and network failures must
* never be interpreted as an absent capability object or as permission to retry a legacy write.
*/
"/api/notebook/getNotebookConf": {
@@ -6393,7 +6398,7 @@ export interface APIPOSTRoutes {
/**
* 接收已锁定的加密笔记本 ID,返回归档 ID 和下载路径,不删除源数据,要求管理员权限。
* 下载完成后,必须由用户确认已保存归档,再调用 `/api/notebook/commitNotebookArchive` 并传入 saved: true。
- * 不支持笔记本寻址模式时返回 -1,保留源目录及密钥材料。
+ * 源格式或认证检查失败时返回 -1,保留源目录及密钥材料。
*/
"/api/notebook/prepareNotebookArchive": {
request: PrepareNotebookArchiveRequestInput;
@@ -6465,7 +6470,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin"];
};
/**
- * 解锁及挂载均检查笔记本寻址能力;不支持的模式不会发布解锁状态或修复源数据。
+ * 解锁及挂载均保留源格式与认证检查;失败时不发布解锁状态或修复源数据。
*/
"/api/notebook/unlockAndOpenNotebook": {
request: UnlockNotebookRequestInput;
@@ -6475,7 +6480,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin","writable"];
};
/**
- * 在密钥恢复和解锁转换前拒绝不支持的笔记本寻址模式,保留原密文和恢复材料。
+ * 密钥恢复和解锁保持既有认证及源格式检查,保留原密文和恢复材料。
*/
"/api/notebook/unlockNotebook": {
request: UnlockNotebookRequestInput;
@@ -8102,8 +8107,7 @@ export interface APIPOSTRoutes {
authorization?: readonly ["authenticated","admin"];
};
/**
- * 保持单个 JSON 文件的设置压缩包,存在本机寻址能力下界时附加 documentAddressing 记录。
- * 记录仅含版本及笔记本身份的最低模式,不导出标题、正文或密钥;无能力记录的旧设置格式不变。
+ * 保持单个 JSON 文件的设置压缩包,不再附加已撤销的 documentAddressing 下界记录。
*/
"/api/system/exportConf": {
request: EmptyRequestInput;
diff --git a/docs/API.ja.md b/docs/API.ja.md
index cb1b836885..205d27d0c1 100644
--- a/docs/API.ja.md
+++ b/docs/API.ja.md
@@ -374,7 +374,7 @@ if (response.code === 0 && response.data) {
### Markdownでドキュメントを作成
-この旧名称パス API は互換モードでのみ利用できます。通常のビルドでは既定でノートブックが構造化タイトルモードに自動移行され、通常のタイトルや `parentID` を指定した場合も、ノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。`/api/filetree/createDocByParent` に親の識別情報とタイトルを別々に渡してください。以下の例は互換モードの動作を示します。
+この旧文字列作成 API は書き込み前にすべての親パスを検証します。祖先のタイトルにスラッシュや空のタイトルがある場合、`code: -1` と `data.reason: "pathAmbiguous"` を返します。同名の有効な親が複数ある場合は、一致する有効な `parentID` が必要です。メタデータが未準備の場合は `indexUnavailable` を返します。親 ID とタイトルを分けて渡す `/api/filetree/createDocByParent` を推奨します。
* `/api/filetree/createDocWithMd`
* パラメータ
@@ -758,7 +758,7 @@ if (response.code === 0 && response.data) {
### 人間が読めるパスからIDを取得
-通常のビルドでは既定でノートブックが構造化タイトルモードに自動移行され、この旧 API はノートブック全体で `code: -1`、`data: {reason: "legacyPathUnsupported"}` を返します。既知のドキュメント ID はそのまま使用し、不明な場所は `/api/filetree/resolveDocPath` にタイトルの配列を渡して解決してください。表示パスだけでは、単一のタイトル `A/B` と 2 階層の `A`、`B` を区別できません。以下の例は互換モード用です。
+この旧検索 API は各候補の実際の祖先を検証します。有効な候補だけならすべての ID を返し、有効な候補とスラッシュや空タイトルを含む候補が混在すると `pathAmbiguous`、後者だけなら `legacyPathUnsupported`、候補がなければ空配列を返します。メタデータが未準備または不整合の場合は `indexUnavailable` です。エラーの候補フィールド `cleanIDs` と `unsupportedIDs` にもアクセス制限を適用します。タイトルを独立した配列で指定する `/api/filetree/resolveDocPath` を推奨します。
* `/api/filetree/getIDsByHPath`
* パラメータ
diff --git a/docs/API.md b/docs/API.md
index 41dd93b76d..cf73ac3500 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -379,7 +379,7 @@ Administrator responses also include the optional read-only `documentCapabilitie
### Create a document with Markdown
-This legacy name-path endpoint is available only in compatibility mode. In ordinary builds, notebooks migrate automatically to structured-title mode by default and this endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook, even with ordinary titles or `parentID`. Use `/api/filetree/createDocByParent` with a separate parent identity and title. The examples below describe compatibility-mode behavior.
+Legacy string creation checks every parent prefix before writing. Slash or empty-title ancestors return `code: -1` with `data.reason: "pathAmbiguous"`. Multiple clean parents require a valid matching `parentID`; otherwise they also return `pathAmbiguous`. Unready metadata returns `indexUnavailable`. Prefer `/api/filetree/createDocByParent` with a separate parent identity and title.
* `/api/filetree/createDocWithMd`
* Parameters
@@ -763,7 +763,7 @@ Move documents by `id`:
### Get IDs based on human-readable path
-In ordinary builds, notebooks migrate automatically to structured-title mode by default and this legacy endpoint returns `code: -1`, `data: {reason: "legacyPathUnsupported"}` for the entire notebook. Use known document IDs directly, or `/api/filetree/resolveDocPath` with explicit title segments. Displayed paths cannot distinguish a single title `A/B` from two levels `A`, `B`. The example below applies to compatibility mode.
+Legacy lookup checks each candidate ancestor chain. It returns all clean matches, `pathAmbiguous` for mixed clean and slash/empty-title candidates, `legacyPathUnsupported` for unsupported candidates only, and an empty array for no matches. Unready or inconsistent metadata returns `indexUnavailable`. Error candidate lists are `cleanIDs` and `unsupportedIDs` and retain access filtering. Prefer `/api/filetree/resolveDocPath` with explicit title segments.
* `/api/filetree/getIDsByHPath`
* Parameters
diff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.md
index ac73da9ee6..5e1acdaa23 100644
--- a/docs/API.zh-CN.md
+++ b/docs/API.zh-CN.md
@@ -379,7 +379,7 @@ if (response.code === 0 && response.data) {
### 通过 Markdown 创建文档
-这是仅在兼容模式可用的旧名称路径接口。普通构建默认自动迁移笔记本到结构化标题模式,该接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`,即使标题普通或提供了 `parentID`。请改用 `/api/filetree/createDocByParent`,分别传入父身份和标题。下面的示例描述兼容模式行为。
+旧字符串创建接口在写入前检查全部父路径前缀。祖先含斜杠或空标题时返回 `code: -1`、`data.reason: "pathAmbiguous"`;多个干净父级需要有效且匹配的 `parentID`,否则同样报歧义。元数据未就绪返回 `indexUnavailable`。建议使用 `/api/filetree/createDocByParent`,分别传递父身份和标题。
* `/api/filetree/createDocWithMd`
* 参数
@@ -763,7 +763,7 @@ if (response.code === 0 && response.data) {
### 根据人类可读路径获取 IDs
-普通构建默认自动迁移笔记本到结构化标题模式,该旧接口对整个笔记本返回 `code: -1`、`data: {reason: "legacyPathUnsupported"}`。已知文档 ID 时直接使用;未知位置请通过 `/api/filetree/resolveDocPath` 传入明确的标题段。显示路径无法区分单标题 `A/B` 与两级 `A`、`B`。下面的示例适用于兼容模式。
+旧查询接口按每个候选的真实祖先链判断。仅有干净候选时返回全部 ID;干净与斜杠或空标题候选并存时返回 `pathAmbiguous`;仅有不兼容候选时返回 `legacyPathUnsupported`;无候选时返回空数组。元数据未就绪或不一致返回 `indexUnavailable`。错误候选字段为 `cleanIDs` 和 `unsupportedIDs`,仍受访问过滤保护。建议使用 `/api/filetree/resolveDocPath`,传入独立标题段。
* `/api/filetree/getIDsByHPath`
* 参数
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.md
index bbba661b6a..07d07fa87d 100644
--- a/docs/DOCUMENT-ADDRESSING.md
+++ b/docs/DOCUMENT-ADDRESSING.md
@@ -12,15 +12,15 @@ The development branch implements a shared title reader, document metadata organ
Creation plans retain fixed IDs and never recreate confirmed ancestors. Desktop and mobile share failure handling: an uncertain response or a failure after source commit retains the plan until the user approves an identity check and continuation. Closing or locking a notebook clears its title and template caches. Local shorthands keep a recovery record containing only identities and digests, verify block identities in the actual source before consuming the input, and preserve unresolved input without automatically replaying the operation.
-The structured-title feature release defaults to mode `2`, without a user setting or manual activation endpoint. The development branch implements automatic mode migration and interruption recovery, `DocumentTitleSpec = "6"`, literal slash reads and writes, and notebook-wide rejection of legacy string addressing. The frontend initializes title input rules from a read-only runtime capability. Ordinary builds default to mode `2` without additional build flags. All clients accessing the same workspace or synchronized data must upgrade together to a version supporting mode `2` and Spec `6`; mixing them with older clients is unsupported. A separate transitional protective release is not required. Existing-data compatibility, format and capability rejection, migration recovery, performance, and platform acceptance remain required; default activation does not establish their completion. Inline-title extension requirements remain unchanged.
+Administrators can read `documentCapabilities` from notebook configuration. The addressing version is fixed at `2`; availability follows index readiness and existing access boundaries. `minimumReaderVersion` is `null`, which does not permit older-client mixed use. Whole-notebook imports still remap notebook and anchor IDs, partial imports retain destination configuration, and encrypted creation targets retain authentication, password-change and backup recovery boundaries.
-Administrator notebook configuration reads expose `documentCapabilities`, distinguishing structured APIs, the effective addressing mode, and index state. The `minimumReaderVersion` field is retained and currently returns `null`; this neither disables the feature nor permits mixed use with older clients. A future value must identify an actual feature release verified to support the required capabilities. 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.
+All notebooks use structured title rules without a mode switch, mode-1 migration or capability floors. New writes with ASCII `/` in a title use Spec 6; legacy string interfaces check each candidate ancestor chain. Every device must still upgrade together. Default support does not establish release-package, historical-data, performance or platform acceptance; inline-title extension requirements remain unchanged.
## Goals and scope
Document IDs determine identity and hierarchy membership; titles express content; readable paths provide presentation. Creation, moves, and references must not recover document identity by parsing display text. Once the affected entry points have migrated and compatibility has been verified, document titles can contain the ASCII slash `/` while remaining distinct from existing fullwidth slashes `/`.
-Future support for inline elements in document titles is a required extension capability of this design. Addressing, title presentation, plain-text extraction, and storage representation must remain separate. The design must not permanently constrain titles to a single plain-text string interpreted directly by every consumer. A complete rich title format, editing interactions, and the supported element set are outside the current scope. Issue #20837 tracks inline titles and bidirectional conversion, literal `/` in notebook names, and verification of actual third-party plugin versions; format and capability checks, existing-data compatibility, and acceptance for this release remain in #19938.
+Inline titles and bidirectional conversion, literal `/` in notebook names, and actual third-party plugin compatibility remain tracked by #20837. Title representation, text extraction, display and identity stay separate; future rich titles require an explicit format and editing design, and current plain-text indexes must never overwrite unknown source representations.
The design covers desktop, browser, mobile, kernel APIs, and plugin-visible data, subject to the respective access boundaries of ordinary and encrypted notebooks. Notebook names participate in path presentation as separate display fields. Their character restrictions and rich text support require a separate assessment of configuration formats and older clients; document title rules do not automatically apply to notebook names.
@@ -29,15 +29,15 @@ 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 | The feature release defaults to structured titles and automatically migrates existing notebooks; mode records are internal compatibility markers, not user settings |
+| Addressing rules | All notebooks use structured titles; configuration version `2` is diagnostic metadata |
| 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 |
+| Legacy string addressing | Validate real candidate ancestry; retain clean paths and reject slash/empty-title conflicts |
| Readable paths | Join original ancestor title text for display; do not encode `/` or decode `/` or `%2F` |
| Indexes | Retain existing `hpath` columns and add internal document metadata; do not store full title segment arrays on every content block |
| Title sources | Keep ordinary titles in the first implementation, with an extension boundary for versioned inline content and one-way plain-text derivation |
| Upgrade policy | Stop all clients accessing the same workspace or synchronized data, upgrade every device to a version supporting mode `2` and Spec `6`, and resume only with those versions; implement rich titles separately |
-The compatibility boundary is the notebook, avoiding guesses about a caller's title intent from individual requests. For example, `/A/B` can describe two levels or display one literal title; the legacy request cannot distinguish them. Once structured title mode is enabled, legacy string addressing fails explicitly throughout that notebook, even for documents whose titles remain ordinary. ID-based operations and ordinary text display remain available. This is the defined plugin adaptation boundary, not a promise that all old plugins work unchanged.
+`/A/B` can describe two documents or one literal title. Legacy queries return results only when every candidate ancestor has a nonempty title without `/`; collisions return an explicit error. Identity operations and structured replacement APIs remain available. Display strings are not stable identities.
The foundational separation requires no new external service, network transmission, or dependency. Implementation continues under the repository's and existing dependencies' licenses; selecting a new dependency later requires its own license review. The main costs are consumer migration, index rebuilding, and cross-version verification. Title and ancestor caches, logs, and errors remain subject to encrypted-notebook boundaries; structured fields must not expand data visibility.
@@ -63,7 +63,7 @@ The names below describe concepts rather than prescribe new API or storage field
| Structured ancestor chain | Document IDs and corresponding title information in hierarchy order | Preserves segment boundaries; keeps notebook names separate; never reconstructed from display strings |
| Title segment array | Input for matching or creating documents level by level from an explicit location | Removes delimiter ambiguity, but does not make names unique |
| Readable path | Presentation for breadcrumbs, tooltips, or copied paths | May have different display forms; does not provide addressing or source recovery |
-| Legacy path protocol | Existing `hPath`, `hpath`, and related fields used by APIs and plugins | Preserve existing behavior in compatibility mode; apply the explicit display and rejection rules below in structured title mode |
+| Legacy path protocol | Existing API/plugin `hPath` and `hpath` strings | Retain compatibility only for candidates with verified clean ancestry |
| Export relative path | File location assigned to a document by an export operation | Determined by an export mapping, separately from titles and UI paths |
The current frontend search configuration's `idPath` is an array of search scope strings. Each entry can contain a notebook ID and a document ID path; it is not an array of successive IDs for one path. Migration must preserve the interpretation of existing configurations. Similarly, blocktree `parent_id` identifies a block node's parent and cannot be reused directly as a document's parent document ID.
@@ -145,7 +145,7 @@ Ordinary creation, daily note reuse, and appending to an existing document are d
The new creation endpoint requires an explicit `title: {format: "plain", text: string}`. An omitted `title`, `null`, or an unknown `format` is an error. `text: ""` means an empty title, retaining `custom-sy-title-empty` and the existing storage placeholder mechanism. Reads return both the actual plain text and `empty`; editors restore empty input from the flag instead of treating a localized placeholder as a user title.
-The first implementation retains the limit of 512 Unicode code points and existing restrictions on invisible and private-use characters, preserving ZWJ needed by combined emoji. The new endpoint returns `invalidTitle` for excessive length, prohibited characters, and surrounding whitespace rather than silently truncating, trimming, or replacing them. A UI that deliberately cleans input shows the resulting title before submission. In compatibility mode the new endpoint rejects `/` and standalone `.` or `..`; structured title mode allows them as ordinary text. Existing legacy normalization behavior remains unchanged in compatibility mode.
+Titles retain the 512 Unicode code-point limit and existing invisible/private-use character restrictions, preserving ZWJ for combined emoji. New APIs return `invalidTitle` for excessive length, forbidden characters, surrounding whitespace and standalone `.` or `..`, while allowing `/` inside titles without silently truncating or replacing input.
Structured title mode performs no filesystem path cleaning, width conversion, percent decoding, or Unicode normalization. `/`, `/`, `%2F`, repeated slashes, and `A/../B` remain literal text; only parent identity determines hierarchy. Ordinary creation permits duplicate titles under the same parent, returning a new ID without implicitly overwriting or reusing an existing document.
@@ -161,7 +161,7 @@ Creation of a missing ancestor must submit its absence condition and retain the
### Commits, partial failures, and retries
-The first version does not add a general atomic multi-file creation API. Kernel workflows use creation plans; plugins compose resolution and single-document creation. Before writing, plans for the new protocol and mode `2` validate all predictable title, depth, ambiguity, template, and permission errors and allocate fixed IDs for every document to create; matched ancestors retain identities and revisions. Execution rechecks matches and revisions, requiring replanning when concurrent same-named candidates appear instead of silently switching documents. Existing mode `1` workflows retain their selection semantics under the compatibility rules below.
+There is no cross-file atomic creation API. Plans validate predictable title, depth, ambiguity, template and permission failures before writes, allocate fixed IDs and record ancestor identities and revisions. Submission revalidates these conditions; concurrent name changes require replanning rather than selecting another document.
General multi-level creation commits documents separately; existing template document trees retain the transaction and undo grouping shared by parent edits and child creation, rather than becoming unrelated user operations during addressing migration. Success requires durable source documents and all body and attribute changes required by that operation, with document metadata already readable; full-text search indexing can remain asynchronous. Templates, footnotes, math, clipping sources, tags, sorting, and refresh notifications retain their workflow semantics rather than being lost when location resolution is separated.
@@ -177,11 +177,11 @@ After successful template document tree creation, undo and redo retain the exist
Legacy string save paths retain their current interpretation, including absolute and relative paths, `..`, trailing `/`, empty templates, cross-notebook context, and an explicit name replacing the final segment. New syntax must have an identifiable version and must not automatically reinterpret existing configurations.
-The 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.
+The compatibility compiler evaluates legacy template syntax into structured plans, passing new titles separately. Relative navigation uses document IDs and parent relationships. A variable containing `/` still creates legacy syntax segments until the configuration explicitly adopts 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; 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`.
+Built-in creation workflows use strict structured plans without selecting arbitrary same-name ancestors. The public legacy creator retains disambiguation by a valid matching `parentID` and its existing unambiguous fallback. Unresolved duplicate parents return `pathAmbiguous`.
-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 so existing configurations remain usable after upgrading. 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.
+`docCreateTarget`, `refCreateTarget` and `dailyNoteTarget` coexist with legacy template fields and are available in all notebooks. Each version `2` object specifies the notebook, start, upward traversal, ancestor segments, final title and missing-ancestor policy. Existing global templates and inheritance remain; save-path syntax and body-template syntax are interpreted separately.
```json
{
@@ -199,7 +199,7 @@ New configuration uses `docCreateTarget`, `refCreateTarget`, and `dailyNoteTarge
New templates establish segment boundaries before rendering and evaluate each title segment separately. A variable whose value is `A/B` remains one title segment; rendering a single string and then calling `split("/")` violates the protocol. All segments use the same context and time snapshot. Daily notes supply `now` from the requested calendar date to prevent date or context changes during evaluation.
-When a new object exists, it is the sole authoritative configuration for that creation target; the old string is retained only as the original configuration. Changing the old field to a different value returns an explicit configuration conflict instead of silently overriding the new object; sending the unchanged old value remains acceptable. Explicitly removing the new object re-enables the legacy template without downgrading the notebook to compatibility mode. Without a new object, retain the existing notebook/global configuration precedence. Cross-notebook targets still validate titles under the destination mode; an enabled source cannot bypass destination restrictions.
+An active new object is authoritative for its workflow. Unchanged legacy fields can be returned, but conflicting edits are rejected. Removing the object restores legacy template evaluation without changing addressing rules. Existing inheritance remains when no object is configured, and cross-notebook targets still require source-format and access checks.
Configuration-derived previews retain the source notebook, workflow purpose, effective configuration revision, and evaluated context. Submission checks configuration through `expectedTarget: {notebook, purpose, revision}`, where `notebook` identifies the configuration source and may differ from the creation destination. The revision covers the effective target, participating inherited configuration, and selected body-template path; unrelated settings do not invalidate a preview. Under coordination shared by configuration updates and document mutations, the kernel resolves effective configuration again and checks its revision and destination notebook before committing. A change returns `planChanged` even if the parent path is unchanged. Body-template previews separately retain rendered content and dependency snapshots; configuration revisions do not replace content snapshot checks.
@@ -212,7 +212,7 @@ Configuration-derived previews retain the source notebook, workflow purpose, eff
| Shorthands | Distinguish appending to an explicit target from creating a new target; clear the source only after destination persistence succeeds |
| New database items | Preserve attribute values, bindings, and sorting; retain the final document ID in the creation plan |
| Template document trees | Preserve previews, ID remapping, insertion order, and grouped undo and redo; validate path, name, and configuration conditions on commit and expose partial completion |
-| MCP and built-in Agent | `document.create/list/move` and `inbox.convert` use notebook + `parentID`; an empty string explicitly selects root, and creation accepts an independent literal title. Mode `2` rejects legacy `path=hPath` before lookup; tools and Agent instructions share this contract |
+| MCP and built-in Agent | Document tools prefer notebook plus `parentID`, with an empty string for root; legacy paths share ancestor validation and reject ambiguous single targets |
| Desktop, browser, and mobile | Inspect menus, shortcuts, dialogs, and handlers separately; shared utility migration does not replace platform verification |
Daily-note reuse is an explicit existing business rule. The generic resolver's ambiguity policy must not turn every multiple-date match into an error; template-target preference compares structured identity chains instead.
@@ -233,11 +233,11 @@ Renames still invalidate display paths, ancestor text search data, and related c
## Import and export
-### Cross-mode moves and recovery
+### Cross-notebook moves and recovery
-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.
+Moves, copies, native imports and history recovery preflight the complete operation set before the first write, including descendants, source formats, title representations, depth and encryption boundaries. Unsupported formats are refused without rewriting titles or deleting sources. Source-version checks protect Spec conflicts independently of retired mode records.
-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.
+Supported historical sources remain readable and recoverable; new writes using title capabilities carry the required Spec. Client upgrades neither rewrite every document nor lower an existing specification to pass validation.
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.
@@ -275,7 +275,7 @@ Resolution accepts at most 128 segments, each within the title length limit; act
### Creation by parent ID
-The minimal request for `/api/filetree/createDocByParent` follows. This example requires structured title mode on the destination notebook.
+The minimal `/api/filetree/createDocByParent` request follows; its required indexes must be ready and existing authorization requirements apply.
```json
{
@@ -313,18 +313,19 @@ Business errors use `code: -1` with a stable `data.reason`. `msg` is for human r
| `parentUnavailable` | Parent absent or outside the target notebook; do not search another notebook |
| `planChanged` | Location, title revision, name matches, configuration, or other preview dependencies changed; resolve and confirm the target again |
| `documentIDConflict` | ID exists; verify the original outcome without overwriting or immediately retrying with a new ID |
-| `legacyPathUnsupported` | Legacy string addressing is disabled for the notebook; use the new API |
+| `legacyPathUnsupported` | Only slash/empty-title ancestor candidates exist; use a structured API |
+| `pathAmbiguous` | Clean and unsupported candidates collide, or a single target has multiple clean matches; select an explicit identity |
| `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 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 |
+| `modeConflict` | Historical error value retained for existing callers; retired addressing modes no longer use it for path ambiguity |
| `writeFailed` | A write or later processing failed; recover using `commitState` and the reported stage |
### Reading the effective creation target
`/api/filetree/getDocCreateTarget` accepts the current `notebook` and `purpose: "document" | "reference" | "dailyNote"`. It reuses each workflow's existing configuration precedence and returns the effective `target`, `docCreateTemplatePath`, and configuration `revision`. `target` is a union tagged by `version`: legacy templates return `{version: 1, notebook, path}`, while new templates return the complete version `2` object above. The returned `docCreateTemplatePath` is the effective body-template path for that workflow: ordinary creation follows existing inheritance, daily notes use `DailyNoteTemplatePath`, and reference creation retains its current behavior without automatic body-template application and returns an empty string. The endpoint only reads configuration; it neither evaluates templates nor guesses the current document or date. Callers supply context when generating the plan and include the source, purpose, and `revision` in submission conditions.
-Legacy `/api/filetree/getDocCreateSavePath` and `/api/filetree/getRefCreateSavePath` retain their responses while their respective effective configurations are legacy templates. When the corresponding new object is active, both return `code: -1`, `data: {reason: "structuredTemplateRequired"}` instead of obsolete paths. This decision follows the configuration source and workflow, not the notebook addressed by an old path or new target; an obsolete destination still using mode `1` does not permit returning historical configuration. Declare the error variant on each legacy contract. Both built-in consumers and plugins use the new reader to avoid reimplementing configuration inheritance independently.
+Legacy `getDocCreateSavePath` and `getRefCreateSavePath` retain their response for effective legacy templates. An active corresponding new object returns `code: -1`, `data: {reason: "structuredTemplateRequired"}`. The decision follows the configuration source and workflow, without inferring configuration from display strings or consulting retired addressing modes.
### Planning a configured creation target
@@ -332,13 +333,11 @@ Legacy `/api/filetree/getDocCreateSavePath` and `/api/filetree/getRefCreateSaveP
The 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 automatic migration
+### Capability discovery
-Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Administrator responses include this object; other roles retain existing configuration filtering. `minimumReaderVersion` is retained as nullable compatibility metadata and currently returns `null`. Any future version string must be backed by verification of an actual feature release supporting mode `2` and Spec `6`; assigning one is not a prerequisite for closing this issue. This field does not control feature activation, and `null` does not mean older clients may access or synchronize the data safely. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.
+Administrator `getNotebookConf` responses include read-only `documentCapabilities`. `addressingVersion` is always `2`. `modeState` is `structured`, or `recovering` when required indexes are not ready; it never returns `legacy`. The existing `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion` and `revision` fields remain. The minimum reader release is `null` until an actual release has been verified, and `literalSlash` is true only with a ready index.
-`revision` summarizes mode records and recovery state. It is neither an individual document's path revision nor a user activation token. Capability declarations grant no access; closed or locked notebooks retain existing restrictions, and status reads expose neither titles nor protected template content. When an older server omits the object, plugins use only legacy capabilities. Authorization, locking, and network errors must not be interpreted as unsupported capabilities or trigger fallback writes.
-
-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`.
+Capability reads no longer write migration or floor records. `revision` summarizes the fixed capability declaration, not an individual document path. `getConf.documentAddressingVersion` stays `2` for desktop, browser and mobile input initialization. Existing closed-notebook, lock, publish-access and request-lease restrictions remain; capability metadata grants no additional access.
### Contract and declaration maintenance
@@ -346,82 +345,42 @@ Implementation follows [Kernel API type contracts](API-CONTRACTS.md): define dec
## API and plugin compatibility
-Mode `1` denotes legacy compatibility; mode `2` is the structured title mode automatically adopted by the feature release. Retaining mode `1` semantics supports legacy data interpretation and limited-reader regression tests, not a separate transitional release plan or permission to mix older clients with upgraded data. 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 |
-| --- | --- | --- | --- |
-| Reads, moves, and deletion by ID | Preserve existing contracts; incoming content must satisfy destination mode | Preserve identity and authorization; cross-mode moves add whole-subtree eligibility checks | Keep using IDs; handle `targetModeUnsupported` and reread location after moves |
-| Rename by ID and creation using ID data paths | Preserve existing title rules | Plain titles can retain `/`; still validate mode and title format | Pass title and location separately; do not overwrite unknown rich formats with plain text |
-| `getIDsByHPath` | Preserve legacy name-path grammar | Reject throughout the notebook with `legacyPathUnsupported` | Use known IDs directly, or `resolveDocPath` for unknown locations |
-| `createDocWithMd` | Preserve legacy grammar and `parentID` fallback | Reject throughout the notebook, even with `parentID` supplied | Use `createDocByParent` without a string path |
-| `getHPathByID`, `getHPathByPath` | Preserve existing output | Join original ancestor titles for display only | Use `getDocPaths` for structure |
-| `getFullHPathByID` | Preserve notebook-name inclusion and nullability | Still display the notebook name; no reverse addressing | Display notebook names separately from document segments |
-| `blocks.hpath`, `blocktrees.hpath` | Preserve column types and existing behavior | Remain strings that can contain indistinguishable title slashes | Query subtrees with ID `path`, read titles from document-row `content`, and obtain parents and depth through structured APIs |
-| `Criterion.hPath`, `SearchPath`, search results | Preserve existing configuration and highlighting semantics | Display text remains searchable; scope and hierarchy use IDs | Do not resubmit highlighted text or displayed paths as locations |
-| Legacy save-path templates | Retain original grammar and legacy duplicate-name selection | Compile internally into strict plans, rejecting ambiguous unknown ancestors | Explicitly use version `2` templates when `/` in a variable must remain within one segment |
-| `getDocCreateSavePath`, `getRefCreateSavePath` | Preserve legacy configuration results | Preserve results for the workflow's old template; return `structuredTemplateRequired` when its new object is active | Use `getDocCreateTarget` for the effective versioned configuration |
+Legacy `getIDsByHPath` checks readiness and pending writes in the same metadata snapshot as the exact display-path candidates and their real ancestor chains. A clean chain has nonempty text, no empty-title flag and no ASCII `/` at every level. A slash, actual empty text or empty-title placeholder makes a candidate unsupported. Attribute entities are decoded once on source read, never again on metadata. Missing ancestors, cycles, inconsistent identities/path revisions and SQL errors return `indexUnavailable`. Even an empty result requires a proven ready index.
-Do not change legacy field types, remove old APIs, or encode mode `2` display paths to present them as compatible addresses. Different structures can display the same string in the new mode, so SQL equality on `hpath` can also match both. Plugins that count separators, take the final segment, or query subtrees by display prefixes must adapt; that is the compatibility cost of enabling the capability.
+| Clean candidates | Unsupported candidates | Query result |
+| --- | --- | --- |
+| Present | Absent | All clean IDs |
+| Present | Present | `pathAmbiguous` |
+| Absent | Present | `legacyPathUnsupported` |
+| Absent | Absent | Empty array |
-Legacy string endpoints gain an explicit mode `2` error variant: `code: -1`, `data: {reason: "legacyPathUnsupported"}`. Declare this variant on the existing contracts and retain its error data. Existing success, null, and error responses in mode `1` stay unchanged. Merely changing error prose and requiring plugins to match localized text is insufficient.
+Failures use `code: -1` and stable `data.reason`, with `cleanIDs` and `unsupportedIDs` candidate fields; empty lists may be omitted. IDs remain subject to publish-access filtering and encrypted response leases. Existing success values remain arrays or document IDs; callers must not match error prose.
-Existing `/`, `%2F`, and similar title content remain literal data without inferred historical encoding. An external channel needing reversible encoding must use a separate version and adapter boundary, never internal identity or title sources.
+Before its first source write, `createDocWithMd` checks every parent prefix, including later prefixes after an earlier missing one. Any slash/empty-title candidate returns `pathAmbiguous`. Multiple clean parents also return that error unless a valid matching `parentID` selects their real ancestor chain; an ID never overrides unsupported candidates. CLI and MCP single-target resolution shares this validation and cannot arbitrarily select a clean duplicate. Root locations retain their existing meaning.
-Plugins migrate through capability discovery, reading known targets by ID, resolving unknown ancestors structurally, creating by parent ID, and operating on returned IDs. Publish this matrix and minimal examples with the replacement APIs; migrate built-in consumers before opening mode `2`. The server cannot identify every plugin SQL query and its later use, so it cannot promise to prevent all plugin misuse of display strings automatically.
+Prefer `resolveDocPath` with independent title segments, `createDocByParent` with a parent ID and independent title, and `planDocCreate` for multiple levels. Legacy requests also return `indexUnavailable` during rebuilding; callers await recovery without falling back to unverified display strings or SQL prefix guesses.
## Versions, encryption, and recovery
### Coordinated upgrades and older-client risks
-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.
-
-This release uses a coordinated upgrade across all devices, without a separate transitional protective release. Before upgrading, stop every client accessing the same workspace or synchronized data, including desktop, mobile, and server instances. Upgrade all of them to a version supporting mode `2` and Spec `6` before resuming access or synchronization. An offline device still running an older client must remain disconnected from this data until it is upgraded. The application cannot prove the state of offline devices, so release notes and user guides must state this requirement explicitly.
-
-Ordinary development builds already default to mode `2`, independently of minimum-version metadata. Keep notebook mode, capability-floor, recovery-record, and document-specification checks at all applicable read, write, mount, index, repair, import, history, backup, sync, and recovery entry points. A reader implementing these checks must reject unsupported capabilities before processing or replacing source data. These checks preserve data within the supported implementation; they cannot retrofit protection into an older client that ignores the records.
-
-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 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.
-
-Tree writes validate both the replacement and the current on-disk source. Authenticate encrypted sources before interpreting them, and hold the same file lock through current-source validation and persistence so stale caches cannot overwrite a newly incompatible source. Automatic repair additionally requires that the source still matches the bytes originally inspected. Validation failures must not fall through to a fallback write or truncate the file. Ordinary documents retain page-based writes; encrypted documents retain atomic ciphertext replacement.
-
-Raw file endpoints apply the same source-format checks to paths composed of notebook and document IDs; uploads, copies, and moves into those paths cannot bypass them. Validate the complete batch before creating destination directories or copying any files. Actual document copies use the validated source bytes and recheck the current destination under the file lock. Concurrent changes or I/O failures after preflight can leave completed copies; batch rollback is not promised. Files ending in `.sy` inside ordinary asset and plugin directories retain raw-file semantics, and encrypted notebooks remain inaccessible through raw file endpoints.
-
-For incoming raw document writes, copies, and renames, a decoded root title containing ASCII `/` requires `Spec >= 6`. Under-versioned input returns `document title requires spec 6` before any destination write; raw endpoints never upgrade or reserialize request bytes. This is a write-only consistency check: existing supported low-spec sources retain authenticated reads, history, backups, sync and recovery, and valid replacements may repair their version marker. Ordinary tree writes continue upgrading the specification as needed.
-
-Mixing older clients with upgraded data can produce inconsistent behavior rather than a reliable refusal to open: some Spec `6` documents may be rejected while documents retaining an older specification remain readable or writable. An older editing snapshot may overwrite newer source data; old title normalization or path parsing may remove a literal `/` or treat it as hierarchy. Synchronization may then propagate those incorrect changes to upgraded devices. This can cause lost edits or incorrect titles and paths, requiring recovery from history or backups. These are reasons to stop using older clients against the same data, not a promise that every older operation will fail safely.
-
-An isolated probe of the published `v3.8.9-alpha.4` source verified rejection of direct Spec `6` reads, continued reads of legacy-specification documents in mode `2`, and a stale editing snapshot overwriting source data. It did not establish the behavior of every old-version operation or a complete mixed-device sync scenario; the additional normalization, hierarchy, and propagation consequences above are risks, not reported results of that probe. Local mode `1` overlay builds are limited-reader regressions of the current source, not candidates for a planned transitional release, and they do not verify an actual release package. Preserve checks and regression coverage for ordinary and encrypted legacy data, unsupported modes and formats, stale writes, sync, and recovery. Keep `minimumReaderVersion` nullable until an actual feature release has been verified; neither a separate protective release nor assignment of that field is required to close this issue.
-
-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
-
-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.
-
-Settings export remains an archive containing one JSON file. When confirmed capability requirements exist, that JSON carries a top-level `documentAddressing` field with the same structure as the local record. Import validates and merges the maximum requirement per identity before adopting ordinary settings; an older backup without this field does not clear the local record, and invalid or unknown record versions fail before settings are adopted. This field only transfers backup information: restoration keeps it in `conf/document-addressing.json`, outside ordinary `conf.json`, and includes no titles, content, or keys. Raw file APIs must not overwrite, rename, or delete the local record. Notebook writes and copies preflight incoming configuration and all destinations; sort recovery preserves original files and pending recovery records for unsupported modes.
-
-Readers recognize both configuration and capability floor records, rejecting modes beyond their supported capabilities before processing source files. Sync application and snapshot restoration check affected notebooks' capability requirements before replacing configuration or files. Once mode `2` is confirmed, incoming old configuration, missing new fields, or deletion of a capability record cannot lower the effective mode; restore configuration projections and floor records before reopening access. If checks can occur only after files are persisted, or the dependency cannot expose required configuration before application, stage A is incomplete. Complete sync and recovery entry points first; index rebuilding does not substitute for pre-application protection.
+Mode 1 is retired. Every notebook follows structured rules without migrating or rewriting document IDs, source files, ciphertext or keys. Ordinary configuration saves write the diagnostic `documentAddressingVersion: 2` marker. Missing notebook configuration or directories no longer cause capability reads to stat missing directories or recreate data.
-Mode markers do not replace document-source checks. Before any file in a sync or snapshot batch is written or removed, validate incoming ordinary document sources and refuse to overwrite or partially delete existing sources identified during preflight as requiring unsupported specifications, title representations, or title capabilities. Missing mode markers must not allow incompatible sources to be persisted before indexing detects them. This check follows the existing recovery process; it does not make ordinary snapshot restoration an atomic transaction isolated from arbitrary external file changes. Valid history may still restore generally corrupted ordinary documents, whole-notebook deletion retains its existing semantics, and `.sy` files inside asset or plugin directories are not interpreted as documents. Locked encrypted notebooks continue transferring original ciphertext under the existing protocol without requiring an unlock for title preflight. Repository chunk verification does not authenticate notebook contents; ciphertext authentication and source-format checks remain within the existing protected read and recovery boundaries.
+New writes with ASCII `/` in a title require at least Spec 6. Retain independent Spec detection, duplicate-property and single entity-decoding checks, and rejection of unknown title representations and future specifications. Supported historical low-Spec slash sources remain readable and recoverable; raw new writes must carry the required specification. Ordinary documents retain the specification required by body features, without bulk upgrades or version downgrades.
-Deleting 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.
+Stop all clients accessing the workspace or synchronized data before upgrading every desktop, mobile and server instance; offline older devices must upgrade before reconnecting. Older clients ignore mode records, and Spec 6 cannot protect every legacy-Spec document in the notebook, so retirement does not permit mixed-version use. The existing isolated `v3.8.9-alpha.4` source probe established direct Spec 6 rejection, continued legacy-Spec reads and stale-edit source overwrite, without covering every old-client operation or complete mixed-device synchronization. Older clients may use verified independent exports or pre-upgrade backups restored into separate workspaces, never overwrite original configuration and resume synchronization.
-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. Readers must interpret valid recovery records as requiring at least mode `2`, including when checking rejection with a limited reader. Preserve unknown configuration fields and opaque encrypted payload values, without scanning or rewriting `.sy` files. Raw file APIs cannot overwrite the recovery directory.
+### Retired records and startup cleanup
-The feature release automatically repairs missing mode projections and outdated configuration without recreating deleted notebooks. Mode migration and index rebuilding remain separate: metadata migration needs no ready index and neither authenticates nor rewrites document ciphertext. Subsequent source reads and index construction must still authenticate source content under existing authorization and encrypted-notebook leases. Report `modeState: "structured"` only after records are consistent and indexes are ready. If an existing notebook has lost its configuration file, retain the confirmed mode without creating a replacement configuration. Encrypted backup recovery must still authenticate the original key and payload and cannot save the notebook as plaintext. Capabilities remain `recovering` until configuration is restored.
+Capability reads, imports, sync, snapshots and settings backups no longer read or generate capability floors, mode migration records or the settings `documentAddressing` field. That field in old settings is ignored. Sync and recovery still preflight source Spec, canonical paths and existing authentication boundaries before applying changes.
-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.
+Startup idempotently removes local `conf/document-addressing.json` and `conf/document-addressing-recovery/`. Missing directories succeed, removal failures log warnings without blocking mounting, and read-only startup skips cleanup. Notebook `.siyuan/document-addressing.json` files are no longer read or created; existing files stay untouched to avoid synchronized deletions. Encryption recovery keys and source-recovery tasks are outside this cleanup.
### Index and task recovery
`document_metadata` uses an independent derived-index version and per-notebook states `missing`, `building`, `ready`, and `error`. Build the new table from source documents and ID locations, not segment boundaries guessed from old `hPath` values. Record incremental changes during construction and catch up before switching; mark the corresponding generation `ready` only after the full scan and incremental validation complete.
-In compatibility mode, existing functionality retains its behavior during rebuilding, while new structured endpoints return `indexUnavailable` if required data is not ready. Mode `2` cannot fall back to old name addressing when indexes are corrupt. Recover through existing source-read paths and hold structured writes until required metadata is ready. Do not automatically recreate missing parent source files or replace corrupt source data with old titles from an index.
+Structured and legacy path endpoints return `indexUnavailable` whenever required metadata is not ready. Recovery authenticates actual sources; never recreate missing parent files or replace corrupt sources using derived titles.
Update in order: persist the source document, update metadata and the corresponding document row within one block-tree database transaction, then submit subsequent `hpath` batches. There is no claimed atomic transaction between source files and databases or between block-tree and content databases. Preserve recovery markers across interruption at any step. After restart or unlock, verify source revisions and current ID locations before resuming derived updates. Revision, move, and deletion checks invalidate queued old trees so they cannot restore stale titles.
@@ -445,10 +404,10 @@ The versioned configuration-payload extension retains the existing authenticated
| Stage | Deliverables | Completion criteria |
| --- | --- | --- |
-| A: Compatibility protection | Notebook capability floors and conflict detection, unknown-mode and source-version protection, existing behavior fixtures | Modes checked before sync and snapshot application; unsupported modes and formats safely refused at applicable read, write, and repair entry points; existing data remains readable and recoverable |
+| A: Compatibility protection | Candidate ancestor-chain validation and source-version protection, existing behavior fixtures | Sources checked before sync and snapshot application; unsupported formats safely refused at applicable read, write, and repair entry points; existing data remains readable and recoverable |
| B: Internal separation | Shared title access, document metadata, ID hierarchy calculations, path refresh, and recovery | Ordinary titles retain behavior; structure is no longer derived from display strings; encrypted indexes rebuild from authenticated sources |
| C: APIs and consumers | New read, resolve, and conditional-create APIs, version `2` templates and encrypted payloads, built-in workflow and platform migration | Name and configuration conditions and old/new contracts verified; partial failures and undo recoverable; daily-note and other business behavior retained |
-| D: New characters | Default structured mode and automatic recovery, legacy API rejection, plugin migration guidance, cross-mode operations, and import/export checks | Ordinary builds support `/` by default; whole-subtree preflight, mode recovery, and all release criteria must pass to complete external release acceptance |
+| D: New characters | Uniform structured rules and index recovery, legacy API rejection, plugin migration guidance, cross-notebook operations, and import/export checks | Ordinary builds support `/` by default; whole-subtree preflight, index recovery, and all release criteria must pass to complete external release acceptance |
| E: Inline titles | Separate source-format, editing, and rendering design | Retain this design's identity APIs and deliver separately after format and old-writer protection |
Stages A through D are implementation and acceptance groups, not a requirement to publish separate transitional releases. The development branch enables new characters by default; external release acceptance still requires their relevant conditions and the coordinated-upgrade instructions above. 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.
@@ -466,12 +425,12 @@ The implementation allocates `.sy` specification `6`. Performance measurements,
| Title content | `/`, `/`, repeated slashes, `%2F`, `.`, `..`, empty titles, Unicode, and length boundaries; no uncontracted character conversion |
| Identity and hierarchy | One title `A/B` versus two levels `A`, `B`; duplicate titles under the same or different parents; ownership checks for duplicate IDs; root locations and notebook documents |
| Creation and concurrency | Direct ID creation following parent location versus revisioned requests rejecting stale previews; concurrent same-named ancestor creation, changed match sets and configuration; parent deletion, cross-notebook moves, closure, or locking; lost responses, partial commits, fixed-ID conflicts, and multi-level recovery |
-| Templates | All legacy syntax boundaries and mode `1` duplicate-name behavior; segment-by-segment rendering, variables containing `/`, relative operations, one time snapshot, configuration inheritance and body-template selection, daily-note and shorthand workflows, and grouped template-tree undo and redo |
+| Templates | All legacy syntax boundaries and legacy template syntax and matching parent-ID disambiguation; segment-by-segment rendering, variables containing `/`, relative operations, one time snapshot, configuration inheritance and body-template selection, daily-note and shorthand workflows, and grouped template-tree undo and redo |
| Search and presentation | Original title character search, ancestor text search, ID scope filtering, title highlights, breadcrumb boundaries, copied text, and ID links |
| Indexes and recovery | Deep subtrees, successive parent and child renames, stale edit snapshots, interrupted batches, restart, moves, deletion, sync, and ordinary and encrypted index migration |
-| Import/export and cross-mode operations | Duplicate names, invalid filenames, case collisions, path escape, relative links, cross-notebook references, title metadata, and lossless round-trip guarantees; moves, copies, and recovery preflight every descendant, with no partial writes on rejection |
-| Legacy APIs and plugins | Unchanged mode `1` responses; notebook-wide legacy-addressing rejection in mode `2`; both legacy target readers reject obsolete configuration even when its destination still uses mode `1`; SQL display collisions, structured replacements, and missing capabilities distinguished from request errors |
-| Legacy data, limited readers, and encryption | Supported historical source and configuration payload fixtures; limited-reader rejection regressions, stale-record and snapshot handling in sync, capability floors never decreasing, mode conflict recovery without a ready index, authentication failure, caches and responses during lock, history and backup recovery, and retained key material |
+| Import/export and cross-notebook operations | Duplicate names, invalid filenames, case collisions, path escape, relative links, cross-notebook references, title metadata, and lossless round-trip guarantees; moves, copies, and recovery preflight every descendant, with no partial writes on rejection |
+| Legacy APIs and plugins | Clean legacy path compatibility and real ancestor-chain collision errors; both legacy target readers reject obsolete configuration independently of destination diagnostic markers; SQL display collisions, structured replacements, and missing capabilities distinguished from request errors |
+| Legacy data, limited readers, and encryption | Supported historical source and configuration payload fixtures; fixed capabilities, snapshot compatibility, pending/unready-index rejection and read-only cleanup skipping, authentication failure, caches and responses during lock, history and backup recovery, and retained key material |
| Inline extension capability | Existing Markdown-like title text remains literal; representation changes do not affect identity or hierarchy; identical plain text does not merge documents; formatted source derives plain text in one direction; #19235 image/link round trips preserve content and asset references without duplication |
| Platforms and performance | Creation and rename on desktop, browser, and mobile; foreground latency, database batch time, memory, CPU, and disk I/O for large subtrees |
@@ -483,9 +442,9 @@ Create a root document `A/B`, a root document `A` with child `B`, a root documen
Have 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. 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`.
+Build a subtree with an ordinary root and slash/unknown-representation descendants. Moves, copies, imports and recovery preflight every descendant, source specification and authentication boundary; changes after preflight are detected without lowering versions or relaxing encryption.
-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.
+Verify old-configuration and snapshot restoration, missing configuration, ignored retired records and startup cleanup. Unready indexes refuse path resolution and creation. Retain ordinary and encrypted historical fixtures, unknown-format and authentication failures, protected target persistence, lock-time cache clearing, backups and password-change recovery.
`TestDocumentAddressingCheckoutSourcePreflight` uses actual repository snapshots to cover unmarked future specifications, unknown title representations, incompatible current sources, and mode-check precedence. Rejection occurs before additions, replacements, or removals in the batch, preserving source bytes, timestamps, and incoming snapshot contents. `TestDocumentAddressingCheckoutSourceRemoval` distinguishes partial removal from whole-notebook deletion. `TestDocumentAddressingCheckoutPreservesOpaqueEncryptedSource` uses historical ciphertext fixtures to verify byte-preserving transfer without unlocking, with configuration and recovery material unchanged. Path regressions cover backslashes, duplicate destinations, and Windows trailing-dot, trailing-space, and default-data-stream aliases so the actual write target cannot bypass source checks. Retain regressions for BOM-prefixed sources, valid slash titles, recovery of generally corrupted sources, and asset `.sy` files so source protection does not introduce unrelated file-operation restrictions.
@@ -507,7 +466,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`.
-CI runs `go test -tags "fts5 sqlcipher" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1` with ordinary build defaults for automatic migration, structured source reads and writes, and actual HTTP contracts, without injecting a test version. Explicit compatibility fixtures cover limited-reader mode rejection, while ordinary builds continue verifying rejection of unknown future modes and source formats. Local mode `1` overlays test that limited-reader boundary without changing ordinary build defaults or creating a transitional-release requirement. These complete acceptance requirements do not claim all checks have run. Documentation changes additionally verify bilingual consistency, examples, links, and diff formatting.
+New ancestor-chain, legacy creation, CLI, MCP and contract regressions are discovered by existing Go test selections. Run affected packages with `fts5 sqlcipher`, retaining Spec 6, historical plain/encrypted fixtures, unknown-format, sync and recovery coverage. No mode-1 overlay or stub for a removed mechanism remains. Documentation also checks bilingual consistency, examples, links and diffs.
## Related code
diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.md
index 5700382eaa..aeceff2667 100644
--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md
+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md
@@ -12,15 +12,15 @@
创建计划采用固定 ID,已确认提交的祖先不会再次创建。桌面与移动端共用失败处理:响应不明或后续处理失败时保留计划,用户确认并按身份核对后才继续;关闭或锁定笔记本清除相应标题和模板缓存。本地速记使用仅含身份和摘要的恢复记录,核对实际源中的块身份后才清理输入,未确认的结果保留原速记并停止自动重放。
-管理员读取笔记本配置时可获取 `documentCapabilities`,区分结构化接口、实际寻址模式和索引状态。未登记经真实发行包验证的最低可读功能版本时,`minimumReaderVersion` 返回 `null`,不会伪造最低版本,也不表示允许与旧版混用;能力记录损坏时明确报错。原生整本导入会同步重映射目标配置中的笔记本和锚点 ID,部分文档导入保留目标笔记本配置。加密目标载荷保持锁定保存、改密及备份恢复的认证边界。
+管理员读取笔记本配置时可获取 `documentCapabilities`。寻址版本固定为 `2`,可用性由索引状态和现有授权边界决定;`minimumReaderVersion` 为 `null`,不表示允许与旧版混用。原生整本导入继续重映射笔记本和锚点 ID,部分导入保留目标配置;加密目标载荷保持认证、改密及备份恢复边界。
-结构化标题功能版本默认采用模式 `2`,不提供用户开关或手动启用接口。开发分支已实现自动模式迁移与中断恢复、`DocumentTitleSpec = "6"`、标题斜杠读写及旧字符串接口的整本拒绝;前端通过只读运行时能力决定标题输入规则。普通构建默认采用模式 `2`,无需额外编译参数。发布采用所有设备统一升级、不与旧版混用的策略,不再要求先发布单独的过渡保护版本。`minimumReaderVersion` 仅报告经验证的兼容版本,留空不阻止新模式启用。功能版本的发行包核对、旧数据兼容、性能及各端验收仍按实际验证结果记录,不能由默认启用推断已经完成。行级标题扩展约束保持不变。
+所有笔记本统一采用结构化标题规则,不提供模式开关,不再执行模式 1 迁移或维护能力下界。含 ASCII `/` 的新写入标题使用 Spec 6,旧字符串接口按候选祖先链判断兼容性。所有设备仍须统一升级;默认支持不代替发行包、旧数据、性能及跨端验收。行级标题扩展约束不变。
## 目标与范围
文档使用 ID 确定身份和所属层级,标题用于表达内容,可读路径用于展示。创建、移动和引用不得依赖从展示文本反向解析文档身份。完成相关入口迁移与兼容验证后,文档标题可以包含半角斜杠 `/`,并与原有全角斜杠 `/` 保持区别。
-未来文档标题支持行级元素是本方案必须保留的扩展能力。寻址、标题显示、纯文本提取和存储表示必须分离,不能将标题永久限定为一个供所有模块直接解释的纯文本字符串。本次不定义完整的富文本标题格式、编辑器交互或元素支持清单。行级标题与双向转换、笔记本名称保留 `/`,以及第三方插件实际版本的适配验证由 #20837 继续跟踪;Spec 与笔记本模式检查、统一升级说明及本轮功能验收仍属于 #19938。
+行级标题与双向转换、笔记本名称保留 `/` 以及第三方插件实际版本适配由 #20837 跟踪。标题表示、纯文本提取、显示和身份必须分离;未来富文本标题需要独立格式及编辑设计,不能让当前纯文本索引覆盖未知来源。
方案覆盖桌面端、浏览器端、移动端、内核接口和插件可见数据,并遵守普通笔记本与加密笔记本各自的访问边界。笔记本名称作为独立显示字段参与路径展示;笔记本名称的字符限制与富文本支持需要单独评估配置格式和旧客户端兼容,不能由文档标题规则自动推导。
@@ -29,15 +29,15 @@
| 项目 | 采用的方案 |
| --- | --- |
| 文档定位 | 笔记本 ID 与文档 ID;创建使用独立的父文档身份与标题 |
-| 新旧模式 | 功能版本默认采用结构化标题模式,自动迁移已有笔记本;模式记录只用于内部兼容保护,不提供开关 |
+| 寻址规则 | 所有笔记本统一采用结构化标题;配置中的版本 `2` 仅作诊断标记 |
| 插件兼容 | 接受依赖旧 `hPath` 规则的插件适配;先交付替代接口及迁移说明,再启用新字符 |
-| 旧字符串寻址 | 兼容模式保留原有行为;结构化标题模式明确拒绝旧字符串定位与创建入口 |
+| 旧字符串寻址 | 按候选真实祖先链判断;干净路径保留兼容,斜杠或空标题冲突明确拒绝 |
| 可读路径 | 保留标题原文并按层级拼接展示;不编码 `/`,不把 `/` 或 `%2F` 解码 |
| 索引 | 保留现有 `hpath` 列,新增文档级内部元数据;不为每个内容块保存完整标题段数组 |
| 标题源 | 首版继续使用普通标题;预留带版本的行级内容及单向纯文本派生 |
| 发布策略 | 直接发布默认支持 `/` 的功能版本;同一份数据的所有客户端统一升级,不与旧版混用;富文本标题单独实现 |
-兼容边界按笔记本划定,避免根据某次请求猜测调用者的标题意图。例如 `/A/B` 可以指两级文档,也可能是单个标题的展示结果,旧请求没有足够信息区分两者。结构化标题模式启用后,该笔记本内即使某篇文档仍使用普通标题,旧字符串寻址入口也会返回明确错误;按 ID 操作和普通文字展示继续可用。这是插件需要适配的明确范围,不承诺所有旧插件零修改运行。
+`/A/B` 既可能表示两级文档,也可能来自单标题。旧查询只在本次候选的所有祖先标题非空且不含 `/` 时返回结果;冲突返回明确错误。按 ID 操作及结构化替代接口继续可用,不能把显示路径当作稳定身份。
基础解耦不需要新增第三方服务、网络传输或依赖。实现继续遵守仓库及现有依赖的授权要求;若后续选择新依赖,应另行核查其许可。主要成本是调用方迁移、索引重建和跨版本验证。标题及祖先链的缓存、日志和错误响应继续受加密笔记本边界约束,不能因增加结构化字段扩大数据可见范围。
@@ -63,7 +63,7 @@
| 结构化祖先链 | 按层级排列的文档 ID 及对应标题信息 | 保留段边界,笔记本名称单独保存,不从展示字符串恢复 |
| 标题段数组 | 从明确位置开始逐级匹配或创建文档的输入 | 只消除分隔符歧义,不保证名称唯一 |
| 可读路径 | 面包屑、提示或复制路径所需的展示内容 | 可以使用不同展示形式,不承担文档寻址或源数据恢复 |
-| 旧路径协议 | 现有接口及插件使用的 `hPath`、`hpath` 等字段 | 兼容模式维持原有行为;结构化标题模式采用后文明确的显示及拒绝规则 |
+| 旧路径协议 | 现有接口及插件的 `hPath`、`hpath` 字符串 | 仅对经过祖先链验证的干净候选保留兼容 |
| 导出相对路径 | 导出任务为文档分配的文件位置 | 由导出映射确定,与标题及界面可读路径分开 |
当前前端搜索配置的 `idPath` 是多个搜索范围字符串组成的数组,其中每项可以包含笔记本 ID 和文档 ID 路径;它不是单条路径的逐级 ID 数组。迁移时必须保持现有配置的解释方式。块树中的 `parent_id` 表示块节点的父节点,也不能直接当作文档的父文档 ID 使用。
@@ -145,7 +145,7 @@
新创建接口要求显式传入 `title: {format: "plain", text: string}`。省略 `title`、传入 `null` 或未知 `format` 均为错误;`text: ""` 表示空标题,沿用 `custom-sy-title-empty` 和既有存储占位机制。读取时同时返回实际纯文本与 `empty`,编辑器根据标志恢复空输入,不把本地化占位文字当作用户标题。
-首版保留 512 个 Unicode 码点的长度上限及现有不可见字符、私用区字符限制,保留组合 Emoji 所需的 ZWJ。新接口对超长、禁止字符和首尾空白返回 `invalidTitle`,不截断、修剪或替换后悄悄保存;界面若主动整理输入,应在提交前显示最终标题。兼容模式下新接口拒绝 `/` 及独立的 `.`、`..`;结构化标题模式允许它们作为普通文字。既有旧接口在兼容模式下的规范化行为保持不变。
+标题保留 512 个 Unicode 码点上限及现有不可见字符、私用区限制,保留组合 Emoji 所需的 ZWJ。新接口拒绝超长、禁止字符、首尾空白和独立的 `.`、`..`,返回 `invalidTitle`;允许标题内的 `/`,不截断或替换输入后悄悄保存。
结构化标题模式不执行文件路径清理、宽窄转换、百分号解码或 Unicode 归一化。`/`、`/`、`%2F`、连续斜杠以及 `A/../B` 均保留原文,层级只由父身份决定。普通新建允许同父同名,返回新 ID,不隐式覆盖或复用已有文档。
@@ -161,7 +161,7 @@
### 提交、部分失败与重试
-首版不新增通用的跨文件原子创建接口。内核业务使用创建计划,插件通过解析接口及单文档创建接口组合操作。新协议及模式 `2` 的计划在写入前校验所有可预知的标题、深度、歧义、模板及权限错误,并为待创建的每篇文档分配固定 ID;已匹配祖先记录身份和版本。执行时重新检查匹配和版本,并发出现同名候选时要求重新规划,不能悄悄改用另一篇文档。模式 `1` 的旧业务按下文兼容规则保持原选择语义。
+首版不提供跨文件原子创建。创建计划在写入前检查可预知的标题、深度、歧义、模板及权限错误,分配固定 ID 并记录祖先身份和版本;提交时重新校验。并发同名变化必须重新规划,不能悄悄改用另一篇文档。
通用多级创建按文档分别提交;已有模板文档树仍保留父文档编辑与子文档创建共用的事务及撤销分组,不能因迁移定位逻辑而拆成互不相关的用户操作。成功响应要求源文档及本次必需的正文、属性修改已同步持久化,文档元数据已可读取;搜索全文索引可按现有机制异步更新。模板、脚注、数学内容、剪藏来源、标签、排序及刷新通知按原业务语义执行,不能因拆分定位逻辑而丢失。
@@ -177,11 +177,11 @@
旧字符串保存路径继续使用原有解释规则,包括绝对与相对路径、`..`、末尾 `/`、空模板、跨笔记本上下文,以及显式名称替换末段的行为。新建语法必须有可识别的版本,不能自动将已有配置按新规则重解释。
-旧模板由兼容编译器按原语法求值,再输出结构化创建计划;另行传入的新标题保持独立,不重新拼入路径字符串。相对起点和向上导航使用当前文档 ID 及父关系,不能先把当前文档的显示路径拆成旧模板段。该内部适配不调用被新模式禁用的公开字符串寻址接口,因此已有日记等配置仍可工作。旧模板内变量产生 `/` 时继续按旧语法分层,只有显式改用新模板后才保留为单段。
+旧模板由兼容编译器按原语法求值并生成结构化计划;新标题独立传递。相对导航使用文档 ID 和父关系。变量内的 `/` 在旧语法中仍分层,只有显式改用新模板后才保留为单段。
-模式 `1` 的旧业务入口及旧字符串模板保留既有同名选择和 `parentID` 回退行为;内部实现改用身份后仍须通过旧行为回归,不能因共享严格解析器而悄悄改成歧义错误。新结构化接口在两个模式中均执行严格歧义检查。模式 `2` 的内置业务使用严格计划,即使输入来自旧模板也不得任取同名父文档;功能版本的迁移说明须说明这一行为变化。跨笔记本目标使用新协议时同样保持严格规则,不因目标为模式 `1` 而恢复任取行为。
+所有内置创建业务使用严格结构化计划,不任取同名祖先。公开旧创建接口保留有效且匹配的 `parentID` 消歧及无冲突时的既有回退;同名集合无法唯一定位时返回 `pathAmbiguous`。
-新配置分别使用 `docCreateTarget`、`refCreateTarget`、`dailyNoteTarget`,与原保存路径字符串字段并存。功能版本在自动迁移为模式 `2` 的笔记本配置中开放这三个对象,全局配置继续保留旧字符串模板及现有继承规则,保留已有配置语义。对象必须带 `version: 2`,指定目标笔记本、起点、向上层数、祖先段、最终标题和缺失祖先策略;各段继续复用现有保存路径模板求值器。示例中的 `{{now | date ...}}` 是保存路径模板语法,不能与正文模板语法混淆。
+`docCreateTarget`、`refCreateTarget`、`dailyNoteTarget` 与旧模板字段并存,所有笔记本均可使用。对象带 `version: 2`,指定笔记本、起点、向上层数、祖先段、最终标题和缺失策略;全局旧模板及继承规则继续保留,保存路径语法与正文模板语法分别解释。
```json
{
@@ -199,7 +199,7 @@
新模板在渲染前确定段边界,各标题段独立求值。变量值为 `A/B` 时仍是一个标题段;先渲染成单个字符串再 `split("/")` 不符合协议。一次创建的各段使用同一份上下文和时间快照,日记按指定日历日期提供 `now`,避免跨日期或上下文变化。
-新对象存在时,它是相应创建目标的唯一权威配置;旧字符串仅保留为原配置记录。修改旧字段为不同值时必须返回明确的配置冲突,不能静默覆盖新对象;原样回传旧字段仍可接受。显式移除新对象后可重新使用旧模板,但不会将笔记本降回兼容模式。未配置新对象时沿用现有笔记本及全局配置选择顺序。跨笔记本的目标仍按目标笔记本模式校验标题,不能因为来源已启用模式 `2` 而绕过目标限制。
+新对象生效时是相应业务的唯一权威配置;旧字段原样回传可以接受,修改为冲突值必须拒绝。移除新对象后恢复旧模板求值,寻址规则仍不变。未配置新对象时保留已有继承顺序;跨笔记本目标继续检查源格式及权限。
由配置生成的预览保存配置来源笔记本、业务用途、有效配置版本及已求值上下文。提交时使用 `expectedTarget: {notebook, purpose, revision}` 校验配置,其中 `notebook` 是读取配置的来源笔记本,可能不同于创建请求的目标笔记本。版本覆盖生效目标、参与继承的配置及选中的正文模板路径;无关设置不使预览失效。内核在配置更新与文档变更共同遵守的协调范围内重新解析有效配置,校验版本和目标笔记本后提交;配置变化返回 `planChanged`,即使父路径未变也不能继续。模板正文预览另保存已渲染内容及依赖快照,不能用配置版本代替正文快照校验。
@@ -212,7 +212,7 @@
| 速记 | 明确追加目标或新建目标;目标持久化成功后才清理来源 |
| 数据库新建条目 | 保留属性值、绑定关系和排序;创建计划保存最终文档 ID |
| 模板文档树 | 保留预览、ID 重映射、插入顺序及整组撤销和重做;提交校验路径、名称与配置条件并展示部分完成结果 |
-| MCP 与内置 Agent | `document.create/list/move` 和 `inbox.convert` 使用笔记本及 `parentID`;空字符串显式表示根位置,创建接受独立的标题原文。模式 `2` 在查询前拒绝旧 `path=hPath`,工具与 Agent 提示词保持相同契约 |
+| MCP 与内置 Agent | 文档工具优先使用笔记本及 `parentID`,空字符串表示根;旧路径复用祖先链判定,单目标同名歧义返回错误 |
| 桌面、浏览器和移动端 | 分别检查菜单、快捷键、对话框及事件处理;共享工具函数迁移不能代替各端验证 |
日记的既有复用策略是明确的业务规则,不因通用解析器拒绝歧义而改成所有同日期情况均报错;模板目标优先匹配改为结构化身份链比较。
@@ -225,7 +225,7 @@
搜索范围过滤与路径文字匹配分开。前者使用文档身份或 ID 数据路径,后者匹配标题的纯文本表示及祖先文字,不进行 `/` 与 `/` 之间的替换。返回内容中的搜索高亮标记和 HTML 是展示结果,不能回写成标题源内容,也不能在补充文档标题时覆盖已有匹配高亮。
-首版保留 `blocks.hpath`、`blocktrees.hpath` 及现有批量更新机制,新增前述文档级元数据作为结构化查询来源。完整祖先链按文档组装,可使用有界缓存,不为每个内容块复制完整标题段数组。插件仍能读取字符串列,但新模式下只能把它们当作显示和文字检索数据。
+首版保留 `blocks.hpath`、`blocktrees.hpath` 及现有批量更新机制,新增前述文档级元数据作为结构化查询来源。完整祖先链按文档组装,可使用有界缓存,不为每个内容块复制完整标题段数组。插件仍能读取字符串列,但只能把它们当作显示和文字检索数据。
`RefreshDocHPaths` 通过 ID 子树和元数据重建祖先标题,不再按深度切割旧 `hPath`。`updateRootContent` 从统一标题读取结果取得文档标题,不使用 `path.Base`。稳态下重命名父文档不为取得标题而读取每篇后代的完整 `.sy`;缺失或失效元数据进入恢复流程,不能以旧显示路径补齐。
@@ -233,11 +233,11 @@
## 导入与导出
-### 跨模式移动与恢复
+### 跨笔记本移动与恢复
-跨笔记本移动、复制、原生导入及历史恢复在首次写入前检查完整操作集合,包括每个根文档的所有后代。检查目标版本支持的能力、标题格式和原文、源格式可读性、目标深度及既有加密边界;不能仅检查顶层标题。功能版本自动补齐目标模式记录;若目标读取器仍不支持所需能力,整次操作返回 `targetModeUnsupported`,并提供授权范围内的冲突文档 ID,不移动目录、不改写标题、不删除来源。
+移动、复制、原生导入及历史恢复在首次写入前检查完整操作集合,包括全部后代、源格式、标题表示、目标深度和加密边界。无法读取的格式必须拒绝,不改写标题、不删除来源;Spec 冲突由源版本保护,不能用已撤销的模式记录代替检查。
-目标客户端升级并完成自动恢复后,重新规划和校验操作。新建目标笔记本采用当前版本的默认能力,不要求用户选择模式。需要的标题能力由标题格式及实际内容决定;`.sy` 版本表示源格式的读取要求,不把所有高于 `DocumentTitleSpec` 的版本都等同于需要模式 `2`,也不为通过检查而降低源版本。符合目标规则的普通标题可以导出给支持其源格式的兼容读取器。
+支持的历史源仍可读取和恢复;需要新标题能力的新写入采用相应 Spec。不因客户端升级而统一改写文档,也不为通过检查降低已有规格。
已就绪元数据可用于检查完整子树,导入和历史使用对应的已认证源快照;缺失或过期索引先恢复,不用旧 `hPath` 推断能力。预检记录整个操作集合的身份、成员及标题和位置版本,提交在变更协调范围内复核,防止预检后后代改名或新增。可预知的不兼容必须在任何写入前拒绝;实际 I/O 失败沿用部分提交记录及恢复规则,不承诺跨文件原子移动。普通与加密笔记本之间、不同加密笔记本之间的既有隔离规则保持不变。
@@ -275,7 +275,7 @@
### 按父 ID 创建
-`/api/filetree/createDocByParent` 的最小请求如下。示例要求目标笔记本已启用结构化标题模式。
+`/api/filetree/createDocByParent` 的最小请求如下;目标索引必须就绪,且满足原有授权要求。
```json
{
@@ -313,18 +313,19 @@
| `parentUnavailable` | 父文档不存在或不属于目标笔记本,不跨笔记本查找 |
| `planChanged` | 位置、标题版本、名称匹配或配置等预览依赖变化,重新解析并确认目标 |
| `documentIDConflict` | ID 已存在,核对原请求结果,不覆盖或直接换 ID 重试 |
-| `legacyPathUnsupported` | 目标笔记本禁用旧字符串寻址,改用新接口 |
+| `legacyPathUnsupported` | 仅有祖先含斜杠或空标题的候选,改用结构化接口 |
+| `pathAmbiguous` | 干净与不兼容候选碰撞,或单目标存在多个干净候选,显式指定身份 |
| `indexUnavailable` | 结构化元数据未就绪,等待恢复,不回退到显示路径 |
| `unsupportedTitleFormat` | 客户端或接口不能处理标题格式,升级或改用对应格式接口 |
| `targetModeUnsupported` | 移动、复制、导入或恢复的完整操作集合超出目标支持能力;升级目标并完成自动恢复后重新规划 |
-| `modeConflict` | 笔记本模式记录与源标题能力不一致,进入受控恢复,不按兼容模式继续写入 |
+| `modeConflict` | 为既有调用方保留的历史错误值,撤销寻址模式后不再用于路径冲突 |
| `writeFailed` | 写入或后续处理失败,依据 `commitState` 及阶段恢复 |
### 读取有效创建目标
`/api/filetree/getDocCreateTarget` 接收当前 `notebook` 与 `purpose: "document" | "reference" | "dailyNote"`,复用各业务现有的配置优先级,返回生效的 `target`、`docCreateTemplatePath` 和配置 `revision`。`target` 为带 `version` 的联合类型:旧模板返回 `{version: 1, notebook, path}`,新模板返回上文完整的版本 `2` 对象。返回字段 `docCreateTemplatePath` 表示该业务的有效正文模板:普通新建按现有继承规则选择,日记取 `DailyNoteTemplatePath`,块引用新建保持当前不自动应用正文模板的行为并返回空字符串。接口只读取配置,不执行模板、不猜测当前文档或当前日期;调用方随后提供上下文生成计划,并将来源、用途及 `revision` 放入提交条件。
-旧 `/api/filetree/getDocCreateSavePath` 与 `/api/filetree/getRefCreateSavePath` 在各自生效配置仍为旧模板时保持原响应;对应的新对象生效时均返回 `code: -1`、`data: {reason: "structuredTemplateRequired"}`,不返回已经失效的旧路径。判断依据是配置来源及对应业务,不取决于旧路径或新目标指向哪个笔记本;旧目标仍为模式 `1` 也不能放行历史配置。两个错误变体分别在旧契约中声明。新增读取入口同时服务内置调用方和插件,避免各自重复实现配置继承规则。
+旧 `getDocCreateSavePath` 和 `getRefCreateSavePath` 在有效配置为旧模板时保持原响应;相应新对象生效时返回 `code: -1`、`data: {reason: "structuredTemplateRequired"}`。判断依据是配置来源及业务,不从显示路径猜测配置,也不读取已撤销的寻址模式。
### 规划配置中的创建目标
@@ -332,13 +333,11 @@
调用方依次提交每个 `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`。
+管理员读取 `getNotebookConf` 时获得只读 `documentCapabilities`。`addressingVersion` 恒为 `2`;`modeState` 为 `structured` 或索引未就绪时的 `recovering`,不再返回 `legacy`。保留 `structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision` 字段;未验证真实发行包前最低读取版本为 `null`。`literalSlash` 只在索引就绪时为 `true`。
-`revision` 是模式记录及恢复状态的版本摘要,不等同于某篇文档的路径版本,也不用于用户启用流程。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。
-
-不提供手动启用接口或设置项。功能版本在访问笔记本源数据前自动确认模式并补齐持久化记录,正常迁移与中断恢复使用同一流程;此过程不要求旧索引预先就绪。`recovering` 表示模式记录尚未一致或索引尚未就绪,不能据此宣称结构化写入已经可用。通用配置更新不能降低内部模式,旧请求省略新字段也不能将模式重置为 `1`。`getConf` 的 `documentAddressingVersion` 只读字段声明当前发行版的默认能力,供桌面、浏览器和移动端初始化输入规则,不保存为用户设置;笔记本实际可用性仍以 `documentCapabilities` 为准。
+能力读取不再写入任何迁移或下界记录;`revision` 是固定能力声明的版本摘要,不是某篇文档的路径版本。`getConf.documentAddressingVersion` 继续为 `2`,用于桌面、浏览器和移动端输入初始化。关闭、锁定、发布访问及请求租约继续执行原有规则,能力信息不授予额外权限。
### 契约及声明维护
@@ -346,82 +345,42 @@
## 接口与插件兼容
-模式 `1` 为旧规则的兼容模式;模式 `2` 为功能版本自动采用的结构化标题模式。旧笔记本记录缺失且没有更高能力记录时,其源记录按 `1` 解释,功能版本在源访问前自动迁移到 `2`;缺省字段不能覆盖已有能力下界。模式决定旧协议是否可用,不根据某一次请求是否恰好包含 `/` 猜测。保留模式 `1` 的读取和回归覆盖用于旧数据兼容,不表示计划发布单独的过渡版本。
-
-| 使用场景 | 兼容模式 `1` | 结构化标题模式 `2` | 插件迁移方式 |
-| --- | --- | --- | --- |
-| 按 ID 读取、移动及删除 | 保持现有契约;移入内容先满足目标模式 | 保持身份及权限;跨模式移动增加整棵子树的准入检查 | 继续使用 ID;处理 `targetModeUnsupported`,移动后重新读取当前位置 |
-| 按 ID 重命名及 ID 数据路径创建 | 保持现有标题规则 | 普通标题可保留 `/`,仍验证模式和标题格式 | 标题与位置分开传递;未知富文本格式不能用纯文本覆盖 |
-| `getIDsByHPath` | 保留原名称路径语法 | 整个笔记本拒绝,返回 `legacyPathUnsupported` | 已知 ID 直接使用;未知位置调用 `resolveDocPath` |
-| `createDocWithMd` | 保留旧语法及 `parentID` 回退行为 | 整个笔记本拒绝,即使传入 `parentID` | 改用 `createDocByParent`,不提交字符串路径 |
-| `getHPathByID`、`getHPathByPath` | 保留现有输出 | 按祖先标题原文拼接,只可显示 | 获取结构时改用 `getDocPaths` |
-| `getFullHPathByID` | 保留含笔记本名称的输出及空值规则 | 仍显示笔记本名称,不能反向定位 | 笔记本名称与文档段分别展示 |
-| `blocks.hpath`、`blocktrees.hpath` | 保留列类型及原行为 | 仍是字符串,可能包含无法区分的标题斜杠 | 子树查询使用 ID `path`,标题读取文档行 `content`,父级及深度通过结构化接口取得 |
-| `Criterion.hPath`、`SearchPath`、搜索结果 | 保留既有配置和高亮语义 | 显示文字仍可检索,范围与层级使用 ID | 不把高亮文本或路径显示值重新提交为位置 |
-| 旧保存路径模板 | 保留原语法及旧入口的同名选择行为 | 内部兼容编译器生成严格计划,未知祖先有歧义时拒绝 | 需要变量中的 `/` 保持单段时显式使用版本 `2` 模板 |
-| `getDocCreateSavePath`、`getRefCreateSavePath` | 保留旧配置结果 | 对应业务的旧模板仍返回原结果,新对象生效时返回 `structuredTemplateRequired` | 通过 `getDocCreateTarget` 读取生效的带版本配置 |
+旧 `getIDsByHPath` 先在同一元数据快照检查就绪状态和 pending,再查询本次显示路径候选,并按真实祖先链分类。每一层标题均非空、不带空标题标志且不含 ASCII `/` 时为干净候选;链上任一斜杠、实际空文本或空标题占位均为不兼容候选。属性实体仅在源读取时解码一次,不能重复解码元数据。祖先缺行、循环、身份或路径版本不一致、SQL 失败均返回 `indexUnavailable`,空结果也须先证明索引就绪。
-不改变旧字段的数据类型,不删除旧 API,也不把模式 `2` 的显示路径编码后伪装成可兼容地址。新模式下两个不同结构可以显示为相同字符串;SQL 的等值 `hpath` 查询也可能返回两种结构。继续按分隔符计数、取末段或做前缀子树查询的插件必须适配,这是启用能力的兼容成本。
+| 干净候选 | 不兼容候选 | 查询结果 |
+| --- | --- | --- |
+| 有 | 无 | 返回所有干净 ID |
+| 有 | 有 | `pathAmbiguous` |
+| 无 | 有 | `legacyPathUnsupported` |
+| 无 | 无 | 空数组 |
-旧字符串接口在模式 `2` 下新增明确的错误变体:`code: -1`、`data: {reason: "legacyPathUnsupported"}`。该变体需在原接口契约中声明并保留错误数据;模式 `1` 下既有成功、空值及错误返回保持不变。不能只改错误文案却让插件通过匹配本地化文字判断能力。
+错误使用 `code: -1` 及稳定的 `data.reason`,候选字段为 `cleanIDs` 和 `unsupportedIDs`,空列表可省略。候选 ID 仍受发布访问过滤和加密响应租约保护。旧成功结果保持数组或文档 ID 类型,不能要求调用方匹配错误文字。
-现有标题中的 `/`、`%2F` 等均按字面数据处理,不推测历史编码意图。若特定对外通道需要可逆编码,必须使用独立版本和适配边界,不能把该编码引入内部身份或标题源内容。
+`createDocWithMd` 在首次源写入前检查全部父路径前缀,不能遇到缺失的早期前缀就漏掉后续冲突;斜杠或空标题候选始终返回 `pathAmbiguous`。多个干净父级也返回该错误,有效且匹配的 `parentID` 可以按真实祖先链消歧,不能绕过不兼容候选。CLI 和 MCP 的单目标定位使用相同判定;没有明确身份时不能任取干净候选。根位置保留既有含义。
-插件迁移顺序为能力探测、按 ID 读取目标、按结构化规则解析未知祖先、按父 ID 创建、使用返回 ID 操作。发布替代接口时同时提供上述迁移矩阵和最小示例;开放模式 `2` 前完成内置调用方迁移。服务端无法识别所有插件 SQL 及其后续用途,不能宣称会自动阻止全部插件误用显示字符串。
+未知位置优先使用 `resolveDocPath` 的独立标题段,创建使用 `createDocByParent` 的父 ID 和独立标题,多层创建使用 `planDocCreate`。索引重建期间旧接口也会返回 `indexUnavailable`;调用方等待恢复,不能回退到未经证明的显示字符串或 SQL 前缀推断。
## 版本、加密与恢复
### 统一升级与旧版混用风险
-笔记本配置保存内部兼容标记 `documentAddressingVersion`:字段缺省或 `1` 表示兼容记录,`2` 表示结构化标题记录;有效模式还须结合后文的能力下界与恢复记录,不能只读取这个字段。该标记不是用户配置项,与加密信封版本独立,不能复用 `BoxCrypt.Spec`。功能版本自动迁移记录,不批量改写已有文档标题或 ID。
-
-直接发布默认采用模式 `2` 的功能版本,不单独发布过渡保护版本,也不支持新旧客户端共同访问同一工作空间或同步数据。升级前停止所有相关客户端的使用和同步,将全部设备统一升级到支持模式 `2` 与 Spec 6 的功能版本后,再恢复访问和同步;离线设备也必须先升级,不能稍后用旧版上线。普通构建默认采用模式 `2`,这一默认值不依赖最低版本元数据。当前实现继续在挂载、索引、修复、编辑及同步应用入口检查笔记本模式和源格式,拒绝不支持的能力,不能先修改数据再提示升级。
-
-混用的后果不限于旧版打不开文档。具有规格检查的旧版可能拒绝 Spec 6 文档,却继续读写同一本中保留旧 Spec 的文档;未识别新模式的旧版还可能按旧规则清理标题中的 `/` 或把标题文字当作层级。已经打开的旧编辑页面可能将缓存快照写回,覆盖新版保存的标题或正文;这些错误改动还可能经同步传播到其他设备,造成修改丢失、标题或路径异常,并需要从历史或备份恢复。不能以某篇旧 Spec 文档仍可打开来判断混用安全,也不能将拒绝读取部分文档等同于整个笔记本受到保护。
-
-真正使用新标题能力的文档采用 `DocumentTitleSpec = "6"`:标题包含 ASCII `/` 时,正常写入将文档 `Spec` 至少提升到 `6`。普通标题仍按正文所需规格保存,不能因升级客户端、迁移模式或普通格式化而全部提升到 `6`,也不降低已有版本。未来富文本表示还需对应的明确格式版本,未知内容不得被容错解析后覆盖。
-
-版本保护必须覆盖完整读取、仅属性读取、只读路径恢复、导入、历史、备份及同步。`readDocIAL` 的严格与非严格分支均须验证源版本;流式 `DocIAL` 读取不能因先遇到属性就跳过其后的 `Spec`,版本错误也不能进入损坏文件修复。源标题需要模式 `2` 而当前读取器只支持模式 `1` 时拒绝访问;功能版本先完成自动模式迁移再处理受支持源格式。不能偷偷清理标题以适配旧模式,版本较新的其他正文功能也不自动要求结构化标题模式。
-
-兼容模式在容错解析、规范化及修复前检查解码后的根标题是否包含 ASCII `/`。存储属性的转义只解码一次,保留 HTML 实体、`/`、`%2F` 和 Markdown 的字面内容;重复的根属性或版本字段不能遮盖此前遇到的不兼容值。未知标题表示保留源格式错误,不进入属性修复。原生导入在安装资源、创建笔记本或重新分配 ID 前检查全部源文档;仅发现冲突不会启用模式或生成已确认的能力下界。
-
-文档写入同时校验待写内容及磁盘上的当前源文件。加密源先认证再解释,在同一文件锁内完成当前源校验和落盘,避免旧缓存覆盖后来出现的不兼容源。自动修复还要求当前源与最初检查的字节一致;校验失败不能继续回退写入或截断文件。普通文档保留按页写入方式,加密文档保留密文原子替换。
-
-原始文件接口中的笔记本及文档 ID 路径同样受源格式检查保护,不能通过上传、复制或移入文件绕过。整批预检在创建目标目录及首次复制前完成,实际文档复制使用已经校验的读取字节,并在文件锁内重新检查目标源;检查后的并发变化或 I/O 失败仍可能留下已完成的复制,不承诺整批回滚。普通附件和插件目录下的 `.sy` 文件保持原始文件语义,加密笔记本仍禁止通过原始文件接口读写。
-
-新传入的原始文档写入、复制和重命名,在解码后的根标题含 ASCII `/` 时要求 `Spec >= 6`。低版本输入在任何目标写入前返回 `document title requires spec 6`;原始文件接口不自动升级或重新序列化请求字节。此项一致性检查仅约束新写入:已有受支持的低 Spec 源保留认证读取、历史、备份、同步和恢复能力,并允许用合法内容替换以修复版本标记。普通树写入继续按需升级版本。
-
-兼容判定依据为文档 Spec 和笔记本有效模式,两者均须在相关读写、同步与恢复入口执行;不混用旧版不构成删除这些检查的理由。已发布且忽略模式标记或缺少写入前检查的旧客户端,无法被新增字段追溯约束,系统也无法证明离线设备已经升级。发布说明及用户指南必须明确全设备统一升级和混用可能损坏数据的后果,不承诺旧版一定被安全拦截。`minimumReaderVersion` 如需登记,须以实际功能发行包的读写与兼容测试为依据;暂为 `null` 不表示支持旧客户端,也不再以过渡保护版本发布或登记其版本号作为本议题关闭条件。
-
-已发布 `v3.8.9-alpha.4` 源码的隔离验证表明:它拒绝直接读取 Spec 6 文档,但仍能读取模式 `2` 中保留旧规格的文档,并将旧编辑快照写回。这些已验证行为说明不能概括为“旧版本一定无法打开”;标题清理、层级误解及错误同步传播是混用风险,不能将其写成该探针已逐项验证的结果。本地临时模式 `1` 构建及回归用于验证能力受限读取器的拒绝行为,不代表一个已发布或必须发布的过渡版本。功能版本仍需遵守常规发行包核对与发布验证,维护者负责发布。
-
-自动迁移到模式 `2` 后不提供改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复升级前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。
-
-### 模式记录与冲突恢复
-
-自动迁移在笔记本 `.siyuan/document-addressing.json` 写入独立的能力下界记录 `{version: 1, notebook, minimumMode: 2}`,只含身份及版本,随原生笔记本导出、备份和同步保存。本机另在工作空间 `conf/document-addressing.json` 保留按笔记本 ID 索引的已确认最低模式。有效模式取合法笔记本配置、笔记本下界、本机下界及有效恢复记录中最严格的要求。记录不是密文认证凭据;未知版本、无效字段或身份不匹配必须保留原文件并拒绝处理,不能按缺省模式 `1` 继续。
-
-本机记录采用 `{version: 1, notebooks: {"<notebookID>": 2}}`,省略尚无较高要求的笔记本;普通兼容模式读取不创建记录或改写源数据。记录写入必须原子替换,合并时逐个身份取最大值,不能用较旧记录整体覆盖。本机或同步、快照预检已经读到合法的较高要求时,即使本次批次因能力不足被拒绝,也保留该要求,防止下一次读取旧的本地配置时恢复普通写入;记住能力要求不等于启用结构化标题。导入时尚未采用的独立原生笔记本身份不因此写入本机记录。
-
-设置导出仍为包含一个 JSON 文件的压缩包,有已确认的能力下界时,在该 JSON 顶层附加 `documentAddressing`,内容与本机记录同构。导入在采用普通设置之前校验并逐身份合并最高要求;旧设置缺少此字段时不清除本机记录,损坏或未知版本在采用设置前报错。该字段只用于备份传递,恢复后仍独立保存在 `conf/document-addressing.json`,不写入普通 `conf.json`,也不包含标题、正文或密钥。原始文件接口不得直接覆盖、重命名或删除本机记录;笔记本写入及复制须预检待写配置和整批目标,排序恢复须保留不支持模式的原文件及恢复记录。
-
-模式检查同时识别配置及能力下界记录;不支持的模式在实际处理源文件前拒绝。同步应用和快照恢复先核对受影响笔记本的能力要求,再替换配置或文件。已确认模式 `2` 时,传入旧配置、缺少新字段或删除能力记录都不能降低有效模式;恢复配置投影和下界记录后再开放访问。若只能在文件落盘后检查,或依赖层不能在应用前提供所需配置数据,阶段 A 尚未完成,须先补齐同步和恢复入口,不能以重建索引代替前置保护。
+模式 1 已撤销,所有笔记本按结构化规则解释,现有文档、ID、密文及密钥不需要迁移或批量改写。`conf.json` 的 `documentAddressingVersion` 在普通配置保存时固定写入 `2`,仅作诊断标记;缺失配置和笔记本目录不会使能力读取触发 syscall 错误或重新创建数据。
-模式标记不能代替文档源检查。同步和快照恢复在整批文件写入或删除前,检查待应用的普通文档源,并拒绝以旧快照覆盖或部分删除预检时已确认使用不支持规格、标题表示或标题能力的现存源;即使来源缺少模式标记,也不能先落盘再依赖索引发现错误。该检查沿用现有恢复过程,不将普通快照恢复变为可隔离任意外部文件修改的原子事务。合法历史源仍可恢复一般损坏的普通文档,整本删除保留既有语义,附件及插件目录中的 `.sy` 不解释为文档。锁定加密笔记本仍按既有协议传输原始密文字节,不为标题预检要求解锁,也不把仓库分块校验当作笔记本内容认证;密文的认证及源格式检查继续在原有受保护读取和恢复边界内完成。
+新写入的标题包含 ASCII `/` 时必须声明至少 Spec 6。保留独立的规格检测、重复属性与实体解码校验、未知标题表示及未来 Spec 拒绝。支持的历史低 Spec 斜杠源仍可读取和恢复,原始新写入必须满足规格要求;普通文档保留正文所需规格,不因升级统一变为 Spec 6,也不降低原版本。
-删除整个笔记本仍按现有语义执行,不为补齐能力记录而重新创建已删除的笔记本;本机保留该身份的已确认下界,恢复同一身份时继续生效。完整笔记本的原生导入先校验源身份与能力记录,再按既有导入规则分配或复用目标身份,并将能力下界绑定到目标身份;不得借身份重映射降低源笔记本已确认的模式。向既有笔记本导入部分文档则按前述完整操作集合检查,不直接复制源笔记本的模式配置。
+升级前停止访问同一工作空间和同步数据的全部客户端,将桌面、移动端和服务端统一升级后再恢复使用;离线旧设备也必须先升级。旧版本不读取这些模式记录,Spec 6 也不能保护同一本中仍为旧 Spec 的全部文档,因此撤销无效下界不表示支持旧版混用。已有 `v3.8.9-alpha.4` 隔离源码验证只证明直接 Spec 6 读取被拒、旧 Spec 仍可读取及旧编辑快照可覆盖来源,未覆盖全部旧端操作或完整混用同步。旧客户端只能使用经过验证的独立导出副本或恢复到独立工作空间的升级前备份,不能覆盖原配置后继续同步。
-自动迁移先在 `conf/document-addressing-recovery/<notebookID>.json` 持久化 `{version: 1, notebook, phase: "records"}`,再依次写入本机下界、笔记本下界及配置中的模式标记,最后删除该恢复记录。任一步骤中断后,下次访问继续同一迁移,不撤回已写入的模式要求;模式检查必须将有效恢复记录视为至少需要模式 `2`。配置的未知字段及加密载荷原值保留,不扫描或批量重写 `.sy` 文件,原始文件接口不能覆盖该恢复目录。
+### 已撤销的记录与启动清理
-普通构建在已有模式记录缺失或配置落后时自动补齐,已删除的笔记本不能因恢复而重建。已有笔记本的配置文件缺失时,仅保留已确认模式,不生成替代配置;加密备份恢复仍须认证原密钥及载荷,不能保存为普通笔记本。配置恢复前能力状态保持 `recovering`。模式迁移与索引重建分开:元数据迁移不依赖就绪索引,也不认证或改写文档密文;后续源读取和索引构建仍必须在原授权及加密租约内先认证源内容。只有模式记录一致且索引就绪时才对外报告 `modeState: "structured"`。
+能力读取、导入、同步、快照及设置备份不再读取或生成能力下界、模式迁移记录和设置中的 `documentAddressing` 字段;旧设置中的该字段被忽略。同步及恢复仍在应用前检查源 Spec、规范路径及原有认证边界。
-模式记录恢复失败时保留恢复记录并报错;索引缺失或重建未完成时报告 `recovering`,结构化写入等待所需索引就绪。源格式未知、文件损坏或认证失败时保留原文件、密钥及待恢复任务,停止受影响操作并报告错误。再次访问或重新启动按既有恢复机制继续,不要求用户选择模式,也不能降级、重建笔记本或跳过格式校验来消除错误。
+启动时幂等清理本机 `conf/document-addressing.json` 和 `conf/document-addressing-recovery/`,目录缺失视为成功,删除失败仅记录警告,不能阻断挂载;只读模式跳过清理。笔记本内部 `.siyuan/document-addressing.json` 不再读取或新建,现存文件保持原样,避免产生同步删除。加密恢复密钥和源恢复任务不属于此次清理范围。
### 索引与任务恢复
`document_metadata` 使用独立的派生索引版本及笔记本状态 `missing`、`building`、`ready`、`error`。新建表后从源文档和 ID 位置构建,不从旧 `hPath` 推测段边界。构建期间记录增量变更并在切换前追平;只有全量扫描和增量校验完成,才将对应代次标记为 `ready`。
-兼容模式下旧功能在重建期间保持既有行为,新结构化接口在需要的数据未就绪时返回 `indexUnavailable`。模式 `2` 下不能因索引损坏回退到旧名称定位;按现有源读取路径恢复,结构化写入等待必需元数据就绪。不存在的父源文件不能自动补建,损坏源文件不能靠索引中的旧标题覆盖。
+结构化和旧路径接口需要的元数据未就绪时均返回 `indexUnavailable`。恢复必须认证实际源,不能补建不存在的父源文件,也不能用派生索引覆盖损坏源。
更新顺序为源文档持久化、同一块树数据库事务内更新文档元数据和对应文档行、提交后续 `hpath` 批次。源文件与数据库、块树库与内容库之间不宣称原子事务。任一步骤中断都保留恢复标记;重新启动或解锁后先验证源版本及当前 ID 位置,再继续派生更新。快照版本、移动或删除检测使排队中的旧树失效,不能恢复旧标题。
@@ -445,15 +404,15 @@
| 阶段 | 交付内容 | 完成条件 |
| --- | --- | --- |
-| A:兼容保护 | 笔记本能力下界及冲突识别、未知模式及源版本保护、旧行为回归样本 | 同步及快照应用前验证模式和来源,所有写入与修复入口安全拒绝不支持的模式或规格;不要求单独发布保护版本 |
+| A:兼容保护 | 候选祖先链冲突识别、源版本保护及历史样本 | 同步及快照应用前验证来源,所有写入与修复入口安全拒绝不支持的源格式或规格;不要求单独发布保护版本 |
| B:内部解耦 | 统一标题读取、文档元数据、ID 层级计算、路径刷新及恢复 | 普通标题行为不变;结构不再从显示字符串推导,加密索引可认证重建 |
| C:接口与调用方 | 新读取、解析、条件创建接口,版本 `2` 模板及加密载荷,内置业务及各端迁移 | 名称与配置并发条件、新旧契约通过验证,部分失败及撤销可恢复,日记等业务行为保持 |
-| D:开放新字符 | 默认采用新模式及自动恢复、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 普通构建默认支持 `/`;完整子树预检、模式恢复及全部发布条件通过后才完成对外发布验收 |
+| D:开放新字符 | 统一结构化规则及索引恢复、旧接口拒绝规则、插件迁移说明、跨笔记本操作及导入导出验证 | 普通构建默认支持 `/`;完整子树预检、索引恢复及全部发布条件通过后才完成对外发布验收 |
| E:行级标题 | 独立的源格式、编辑及渲染设计 | 保持本方案身份接口,完成格式及旧写入保护后另行交付 |
-阶段 A 至 D 为同一功能版本的实现与验证拆分,不要求先交付单独的模式 `1` 版本;开发分支已默认开放新字符,对外发布验收仍要求 A 至 D 的相关条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。
+阶段 A 至 D 为同一功能版本的实现与验证拆分,不保留独立的旧寻址模式;开发分支已默认开放新字符,对外发布验收仍要求 A 至 D 的相关条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。
-开放条件包括:所有内置消费者已迁移;替代接口和插件适配文档已发布;当前实现的 Spec、模式及写入前拒绝检查通过验证;普通与加密索引迁移可中断恢复;导入导出不会因显示路径冲突覆盖文件;桌面、浏览器和移动端行为一致;四种语言的用户指南说明默认行为、插件影响、全部设备统一升级及混用后果。对旧数据及旧协议的回归不构成与旧客户端混用的支持承诺。
+开放条件包括:所有内置消费者已迁移;替代接口和插件适配文档已发布;当前实现的 Spec 及写入前拒绝检查通过验证;普通与加密索引迁移可中断恢复;导入导出不会因显示路径冲突覆盖文件;桌面、浏览器和移动端行为一致;四种语言的用户指南说明默认行为、插件影响、全部设备统一升级及混用后果。对旧数据及旧协议的回归不构成与旧客户端混用的支持承诺。
实施已分配 `.sy` 规格 `6`;功能版本发布时附上已有性能测量与兼容测试结果,并如实说明验证限制。不再以先发布保护版本或登记其版本号作为本议题的验收前置条件,`minimumReaderVersion` 保留为经实际发行包验证后登记的信息字段。这些是发布证据,不是重新悬置身份、模板、插件边界或失败语义的决策。不能以完成文档、通过隔离测试或一次索引重建代替全部功能验收。
@@ -466,12 +425,12 @@
| 标题内容 | `/`、`/`、连续斜杠、`%2F`、`.`、`..`、空标题、Unicode 和长度边界;原字符不发生未经约定的转换 |
| 身份与层级 | 单标题 `A/B` 与两级 `A`、`B`,同父同名、不同父同名、重复 ID 的归属校验、根位置及笔记本文档 |
| 创建与并发 | 直接按 ID 跟随父位置及带版本请求拒绝过期预览;同名祖先并发创建、匹配集合及配置变化;父文档删除、跨笔记本移动、关闭或锁定;响应丢失、部分提交、固定 ID 冲突及多级恢复 |
-| 模板 | 旧语法全部边界及模式 `1` 的旧同名行为、新语法逐段渲染、变量包含 `/`、相对操作、同一时间快照、配置继承及正文模板选择、日记与速记等入口、模板文档树整组撤销和重做 |
+| 模板 | 旧语法全部边界及旧模板语法及有效父 ID 消歧、新语法逐段渲染、变量包含 `/`、相对操作、同一时间快照、配置继承及正文模板选择、日记与速记等入口、模板文档树整组撤销和重做 |
| 搜索与展示 | 原始标题字符检索、祖先文字检索、ID 范围过滤、标题高亮、面包屑段边界、复制文字与 ID 链接 |
| 索引与恢复 | 深层子树、父子连续重命名、旧编辑快照、批次中断、重启、移动、删除、同步及普通与加密索引迁移 |
-| 导入导出及跨模式操作 | 重名、非法文件名、大小写冲突、路径越界、相对链接、跨笔记本引用、标题元数据及无损往返承诺;移动、复制和恢复预检全部后代,拒绝时不产生部分写入 |
-| 旧接口与插件 | 模式 `1` 旧返回不变;模式 `2` 整个笔记本拒绝旧寻址;两个旧目标读取接口拒绝失效配置,即使旧目标仍为模式 `1`;SQL 显示字符串碰撞、结构化替代接口、能力缺失与请求失败的区别 |
-| 旧数据兼容与加密 | 支持的历史格式及配置载荷样本、旧同步来源的预检与拒绝、能力下界不降级、无就绪索引的模式冲突恢复、认证失败、锁定期间的缓存和响应、历史及备份恢复、密钥材料保留;不承诺新旧客户端混用 |
+| 导入导出及跨笔记本操作 | 重名、非法文件名、大小写冲突、路径越界、相对链接、跨笔记本引用、标题元数据及无损往返承诺;移动、复制和恢复预检全部后代,拒绝时不产生部分写入 |
+| 旧接口与插件 | 干净旧路径兼容;真实祖先链冲突拒绝;两个旧目标读取接口拒绝失效配置,不依赖旧目标的诊断版本;SQL 显示字符串碰撞、结构化替代接口、能力缺失与请求失败的区别 |
+| 旧数据兼容与加密 | 支持的历史格式及配置载荷样本、旧同步来源的预检与拒绝、固定版本、缺失及 pending 索引拒绝、只读启动清理跳过、认证失败、锁定期间的缓存和响应、历史及备份恢复、密钥材料保留;不承诺新旧客户端混用 |
| 行级元素扩展 | 现有 Markdown 样式文字保持字面含义;标题表示变化不影响身份与层级;纯文本相同不合并文档;格式与纯文本来源单向派生;#19235 的图片及链接双向转换保留、资源引用和防重复要求 |
| 跨端与性能 | 桌面、浏览器和移动端创建及重命名;大子树下的前台延迟、数据库批次时间、内存、CPU 和磁盘读写 |
@@ -483,9 +442,9 @@
两个请求同时解析缺失祖先并提交同一不存在条件,验证只成功一次,另一次返回 `planChanged`;普通同名最终文档仍可分别创建。已匹配祖先出现第二个同名文档时,唯一身份条件失败。配置预览后改变目标笔记本、继承配置或正文模板路径,即使父路径版本相同也须拒绝;重命名与配置更新发生在最后校验和提交之间的竞争也需覆盖。
-构造标题普通但后代包含 `/` 或新标题格式的子树,使用不支持相应能力的读取器移动、复制、导入和恢复,均在首次源写入前拒绝;预检后后代变化也须被发现。目标升级并完成自动恢复后重新执行成功,既有加密边界不放宽。仅使用其他新版正文功能而标题仍兼容的文档不得被误判为需要模式 `2`。
+构造普通根标题但后代含 `/` 或未知标题表示的子树,验证移动、复制、导入和恢复在源写入前检查全部后代、源规格与认证;预检后变化仍须被发现,不能降低规格或绕过加密边界。
-模拟旧配置覆盖、能力记录缺失或损坏、同步中断,以及源文档已经需要模式 `2` 但索引尚不可用的场景。验证有效模式不下降、未知格式保留原数据、无开关的自动迁移可在索引未就绪时进行、重启继续同一恢复任务。覆盖迁移每一步的写入故障、整本删除后按同一身份恢复,以及完整导入重映射笔记本身份时保留能力下界。对新配置载荷检查磁盘及锁定后的接口和缓存均无新目标对象明文,并验证旧载荷读取及备份、改密后的恢复。
+验证旧配置和历史快照恢复、缺失配置、已撤销记录的忽略与启动清理;索引未就绪必须拒绝路径定位及创建。使用受支持的普通和加密历史样本,检查未知源格式保护、认证失败、目标配置无明文落盘和锁定后的缓存清理,保留备份及改密恢复覆盖。
`TestDocumentAddressingCheckoutSourcePreflight` 使用实际仓库快照,覆盖缺少模式标记的未来规格、未知标题表示、现存不兼容源及模式检查优先级;拒绝时同批新增、替换和删除均不开始,源字节、时间及快照来源保持不变。`TestDocumentAddressingCheckoutSourceRemoval` 区分部分删除与整本删除;`TestDocumentAddressingCheckoutPreservesOpaqueEncryptedSource` 使用历史密文样本验证无需解锁的原字节传输,并检查配置及恢复材料不变。路径回归覆盖反斜杠、重复目标,以及 Windows 的尾点、尾空格和默认数据流别名,不能让实际落盘目标绕过来源检查。另保留 BOM、合法斜杠标题、一般损坏源恢复和附件 `.sy` 的回归,避免来源保护扩大为不兼容的文件操作限制。
@@ -507,7 +466,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" ./documentaddressing ./filesys ./model ./api ./cli/cmd -run '^TestStructuredTitles' -count=1`,覆盖自动迁移、新模式读写及真实 HTTP 契约,不再注入测试版本号。能力受限读取器的模式拒绝由显式兼容测试夹具覆盖,未知未来模式与源格式的拒绝继续在默认构建中验证。本地模式 `1` 临时覆盖构建验证受限读取器的检查边界,不改变普通构建默认值,也不要求发布过渡版本。以上完整验收要求不等于已全部执行,文档修改另检查双语一致性、示例、链接及差异格式。
+新增祖先链、旧路径创建、CLI、MCP 和契约回归位于现有 Go 测试发现范围。执行带 `fts5 sqlcipher` 的相关包测试,保留 Spec 6、历史普通与加密样本、未知源格式、同步及恢复覆盖;不保留模式 1 覆盖构建或已删除机制的桩。文档另检查双语一致性、示例、链接及差异。
## 相关代码
diff --git a/kernel/api/contract_document_addressing_archive_test.go b/kernel/api/contract_document_addressing_archive_test.go
index 11427330a1..fb6ed26c08 100644
--- a/kernel/api/contract_document_addressing_archive_test.go
+++ b/kernel/api/contract_document_addressing_archive_test.go
@@ -42,7 +42,6 @@ func TestAPIContractDocumentAddressingArchives(t *testing.T) {
name := addressingAPIBox + "/" + document
for _, entries := range [][][2]string{
{{"first.txt", "first"}, {name, future}},
- {{"first.txt", "first"}, {addressingAPIBox + "/.siyuan/conf.json", `{"documentAddressingVersion":3}`}},
{{"first.txt", "first"}, {name, future}, {name, ordinary}},
} {
write(entries)
@@ -54,7 +53,7 @@ func TestAPIContractDocumentAddressingArchives(t *testing.T) {
t.Fatal("unzip wrote an earlier entry before checking the full batch", err)
}
}
- // 采用过更高模式的身份不能复用;兼容成功使用独立笔记本身份。
+ // A compatible archive is admitted based on source formats, without remembered modes.
name = "20261023000001-rawbox2/" + document
write([][2]string{{name, ordinary}, {"assets/" + document, "arbitrary attachment"}, {"empty/", ""}})
if result := callArchiveAPI(t, unzip, `{"zipPath":"source.zip","path":"data"}`); result.Code != 0 {
diff --git a/kernel/api/contract_document_addressing_test.go b/kernel/api/contract_document_addressing_test.go
index eef4733cb7..8b31d2742b 100644
--- a/kernel/api/contract_document_addressing_test.go
+++ b/kernel/api/contract_document_addressing_test.go
@@ -167,66 +167,6 @@ func TestAPIContractDocumentAddressingRawTitleSpec(t *testing.T) {
}
}
-func TestAPIContractDocumentAddressingRawWrites(t *testing.T) {
- addressingAPIWorkspace(t)
- confPath := filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json")
- addressingAPIWrite(t, confPath, `{"documentAddressingVersion":3}`)
- name := "data/" + addressingAPIBox + "/original.sy"
- abs := filepath.Join(util.WorkspaceDir, name)
- addressingAPIWrite(t, abs, "future source")
- addressingAPIWrite(t, filepath.Join(util.DataDir, "assets", "source.txt"), "asset")
- before, _ := os.Stat(abs)
- if code := addressingAPIPut(t, name, "overwrite", false); code != -1 {
- t.Fatalf("put accepted unsupported notebook: %d", code)
- }
- if code := addressingAPIPut(t, "data/"+addressingAPIBox+"/new/child", "", true); code != -1 {
- t.Fatalf("mkdir accepted unsupported notebook: %d", code)
- }
- for _, test := range []struct {
- route string
- handler gin.HandlerFunc
- body interface{}
- }{
- {"removeFile", removeFile, apicontract.RemoveFileRequest{Path: name}},
- {"removeFile", removeFile, apicontract.RemoveFileRequest{Path: "data/" + addressingAPIBox + "/.siyuan"}},
- {"renameFile", renameFile, apicontract.RenameFileRequest{Path: name, NewPath: "new-parent/moved.sy"}},
- {"workspaceCopyFiles", workspaceCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{name}, DestDir: "new-parent"}},
- {"globalCopyFiles", globalCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{abs}, DestDir: "new-parent"}},
- {"copyFile", copyFile, apicontract.CopyFileRequest{Src: "assets/source.txt", Dest: abs}},
- } {
- if code := addressingAPIRequest(t, test.route, test.handler, test.body); code != -1 {
- t.Fatalf("%s accepted unsupported notebook: %d", test.route, code)
- }
- }
- after, _ := os.Stat(abs)
- data, _ := os.ReadFile(abs)
- if string(data) != "future source" || !before.ModTime().Equal(after.ModTime()) {
- t.Fatal("rejected operations modified the source")
- }
- for _, path := range []string{filepath.Join(util.WorkspaceDir, "new-parent"), filepath.Join(util.DataDir, addressingAPIBox, "new")} {
- if _, err := os.Stat(path); !os.IsNotExist(err) {
- t.Fatalf("rejected operation created directory: %s, %v", path, err)
- }
- }
- if code := addressingAPIRequest(t, "removeFile", removeFile, apicontract.RemoveFileRequest{Path: "data/" + addressingAPIBox}); code != 0 {
- t.Fatalf("whole notebook deletion failed: %d", code)
- }
- if code := addressingAPIPut(t, name, "old restored source", false); code != -1 {
- t.Fatalf("same identity lost its remembered requirement: %d", code)
- }
- if _, err := os.Stat(filepath.Dir(abs)); !os.IsNotExist(err) {
- t.Fatal("rejected restore recreated the deleted notebook")
- }
- for path, expected := range map[string]int{"conf/document-addressing.json": -1, "conf": 403} {
- if code := addressingAPIRequest(t, "removeFile", removeFile, apicontract.RemoveFileRequest{Path: path}); code != expected {
- t.Fatalf("local floor protection changed for %s: %d", path, code)
- }
- }
- if code := addressingAPIPut(t, "conf/document-addressing.json", `{"version":1,"notebooks":{}}`, false); code != -1 {
- t.Fatalf("local floor overwritten: %d", code)
- }
-}
-
func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
addressingAPIWorkspace(t)
source := testutil.PublicDataDir(t)
@@ -234,7 +174,7 @@ func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
future := filepath.Join(source, addressingAPIBox)
addressingAPIWrite(t, plain, "first")
addressingAPIWrite(t, filepath.Join(future, ".siyuan", "conf.json"), `{"documentAddressingVersion":3}`)
- addressingAPIWrite(t, filepath.Join(future, "document.sy"), "future source")
+ addressingAPIWrite(t, filepath.Join(future, "20261022130000-rawdoc1.sy"), `{"Spec":"999","Properties":{"title":"Future"}}`)
if code := addressingAPIRequest(t, "globalCopyFiles", globalCopyFiles,
apicontract.CopyFilesRequest{Srcs: []string{plain, future}, DestDir: "data"}); code != -1 {
t.Fatalf("incoming unsupported batch accepted: %d", code)
@@ -243,16 +183,10 @@ func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {
if len(entries) != 0 {
t.Fatalf("batch wrote files before checking all notebooks: %v", entries)
}
- if code := addressingAPIPut(t, "data/20261022120000-rawbox2/.siyuan/conf.json", `{"documentAddressingVersion":3}`, false); code != -1 {
- t.Fatalf("incoming mode accepted: %d", code)
- }
- entries, _ = os.ReadDir(util.DataDir)
- if len(entries) != 0 {
- t.Fatal("rejected put created the notebook directory")
- }
- if code := addressingAPIPut(t, "data/20261022120000-rawbox3/document.sy", "legacy raw data", false); code != 0 {
- t.Fatalf("legacy write changed: %d", code)
+ if code := addressingAPIPut(t, "data/20261022120000-rawbox2/.siyuan/conf.json", `{"documentAddressingVersion":3}`, false); code != 0 {
+ t.Fatal("retired marker blocked config copy", code)
}
+
}
func TestAPIContractDocumentAddressingDocumentSources(t *testing.T) {
@@ -263,7 +197,6 @@ func TestAPIContractDocumentAddressingDocumentSources(t *testing.T) {
ordinary := `{"Spec":"2","Properties":{"title":"Ordinary"}}`
for _, unsupported := range []string{
`{"Spec":"999","Properties":{"title":"Future"}}`,
- `{"Spec":"2","Properties":{"title":"A/B"}}`,
`{"Spec":"2","Properties":{"title":{"format":"future"}}}`,
`{"Spec":"999","Spec":"2","Properties":{"title":"Future"}}`,
`null`,
@@ -411,27 +344,17 @@ func TestAPIContractDocumentAddressingSettingsBackup(t *testing.T) {
}
data, err := io.ReadAll(file)
file.Close()
- if err != nil || !bytes.Contains(data, []byte(`"documentAddressing"`)) {
- t.Fatalf("settings backup omitted the floor: %s, %v", data, err)
- }
- if code := importPreferencesRequest(t, "old.json", []byte(`{"editor":{"fontSize":18}}`)); code != 0 {
- t.Fatalf("legacy settings import changed: %d", code)
+ if err != nil || bytes.Contains(data, []byte(`"documentAddressing"`)) {
+ t.Fatal("settings export regenerated retired records", err)
}
- if err = documentaddressing.CheckBox(util.DataDir, util.ConfDir, addressingAPIBox); err == nil {
- t.Fatal("legacy settings lowered the floor")
+ if code := importPreferencesRequest(t, "old.json", []byte(`{"editor":{"fontSize":18},"documentAddressing":{"version":99,"notebooks":{}}}`)); code != 0 {
+ t.Fatal("retired settings field blocked ordinary import", code)
}
- before := model.Conf.Editor.Load().FontSize
- if code := importPreferencesRequest(t, "invalid.json", []byte(`{"editor":{"fontSize":27},"documentAddressing":{"version":99,"notebooks":{}}}`)); code != -1 {
- t.Fatalf("invalid backup accepted: %d", code)
+ if model.Conf.Editor.Load().FontSize != 18 {
+ t.Fatal("ordinary settings were lost")
}
- if model.Conf.Editor.Load().FontSize != before {
- t.Fatal("invalid backup partially applied ordinary settings")
- }
- util.ConfDir = t.TempDir()
- if code := importPreferencesRequest(t, "backup.json", data); code != 0 {
- t.Fatalf("backed up floor could not be restored: %d", code)
- }
- if _, err = os.Stat(filepath.Join(util.ConfDir, "document-addressing.json")); err != nil {
- t.Fatal(err)
+ if _, err := os.Stat(filepath.Join(util.ConfDir, "document-addressing.json")); !os.IsNotExist(err) {
+ t.Fatal("settings import created retired record", err)
}
+
}
diff --git a/kernel/api/contract_document_capabilities_test.go b/kernel/api/contract_document_capabilities_test.go
index b2f83e2086..ed5d1b5e17 100644
--- a/kernel/api/contract_document_capabilities_test.go
+++ b/kernel/api/contract_document_capabilities_test.go
@@ -53,17 +53,15 @@ func TestAPIContractDocumentCapabilities(t *testing.T) {
t.Fatalf("ready metadata did not enable structured titles or changed the configuration revision: %+v", current)
}
name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)
- if err := os.WriteFile(name, []byte(`{"version":1,"notebook":"`+boxID+`","minimumMode":3}`), 0600); err != nil {
- t.Fatal(err)
- }
- if current := read(); current.AddressingVersion != 3 || current.ModeState != "conflict" || current.LiteralSlash || current.Revision == capabilities.Revision {
- t.Fatalf("unsupported mode was reported as writable: %+v", current)
- }
- if err := os.WriteFile(name, []byte(`{"version":99}`), 0600); err != nil {
- t.Fatal(err)
- }
- data := documentPathAPIRequest(t, "/api/notebook/getNotebookConf", admin, map[string]string{"notebook": boxID})
- if !bytes.Contains(data, []byte(`"code":-1`)) || bytes.Contains(data, []byte(`"documentCapabilities"`)) {
- t.Fatalf("damaged capability record silently fell back to legacy mode: %s", data)
+ for _, record := range []string{`{"version":1,"notebook":"` + boxID + `","minimumMode":3}`, `{"version":99}`, `{`} {
+ if err := os.WriteFile(name, []byte(record), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if current := read(); current.AddressingVersion != 2 || current.ModeState != "structured" || !current.LiteralSlash || current.Revision != capabilities.Revision {
+ t.Fatal("retired record changed fixed capabilities", current)
+ }
+ if data, err := os.ReadFile(name); err != nil || string(data) != record {
+ t.Fatal("capability read changed notebook record", err)
+ }
}
}
diff --git a/kernel/api/contract_document_legacy_test.go b/kernel/api/contract_document_legacy_test.go
new file mode 100644
index 0000000000..097a6db9d1
--- /dev/null
+++ b/kernel/api/contract_document_legacy_test.go
@@ -0,0 +1,114 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/parse"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractLegacyDocumentPaths(t *testing.T) {
+ box := documentPathAPIWorkspace(t)
+ parent := treenode.NewTree(box, "/20261026000001-parent1.sy", "/A", "A")
+ child := treenode.NewTree(box, "/20261026000001-parent1/20261026000002-child01.sy", "/A/B", "B")
+ slash := treenode.NewTree(box, "/20261026000003-slash01.sy", "/A/B", "A/B")
+ leaf := treenode.NewTree(box, "/20261026000003-slash01/20261026000004-leaf001.sy", "/A/B/C", "C")
+ placeholder := treenode.NewTree(box, "/20261026000005-empty01.sy", "/Empty", "Empty")
+ placeholder.Root.SetIALAttr(treenode.DocumentTitleEmptyAttr, "true")
+ for _, tree := range []*parse.Tree{parent, child, slash, leaf, placeholder} {
+ treenode.UpsertBlockTree(tree)
+ }
+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ hp, reason string
+ clean, unsupported int
+ }{
+ {"/A", "", 0, 0}, {"/missing", "", 0, 0}, {"/A/B", "pathAmbiguous", 1, 1}, {"/A/B/C", "legacyPathUnsupported", 0, 1}, {"/Empty", "legacyPathUnsupported", 0, 1},
+ } {
+ response := documentPathAPIRequest(t, "/api/filetree/getIDsByHPath", getIDsByHPath, map[string]string{"notebook": box, "path": test.hp})
+ var result struct {
+ Code int
+ Data json.RawMessage
+ }
+ if err := json.Unmarshal(response, &result); err != nil {
+ t.Fatal(err)
+ }
+ if test.reason == "" {
+ if result.Code != 0 {
+ t.Fatal(string(response))
+ }
+ if test.hp == "/missing" && !bytes.Equal(result.Data, []byte("[]")) {
+ t.Fatal(string(response))
+ }
+ } else {
+ var failure struct {
+ Reason string
+ CleanIDs, UnsupportedIDs []string
+ }
+ if err := json.Unmarshal(result.Data, &failure); err != nil || result.Code != -1 || failure.Reason != test.reason || len(failure.CleanIDs) != test.clean || len(failure.UnsupportedIDs) != test.unsupported {
+ t.Fatal(string(response), err)
+ }
+ }
+ }
+ for _, hp := range []string{"/A/B/New", "/A/B/C/M/New", "/Empty/New"} {
+ response := documentPathAPIRequest(t, "/api/filetree/createDocWithMd", createDocWithMd, map[string]string{"notebook": box, "path": hp, "markdown": "body"})
+ if !bytes.Contains(response, []byte("\"reason\":\"pathAmbiguous\"")) {
+ t.Fatal(string(response))
+ }
+ }
+ entries, err := os.ReadDir(filepath.Join(util.DataDir, box))
+ if err != nil || len(entries) != 1 || entries[0].Name() != ".siyuan" {
+ t.Fatal("rejected creation wrote sources", entries, err)
+ }
+ if _, err := treenode.BeginDocumentMetadataRecovery(treenode.GetBlockTreeInExactBox(parent.ID, box)); err != nil {
+ t.Fatal(err)
+ }
+ response := documentPathAPIRequest(t, "/api/filetree/getIDsByHPath", getIDsByHPath, map[string]string{"notebook": box, "path": "/missing"})
+ if !bytes.Contains(response, []byte("\"reason\":\"indexUnavailable\"")) {
+ t.Fatal(string(response))
+ }
+}
+
+func TestAPIContractLegacyDocumentCandidateVisibility(t *testing.T) {
+ box := documentPathAPIWorkspace(t)
+ parent := treenode.NewTree(box, "/20261026000001-parent1.sy", "/A", "A")
+ child := treenode.NewTree(box, "/20261026000001-parent1/20261026000002-child01.sy", "/A/B", "B")
+ slash := treenode.NewTree(box, "/20261026000003-slash01.sy", "/A/B", "A/B")
+ for _, tree := range []*parse.Tree{parent, child, slash} {
+ treenode.UpsertBlockTree(tree)
+ }
+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ previous := model.GetPublishAccess()
+ t.Cleanup(func() {
+ if err := model.SetPublishAccess(previous); err != nil {
+ t.Error(err)
+ }
+ })
+ for _, hidden := range []string{slash.ID, parent.ID} {
+ if err := model.SetPublishAccess(model.PublishAccess{{ID: hidden, Visible: false}}); err != nil {
+ t.Fatal(err)
+ }
+ response := documentPathAPIRequest(t, "/api/filetree/getIDsByHPath", func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleReader); getIDsByHPath(c) }, map[string]string{"notebook": box, "path": "/A/B"})
+ if !bytes.Contains(response, []byte("\"reason\":\"pathAmbiguous\"")) {
+ t.Fatal(string(response))
+ }
+ forbidden := hidden
+ if hidden == parent.ID {
+ forbidden = child.ID
+ }
+ if bytes.Contains(response, []byte(forbidden)) {
+ t.Fatal("error exposed an unpublished candidate", string(response))
+ }
+ }
+}
diff --git a/kernel/api/contract_notebook_test.go b/kernel/api/contract_notebook_test.go
index 2ecb989ff3..407ba68c11 100644
--- a/kernel/api/contract_notebook_test.go
+++ b/kernel/api/contract_notebook_test.go
@@ -17,10 +17,8 @@ import (
func TestAPIContractNotebookConfConversion(t *testing.T) {
for _, bytes := range [][]byte{nil, {}, {0, 1, 254, 255}} {
value := conf.NewBoxConf()
- value.DocumentAddressingVersion = 2
value.BoxCrypt = &conf.BoxEncryption{Spec: 2, WrappedDEK: bytes, WrapNonce: bytes, Metadata: bytes, CreatedAt: 1234567890}
publicFields := *value
- publicFields.DocumentAddressingVersion = 0 // 内部格式标记仅通过只读能力声明,不作为可写配置返回。
before, err := json.Marshal(&publicFields)
if err != nil {
t.Fatal(err)
@@ -32,7 +30,6 @@ func TestAPIContractNotebookConfConversion(t *testing.T) {
}
value := conf.NewBoxConf()
publicFields := *value
- publicFields.DocumentAddressingVersion = 0
before, _ := json.Marshal(&publicFields)
after, err := json.Marshal(notebookConfContract(value))
if err != nil || string(before) != string(after) {
diff --git a/kernel/api/contract_structured_titles_test.go b/kernel/api/contract_structured_titles_test.go
index 4e41db6008..ac648a9e9b 100644
--- a/kernel/api/contract_structured_titles_test.go
+++ b/kernel/api/contract_structured_titles_test.go
@@ -19,12 +19,12 @@ func TestStructuredTitlesAPIContracts(t *testing.T) {
}
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"`)) {
+ if !bytes.Contains(data, []byte(`"reason":"indexUnavailable"`)) {
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"`)) {
+ if !bytes.Contains(data, []byte(`"reason":"indexUnavailable"`)) {
t.Fatal(string(data))
}
}
diff --git a/kernel/api/document_addressing.go b/kernel/api/document_addressing.go
index 21557e173f..9584896202 100644
--- a/kernel/api/document_addressing.go
+++ b/kernel/api/document_addressing.go
@@ -7,7 +7,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/conf"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/treenode"
)
@@ -17,9 +16,6 @@ func documentAddressingFailure(err error) (apicontract.DocumentAddressingFailure
if errors.As(err, &addressingErr) {
return apicontract.DocumentAddressingFailure{Reason: addressingErr.Reason}, true
}
- if errors.Is(err, documentaddressing.ErrModeConflict) {
- return apicontract.DocumentAddressingFailure{Reason: "modeConflict"}, true
- }
return apicontract.DocumentAddressingFailure{}, false
}
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 3853a7f4c5..f90d9561ca 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -32,7 +32,6 @@ 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"
@@ -460,16 +459,19 @@ func getIDsByHPathContract(c *gin.Context, request apicontract.FileTreeOptionalP
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())
- }
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
return apicontract.Failure[apicontract.LegacyPathIDsResult](-1, err.Error())
}
p := *request.Path
ids, err := model.GetIDsByHPath(p, notebook)
if err != nil {
+ if failure, ok := model.LegacyPathFailure(err); ok {
+ data := apicontract.LegacyPathUnsupported{Reason: failure.Reason,
+ CleanIDs: filterFileTreeBlockIDsByPublishDiscoverability(c, failure.CleanIDs, notebook),
+ UnsupportedIDs: filterFileTreeBlockIDsByPublishDiscoverability(c, failure.UnsupportedIDs, notebook)}
+ return apicontract.GetIDsByHPath.FailureWithData(-1, err.Error(), apicontract.NewLegacyPathIDsFailure(data))
+ }
ret.Code = -1
ret.Msg = err.Error()
return contractFailure[apicontract.LegacyPathIDsResult](ret)
@@ -837,10 +839,7 @@ func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateM
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())
- }
+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {
return apicontract.Failure[apicontract.LegacyPathDocumentResult](-1, err.Error())
}
@@ -868,6 +867,12 @@ func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateM
context["titleEmpty"] = request.TitleEmpty
id, err := model.CreateWithMarkdown(tags, notebook, hPath, markdown, parentID, id, withMath, clippingHref, context)
if err != nil {
+ if failure, ok := model.LegacyPathFailure(err); ok {
+ data := apicontract.LegacyPathUnsupported{Reason: failure.Reason,
+ CleanIDs: filterFileTreeBlockIDsByPublishDiscoverability(c, failure.CleanIDs, notebook),
+ UnsupportedIDs: filterFileTreeBlockIDsByPublishDiscoverability(c, failure.UnsupportedIDs, notebook)}
+ return apicontract.CreateDocWithMd.FailureWithData(-1, err.Error(), apicontract.NewLegacyPathDocumentFailure(data))
+ }
ret.Code = -1
ret.Msg = err.Error()
return contractFailure[apicontract.LegacyPathDocumentResult](ret)
diff --git a/kernel/api/system.go b/kernel/api/system.go
index 945f753d55..8d2c410448 100644
--- a/kernel/api/system.go
+++ b/kernel/api/system.go
@@ -568,10 +568,6 @@ var exportConf = contractHandler(apicontract.SystemExportConf, func(c *gin.Conte
return
}
- data, err = documentaddressing.ExportBackup(util.ConfDir, data)
- if err != nil {
- return apicontract.Failure[apicontract.SystemExportConfData](-1, err.Error())
- }
tmp := filepath.Join(tmpDir, name)
if err = os.WriteFile(tmp, data, 0644); err != nil {
logging.LogErrorf("export conf failed: %s", err)
@@ -723,9 +719,6 @@ var importConf = contractHandler(apicontract.SystemImportConf, func(c *gin.Conte
if err = model.LoadChatGPTAccountBindings(importedConf.AI.Load()); err != nil {
return apicontract.Failure[apicontract.Null](-1, err.Error())
}
- if err = documentaddressing.RestoreBackup(util.ConfDir, data); err != nil {
- return apicontract.Failure[apicontract.Null](-1, err.Error())
- }
// 旧版包缺失的新增配置段保持不变;外观资源列表仍以目标工作空间为准。
if importAppearance {
appearance := importedConf.Appearance.Load()
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 95dc8e2c80..9cf9294330 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -134,12 +134,11 @@ 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. Ordinary builds migrate to mode 2
- // automatically without a user setting or special build flags. literalSlash requires consistent
- // mode records and ready indexes. minimumReaderVersion stays null until the minimum compatible
+ // not permission to open a closed or locked notebook. All notebooks use addressing version 2
+ // without a user setting or special build flags. literalSlash requires ready indexes. minimumReaderVersion stays null until the minimum compatible
// feature release is verified; it neither controls activation nor permits mixing with older clients.
- // Revision covers configuration, confirmed capability and recovery records, not a document path.
- // Malformed capability records fail the request; authentication, locking and network failures must
+ // Revision identifies the fixed capability declaration, not a document path or retired record.
+ // 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")
)
@@ -368,9 +367,9 @@ var (
EnableEncryptedNotebooks = define[NotebookPasswordRequest, Null]("enableEncryptedNotebooks", "/api/notebook/enableEncryptedNotebooks", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
DisableEncryptedNotebooks = define[EmptyRequest, Null]("disableEncryptedNotebooks", "/api/notebook/disableEncryptedNotebooks", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
CreateEncryptedNotebook = define[CreateEncryptedNotebookRequest, CreateNotebookData]("createEncryptedNotebook", "/api/notebook/createEncryptedNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
- // 在密钥恢复和解锁转换前拒绝不支持的笔记本寻址模式,保留原密文和恢复材料。
+ // 密钥恢复和解锁保持既有认证及源格式检查,保留原密文和恢复材料。
UnlockNotebook = define[UnlockNotebookRequest, Null]("unlockNotebook", "/api/notebook/unlockNotebook", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")
- // 解锁及挂载均检查笔记本寻址能力;不支持的模式不会发布解锁状态或修复源数据。
+ // 解锁及挂载均保留源格式与认证检查;失败时不发布解锁状态或修复源数据。
UnlockAndOpenNotebook = define[UnlockNotebookRequest, Null]("unlockAndOpenNotebook", "/api/notebook/unlockAndOpenNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
LockNotebook = define[NotebookIDRequest, Null]("lockNotebook", "/api/notebook/lockNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 保存本机加密笔记本锁屏策略,成功后广播 system 设置变更通知,供其他客户端重新读取配置。
@@ -378,18 +377,18 @@ var (
LockEncryptedNotebooksOnSystemLock = define[EmptyRequest, Null]("lockEncryptedNotebooksOnSystemLock", "/api/notebook/lockEncryptedNotebooksOnSystemLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 自动锁定分钟数由内核内存值驱动锁定行为,写入后无需广播供其他客户端重读。
SetNotebookCryptoAutoLock = define[NotebookCryptoAutoLockRequest, Null]("setNotebookCryptoAutoLock", "/api/notebook/setNotebookCryptoAutoLock", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{Setting: SettingWrite{Namespace: "notebookCrypto", Mode: SettingSilent}}, "POST")
- // 在改密恢复、密钥切换及迁移记录写入前预检全部现存加密笔记本,不支持的寻址模式返回 -1。
+ // 改密恢复和密钥切换保留现存加密笔记本的认证、信封格式及中断恢复检查。
ChangeMasterPassword = define[ChangeMasterPasswordRequest, Null]("changeMasterPassword", "/api/notebook/changeMasterPassword", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
ExportNotebookCryptoBackup = define[EmptyRequest, NotebookCryptoBackupData]("exportNotebookCryptoBackup", "/api/notebook/exportNotebookCryptoBackup", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
TouchEncryptedNotebooks = define[EmptyRequest, Null]("touchEncryptedNotebooks", "/api/notebook/touchEncryptedNotebooks", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
GetNotebookArchiveCandidates = define[EmptyRequest, NotebookArchiveCandidatesData]("getNotebookArchiveCandidates", "/api/notebook/getNotebookArchiveCandidates", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
// 接收已锁定的加密笔记本 ID,返回归档 ID 和下载路径,不删除源数据,要求管理员权限。
// 下载完成后,必须由用户确认已保存归档,再调用 `/api/notebook/commitNotebookArchive` 并传入 saved: true。
- // 不支持笔记本寻址模式时返回 -1,保留源目录及密钥材料。
+ // 源格式或认证检查失败时返回 -1,保留源目录及密钥材料。
PrepareNotebookArchive = define[PrepareNotebookArchiveRequest, NotebookArchiveData]("prepareNotebookArchive", "/api/notebook/prepareNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 移出已导出的加密笔记本,要求管理员权限并禁止只读模式;saved: true 表示用户确认已保存归档。
// 提交前重新检查源文件,内容变化需重新导出;重复提交同一归档不会重复移出,未选择的笔记本不受影响。
- // 移出前重新检查笔记本寻址能力,不支持的模式返回 -1,保留原归档及源目录。
+ // 移出前保留归档及源目录检查,失败时保留原归档和密钥材料。
CommitNotebookArchive = define[CommitNotebookArchiveRequest, Null]("commitNotebookArchive", "/api/notebook/commitNotebookArchive", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// 接收 multipart 的 file、旧 password 和可选密钥备份 key,要求管理员权限并禁止只读模式。
// 恢复目标必须关闭同步,且没有加密密钥配置或加密数据;密文全部通过认证后才发布,恢复后保持锁定。
@@ -642,35 +641,33 @@ var GetUniqueFilename = define[FilePathRequest, FilePathData]("getUniqueFilename
var ReadDirectory = define[ReadDirectoryRequest, []DirectoryEntry]("readDir", "/api/file/readDir", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}, NonNullable: true}, "POST")
-// RenameFile 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。
+// RenameFile 在创建目标父目录或移动源文件前预检文档源格式与规范路径,失败返回 -1。
// 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。
// 新移入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
-// 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。
var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/renameFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}}, "POST")
-// RemoveFile 对不支持寻址模式的笔记本拒绝部分删除,返回 -1;整本删除保留已确认的本机能力下界。
-// 不能删除本机 conf/document-addressing.json 或其父目录,既有加密笔记本删除限制不变。
+// RemoveFile 保留既有敏感路径和加密边界检查;整本删除不读取已撤销的寻址模式记录。
var RemoveFile = define[RemoveFileRequest, Null]("removeFile", "/api/file/removeFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 500}}, "POST")
-// GlobalCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+// GlobalCopyFiles 在创建目标目录及复制前预检整批规范路径和文档源;预检不兼容时返回 -1,不写入目标。
// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
-// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+// 原有敏感路径、加密笔记本和符号链接限制继续生效。
var GlobalCopyFiles = define[CopyFilesRequest, Null]("globalCopyFiles", "/api/file/globalCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
-// WorkspaceCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。
+// WorkspaceCopyFiles 在创建目标目录及复制前预检整批规范路径和文档源;预检不兼容时返回 -1,不写入目标。
// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;不自动改写原始内容。
// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。
-// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。
+// 原有敏感路径、加密笔记本和符号链接限制继续生效。
var WorkspaceCopyFiles = define[CopyFilesRequest, Null]("workspaceCopyFiles", "/api/file/workspaceCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")
-// CopyFile 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。
+// CopyFile 在写入前检查文档源格式及规范路径,预检失败返回 -1。
// 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。
// 新复制的文档标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有源的读取和恢复不受此写入检查影响。
// 工作空间外的加密资源解密导出仍要求既有授权和操作租约。
var CopyFile = define[CopyFileRequest, Null]("copyFile", "/api/file/copyFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2}}, "POST")
-// PutFile 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。
+// PutFile 在创建目录、写入内容及更新时间前校验文档源格式与规范路径;不兼容时返回 -1。
// 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。
// 新传入的标题含 ASCII / 时必须声明 Spec >= 6,否则返回 -1 和 document title requires spec 6;已有低 Spec 源仍可读取并由合法内容替换。
// 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。
@@ -1101,7 +1098,7 @@ var GetDocPaths = define[GetDocPathsRequest, DocumentPathsResult]("getDocPaths",
// 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。
// candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。
// 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。
-// 索引未就绪返回 indexUnavailable;普通构建默认保留段内 /,内部兼容模式 1 仍遵守原有标题限制。
+// 索引未就绪返回 indexUnavailable;标题段保留字面 /,不按笔记本选择不同的寻址模式。
var ResolveDocPath = define[ResolveDocPathRequest, ResolveDocPathResult]("resolveDocPath", "/api/filetree/resolveDocPath", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")
// CreateDocByParent 在显式父文档 ID 或 null 根位置创建固定 ID 文档,不接收 path/hPath 或名称回退。
@@ -1109,8 +1106,8 @@ var ResolveDocPath = define[ResolveDocPathRequest, ResolveDocPathResult]("resolv
// 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。
// ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。
// 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。
-// 普通构建默认保留标题中的 /,该文档写入 Spec 6;普通文档不因迁移统一升级,内部兼容模式 1 仍拒绝 /。
-// 加密笔记本使用原有认证写入与响应租约;自动模式迁移不改变密文格式或密钥材料。
+// 保留标题中的 /,新写入含斜杠标题使用 Spec 6;普通文档不统一升级规格。
+// 加密笔记本使用原有认证写入与响应租约;寻址规则不改变密文格式或密钥材料。
var CreateDocByParent = define[CreateDocByParentRequest, CreateDocByParentResult]("createDocByParent", "/api/filetree/createDocByParent", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
// GetDocCreateTarget 返回指定用途的有效目标及正文模板,不渲染模板、不猜测上下文或日期。
@@ -1127,7 +1124,12 @@ var PlanDocCreate = define[PlanDocCreateRequest, DocumentCreatePlan]("planDocCre
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")
-// GetIDsByHPath 在兼容模式保留旧名称路径查询;模式 2 整本返回 legacyPathUnsupported,改用 resolveDocPath。
+// GetIDsByHPath queries exact legacy display paths and verifies each candidate's real ancestor chain.
+// Clean candidates have nonempty titles without ASCII / and no empty-title flag at every level.
+// Returns every clean ID, an empty array for no matches, pathAmbiguous for mixed candidates,
+// or legacyPathUnsupported for unsupported candidates only. Error data may include cleanIDs and
+// unsupportedIDs, filtered by existing access restrictions. Missing, pending, inconsistent or failed
+// metadata returns indexUnavailable. Prefer resolveDocPath with independent title segments.
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")
@@ -1145,7 +1147,10 @@ var GetDailyNoteInfo = define[DailyNoteInfoRequest, *DailyNoteInfo]("getDailyNot
// 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。
// 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。
-// 模式 2 对整个笔记本返回 legacyPathUnsupported,即使提供 parentID;改用 createDocByParent。
+// Every parent prefix is checked before writing; slash/empty-title candidates return pathAmbiguous.
+// Multiple clean parents also return pathAmbiguous unless a valid matching parentID selects their
+// real ancestor chain. An ID cannot bypass unsupported candidates. Unready or inconsistent metadata
+// returns indexUnavailable. Prefer createDocByParent with a separate parent identity and title.
var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, LegacyPathDocumentResult]("createDocWithMd", "/api/filetree/createDocWithMd", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")
// 旧模板保持既有渲染及回退;对应的新目标对象生效时返回 structuredTemplateRequired,不读取历史路径。
@@ -1668,8 +1673,7 @@ var SystemEnsureOnboarding = define[EmptyRequest, *SystemOnboarding]("ensureOnbo
// 省略或传入 null 时保持原行为及数字截断规则,认证、管理员权限及加密笔记本关闭流程不变。
var SystemExit = define[SystemExitRequest, SystemExitData]("exit", "/api/system/exit", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 2, 3}, DataOnError: true}, "POST")
-// SystemExportConf 保持单个 JSON 文件的设置压缩包,存在本机寻址能力下界时附加 documentAddressing 记录。
-// 记录仅含版本及笔记本身份的最低模式,不导出标题、正文或密钥;无能力记录的旧设置格式不变。
+// SystemExportConf 保持单个 JSON 文件的设置压缩包,不再附加已撤销的 documentAddressing 下界记录。
var SystemExportConf = define[EmptyRequest, SystemExportConfData]("exportConf", "/api/system/exportConf", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportLog = define[EmptyRequest, SystemZipData]("exportLog", "/api/system/exportLog", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
var SystemExportTLSCABundle = define[EmptyRequest, SystemPathData]("exportTLSCABundle", "/api/system/exportTLSCABundle", AuthenticatedAccess|AdminAccess, NoBody, ResponseOptions{}, "POST")
diff --git a/kernel/apicontract/document_addressing.go b/kernel/apicontract/document_addressing.go
index 87fe680147..de4a29fb64 100644
--- a/kernel/apicontract/document_addressing.go
+++ b/kernel/apicontract/document_addressing.go
@@ -199,7 +199,7 @@ type ResolvedDocumentPathData struct {
}
type DocumentAddressingFailure struct {
- Reason string `json:"reason" api:"enum=invalidTitle|parentUnavailable|planChanged|documentIDConflict|legacyPathUnsupported|indexUnavailable|unsupportedTitleFormat|targetModeUnsupported|modeConflict|writeFailed"`
+ Reason string `json:"reason" api:"enum=invalidTitle|parentUnavailable|planChanged|documentIDConflict|legacyPathUnsupported|pathAmbiguous|indexUnavailable|unsupportedTitleFormat|targetModeUnsupported|modeConflict|writeFailed"`
}
type DocumentPathsResult struct {
diff --git a/kernel/apicontract/document_legacy.go b/kernel/apicontract/document_legacy.go
index fd32bee481..729c95430c 100644
--- a/kernel/apicontract/document_legacy.go
+++ b/kernel/apicontract/document_legacy.go
@@ -10,7 +10,10 @@ type StructuredTemplateRequired struct {
}
type LegacyPathUnsupported struct {
- Reason string `json:"reason" api:"enum=legacyPathUnsupported"`
+ // The historical type name is retained for plugin source compatibility.
+ Reason string `json:"reason" api:"enum=legacyPathUnsupported|pathAmbiguous|indexUnavailable"`
+ CleanIDs []string `json:"cleanIDs,omitempty"`
+ UnsupportedIDs []string `json:"unsupportedIDs,omitempty"`
}
type LegacyPathIDsResult struct {
@@ -18,6 +21,9 @@ type LegacyPathIDsResult struct {
failure *LegacyPathUnsupported
}
+func NewLegacyPathIDsFailure(value LegacyPathUnsupported) LegacyPathIDsResult {
+ return LegacyPathIDsResult{failure: &value}
+}
func NewLegacyPathIDs(value []string) LegacyPathIDsResult { return LegacyPathIDsResult{value: value} }
func UnsupportedLegacyPathIDs() LegacyPathIDsResult {
return LegacyPathIDsResult{failure: &LegacyPathUnsupported{Reason: "legacyPathUnsupported"}}
@@ -34,6 +40,9 @@ type LegacyPathDocumentResult struct {
failure *LegacyPathUnsupported
}
+func NewLegacyPathDocumentFailure(value LegacyPathUnsupported) LegacyPathDocumentResult {
+ return LegacyPathDocumentResult{failure: &value}
+}
func NewLegacyPathDocument(value string) LegacyPathDocumentResult {
return LegacyPathDocumentResult{value: value}
}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 2862fd1b7b..82a96e8ac3 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -23956,6 +23956,7 @@
"planChanged",
"documentIDConflict",
"legacyPathUnsupported",
+ "pathAmbiguous",
"indexUnavailable",
"unsupportedTitleFormat",
"targetModeUnsupported",
@@ -32208,11 +32209,25 @@
"LegacyPathUnsupported": {
"type": "object",
"properties": {
+ "cleanIDs": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
"reason": {
"type": "string",
"enum": [
- "legacyPathUnsupported"
+ "legacyPathUnsupported",
+ "pathAmbiguous",
+ "indexUnavailable"
]
+ },
+ "unsupportedIDs": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
},
"required": [
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.go
index 98d8605a26..c269e13d03 100644
--- a/kernel/cli/cmd/document.go
+++ b/kernel/cli/cmd/document.go
@@ -297,18 +297,19 @@ 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 {
+ var lookupErr error
+ result, err := resolvePathWithLookup(userPath, hpath, func(targetHPath string) (string, bool) {
+ var bt *treenode.BlockTree
+ bt, lookupErr = model.ResolveLegacyDocumentPath(boxID, targetHPath, false)
+ if lookupErr != nil || bt == nil {
return "", false
}
return bt.Path, true
})
+ if lookupErr != nil {
+ return "", lookupErr
+ }
+ return result, err
}
func resolvePathWithLookup(userPath, hpath string, lookup func(string) (string, bool)) (string, error) {
@@ -330,18 +331,19 @@ 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 {
+ var lookupErr error
+ result, err := resolveDocumentMovePathWithLookup(userPath, hpath, sourceTitle, func(targetHPath string) (string, bool) {
+ var bt *treenode.BlockTree
+ bt, lookupErr = model.ResolveLegacyDocumentPath(boxID, targetHPath, true)
+ if lookupErr != nil || bt == nil {
return "", false
}
return bt.Path, true
})
+ if lookupErr != nil {
+ return "", lookupErr
+ }
+ return result, err
}
func resolveDocumentMovePathWithLookup(
diff --git a/kernel/cli/cmd/document_test.go b/kernel/cli/cmd/document_test.go
index e9358da6bf..88bac25c1d 100644
--- a/kernel/cli/cmd/document_test.go
+++ b/kernel/cli/cmd/document_test.go
@@ -2,40 +2,76 @@ package cmd
import (
"errors"
- "os"
"path/filepath"
"testing"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
func TestStructuredTitlesCLI(t *testing.T) {
- previousData, previousConf := util.DataDir, util.ConfDir
+ previousData, previousConf, previousDB, previousModel := util.DataDir, util.ConfDir, util.BlockTreeDBPath, model.Conf
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 {
+ util.DataDir, util.ConfDir, util.BlockTreeDBPath = filepath.Join(root, "data"), filepath.Join(root, "conf"), filepath.Join(root, "tree.db")
+ model.Conf = model.NewAppConf()
+ model.Conf.FileTree.Store(conf.NewFileTree())
+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ treenode.InitBlockTree(true)
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ util.DataDir, util.ConfDir, util.BlockTreeDBPath, model.Conf = previousData, previousConf, previousDB, previousModel
+ if previousDB != "" {
+ treenode.InitBlockTree(false)
+ }
+ })
+ box := &model.Box{ID: "20261023000000-cli0001"}
+ bc := conf.NewBoxConf()
+ bc.Name = "CLI"
+ bc.Closed = false
+ if err := box.SaveConf(bc); err != nil {
t.Fatal(err)
}
- if err := os.WriteFile(name, []byte(`{"name":"Existing"}`), 0644); err != nil {
+ plain := treenode.NewTree(box.ID, "/20261026000000-plain01.sy", "/Plain", "Plain")
+ parent := treenode.NewTree(box.ID, "/20261026000001-parent1.sy", "/A", "A")
+ child := treenode.NewTree(box.ID, "/20261026000001-parent1/20261026000002-child01.sy", "/A/B", "B")
+ slash := treenode.NewTree(box.ID, "/20261026000003-slash01.sy", "/A/B", "A/B")
+ leaf := treenode.NewTree(box.ID, "/20261026000003-slash01/20261026000004-leaf001.sy", "/A/B/C", "C")
+ for _, tree := range []*parse.Tree{plain, parent, child, slash, leaf} {
+ treenode.UpsertBlockTree(tree)
+ }
+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); 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)
- }
+ if got, err := resolvePath(box.ID, "", "/Plain"); err != nil || got != plain.Path {
+ t.Fatal(got, err)
+ }
+ if _, err := resolvePath(box.ID, "", "/A/B"); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal(err)
+ }
+ if _, err := resolvePath(box.ID, "", "/A/B/C"); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {
+ t.Fatal(err)
+ }
+ if _, err := resolveDocumentMovePath(box.ID, "", "/A/B/New", "New"); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal(err)
+ }
+ if _, err := resolvePath(box.ID, "", "/missing"); err == nil {
+ t.Fatal("missing target accepted")
}
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(box.ID, idPath, "/ignored"); err != nil || got != idPath {
+ t.Fatal(got, err)
+ }
+ if got, err := resolvePath(box.ID, "", ""); err != nil || got != "/" {
+ t.Fatal(got, err)
+ }
+ if err := treenode.SetDocumentMetadataState(box.ID, "building"); err != nil {
+ t.Fatal(err)
}
- if got, err := resolvePath(boxID, "", ""); err != nil || got != "/" {
- t.Fatal("default root changed", got, err)
+ if _, err := resolvePath(box.ID, "", "/Plain"); err == nil {
+ t.Fatal("unready index accepted")
}
}
diff --git a/kernel/conf/box.go b/kernel/conf/box.go
index 73990384be..b18d8c40ad 100644
--- a/kernel/conf/box.go
+++ b/kernel/conf/box.go
@@ -17,31 +17,29 @@
package conf
import (
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/util"
)
// BoxConf 维护 .siyuan/conf.json 笔记本配置。
type BoxConf struct {
- 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 时有值
+ 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,本身可落盘。
@@ -55,12 +53,11 @@ type BoxEncryption struct {
func NewBoxConf() *BoxConf {
return &BoxConf{
- 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,
+ 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/backup.go b/kernel/documentaddressing/backup.go
deleted file mode 100644
index 205df8e14b..0000000000
--- a/kernel/documentaddressing/backup.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// 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"
- "path/filepath"
-)
-
-// ExportBackup 将已确认的能力下界附在设置导出副本中,不改变普通设置或本机记录。
-func ExportBackup(confDir string, configuration []byte) ([]byte, error) {
- storeLock.Lock()
- defer storeLock.Unlock()
- store, err := backupStore(confDir)
- if err != nil {
- return nil, err
- }
- if len(store.Notebooks) == 0 {
- return configuration, nil
- }
- fields, err := object(configuration, false)
- if err != nil {
- return nil, err
- }
- fields["documentAddressing"], err = json.Marshal(store)
- if err != nil {
- return nil, err
- }
- return json.MarshalIndent(fields, "", " ")
-}
-
-// RestoreBackup 在采用设置前合并能力下界;旧设置没有该字段时保持本机记录不变。
-// 高版本要求只被记住,不代表当前客户端能够处理对应的笔记本。
-func RestoreBackup(confDir string, configuration []byte) error {
- fields, err := object(configuration, true)
- if err != nil {
- return err
- }
- data, exists := fields["documentaddressing"]
- if !exists {
- return nil
- }
- notebooks, err := parseStore(data)
- if err != nil {
- return err
- }
- storeLock.Lock()
- defer storeLock.Unlock()
- store, err := backupStore(confDir)
- if err != nil {
- return err
- }
- for id, mode := range notebooks {
- store.confirm(id, mode)
- }
- return store.save()
-}
-
-func backupStore(confDir string) (*localStore, error) {
- if !filepath.IsAbs(confDir) {
- return nil, ErrInvalid
- }
- return readStore(&localStore{Version: 1, Notebooks: map[string]int{}, path: filepath.Join(confDir, "document-addressing.json")})
-}
diff --git a/kernel/documentaddressing/backup_test.go b/kernel/documentaddressing/backup_test.go
deleted file mode 100644
index fd24ef19de..0000000000
--- a/kernel/documentaddressing/backup_test.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package documentaddressing
-
-import (
- "bytes"
- "errors"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestBackupRetainsMaximumRequirements(t *testing.T) {
- confDir := t.TempDir()
- name := filepath.Join(confDir, "document-addressing.json")
- old := []byte(`{"documentAddressing":{"version":1,"notebooks":{"20261022120000-noteb01":2}}}`)
- newer := []byte(`{"documentAddressing":{"version":1,"notebooks":{"20261022120000-noteb01":3,"20261022120000-noteb02":2}}}`)
- for _, data := range [][]byte{old, newer, old, []byte(`{"editor":{}}`)} {
- if err := RestoreBackup(confDir, data); err != nil {
- t.Fatal(err)
- }
- }
- source, err := os.ReadFile(name)
- if err != nil {
- t.Fatal(err)
- }
- record, err := parseStore(source)
- if err != nil || record["20261022120000-noteb01"] != 3 || record["20261022120000-noteb02"] != 2 {
- t.Fatalf("capability requirements were lost: %s, %v", source, err)
- }
- backup, err := ExportBackup(confDir, []byte(`{"editor":{"fontSize":16}}`))
- if err != nil {
- t.Fatal(err)
- }
- restoredDir := t.TempDir()
- if err = RestoreBackup(restoredDir, backup); err != nil {
- t.Fatal(err)
- }
- restored, err := os.ReadFile(filepath.Join(restoredDir, "document-addressing.json"))
- if err != nil || !bytes.Equal(restored, source) {
- t.Fatalf("backup did not preserve requirements: %s, %v", restored, err)
- }
- for _, invalid := range []string{
- `{"documentAddressing":null}`,
- `{"documentAddressing":{"version":2,"notebooks":{}}}`,
- `{"documentAddressing":{"version":1,"notebooks":{"invalid":2}}}`,
- `{"documentAddressing":{"version":1,"notebooks":{}},"DocumentAddressing":{}}`,
- } {
- if err = RestoreBackup(confDir, []byte(invalid)); !errors.Is(err, ErrInvalid) {
- t.Fatalf("invalid backup accepted: %s, %v", invalid, err)
- }
- after, _ := os.ReadFile(name)
- if !bytes.Equal(after, source) {
- t.Fatal("invalid backup changed the local record")
- }
- }
- if err = os.WriteFile(name, []byte(`{"version":99}`), 0600); err != nil {
- t.Fatal(err)
- }
- if _, err = ExportBackup(confDir, []byte(`{}`)); !errors.Is(err, ErrInvalid) {
- t.Fatalf("invalid local record exported: %v", err)
- }
- if err = RestoreBackup(confDir, old); !errors.Is(err, ErrInvalid) {
- t.Fatalf("invalid local record overwritten: %v", err)
- }
- unchanged, _ := os.ReadFile(name)
- if string(unchanged) != `{"version":99}` {
- t.Fatal("invalid local record changed")
- }
-}
-
-func TestBackupDoesNotMigrateLegacySettings(t *testing.T) {
- confDir := t.TempDir()
- data := []byte(`{"editor":{"fontSize":16}}`)
- backup, err := ExportBackup(confDir, data)
- if err != nil || !bytes.Equal(backup, data) {
- t.Fatalf("legacy export changed: %s, %v", backup, err)
- }
- if err = RestoreBackup(confDir, backup); err != nil {
- t.Fatal(err)
- }
- entries, _ := os.ReadDir(confDir)
- if len(entries) != 0 {
- t.Fatal("legacy settings created a capability record")
- }
-}
diff --git a/kernel/documentaddressing/capabilities.go b/kernel/documentaddressing/capabilities.go
index 5b4c5feb52..98c5b6a896 100644
--- a/kernel/documentaddressing/capabilities.go
+++ b/kernel/documentaddressing/capabilities.go
@@ -1,102 +1,19 @@
-// SiYuan - From thought to insight, with agents
-// Copyright (c) 2020-present, b3log.org
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
package documentaddressing
-import (
- "crypto/sha256"
- "encoding/hex"
- "encoding/json"
- "errors"
- "fmt"
- "os"
- "path/filepath"
-
- "github.com/88250/lute/ast"
-)
+import "fmt"
-// ModeSnapshot 描述经过校验的能力要求,不代表当前读取器可以处理该模式。
type ModeSnapshot struct {
- Mode int
- Revision string
- State string
- Phase string
- RecordsConsistent bool
+ Mode int
+ Revision string
+ State string
}
-// InspectBox 不读取文档或派生索引。合法的高模式与 CheckBox 一样记入本机下界,
-// 配置损坏则返回错误,不向调用方伪装成旧服务端或兼容模式。
+// InspectBox reports the fixed capability without source reads or migration writes.
+// The API combines this with the independently tracked metadata index state.
func InspectBox(dataDir, confDir, boxID string) (*ModeSnapshot, error) {
- 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, nil, err
- }
- read := directoryReader(filepath.Join(dataDir, boxID))
- sources := map[string]string{}
- consistent := true
- mode, 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, nil, fmt.Errorf("notebook [%s]: %w", boxID, err)
- }
- mode = store.confirm(boxID, mode)
- if err = store.save(); err != nil {
- 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{}{2, boxID, snapshot.Mode, sources, record})
+ mode, err := BoxMode(dataDir, confDir, boxID)
if err != nil {
- return nil, nil, err
+ return nil, err
}
- digest := sha256.Sum256(data)
- snapshot.Revision = "2:" + hex.EncodeToString(digest[:])
- return snapshot, store, nil
+ return &ModeSnapshot{Mode: mode, State: "structured", Revision: fmt.Sprintf("3:%s:2", boxID)}, nil
}
diff --git a/kernel/documentaddressing/capabilities_test.go b/kernel/documentaddressing/capabilities_test.go
deleted file mode 100644
index d27206d03d..0000000000
--- a/kernel/documentaddressing/capabilities_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-package documentaddressing
-
-import (
- "errors"
- "os"
- "path/filepath"
- "testing"
-)
-
-func TestInspectBoxCapabilities(t *testing.T) {
- readerModeForTest(t, 1)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- first, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || first.Mode != 1 || first.Revision == "" {
- t.Fatal("legacy capability read failed", first, err)
- }
- if _, err = os.Stat(confDir); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("legacy capability read created a floor record", err)
- }
- boxDir := filepath.Join(dataDir, testBox)
- writeTestFile(t, boxDir, ConfigPath, `{"name":"Private configuration"}`)
- second, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || second.Mode != 1 || second.Revision == first.Revision {
- t.Fatal("configuration changes did not invalidate the revision", err)
- }
- writeTestFile(t, boxDir, FloorPath, `{"version":1,"notebook":"`+testBox+`","minimumMode":2}`)
- third, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || third.Mode != 2 || third.Revision == second.Revision {
- t.Fatal("higher capability was hidden", third, err)
- }
- if err = os.Remove(filepath.Join(boxDir, FloorPath)); err != nil {
- t.Fatal(err)
- }
- fourth, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || fourth.Mode != 2 {
- t.Fatal("capability read forgot the confirmed floor", fourth, err)
- }
- if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatal("capability probe enabled an unsupported writer", err)
- }
- writeTestFile(t, boxDir, FloorPath, `{"version":9}`)
- if _, err = InspectBox(dataDir, confDir, testBox); !errors.Is(err, ErrInvalid) {
- t.Fatal("unknown capability record was hidden", err)
- }
-}
diff --git a/kernel/documentaddressing/cleanup.go b/kernel/documentaddressing/cleanup.go
new file mode 100644
index 0000000000..9492dc6c82
--- /dev/null
+++ b/kernel/documentaddressing/cleanup.go
@@ -0,0 +1,34 @@
+package documentaddressing
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+)
+
+// CleanupRetiredRecords only removes local, identity-only addressing records.
+// Notebook records, authenticated source data and encryption recovery material
+// are outside this directory. The startup caller skips this in read-only mode.
+func CleanupRetiredRecords(confDir string) error {
+ if !filepath.IsAbs(confDir) {
+ return ErrInvalid
+ }
+ if _, err := os.ReadDir(confDir); err != nil {
+ if os.IsNotExist(err) {
+ if _, statErr := os.Lstat(confDir); os.IsNotExist(statErr) {
+ return nil
+ }
+ }
+ return err
+ }
+ var failures []error
+ for _, name := range []string{"document-addressing.json", "document-addressing-recovery"} {
+ target := filepath.Join(confDir, name)
+ relative, err := filepath.Rel(confDir, target)
+ if err != nil || relative != name {
+ return ErrInvalid
+ }
+ failures = append(failures, os.RemoveAll(target))
+ }
+ return errors.Join(failures...)
+}
diff --git a/kernel/documentaddressing/cleanup_test.go b/kernel/documentaddressing/cleanup_test.go
new file mode 100644
index 0000000000..9b4da7dab1
--- /dev/null
+++ b/kernel/documentaddressing/cleanup_test.go
@@ -0,0 +1,50 @@
+package documentaddressing
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestCleanupRetiredRecordsIsLocalAndIdempotent(t *testing.T) {
+ root := t.TempDir()
+ conf := filepath.Join(root, "conf")
+ if err := CleanupRetiredRecords(conf); err != nil {
+ t.Fatal(err)
+ }
+ notebook := filepath.Join(root, "data", "notebook", FloorPath)
+ for _, name := range []string{filepath.Join(conf, "document-addressing.json"), filepath.Join(conf, "document-addressing-recovery", "notebook.json"), notebook} {
+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(name, []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 2; i++ {
+ if err := CleanupRetiredRecords(conf); err != nil {
+ t.Fatal(err)
+ }
+ entries, err := os.ReadDir(conf)
+ if err != nil || len(entries) != 0 {
+ t.Fatal("local records survived cleanup", entries, err)
+ }
+ data, err := os.ReadFile(notebook)
+ if err != nil || string(data) != "original" {
+ t.Fatal("cleanup changed notebook data", err)
+ }
+ }
+}
+
+func TestCleanupRetiredRecordsReportsErrors(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "conf")
+ if err := os.WriteFile(file, []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := CleanupRetiredRecords(file); err == nil {
+ t.Fatal("invalid configuration directory accepted")
+ }
+ if data, err := os.ReadFile(file); err != nil || string(data) != "original" {
+ t.Fatal("failed cleanup changed data", err)
+ }
+}
diff --git a/kernel/documentaddressing/cleanup_windows_test.go b/kernel/documentaddressing/cleanup_windows_test.go
new file mode 100644
index 0000000000..434098460d
--- /dev/null
+++ b/kernel/documentaddressing/cleanup_windows_test.go
@@ -0,0 +1,44 @@
+package documentaddressing
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+func TestCleanupRetiredRecordsLockedFile(t *testing.T) {
+ conf := t.TempDir()
+ name := filepath.Join(conf, "document-addressing.json")
+ if err := os.WriteFile(name, []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ ptr, err := windows.UTF16PtrFromString(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ handle, err := windows.CreateFile(ptr, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ locked := true
+ defer func() {
+ if locked {
+ windows.CloseHandle(handle)
+ }
+ }()
+ if err := CleanupRetiredRecords(conf); err == nil {
+ t.Fatal("locked record deletion did not report failure")
+ }
+ if data, err := os.ReadFile(name); err != nil || string(data) != "original" {
+ t.Fatal("failed cleanup changed the record", err)
+ }
+ if err := windows.CloseHandle(handle); err != nil {
+ t.Fatal(err)
+ }
+ locked = false
+ if err := CleanupRetiredRecords(conf); err != nil {
+ t.Fatal("cleanup did not recover on next attempt", err)
+ }
+}
diff --git a/kernel/documentaddressing/migration.go b/kernel/documentaddressing/migration.go
deleted file mode 100644
index 343716e07a..0000000000
--- a/kernel/documentaddressing/migration.go
+++ /dev/null
@@ -1,122 +0,0 @@
-// 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 defaultMode = 2
-
-var ErrRecovering = errors.New("document addressing recovery is pending")
-
-func MinimumReaderVersion() *string {
- if minimumReaderVersion == "" {
- return nil
- }
- version := minimumReaderVersion
- return &version
-}
-
-// DefaultMode 是当前发行版自动采用的内部模式,不暴露为用户可写配置。
-func DefaultMode() int {
- return defaultMode
-}
-
-// 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.go
deleted file mode 100644
index 2a66287062..0000000000
--- a/kernel/documentaddressing/migration_test.go
+++ /dev/null
@@ -1,308 +0,0 @@
-package documentaddressing
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "errors"
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "strconv"
- "testing"
- "time"
-
- "github.com/siyuan-note/filelock"
-)
-
-func readerModeForTest(t *testing.T, mode int) {
- t.Helper()
- previous := defaultMode
- defaultMode = mode
- t.Cleanup(func() { defaultMode = previous })
-}
-
-func TestStructuredTitlesDefaultWithoutReaderRelease(t *testing.T) {
- if DefaultMode() != 2 {
- t.Fatal("ordinary builds must enable structured titles")
- }
- previous := minimumReaderVersion
- minimumReaderVersion = ""
- t.Cleanup(func() { minimumReaderVersion = previous })
- if DefaultMode() != 2 || MinimumReaderVersion() != nil {
- t.Fatal("unverified reader release disabled titles or reported a fabricated version")
- }
-}
-
-func TestStructuredTitlesAutomaticMigration(t *testing.T) {
- 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) {
- readerModeForTest(t, 2)
- 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)
- }
- // 下界尚未写入时,保护读取器也必须识别迁移决定并拒绝访问。
- defaultMode = 1
- if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatal(err)
- }
- defaultMode = 2
- 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) {
- 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)
- }
-}
-
-func TestStructuredTitlesMissingConfigurationRetainsFloor(t *testing.T) {
- readerModeForTest(t, 2)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- boxDir := filepath.Join(dataDir, testBox)
- writeTestFile(t, boxDir, ConfigPath, `{}`)
- if err := CheckBox(dataDir, confDir, testBox); err != nil {
- t.Fatal(err)
- }
- if err := os.Remove(filepath.Join(boxDir, ConfigPath)); err != nil {
- t.Fatal(err)
- }
- floor, _ := os.ReadFile(filepath.Join(boxDir, FloorPath))
- if mode, err := BoxMode(dataDir, confDir, testBox); err != nil || mode != 2 {
- t.Fatal("missing configuration blocked recovery or lowered the floor", mode, err)
- }
- if _, err := os.Stat(filepath.Join(boxDir, ConfigPath)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("mode inspection created a replacement configuration", err)
- }
- if after, err := os.ReadFile(filepath.Join(boxDir, FloorPath)); err != nil || !bytes.Equal(after, floor) {
- t.Fatal("mode inspection changed the source floor", err)
- }
- snapshot, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || snapshot.State != "recovering" || snapshot.RecordsConsistent {
- t.Fatal("missing configuration was reported as ready", snapshot, err)
- }
- defaultMode = 1
- if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatal("missing configuration bypassed the old reader guard", err)
- }
- defaultMode = 2
- if err = os.RemoveAll(boxDir); err != nil {
- t.Fatal(err)
- }
- if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("deleted notebook was accepted for recovery", err)
- }
- if _, err = os.Stat(boxDir); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("mode inspection recreated a deleted notebook", err)
- }
-}
-
-func TestStructuredTitlesMigrationProcessRestart(t *testing.T) {
- const rootVariable = "SIYUAN_TEST_TITLE_MIGRATION_ROOT"
- const phaseVariable = "SIYUAN_TEST_TITLE_MIGRATION_PHASE"
- const interruptedExit = 73
- if root := os.Getenv(rootVariable); root != "" {
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- phase := os.Getenv(phaseVariable)
- switch phase {
- case "guard":
- defaultMode = 1
- if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatal("protective reader admitted an interrupted or upgraded notebook", err)
- }
- case "recover":
- if err := CheckBox(dataDir, confDir, testBox); err != nil {
- t.Fatal(err)
- }
- snapshot, err := InspectBox(dataDir, confDir, testBox)
- if err != nil || snapshot.Mode != 2 || !snapshot.RecordsConsistent || snapshot.State != "structured" {
- t.Fatal("fresh process did not finish migration", snapshot, err)
- }
- default:
- stage, err := strconv.Atoi(phase)
- if err != nil || stage < 0 || stage > 4 {
- t.Fatal("invalid interruption stage", phase)
- }
- store, err := loadStore(dataDir, confDir)
- if err != nil {
- t.Fatal(err)
- }
- writes := 0
- err = migrateBoxRecords(dataDir, testBox, store, func(name string, data []byte) error {
- if err := filelock.WriteFile(name, data); err != nil {
- return err
- }
- writes++
- if writes == stage {
- // 已完成的持久写入保留;直接结束进程,禁止清理函数代为完成迁移。
- os.Exit(interruptedExit)
- }
- return nil
- })
- if err != nil {
- t.Fatal(err)
- }
- }
- return
- }
-
- for stage := 0; stage <= 4; stage++ {
- t.Run(strconv.Itoa(stage), func(t *testing.T) {
- root := t.TempDir()
- boxDir := filepath.Join(root, "data", testBox)
- original := `{"name":"legacy","closed":false,"custom":{"keep":[1,2,3]}}`
- writeTestFile(t, boxDir, ConfigPath, original)
- const document = "20261023000001-abcdefg.sy"
- const source = `{"ID":"20261023000001-abcdefg","Spec":"2","Type":"NodeDocument","Properties":{"id":"20261023000001-abcdefg","title":"Legacy %2F"}}`
- writeTestFile(t, boxDir, document, source)
- writeTestFile(t, boxDir, "assets/retained.bin", "existing attachment")
- run := func(phase string, exitCode int) {
- t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- defer cancel()
- command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStructuredTitlesMigrationProcessRestart$", "-test.v")
- command.Env = append(os.Environ(), rootVariable+"="+root, phaseVariable+"="+phase)
- output, err := command.CombinedOutput()
- if exitCode == 0 && err == nil {
- return
- }
- var exited *exec.ExitError
- if errors.As(err, &exited) && exited.ExitCode() == exitCode {
- return
- }
- t.Fatalf("phase %s: expected exit %d, got %v\n%s", phase, exitCode, err, output)
- }
- expectedExit := 0
- if stage > 0 {
- expectedExit = interruptedExit
- }
- run(strconv.Itoa(stage), expectedExit)
- run("guard", 0)
- run("recover", 0)
- config, err := os.ReadFile(filepath.Join(boxDir, ConfigPath))
- if err != nil {
- t.Fatal(err)
- }
- var fields map[string]json.RawMessage
- if err = json.Unmarshal(config, &fields); err != nil || string(fields["documentAddressingVersion"]) != "2" {
- t.Fatal("configuration projection was not recovered", err)
- }
- delete(fields, "documentAddressingVersion")
- var wanted map[string]json.RawMessage
- _ = json.Unmarshal([]byte(original), &wanted)
- for key, value := range wanted {
- var compact bytes.Buffer
- if err = json.Compact(&compact, fields[key]); err != nil || !bytes.Equal(value, compact.Bytes()) {
- t.Fatalf("migration changed configuration field %s", key)
- }
- }
- run("recover", 0)
- for name, want := range map[string]string{ConfigPath: string(config), document: source, "assets/retained.bin": "existing attachment"} {
- data, err := os.ReadFile(filepath.Join(boxDir, name))
- if err != nil || string(data) != want {
- t.Fatalf("restart changed %s: %v", name, err)
- }
- }
- journal := filepath.Join(root, "conf", "document-addressing-recovery", testBox+".json")
- if _, err = os.Stat(journal); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("recovered process retained a migration journal", err)
- }
- })
- }
-}
diff --git a/kernel/documentaddressing/mode.go b/kernel/documentaddressing/mode.go
index 8745f956e9..15df92a9a0 100644
--- a/kernel/documentaddressing/mode.go
+++ b/kernel/documentaddressing/mode.go
@@ -1,429 +1,67 @@
-// SiYuan - From thought to insight, with agents
-// Copyright (c) 2020-present, b3log.org
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-// Package documentaddressing 校验笔记本寻址模式,阻止不支持的客户端修复或改写源数据。
+// Package documentaddressing validates document title sources and legacy path compatibility.
package documentaddressing
import (
- "bytes"
- "encoding/json"
"errors"
- "fmt"
- "io"
- "os"
"path/filepath"
- "sort"
"strings"
- "sync"
"github.com/88250/lute/ast"
- "github.com/siyuan-note/filelock"
)
-const (
- ConfigPath = ".siyuan/conf.json"
- FloorPath = ".siyuan/document-addressing.json"
-)
+const ConfigPath = ".siyuan/conf.json"
+
+// FloorPath is a retired notebook record. Existing files are left untouched.
+const FloorPath = ".siyuan/document-addressing.json"
var (
- ErrInvalid = errors.New("invalid document addressing metadata")
- ErrUnsupported = errors.New("unsupported document addressing mode")
- storeLock sync.Mutex
+ ErrInvalid = errors.New("invalid document addressing metadata")
)
-// Reader 读取相对路径;不存在的文件必须返回 os.ErrNotExist,不能以空内容代替。
-type Reader func(string) ([]byte, error)
-
-// ReadMode 只检查源记录,不修改源文件,也不将导入档案的身份记入本机能力下界。
-func ReadMode(boxID string, read Reader) (int, error) {
- mode := 1
- data, err := read(ConfigPath)
- if err != nil && !errors.Is(err, os.ErrNotExist) {
- return 0, err
- }
- if err == nil {
- fields, parseErr := object(data, true)
- if parseErr != nil {
- return 0, parseErr
- }
- if value, exists := fields["documentaddressingversion"]; exists {
- if mode, err = positiveInt(value); err != nil {
- return 0, err
- }
- }
- }
- data, err = read(FloorPath)
- if errors.Is(err, os.ErrNotExist) {
- return mode, nil
- }
- if err != nil {
- return 0, err
- }
- fields, err := versionedObject(data)
- if err != nil || len(fields) != 3 {
- return 0, ErrInvalid
- }
- var notebook string
- if json.Unmarshal(fields["notebook"], &notebook) != nil || !ast.IsNodeIDPattern(notebook) || notebook != boxID {
+// BoxMode reports the fixed addressing version without reading or changing any files.
+// Notebook existence and source authentication belong to the caller's access boundary.
+func BoxMode(dataDir, confDir, boxID string) (int, error) {
+ if !ast.IsNodeIDPattern(boxID) {
return 0, ErrInvalid
}
- floor, err := positiveInt(fields["minimumMode"])
- if err != nil {
- return 0, err
- }
- return max(mode, floor), nil
-}
-
-// CheckSource 检查尚未导入工作空间的笔记本,不确认或改变其本机模式。
-func CheckSource(boxID, directory string) error {
- mode, err := ReadMode(boxID, directoryReader(directory))
- if err != nil {
- return err
- }
- return checkSupported(boxID, mode)
-}
-
-// CheckImport 采用已经确认的源身份下界,但不因检查未采用的档案而登记新的身份。
-func CheckImport(dataDir, confDir, boxID, directory string) error {
- storeLock.Lock()
- defer storeLock.Unlock()
- store, err := loadStore(dataDir, confDir)
- if err != nil {
- return err
- }
- mode, err := ReadMode(boxID, directoryReader(directory))
- 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]))
+ return DefaultMode(), nil
}
-// CheckBox 在任何源数据修复、索引和读写前确认能力下界。合法的较高要求只升不降。
func CheckBox(dataDir, confDir, boxID string) error {
_, err := BoxMode(dataDir, confDir, boxID)
return err
}
-// BoxMode 在确认能力下界和完成自动迁移后返回可用模式,避免调用者重复读取元数据。
-func BoxMode(dataDir, confDir, boxID string) (int, error) {
- storeLock.Lock()
- defer storeLock.Unlock()
- snapshot, store, err := inspectBox(dataDir, confDir, boxID)
- if err != nil {
- return 0, err
- }
- if err = checkSupported(boxID, snapshot.Mode); err != nil {
- return 0, err
- }
- if DefaultMode() == 2 && (snapshot.Mode == 1 || snapshot.State == "recovering") {
- // 配置缺失时不自动创建配置,保留已确认模式供加密备份认证及配置恢复使用。
- // 不能降低下界,也不能借本机记录重新创建已删除的笔记本。
- _, statErr := os.Stat(filepath.Join(dataDir, boxID, ConfigPath))
- if errors.Is(statErr, os.ErrNotExist) {
- if snapshot.Mode == 1 {
- return 1, nil
- }
- info, dirErr := os.Lstat(filepath.Join(dataDir, boxID))
- if dirErr != nil {
- return 0, dirErr
- }
- if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
- return 0, ErrInvalid
+// CheckPaths retains canonical replacement-path validation independently of retired modes.
+// Source Spec and authenticated ciphertext checks are performed by the caller before applying a batch.
+func CheckPaths(upserts, removes []string) error {
+ for _, group := range [][]string{upserts, removes} {
+ for _, name := range group {
+ if strings.Contains(name, "\\") {
+ return ErrInvalid
}
- return snapshot.Mode, nil
- }
- if statErr != nil {
- return 0, statErr
- }
- if err = migrateBoxRecords(dataDir, boxID, store, filelock.WriteFile); err != nil {
- return 0, err
- }
- return 2, nil
- }
- if snapshot.State == "conflict" {
- return 0, ErrModeConflict
- }
- if snapshot.State == "recovering" {
- return 0, ErrRecovering
- }
- return snapshot.Mode, nil
-}
-
-// CheckBatch 校验一次同步或恢复的完整替换计划;调用者必须在任何源文件变动前调用。
-// read 只读取计划中的新文件,不能回读当前工作空间。拒绝批次时仍保留已确认的能力下界。
-func CheckBatch(dataDir, confDir string, upserts, removes []string, read Reader) error {
- storeLock.Lock()
- defer storeLock.Unlock()
- store, err := loadStore(dataDir, confDir)
- if err != nil {
- return err
- }
- upsertSet, removeSet, boxes := map[string]bool{}, map[string]bool{}, map[string]bool{}
- for _, group := range []struct {
- paths []string
- set map[string]bool
- }{{upserts, upsertSet}, {removes, removeSet}} {
- for _, name := range group.paths {
name = strings.TrimPrefix(filepath.ToSlash(name), "/")
if name == "" || name == "." || name == ".." || strings.HasPrefix(name, "../") ||
filepath.IsAbs(name) || filepath.VolumeName(name) != "" ||
filepath.ToSlash(filepath.Clean(name)) != name || strings.Contains(name, "\\") {
return ErrInvalid
}
- group.set[name] = true
boxID, relative, found := strings.Cut(name, "/")
if found && ast.IsNodeIDPattern(strings.ToLower(boxID)) {
- // 大小写别名在部分文件系统上会覆盖规范路径,不能绕过元数据预检。
metadata := strings.ToLower(relative)
if boxID != strings.ToLower(boxID) ||
((metadata == ConfigPath || metadata == FloorPath) && relative != metadata) {
return ErrInvalid
}
- boxes[boxID] = true
- }
- }
- }
- ids := make([]string, 0, len(boxes))
- for id := range boxes {
- ids = append(ids, id)
- }
- sort.Strings(ids)
- var failures []error
- 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)
- }
- deleted, deleteErr := deletesNotebook(dataDir, boxID, upsertSet, removeSet)
- if deleteErr != nil {
- failures = append(failures, deleteErr)
- continue
- }
- if deleted {
- // 整本删除不要求解释源格式,也不能为了恢复下界而重建已删除的目录。
- continue
- }
- incoming, incomingErr := ReadMode(boxID, func(name string) ([]byte, error) {
- rel := boxID + "/" + name
- if upsertSet[rel] {
- return read(rel)
- }
- if removeSet[rel] {
- return nil, os.ErrNotExist
}
- return current(name)
- })
- if incomingErr == nil {
- mode = max(mode, store.confirm(boxID, incoming))
}
- if currentErr != nil || incomingErr != nil {
- failures = append(failures, fmt.Errorf("notebook [%s]: %w", boxID, errors.Join(currentErr, incomingErr)))
- } else if err = checkSupported(boxID, mode); err != nil {
- failures = append(failures, err)
- }
- }
- if err = store.save(); err != nil {
- failures = append(failures, err)
- }
- return errors.Join(failures...)
-}
-
-func checkSupported(boxID string, mode int) error {
- if mode > DefaultMode() {
- return fmt.Errorf("%w [%s, mode=%d]", ErrUnsupported, boxID, mode)
}
return nil
}
-func directoryReader(directory string) Reader {
- return func(name string) ([]byte, error) { return filelock.ReadFile(filepath.Join(directory, name)) }
-}
+// DefaultMode is the fixed diagnostic addressing version, not a notebook setting.
+func DefaultMode() int { return 2 }
-func deletesNotebook(dataDir, boxID string, upserts, removes map[string]bool) (bool, error) {
- prefix := boxID + "/"
- for name := range upserts {
- if strings.HasPrefix(name, prefix) {
- return false, nil
- }
- }
- deleted := true
- err := filepath.WalkDir(filepath.Join(dataDir, boxID), func(name string, entry os.DirEntry, err error) error {
- if errors.Is(err, os.ErrNotExist) {
- return nil
- }
- if err != nil {
- return err
- }
- if !entry.IsDir() {
- rel, relErr := filepath.Rel(dataDir, name)
- if relErr != nil {
- return relErr
- }
- if !removes[filepath.ToSlash(rel)] {
- deleted = false
- return filepath.SkipAll
- }
- }
- return nil
- })
- return deleted, err
-}
-
-// object 拒绝重复字段及尾随数据,避免重复的模式字段被后面的低版本遮盖。
-func object(data []byte, foldCase bool) (map[string]json.RawMessage, error) {
- decoder := json.NewDecoder(bytes.NewReader(data))
- token, err := decoder.Token()
- if err != nil || token != json.Delim('{') {
- return nil, ErrInvalid
- }
- ret := map[string]json.RawMessage{}
- for decoder.More() {
- token, err = decoder.Token()
- if err != nil {
- return nil, ErrInvalid
- }
- name, ok := token.(string)
- if !ok {
- return nil, ErrInvalid
- }
- if foldCase {
- name = strings.ToLower(name)
- }
- if _, exists := ret[name]; exists {
- return nil, ErrInvalid
- }
- var value json.RawMessage
- if decoder.Decode(&value) != nil {
- return nil, ErrInvalid
- }
- ret[name] = value
- }
- if token, err = decoder.Token(); err != nil || token != json.Delim('}') {
- return nil, ErrInvalid
- }
- if _, err = decoder.Token(); err != io.EOF {
- return nil, ErrInvalid
- }
- return ret, nil
-}
-
-func positiveInt(value []byte) (int, error) {
- var ret int
- if json.Unmarshal(value, &ret) != nil || ret < 1 {
- return 0, ErrInvalid
- }
- return ret, nil
-}
-
-func versionedObject(data []byte) (map[string]json.RawMessage, error) {
- fields, err := object(data, false)
- if err != nil {
- return nil, err
- }
- version, err := positiveInt(fields["version"])
- if err != nil || version != 1 {
- return nil, ErrInvalid
- }
- return fields, nil
-}
-
-type localStore struct {
- Version int `json:"version"`
- Notebooks map[string]int `json:"notebooks"`
- path string
- dirty bool
-}
-
-func loadStore(dataDir, confDir string) (*localStore, error) {
- if !filepath.IsAbs(dataDir) {
- return nil, ErrInvalid
- }
- if confDir == "" {
- confDir = filepath.Join(filepath.Dir(filepath.Clean(dataDir)), "conf")
- }
- if !filepath.IsAbs(confDir) {
- return nil, ErrInvalid
- }
- ret := &localStore{Version: 1, Notebooks: map[string]int{}, path: filepath.Join(confDir, "document-addressing.json")}
- return readStore(ret)
-}
-
-func readStore(ret *localStore) (*localStore, error) {
- data, err := filelock.ReadFile(ret.path)
- if errors.Is(err, os.ErrNotExist) {
- return ret, nil
- }
- if err != nil {
- return nil, err
- }
- notebooks, err := parseStore(data)
- if err != nil {
- return nil, err
- }
- ret.Notebooks = notebooks
- return ret, nil
-}
-
-func parseStore(data []byte) (map[string]int, error) {
- fields, err := versionedObject(data)
- if err != nil || len(fields) != 2 {
- return nil, ErrInvalid
- }
- notebooks, err := object(fields["notebooks"], false)
- if err != nil {
- return nil, err
- }
- ret := map[string]int{}
- for id, value := range notebooks {
- if !ast.IsNodeIDPattern(id) {
- return nil, ErrInvalid
- }
- mode, err := positiveInt(value)
- if err != nil {
- return nil, err
- }
- ret[id] = mode
- }
- return ret, nil
-}
-
-func (store *localStore) confirm(boxID string, mode int) int {
- if mode > 1 && mode > store.Notebooks[boxID] {
- store.Notebooks[boxID], store.dirty = mode, true
- }
- return max(mode, store.Notebooks[boxID])
-}
-
-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
- }
- data, err := json.MarshalIndent(store, "", " ")
- if err != nil {
- return err
- }
- if err = os.MkdirAll(filepath.Dir(store.path), 0755); err != nil {
- return err
- }
- return write(store.path, data)
-}
+// MinimumReaderVersion is unset until an actual released reader has been verified.
+// A nil value does not permit mixing structured-title notebooks with older clients.
+func MinimumReaderVersion() *string { return nil }
diff --git a/kernel/documentaddressing/mode_test.go b/kernel/documentaddressing/mode_test.go
index f0561f2d2d..68145b0f3d 100644
--- a/kernel/documentaddressing/mode_test.go
+++ b/kernel/documentaddressing/mode_test.go
@@ -1,292 +1,58 @@
package documentaddressing
import (
- "bytes"
- "encoding/json"
- "errors"
"os"
"path/filepath"
"testing"
)
-const testBox = "20260101120000-abcdefg"
-
-func writeTestFile(t *testing.T, directory, name, data string) {
- t.Helper()
- name = filepath.Join(directory, name)
- if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(name, []byte(data), 0644); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestReadMode(t *testing.T) {
- for _, tc := range []struct {
- name, config, floor string
- mode int
- invalid bool
- }{
- {name: "missing", mode: 1},
- {name: "legacy", config: `{"name":"legacy"}`, mode: 1},
- {name: "explicit legacy", config: `{"documentAddressingVersion":1}`, mode: 1},
- {name: "structured", config: `{"documentAddressingVersion":2}`, mode: 2},
- {name: "future", config: `{"documentAddressingVersion":99}`, mode: 99},
- {name: "case folding", config: `{"DocumentAddressingVersion":2}`, mode: 2},
- {name: "escaped field", config: `{"documentAddressing\u0056ersion":2}`, mode: 2},
- {name: "nested field is unrelated", config: `{"boxCrypt":{"documentAddressingVersion":2}}`, mode: 1},
- {name: "floor", config: `{}`, floor: `{"version":1,"notebook":"` + testBox + `","minimumMode":2}`, mode: 2},
- {name: "maximum", config: `{"documentAddressingVersion":3}`, floor: `{"version":1,"notebook":"` + testBox + `","minimumMode":2}`, mode: 3},
- {name: "duplicate", config: `{"documentAddressingVersion":2,"documentAddressingVersion":1}`, invalid: true},
- {name: "duplicate case", config: `{"documentAddressingVersion":2,"DocumentAddressingVersion":1}`, invalid: true},
- {name: "null", config: `{"documentAddressingVersion":null}`, invalid: true},
- {name: "string", config: `{"documentAddressingVersion":"2"}`, invalid: true},
- {name: "zero", config: `{"documentAddressingVersion":0}`, invalid: true},
- {name: "negative", config: `{"documentAddressingVersion":-1}`, invalid: true},
- {name: "fraction", config: `{"documentAddressingVersion":1.5}`, invalid: true},
- {name: "trailing data", config: `{} {}`, invalid: true},
- {name: "not an object", config: `null`, invalid: true},
- {name: "truncated config", config: `{"name":"sensitive`, invalid: true},
- {name: "unknown record", floor: `{"version":2,"notebook":"` + testBox + `","minimumMode":2}`, invalid: true},
- {name: "missing mode", floor: `{"version":1,"notebook":"` + testBox + `"}`, invalid: true},
- {name: "foreign identity", floor: `{"version":1,"notebook":"20260101120000-hijklmn","minimumMode":2}`, invalid: true},
- {name: "unknown record field", floor: `{"version":1,"notebook":"` + testBox + `","minimumMode":2,"extra":true}`, invalid: true},
- {name: "duplicate record mode", floor: `{"version":1,"notebook":"` + testBox + `","minimumMode":2,"minimumMode":1}`, invalid: true},
- } {
- t.Run(tc.name, func(t *testing.T) {
- mode, err := ReadMode(testBox, func(name string) ([]byte, error) {
- value := tc.config
- if name == FloorPath {
- value = tc.floor
- }
- if value == "" {
- return nil, os.ErrNotExist
- }
- return []byte(value), nil
- })
- if tc.invalid {
- if !errors.Is(err, ErrInvalid) || err.Error() != ErrInvalid.Error() {
- t.Fatalf("expected safe metadata error, got %v", err)
- }
- } else if err != nil || mode != tc.mode {
- t.Fatalf("got mode %d, error %v", mode, err)
- }
- })
- }
-}
-
-func TestCheckBoxPreservesSourcesAndNeverLowersFloor(t *testing.T) {
- readerModeForTest(t, 1)
- for _, marker := range []string{"config", "floor"} {
- t.Run(marker, func(t *testing.T) {
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- boxDir := filepath.Join(dataDir, testBox)
- config := `{"documentAddressingVersion":2,"name":"private"}`
- if marker == "floor" {
- config = `{}`
- writeTestFile(t, boxDir, FloorPath, `{"version":1,"notebook":"`+testBox+`","minimumMode":2}`)
- }
- writeTestFile(t, boxDir, ConfigPath, config)
- for i := 0; i < 3; i++ {
- if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatalf("check %d: %v", i, err)
- }
- if i == 0 {
- actual, err := os.ReadFile(filepath.Join(boxDir, ConfigPath))
- if err != nil || string(actual) != config {
- t.Fatal("source config changed")
- }
- writeTestFile(t, boxDir, ConfigPath, `{}`)
- if marker == "floor" {
- if err := os.Remove(filepath.Join(boxDir, FloorPath)); err != nil {
- t.Fatal(err)
- }
- }
- } else if i == 1 {
- if err := os.Remove(filepath.Join(boxDir, ConfigPath)); err != nil {
- t.Fatal(err)
- }
- }
- }
- data, err := os.ReadFile(filepath.Join(confDir, "document-addressing.json"))
- var stored localStore
- if err != nil || json.Unmarshal(data, &stored) != nil || stored.Notebooks[testBox] != 2 {
- t.Fatalf("floor not retained: %s, %v", data, err)
- }
- if _, err := os.Stat(filepath.Join(boxDir, ConfigPath)); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("missing config repaired: %v", err)
- }
- })
- }
-}
-
-func TestCheckBoxRejectsRemovedNotebookWithConfirmedFloor(t *testing.T) {
- readerModeForTest(t, 2)
+func TestFixedAddressingVersionDoesNotReadOrWriteRecords(t *testing.T) {
root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- writeTestFile(t, confDir, "document-addressing.json", `{"version":1,"notebooks":{"`+testBox+`":2}}`)
- if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("removed notebook passed the addressing preflight on the local floor alone: %v", err)
- }
- if _, err := os.Stat(filepath.Join(dataDir, testBox)); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("preflight recreated removed notebook: %v", err)
- }
- writeTestFile(t, dataDir, testBox+"/existing.txt", "x")
- if err := CheckBox(dataDir, confDir, testBox); err != nil {
- t.Fatalf("existing notebook with a missing config must retain the confirmed floor: %v", err)
- }
-}
-
-func TestLegacyReaderDoesNotMigrateData(t *testing.T) {
- readerModeForTest(t, 1)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- writeTestFile(t, dataDir, testBox+"/"+ConfigPath, `{"name":"legacy"}`)
- if err := CheckBox(dataDir, confDir, testBox); err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(confDir); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("unexpected migration: %v", err)
- }
-}
-
-func TestCheckBoxPreservesInvalidLocalFloor(t *testing.T) {
- for _, data := range []string{
- `{"version":2,"notebooks":{}}`,
- `{"version":1,"notebooks":null}`,
- `{"version":1,"notebooks":{"` + testBox + `":2,"` + testBox + `":1}}`,
- `{"version":1,"notebooks":{"` + testBox + `":0}}`,
- `{"version":1,"notebooks":{"other":2}}`,
- `{`,
- } {
- t.Run(data, func(t *testing.T) {
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- writeTestFile(t, confDir, "document-addressing.json", data)
- writeTestFile(t, dataDir, testBox+"/"+ConfigPath, `{"documentAddressingVersion":2}`)
- if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrInvalid) {
+ data, conf := filepath.Join(root, "data"), filepath.Join(root, "conf")
+ const box = "20261026000000-fixed01"
+ for _, existing := range []bool{false, true} {
+ if existing {
+ if err := os.MkdirAll(filepath.Join(data, box, ".siyuan"), 0755); err != nil {
t.Fatal(err)
}
- actual, err := os.ReadFile(filepath.Join(confDir, "document-addressing.json"))
- if err != nil || !bytes.Equal(actual, []byte(data)) {
- t.Fatal("invalid local floor overwritten")
+ if err := os.WriteFile(filepath.Join(data, box, ConfigPath), []byte(`{"documentAddressingVersion":999}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mode, err := BoxMode(data, conf, box)
+ if err != nil || mode != 2 || DefaultMode() != 2 || MinimumReaderVersion() != nil {
+ t.Fatal(mode, err)
+ }
+ capability, err := InspectBox(data, conf, box)
+ if err != nil || capability.Mode != 2 || capability.State != "structured" {
+ t.Fatal(capability, err)
+ }
+ if _, err := os.Stat(conf); !os.IsNotExist(err) {
+ t.Fatal("inspection created local records", err)
+ }
+ if !existing {
+ if _, err := os.Stat(data); !os.IsNotExist(err) {
+ t.Fatal("inspection recreated a missing notebook", err)
+ }
+ } else {
+ got, err := os.ReadFile(filepath.Join(data, box, ConfigPath))
+ if err != nil || string(got) != `{"documentAddressingVersion":999}` {
+ t.Fatal("inspection rewrote a diagnostic marker", err)
}
- })
- }
-}
-
-func TestCheckBatchUsesIncomingModeAndRetainsObservedFloor(t *testing.T) {
- readerModeForTest(t, 1)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- config := testBox + "/" + ConfigPath
- writeTestFile(t, dataDir, config, `{}`)
- err := CheckBatch(dataDir, confDir, []string{config, testBox + "/new.sy"}, nil, func(name string) ([]byte, error) {
- if name != config {
- t.Fatalf("unexpected read %s", name)
}
- return []byte(`{"documentAddressingVersion":2}`), nil
- })
- if !errors.Is(err, ErrUnsupported) {
- t.Fatal(err)
- }
- data, err := os.ReadFile(filepath.Join(dataDir, config))
- if err != nil || string(data) != `{}` {
- t.Fatal("preflight changed source")
- }
- if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatalf("rejected incoming floor forgotten: %v", err)
- }
-}
-
-func TestCheckBatchAllowsOnlyWholeNotebookDeletion(t *testing.T) {
- readerModeForTest(t, 1)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- config, doc := testBox+"/"+ConfigPath, testBox+"/document.sy"
- writeTestFile(t, dataDir, config, `{"documentAddressingVersion":2}`)
- writeTestFile(t, dataDir, doc, "source")
- read := func(string) ([]byte, error) { t.Fatal("unexpected incoming file"); return nil, nil }
- if err := CheckBatch(dataDir, confDir, nil, []string{config}, read); !errors.Is(err, ErrUnsupported) {
- t.Fatal(err)
- }
- if err := CheckBatch(dataDir, confDir, nil, []string{config, doc}, read); err != nil {
- t.Fatal(err)
- }
- if err := os.RemoveAll(filepath.Join(dataDir, testBox)); err != nil {
- t.Fatal(err)
- }
- if err := CheckBatch(dataDir, confDir, nil, []string{config, doc}, read); err != nil {
- t.Fatal(err)
- }
- if _, err := os.Stat(filepath.Join(dataDir, testBox)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("deleted notebook recreated")
- }
- writeTestFile(t, dataDir, config, `{}`)
- if err := CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {
- t.Fatalf("restored identity lost floor: %v", err)
- }
-}
-
-func TestCheckBatchCannotEraseAnUnobservedFloor(t *testing.T) {
- readerModeForTest(t, 1)
- root := t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- config, floor := testBox+"/"+ConfigPath, testBox+"/"+FloorPath
- writeTestFile(t, dataDir, config, `{}`)
- writeTestFile(t, dataDir, floor, `{"version":1,"notebook":"`+testBox+`","minimumMode":2}`)
- err := CheckBatch(dataDir, confDir, []string{config}, []string{floor}, func(string) ([]byte, error) { return []byte(`{}`), nil })
- if !errors.Is(err, ErrUnsupported) {
- t.Fatal(err)
- }
- if _, err = os.Stat(filepath.Join(dataDir, floor)); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestReadModePreservesIOErrors(t *testing.T) {
- want := errors.New("source unavailable")
- _, err := ReadMode(testBox, func(string) ([]byte, error) { return nil, want })
- if !errors.Is(err, want) {
- t.Fatal(err)
- }
-}
-
-func TestCheckImportUsesConfirmedSourceFloorWithoutAdoptingNewIdentities(t *testing.T) {
- readerModeForTest(t, 1)
- root, source := t.TempDir(), t.TempDir()
- dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")
- writeTestFile(t, source, ConfigPath, `{"documentAddressingVersion":2}`)
- if err := CheckImport(dataDir, confDir, testBox, source); !errors.Is(err, ErrUnsupported) {
- t.Fatal(err)
- }
- if _, err := os.Stat(filepath.Join(confDir, "document-addressing.json")); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("rejected standalone source identity was adopted")
}
- writeTestFile(t, confDir, "document-addressing.json", `{"version":1,"notebooks":{"`+testBox+`":2}}`)
- writeTestFile(t, source, ConfigPath, `{}`)
- if err := CheckImport(dataDir, confDir, testBox, source); !errors.Is(err, ErrUnsupported) {
- t.Fatalf("identity remapping could downgrade a known source: %v", err)
+ if _, err := BoxMode(data, conf, "../invalid"); err == nil {
+ t.Fatal("invalid notebook identity accepted")
}
}
-func TestCheckBatchRejectsPathAliases(t *testing.T) {
- for _, name := range []string{
- "../" + testBox + "/" + ConfigPath,
- testBox + "/.siyuan/../.siyuan/conf.json",
- testBox + "/.siyuan/CONF.JSON",
- testBox + "/.SIYUAN/document-addressing.json",
- "20260101120000-ABCDEFG/" + ConfigPath,
- } {
- t.Run(name, func(t *testing.T) {
- root := t.TempDir()
- err := CheckBatch(filepath.Join(root, "data"), filepath.Join(root, "conf"), []string{name}, nil,
- func(string) ([]byte, error) { t.Fatal("invalid path reached snapshot reader"); return nil, nil })
- if !errors.Is(err, ErrInvalid) {
- t.Fatal(err)
- }
- })
+func TestReplacementPathsRejectAliases(t *testing.T) {
+ for _, path := range []string{"../outside", "a//b", "a/../b", "a\\b", "20261026000000-FIXED01/.siyuan/conf.json", "20261026000000-fixed01/.siyuan/CONF.json"} {
+ if err := CheckPaths([]string{path}, nil); err == nil {
+ t.Fatalf("upsert alias accepted: %q", path)
+ }
+ if err := CheckPaths(nil, []string{path}); err == nil {
+ t.Fatalf("removal alias accepted: %q", path)
+ }
}
}
diff --git a/kernel/documentaddressing/title.go b/kernel/documentaddressing/title.go
index 9ac5052c6d..4586773a29 100644
--- a/kernel/documentaddressing/title.go
+++ b/kernel/documentaddressing/title.go
@@ -11,44 +11,34 @@ import (
)
var (
- ErrModeConflict = errors.New("document title requires structured addressing")
ErrInvalidTitle = errors.New("invalid document title source")
+ ErrPathAmbiguous = errors.New("document path is ambiguous; use a document ID or resolveDocPath")
ErrLegacyPathUnsupported = errors.New("legacy document paths are unsupported; use structured document addressing")
)
-// CheckLegacyTitle 检查已经解码的兼容模式标题,不清洗内容,也不将冲突视为已确认的模式启用。
-// 保留全角斜杆、百分号编码、HTML 实体和 Markdown 字面文本。
-func CheckLegacyTitle(title string) error {
- if strings.Contains(title, "/") {
- return ErrModeConflict
- }
- return nil
-}
-
-// CheckLegacyTitleProperties 在属性解码和修复前检查每个标题值,重复字段不能遮盖冲突源。
-func CheckLegacyTitleProperties(data []byte) error {
- return CheckTitleProperties(data, 1)
-}
+// TitleRequiresSpec reports whether an already decoded title requires Spec 6.
+func TitleRequiresSpec(title string) bool { return strings.Contains(title, "/") }
-// CheckTitleProperties 保留原始字符;模式只决定是否允许新字符,不能清洗冲突源。
-func CheckTitleProperties(data []byte, mode int) error {
+// CheckTitleProperties validates every raw title property, including duplicate values.
+// It decodes HTML entities exactly once and reports the independent Spec 6 requirement.
+func CheckTitleProperties(data []byte) (requiresSpec bool, err error) {
if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
- return nil
+ return false, nil
}
decoder := json.NewDecoder(bytes.NewReader(data))
token, err := decoder.Token()
if err != nil || token != json.Delim('{') {
- return ErrInvalidTitle
+ return false, ErrInvalidTitle
}
var titleErr error
for decoder.More() {
token, err = decoder.Token()
if err != nil {
- return ErrInvalidTitle
+ return false, ErrInvalidTitle
}
var value json.RawMessage
if decoder.Decode(&value) != nil {
- return ErrInvalidTitle
+ return false, ErrInvalidTitle
}
if token != "title" {
continue
@@ -58,15 +48,15 @@ func CheckTitleProperties(data []byte, mode int) error {
if titleErr == nil {
titleErr = ErrInvalidTitle
}
- } else if err = CheckLegacyTitle(html.UnescapeAttrVal(title)); mode < 2 && err != nil {
- titleErr = err
+ } else if TitleRequiresSpec(html.UnescapeAttrVal(title)) {
+ requiresSpec = true
}
}
if token, err = decoder.Token(); err != nil || token != json.Delim('}') {
- return ErrInvalidTitle
+ return false, ErrInvalidTitle
}
if _, err = decoder.Token(); err != io.EOF {
- return ErrInvalidTitle
+ return false, ErrInvalidTitle
}
- return titleErr
+ return requiresSpec, titleErr
}
diff --git a/kernel/documentaddressing/title_test.go b/kernel/documentaddressing/title_test.go
index 1c6cd2a15e..9b0420bea5 100644
--- a/kernel/documentaddressing/title_test.go
+++ b/kernel/documentaddressing/title_test.go
@@ -6,7 +6,7 @@ import (
"testing"
)
-func TestLegacyTitlePropertiesPreserveUnknownSources(t *testing.T) {
+func TestTitlePropertiesPreserveUnknownSources(t *testing.T) {
for _, source := range []string{
`{"title":{"format":"future","content":"private"}}`,
`{"title":["private"]}`,
@@ -14,7 +14,7 @@ func TestLegacyTitlePropertiesPreserveUnknownSources(t *testing.T) {
`{"title":false}`,
`{"title":"ordinary"} {}`,
} {
- if err := CheckLegacyTitleProperties([]byte(source)); !errors.Is(err, ErrInvalidTitle) || strings.Contains(err.Error(), "private") {
+ if _, err := CheckTitleProperties([]byte(source)); !errors.Is(err, ErrInvalidTitle) || strings.Contains(err.Error(), "private") {
t.Fatalf("unknown title was accepted or exposed: %v", err)
}
}
@@ -22,7 +22,7 @@ func TestLegacyTitlePropertiesPreserveUnknownSources(t *testing.T) {
`{"title":null}`, `null`, `{}`, `{"title":"ordinary","other":"A/B"}`,
`{"title":"A&amp;#47;B"}`, `{"title":"A%2FB/C **literal**"}`,
} {
- if err := CheckLegacyTitleProperties([]byte(source)); err != nil {
+ if _, err := CheckTitleProperties([]byte(source)); err != nil {
t.Fatal("legacy title semantics changed", err)
}
}
diff --git a/kernel/filesys/doc_ial_test.go b/kernel/filesys/doc_ial_test.go
index 20705f226b..5e07c3e4a8 100644
--- a/kernel/filesys/doc_ial_test.go
+++ b/kernel/filesys/doc_ial_test.go
@@ -10,23 +10,23 @@ import (
"strings"
"testing"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestParseDocIALTitleConflict(t *testing.T) {
+func TestParseDocIALRetainsSourceChecksWithoutModes(t *testing.T) {
for _, source := range []string{
`{"Spec":"2","Properties":{"title":"A/B"}}`,
`{"Spec":"2","Properties":{"title":"A/B","title":"Legacy"}}`,
`{"Spec":"2","Properties":{"title":"A/B"},"Properties":{"title":"Legacy"}}`,
- `{"Spec":"999","Properties":{"title":"A/B"}}`,
} {
- ial, err := parseDocIAL(strings.NewReader(source))
- if ial != nil || !errors.Is(err, documentaddressing.ErrModeConflict) || errors.Is(err, ErrInvalidDocIAL) {
- t.Fatalf("title conflict was treated as repairable properties: %v, %v", ial, err)
+ if _, err := parseDocIAL(strings.NewReader(source)); err != nil {
+ t.Fatal("supported slash title rejected", err)
}
}
+ if _, err := parseDocIAL(strings.NewReader(`{"Spec":"999","Properties":{"title":"A/B"}}`)); !errors.Is(err, treenode.ErrSpecTooNew) {
+ t.Fatal("Spec check lost", err)
+ }
}
type failingDocIALReader struct {
diff --git a/kernel/filesys/document_addressing.go b/kernel/filesys/document_addressing.go
index 2adf0d73c8..f83df0e25e 100644
--- a/kernel/filesys/document_addressing.go
+++ b/kernel/filesys/document_addressing.go
@@ -16,23 +16,23 @@ func CheckDocumentAddressing(boxID string) error {
func DocumentAddressingMode(boxID string) (int, error) {
if boxID == "" {
- return 1, nil
+ return documentaddressing.DefaultMode(), nil
}
return documentaddressing.BoxMode(util.DataDir, util.ConfDir, boxID)
}
func CheckDocumentSpecJSON(boxID string, data []byte) error {
- mode, err := DocumentAddressingMode(boxID)
+ _, err := DocumentAddressingMode(boxID)
if err != nil {
return err
}
- return treenode.CheckSpecJSONForMode(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")), mode)
+ return treenode.CheckSpecJSON(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")))
}
func checkDocumentTreeSpec(tree *parse.Tree) error {
- mode, err := DocumentAddressingMode(tree.Box)
+ _, err := DocumentAddressingMode(tree.Box)
if err != nil {
return err
}
- return treenode.CheckSpecForMode(tree, mode)
+ return treenode.CheckSpec(tree)
}
diff --git a/kernel/filesys/document_addressing_test.go b/kernel/filesys/document_addressing_test.go
index 61076ab9cb..37e5e36c2c 100644
--- a/kernel/filesys/document_addressing_test.go
+++ b/kernel/filesys/document_addressing_test.go
@@ -7,7 +7,6 @@ import (
"os"
"path/filepath"
"testing"
- "time"
"github.com/siyuan-note/siyuan/kernel/cache"
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
@@ -35,127 +34,17 @@ func TestDocumentAddressingOrdinaryTitleRoundTrip(t *testing.T) {
}
}
-func TestDocumentAddressingTitleConflictPreservesSources(t *testing.T) {
+func TestDocumentAddressingPreservesPlainAndEncryptedSources(t *testing.T) {
legacy, err := os.ReadFile("../treenode/testdata/table-cell-legacy.sy")
if err != nil {
t.Fatal(err)
}
- var doc map[string]json.RawMessage
- if err = json.Unmarshal(legacy, &doc); err != nil {
- t.Fatal(err)
- }
- doc["Properties"] = json.RawMessage(`{"title":"private/title"}`)
- conflict, err := json.Marshal(doc)
- if err != nil {
+ var future map[string]json.RawMessage
+ if err = json.Unmarshal(legacy, &future); err != nil {
t.Fatal(err)
}
- conflict = append([]byte("\xef\xbb\xbf"), conflict...)
- for _, encrypted := range []bool{false, true} {
- t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
- box, parent, p, _ := setupStalePathTest(t)
- oldConf := util.ConfDir
- oldProvider, oldAcquire, oldRelease := DEKProvider, DEKLockAcquire, DEKLockRelease
- util.ConfDir = t.TempDir()
- DEKLockAcquire, DEKLockRelease = nil, nil
- t.Cleanup(func() {
- util.ConfDir = oldConf
- DEKProvider, DEKLockAcquire, DEKLockRelease = oldProvider, oldAcquire, oldRelease
- })
- var dek []byte
- if encrypted {
- dek = bytes.Repeat([]byte{23}, 32)
- }
- DEKProvider = func(string) ([]byte, error) { return bytes.Clone(dek), nil }
- source, err := encryptDataWithDEK(box, p, conflict, dek)
- if err != nil {
- t.Fatal(err)
- }
- absPath := writeStalePathFixture(t, box, p, source)
- before, err := os.Stat(absPath)
- if err != nil {
- t.Fatal(err)
- }
- operations := map[string]func() error{
- "properties": func() error { _, err := DocIAL(absPath); return err },
- "parent": func() error { _, err := readParentDocIAL(absPath); return err },
- "load": func() error { _, err := LoadTree(box, p, util.NewLute()); return err },
- "snapshot": func() error {
- _, _, err := LoadTreeSnapshot(box, p, util.NewLute())
- return err
- },
- "cached source": func() error {
- cache.SetTreeDataInBox(util.GetTreeID(p), box, conflict)
- defer cache.RemoveTreeDataInBox(util.GetTreeID(p), box)
- deadline := time.Now().Add(time.Second)
- for {
- if _, ok := cache.GetTreeDataInBox(util.GetTreeID(p), box); ok {
- break
- }
- if time.Now().After(deadline) {
- t.Fatal("cache entry was not published")
- }
- time.Sleep(time.Millisecond)
- }
- _, err := LoadTree(box, p, util.NewLute())
- return err
- },
- "conditional overwrite": func() error {
- _, err := WriteTreeIfUnchanged(treenode.NewTree(box, p, "/Legacy", "Legacy"), source)
- return err
- },
- "ordinary overwrite": func() error {
- _, err := WriteTree(treenode.NewTree(box, p, "/Legacy", "Legacy"))
- return err
- },
- "new source write": func() error {
- _, err := WriteTree(treenode.NewTree(box, p, "/private/title", "private/title"))
- return err
- },
- }
- for name, operation := range operations {
- if err := operation(); !errors.Is(err, documentaddressing.ErrModeConflict) || errors.Is(err, ErrInvalidDocIAL) {
- t.Errorf("%s did not preserve title conflict: %v", name, err)
- }
- }
- actual, err := os.ReadFile(absPath)
- if err != nil || !bytes.Equal(source, actual) {
- t.Fatal("conflicting source was changed")
- }
- after, err := os.Stat(absPath)
- if err != nil || !before.ModTime().Equal(after.ModTime()) {
- t.Fatal("conflicting source modification time changed")
- }
- if _, err = os.Stat(filepath.Join(util.DataDir, box, parent+".sy")); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("missing parent was repaired before source validation")
- }
- if _, _, err = ReadDocHPath(box, p); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("path read did not retain the missing-parent error", err)
- }
- if _, err = WriteTree(treenode.NewTree(box, "/"+parent+".sy", "/Parent", "Parent")); err != nil {
- t.Fatal(err)
- }
- if _, _, err = ReadDocHPath(box, p); !errors.Is(err, documentaddressing.ErrModeConflict) {
- t.Fatal("path read accepted a conflicting descendant", err)
- }
- if entries, err := os.ReadDir(util.ConfDir); err != nil || len(entries) != 0 {
- t.Fatal("source conflict silently activated the notebook")
- }
- if encrypted {
- corrupt := bytes.Clone(source)
- corrupt[len(corrupt)-1] ^= 1
- if err = os.WriteFile(absPath, corrupt, 0600); err != nil {
- t.Fatal(err)
- }
- if _, err = DocIAL(absPath); err == nil || errors.Is(err, documentaddressing.ErrModeConflict) {
- t.Fatal("title inspection bypassed source authentication", err)
- }
- }
- })
- }
-}
-
-func TestDocumentAddressingPreservesPlainAndEncryptedSources(t *testing.T) {
- legacy, err := os.ReadFile("../treenode/testdata/table-cell-legacy.sy")
+ future["Spec"] = json.RawMessage(`"999"`)
+ legacy, err = json.Marshal(future)
if err != nil {
t.Fatal(err)
}
@@ -195,12 +84,12 @@ func TestDocumentAddressingPreservesPlainAndEncryptedSources(t *testing.T) {
},
}
for name, read := range readers {
- if err := read(); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err := read(); !(name == "path" && os.IsNotExist(err)) && !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("%s: %v", name, err)
}
}
- if decryptCalls != 0 {
- t.Fatal("unsupported notebook reached decryption")
+ if encrypted && decryptCalls == 0 {
+ t.Fatal("encrypted source was not authenticated")
}
actual, err := os.ReadFile(absPath)
if err != nil || !bytes.Equal(actual, source) {
diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.go
index 1f96c09950..827f97b784 100644
--- a/kernel/filesys/tree.go
+++ b/kernel/filesys/tree.go
@@ -415,7 +415,7 @@ func readDocumentHeaderInMode(absPath string, strict bool, mode int) (*documentH
return nil, err
}
data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf"))
- if err = treenode.CheckSpecJSONForMode(data, mode); err != nil {
+ if err = treenode.CheckSpecJSON(data); err != nil {
return nil, err
}
var doc documentHeader
@@ -523,8 +523,7 @@ func parseDocIALForMode(reader io.Reader, mode int) (ret map[string]string, err
}
case field == "Properties":
properties = iter.SkipAndReturnBytes()
- if checkErr := documentaddressing.CheckTitleProperties(properties, mode); checkErr != nil &&
- (titleErr == nil || errors.Is(checkErr, documentaddressing.ErrModeConflict)) {
+ if _, checkErr := documentaddressing.CheckTitleProperties(properties); checkErr != nil && titleErr == nil {
titleErr = checkErr
}
default:
@@ -538,9 +537,6 @@ func parseDocIALForMode(reader io.Reader, mode int) (ret map[string]string, err
if r.err != nil {
return nil, r.err
}
- if errors.Is(titleErr, documentaddressing.ErrModeConflict) {
- return nil, titleErr
- }
// 属性可以排在版本之前,完整检查根对象后才能返回,版本错误不能进入属性修复。
if specErr != nil {
return nil, specErr
@@ -661,14 +657,14 @@ func WriteTreeWithPreflight(tree *parse.Tree, preflight func() error) (size uint
}
func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err error) {
- mode, err := validateTreePathMode(tree.Box, tree.Path)
+ _, err = validateTreePathMode(tree.Box, tree.Path)
if err != nil {
return
}
if err = treenode.SyncTableCellRichInlineChanges(tree.Root); nil != err {
return
}
- if err = treenode.CheckSpecForMode(tree, mode); nil != err {
+ if err = treenode.CheckSpec(tree); nil != err {
return
}
luteEngine := util.NewLute() // 不关注用户的自定义解析渲染选项
@@ -775,7 +771,7 @@ func fixTreeJSONDataInMode(boxID, p string, jsonData []byte, luteEngine *lute.Lu
withoutBOM := bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))
needFix = len(withoutBOM) != len(jsonData)
jsonData = withoutBOM
- if err = treenode.CheckSpecJSONForMode(jsonData, mode); nil != err {
+ if err = treenode.CheckSpecJSON(jsonData); nil != err {
return
}
jsonData, removedNull := removeUnescapedUnicodeNull(jsonData)
@@ -793,7 +789,7 @@ func fixTreeJSONDataInMode(boxID, p string, jsonData []byte, luteEngine *lute.Lu
ret.Box = boxID
ret.Path = p
- if err = treenode.CheckSpecForMode(ret, mode); nil != err {
+ if err = treenode.CheckSpec(ret); nil != err {
return
}
if err = treenode.RefreshTableCellRichProjection(ret.Root); nil != err {
@@ -887,7 +883,7 @@ func parseJSON2Tree(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (re
func parseJSON2TreeInMode(boxID, p string, jsonData []byte, luteEngine *lute.Lute, mode int) (ret *parse.Tree, err error) {
jsonData = bytes.TrimPrefix(jsonData, []byte("\xef\xbb\xbf"))
- if err = treenode.CheckSpecJSONForMode(jsonData, mode); nil != err {
+ if err = treenode.CheckSpecJSON(jsonData); nil != err {
return
}
ret, _, err = dataparser.ParseJSON(jsonData, luteEngine.ParseOptions)
@@ -900,7 +896,7 @@ func parseJSON2TreeInMode(boxID, p string, jsonData []byte, luteEngine *lute.Lut
ret.Box = boxID
ret.Path = p
- if err = treenode.CheckSpecForMode(ret, mode); nil != err {
+ if err = treenode.CheckSpec(ret); nil != err {
return
}
err = treenode.RefreshTableCellRichProjection(ret.Root)
diff --git a/kernel/filesys/tree_cached_source_test.go b/kernel/filesys/tree_cached_source_test.go
index 8cf1cd11eb..5d1a070486 100644
--- a/kernel/filesys/tree_cached_source_test.go
+++ b/kernel/filesys/tree_cached_source_test.go
@@ -113,7 +113,7 @@ func TestCachedTreeSourceRetainsFallbackAndAuthorization(t *testing.T) {
}
}
-func TestCachedTreeSourceCapturesModeWithoutReusingItForNewAccess(t *testing.T) {
+func TestCachedTreeSourceIgnoresRetiredModeAndValidatesSpec(t *testing.T) {
boxID, id, _, _ := setupStalePathTest(t)
previousConfDir := util.ConfDir
util.ConfDir = t.TempDir()
@@ -135,7 +135,7 @@ func TestCachedTreeSourceCapturesModeWithoutReusingItForNewAccess(t *testing.T)
t.Fatal(err)
}
- // 已捕获的来源只按捕获时的能力解析,下一次来源访问仍检查当前能力。
+ // Retired diagnostic markers do not change supported source reads.
writeStalePathFixture(t, boxID, documentaddressing.ConfigPath, []byte(`{"documentAddressingVersion":3}`))
luteEngine := util.NewLute()
captured, err := source.Parse(luteEngine)
@@ -154,8 +154,8 @@ func TestCachedTreeSourceCapturesModeWithoutReusingItForNewAccess(t *testing.T)
{"write", func() error { _, err := WriteTree(captured); return err }},
} {
t.Run(access.name, func(t *testing.T) {
- if err := access.run(); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("new access reused an earlier addressing check: %v", err)
+ if err := access.run(); err != nil {
+ t.Fatalf("retired mode blocked source access: %v", err)
}
})
}
diff --git a/kernel/filesys/tree_compare_write_test.go b/kernel/filesys/tree_compare_write_test.go
index 22b7160255..d7474ef8d0 100644
--- a/kernel/filesys/tree_compare_write_test.go
+++ b/kernel/filesys/tree_compare_write_test.go
@@ -47,7 +47,6 @@ func TestTreeWritesValidateCurrentSourceBehindCache(t *testing.T) {
err error
}{
{`{"Spec":"999","Properties":{"title":"Future"}}`, treenode.ErrSpecTooNew},
- {`{"Spec":"2","Properties":{"title":"A/B"}}`, documentaddressing.ErrModeConflict},
{`{"Spec":"2","Properties":{"title":{"format":"future"}}}`, documentaddressing.ErrInvalidTitle},
} {
disk, err := encryptDataWithDEK(box, p, []byte(source.data), dek)
diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.go
index c148ecba0d..06e62121c0 100644
--- a/kernel/mcp/tools/document.go
+++ b/kernel/mcp/tools/document.go
@@ -23,9 +23,7 @@ import (
"strings"
"github.com/88250/lute/ast"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/model"
- "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -152,10 +150,13 @@ type documentTarget struct {
}
func documentTargetFailure(err error) CallToolResult {
+ if failure, ok := model.LegacyPathFailure(err); ok {
+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: failure.Reason + ": " + err.Error()}}, IsError: true}
+ }
return CallToolResult{Content: []ContentItem{{Type: "text", Text: err.Error()}}, IsError: true}
}
-// resolveDocumentTarget 在任何旧 hPath 查询前检查整本模式,父身份只通过结构化模型解析。
+// resolveDocumentTarget uses the shared ancestor-chain check for legacy paths and identity resolution for parentID.
func resolveDocumentTarget(notebook string, args map[string]any, create, defaultRoot bool) (*documentTarget, error) {
parent, hasParent := args["parentID"]
legacy, hasPath := args["path"]
@@ -189,22 +190,19 @@ func resolveDocumentTarget(notebook string, args map[string]any, create, default
if !hasPath || !ok || hPath == "" {
return nil, errors.New("parentID or path is required")
}
- if err := model.CheckLegacyDocumentPath(notebook); err != nil {
- if errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {
- return nil, fmt.Errorf("legacyPathUnsupported: %w; use parentID (empty string for the notebook root), or resolveDocPath/createDocByParent via the HTTP API", err)
- }
- return nil, err
- }
if create {
hPath = parentDir(hPath)
}
- target := &documentTarget{path: "/", hPath: hPath}
- if hPath != "/" {
- bt := treenode.GetBlockTreeRootByHPath(notebook, hPath)
- if bt == nil {
- return nil, fmt.Errorf("target path not found: %s", hPath)
- }
- target.path, target.id = bt.Path, &bt.ID
+ bt, err := model.ResolveLegacyDocumentPath(notebook, hPath, create)
+ if err != nil {
+ return nil, err
+ }
+ if bt == nil {
+ return nil, fmt.Errorf("target path not found: %s", hPath)
+ }
+ target := &documentTarget{path: bt.Path, hPath: hPath}
+ if bt.Path != "/" {
+ target.id = &bt.ID
}
return target, nil
}
diff --git a/kernel/mcp/tools/document_addressing_fts5_test.go b/kernel/mcp/tools/document_addressing_fts5_test.go
index f3a9410ca0..3d7d11e2d9 100644
--- a/kernel/mcp/tools/document_addressing_fts5_test.go
+++ b/kernel/mcp/tools/document_addressing_fts5_test.go
@@ -97,14 +97,22 @@ func TestDocumentStructuredAddressing(t *testing.T) {
}
before, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, source.Path))
for _, action := range []string{"create", "list", "move"} {
- for _, hPath := range []string{"/A/B", "/"} {
- args := map[string]any{"action": action, "notebook": box.ID, "path": hPath, "id": source.ID, "title": "New"}
- result, err := documentHandler(args)
- if err != nil || !result.IsError || !strings.Contains(result.Content[0].Text, "legacyPathUnsupported") {
- t.Fatalf("%s accepted a legacy path: %+v, %v", action, result, err)
- }
+ hPath := "/A/B"
+ if action == "create" {
+ hPath += "/New"
+ }
+ args := map[string]any{"action": action, "notebook": box.ID, "path": hPath, "id": source.ID, "title": "New"}
+ result, err := documentHandler(args)
+ if err != nil || !result.IsError || !strings.Contains(result.Content[0].Text, "pathAmbiguous") {
+ t.Fatalf("%s: %+v %v", action, result, err)
}
}
+ if target, err := resolveDocumentTarget(box.ID, map[string]any{"path": "/Move me"}, false, false); err != nil || target.path != source.Path {
+ t.Fatal(target, err)
+ }
+ if target, err := resolveDocumentTarget(box.ID, map[string]any{"path": "/"}, false, false); err != nil || target.path != "/" {
+ t.Fatal(target, err)
+ }
after, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, source.Path))
if !bytes.Equal(before, after) {
t.Fatal("rejected move changed the source")
@@ -165,10 +173,16 @@ func TestDocumentStructuredAddressing(t *testing.T) {
if _, err := resolveDocumentTarget(foreign.ID, map[string]any{"parentID": literal.ID}, false, false); err == nil {
t.Fatal("parent from a different notebook was accepted")
}
- // 缺少配置的旧模式夹具不触发自动升级,保留旧路径的父目录解释。
+ // Clean legacy paths use the same ready metadata checks as structured paths.
legacyBox := ast.NewNodeID()
+ if err := (&model.Box{ID: legacyBox}).SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
legacyDoc := treenode.NewTree(legacyBox, "/"+ast.NewNodeID()+".sy", "/Legacy", "Legacy")
treenode.UpsertBlockTree(legacyDoc)
+ if err := treenode.SetDocumentMetadataState(legacyBox, "ready"); err != nil {
+ t.Fatal(err)
+ }
for _, create := range []bool{false, true} {
hPath := "/Legacy"
if create {
@@ -180,7 +194,7 @@ func TestDocumentStructuredAddressing(t *testing.T) {
}
}
if result, err = inboxConvert(map[string]any{"notebook": box.ID, "path": "/A/B/New", "ids": "1"}); err != nil || !result.IsError ||
- !strings.Contains(result.Content[0].Text, "legacyPathUnsupported") {
+ !strings.Contains(result.Content[0].Text, "pathAmbiguous") {
t.Fatalf("inbox reached cloud conversion before rejecting the legacy path: %+v, %v", result, err)
}
}
diff --git a/kernel/model/box.go b/kernel/model/box.go
index ecdea80412..3ca575bf62 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -18,6 +18,7 @@ package model
import (
"bytes"
+ "encoding/json"
"errors"
"fmt"
"io/fs"
@@ -40,7 +41,6 @@ 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"
@@ -190,9 +190,9 @@ func listNotebooks(repairMissingConf bool) (ret []*Box, err error) {
}
if readErr = gulu.JSON.UnmarshalJSON(data, boxConf); nil != readErr {
logging.LogErrorf("parse box conf [%s] failed: %s", boxConfPath, readErr)
- // 检查加密备份,有备份则保留损坏 conf 不删(避免标记为缺失后自动恢复旧数据)
+ // 检查备份及加密身份,保留损坏配置中的恢复材料,不能按普通配置删除。
backup, backupErr := readNotebookCryptBackup(id)
- if backupErr != nil || backup != nil {
+ if backupErr != nil || backup != nil || IsEncryptedBox(id) {
markRuntimeEncryptedBox(id)
continue
}
@@ -359,12 +359,14 @@ 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 {
+ var fields map[string]json.RawMessage
+ if err = json.Unmarshal(newData, &fields); err == nil {
+ fields["documentAddressingVersion"] = json.RawMessage("2")
+ newData, err = json.MarshalIndent(fields, "", " ")
+ }
+ }
if err != nil {
return fmt.Errorf("marshal box conf [%s] failed: %w", confPath, err)
}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index b589a43f53..525e14f0d8 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -307,6 +307,9 @@ func InitConf() {
if err := CleanupRetiredInstallResources(); err != nil {
logging.LogWarnf("clean up retired install resources failed: %s", err)
}
+ if err := cleanupRetiredDocumentAddressing(); err != nil {
+ logging.LogWarnf("clean up retired document addressing records failed: %s", err)
+ }
confPath := filepath.Join(util.ConfDir, "conf.json")
confFileExists := gulu.File.IsExist(confPath)
var confData []byte
diff --git a/kernel/model/document_addressing.go b/kernel/model/document_addressing.go
index 7fa26ef379..696d2d99e2 100644
--- a/kernel/model/document_addressing.go
+++ b/kernel/model/document_addressing.go
@@ -14,17 +14,16 @@ import (
"github.com/siyuan-note/dejavu"
"github.com/siyuan-note/filelock"
"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 checkDocumentAddressingConf(boxID string, data []byte) error {
- return documentaddressing.CheckBatch(util.DataDir, util.ConfDir,
- []string{boxID + "/" + documentaddressing.ConfigPath}, nil,
- func(string) ([]byte, error) { return data, nil })
+ return filesys.CheckDocumentAddressing(boxID)
}
-// documentAddressingPreflight 读取待恢复快照中的记录,在整批写入和删除前检查能力。
+// documentAddressingPreflight 在整批写入和删除前检查快照的规范路径及源规格。
func documentAddressingPreflight(repo *dejavu.Repo) func(*dejavu.CheckoutPlan) error {
return func(plan *dejavu.CheckoutPlan) error {
upserts := make([]string, 0, len(plan.Upserts))
@@ -69,8 +68,7 @@ func documentAddressingPreflight(repo *dejavu.Repo) func(*dejavu.CheckoutPlan) e
removes = append(removes, file.Path)
removedPaths[strings.TrimPrefix(file.Path, "/")] = true
}
- if err := documentaddressing.CheckBatch(repo.DataPath, util.ConfDir, upserts, removes,
- func(name string) ([]byte, error) { return plan.ReadFile(paths[name]) }); err != nil {
+ if err := documentaddressing.CheckPaths(upserts, removes); err != nil {
return err
}
for _, file := range plan.Upserts {
@@ -127,7 +125,7 @@ func checkDocumentAddressingCheckoutCurrent(dataDir, name string) error {
}
// 已识别的不支持版本或标题不能被覆盖或部分删除;普通损坏源仍可用合法历史恢复。
if err = checkDocumentAddressingCheckoutSource(data); errors.Is(err, treenode.ErrSpecTooNew) ||
- errors.Is(err, documentaddressing.ErrModeConflict) || errors.Is(err, documentaddressing.ErrInvalidTitle) {
+ errors.Is(err, documentaddressing.ErrInvalidTitle) {
return fmt.Errorf("document [%s]: %w", name, err)
}
return nil
@@ -162,19 +160,15 @@ func checkDocumentAddressingCheckoutSource(data []byte) error {
if util.IsCiphertext(data) {
return nil
}
- return treenode.CheckSpecJSONForMode(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")), documentaddressing.DefaultMode())
+ return treenode.CheckSpecJSON(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")))
}
func documentAddressingCheckoutHooks(repo *dejavu.Repo) dejavu.CheckoutHooks {
return dejavu.CheckoutHooks{Preflight: documentAddressingPreflight(repo)}
}
-// checkImportedDocumentAddressing 在重新生成 ID 或删除档案配置前校验原始笔记本身份和模式。
+// checkImportedDocumentAddressing 在重新生成 ID 或删除档案配置前校验原始笔记本文档身份。
func checkImportedDocumentAddressing(directory string) error {
- boxID := filepath.Base(directory)
- if !ast.IsNodeIDPattern(boxID) {
- boxID = ""
- }
data, err := filelock.ReadFile(filepath.Join(directory, ".siyuan", boxDocMetaName))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
@@ -184,57 +178,11 @@ func checkImportedDocumentAddressing(directory string) error {
if json.Unmarshal(data, &meta) != nil || meta.Spec != boxDocMetaSpec || !ast.IsNodeIDPattern(meta.BoxDocID) {
return documentaddressing.ErrInvalid
}
- boxID = meta.BoxDocID
- }
- if boxID == "" {
- // 按名称导出的笔记本可能没有笔记本文档;从寻址记录取得身份后仍校验完整源记录。
- data, err = filelock.ReadFile(filepath.Join(directory, documentaddressing.FloorPath))
- if err != nil && !errors.Is(err, os.ErrNotExist) {
- return err
- }
- if err == nil {
- var record struct {
- Notebook string `json:"notebook"`
- }
- if json.Unmarshal(data, &record) != nil || !ast.IsNodeIDPattern(record.Notebook) {
- return documentaddressing.ErrInvalid
- }
- boxID = record.Notebook
- }
- }
- return documentaddressing.CheckImport(util.DataDir, util.ConfDir, boxID, directory)
-}
-
-// prepareImportedDocumentAddressing 仅处理已经通过源身份和模式检查的临时档案。
-func prepareImportedDocumentAddressing(directory, newBoxID string, wholeNotebook bool) error {
- name := filepath.Join(directory, documentaddressing.FloorPath)
- data, err := filelock.ReadFile(name)
- if errors.Is(err, os.ErrNotExist) {
- return nil
- }
- if err != nil {
- return err
- }
- if !wholeNotebook {
- // 文档级导入沿用目标能力,不复制源笔记本的模式记录。
- return filelock.Remove(name)
- }
- var record map[string]json.RawMessage
- if err = json.Unmarshal(data, &record); err != nil {
- return err
- }
- record["notebook"], err = json.Marshal(newBoxID)
- if err != nil {
- return err
}
- data, err = json.Marshal(record)
- if err != nil {
- return err
- }
- return filelock.WriteFile(name, data)
+ return nil
}
-// checkDocumentAddressingCopy 在整批导入或历史恢复开始复制前检查源配置及目标已确认的下界。
+// checkDocumentAddressingCopy 在整批导入或历史恢复开始复制前检查规范路径及文档源规格。
func checkDocumentAddressingCopy(sourceRoot, boxID string) error {
var upserts []string
err := filepath.WalkDir(sourceRoot, func(name string, entry os.DirEntry, err error) error {
@@ -257,23 +205,26 @@ func checkDocumentAddressingCopy(sourceRoot, boxID string) error {
if err != nil {
return err
}
- return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, upserts, nil, func(name string) ([]byte, error) {
+ if err := documentaddressing.CheckPaths(upserts, nil); err != nil {
+ return err
+ }
+ for _, name := range upserts {
+ if !isDocumentAddressingSource([]string{name}) {
+ continue
+ }
+ relative := name
if boxID != "" {
- name = strings.TrimPrefix(name, boxID+"/")
+ relative = strings.TrimPrefix(name, boxID+"/")
+ }
+ data, err := filelock.ReadFile(filepath.Join(sourceRoot, filepath.FromSlash(relative)))
+ if err != nil {
+ return err
+ }
+ if err = checkDocumentAddressingCheckoutSource(data); err != nil {
+ return err
}
- return filelock.ReadFile(filepath.Join(sourceRoot, filepath.FromSlash(name)))
- })
-}
-
-func copyExportedDocumentAddressing(boxID, directory string) error {
- data, err := filelock.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath))
- if errors.Is(err, os.ErrNotExist) {
- return nil
- }
- if err != nil {
- return err
}
- return filelock.WriteFile(filepath.Join(directory, documentaddressing.FloorPath), data)
+ return nil
}
// backupUnsupportedNotebookAttributeViews 无法解析源文档时保留共享数据库的原始快照,避免丢失恢复材料。
diff --git a/kernel/model/document_addressing_crypto_test.go b/kernel/model/document_addressing_crypto_test.go
index 810af643c8..428779b384 100644
--- a/kernel/model/document_addressing_crypto_test.go
+++ b/kernel/model/document_addressing_crypto_test.go
@@ -8,7 +8,9 @@ import (
"path/filepath"
"testing"
+ "github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
+
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -33,7 +35,7 @@ func setDocumentAddressingTestMode(t *testing.T, boxDirectory string, mode int)
}
}
-func TestDocumentAddressingEncryptedRecoveryPreservesKeys(t *testing.T) {
+func TestDocumentAddressingEncryptedAuthenticationPreservesKeys(t *testing.T) {
notebookArchiveTestWorkspace(t)
password := "addressing-password"
if err := EnableEncryptedNotebook(password); err != nil {
@@ -56,17 +58,8 @@ func TestDocumentAddressingEncryptedRecoveryPreservesKeys(t *testing.T) {
t.Fatal(err)
}
keyState, _ := json.Marshal(currentNotebookCrypto())
- for _, operation := range []func() error{
- func() error { return UnlockBox(boxID, password, crypt) },
- func() error { _, err := UnlockAndMountBox(boxID, password, crypt); return err },
- func() error { return AcquireEncryptedBoxOperation(boxID) },
- func() error { return writeNotebookCryptBackup(boxID, crypt) },
- func() error { return ChangeMasterPassword(password, "different-password") },
- func() error { _, _, err := PrepareNotebookArchive([]string{boxID}); return err },
- } {
- if err = operation(); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("encrypted operation admitted unsupported mode: %v", err)
- }
+ if err := UnlockBox(boxID, "wrong-password", crypt); err == nil {
+ t.Fatal("wrong password accepted")
}
after, err := archiveDirectoryFiles(util.DataDir)
if err != nil {
@@ -86,7 +79,41 @@ func TestDocumentAddressingEncryptedRecoveryPreservesKeys(t *testing.T) {
}
}
-func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
+func TestDocumentAddressingCorruptEncryptedConfigurationWithoutBackup(t *testing.T) {
+ notebookArchiveTestWorkspace(t)
+ Conf.FileTree.Store(conf.NewFileTree())
+ password := "corrupt-addressing-configuration"
+ if err := EnableEncryptedNotebook(password); err != nil {
+ t.Fatal(err)
+ }
+ kek, err := deriveKEK(password)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(kek)
+ const boxID = "20261026000000-corrupt"
+ _ = notebookArchiveTestBox(t, boxID, kek)
+ name := filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath)
+ original, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ corrupt := append(bytes.Clone(original), '{')
+ if err := os.WriteFile(name, corrupt, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(notebookCryptoBackupPath(boxID)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := listNotebooks(true); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := os.ReadFile(name); err != nil || !bytes.Equal(got, corrupt) {
+ t.Fatal("notebook discovery removed recoverable encrypted configuration", err)
+ }
+}
+
+func TestDocumentAddressingEncryptedArchiveIgnoresRetiredModes(t *testing.T) {
notebookArchiveTestWorkspace(t)
password := "addressing-archive-password"
if err := EnableEncryptedNotebook(password); err != nil {
@@ -126,7 +153,7 @@ func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
notebookArchiveTestWorkspace(t)
if test.remembered {
backup := []byte(`{"documentAddressing":{"version":1,"notebooks":{"` + boxID + `":3}}}`)
- if err := documentaddressing.RestoreBackup(util.ConfDir, backup); err != nil {
+ if err := os.WriteFile(filepath.Join(util.ConfDir, "document-addressing.json"), backup, 0600); err != nil {
t.Fatal(err)
}
}
@@ -134,12 +161,12 @@ func TestDocumentAddressingEncryptedArchiveImportPreflight(t *testing.T) {
if err := ImportNotebookArchive(test.archive, "wrong-password", nil); !errors.Is(err, ErrNotebookArchiveAuthentication) {
t.Fatalf("mode check bypassed authentication: %v", err)
}
- if err := ImportNotebookArchive(test.archive, password, nil); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("archive restored unsupported notebook: %v", err)
+ if err := ImportNotebookArchive(test.archive, password, nil); err != nil {
+ t.Fatalf("retired mode blocked authenticated archive: %v", err)
}
entries, _ := os.ReadDir(util.DataDir)
- if len(entries) != 0 || currentNotebookCrypto().Enabled {
- t.Fatal("rejected archive partially installed data or keys")
+ if len(entries) == 0 || !currentNotebookCrypto().Enabled {
+ t.Fatal("authenticated archive lost data or keys")
}
current, _ := os.ReadFile(test.archive)
if !bytes.Equal(current, original) {
diff --git a/kernel/model/document_addressing_file.go b/kernel/model/document_addressing_file.go
index 1c3803e025..8a631db861 100644
--- a/kernel/model/document_addressing_file.go
+++ b/kernel/model/document_addressing_file.go
@@ -78,33 +78,8 @@ func documentAddressingDataPaths(absPath string) ([]string, error) {
return ret, nil
}
-// 本机能力下界只能通过专用合并写入,原始文件接口不能覆盖、移动或删除它及其父目录。
-func checkDocumentAddressingLocalFile(absPath string, ancestors bool) error {
- confDir := util.ConfDir
- if confDir == "" && filepath.IsAbs(util.DataDir) {
- confDir = filepath.Join(filepath.Dir(util.DataDir), "conf")
- }
- if !filepath.IsAbs(confDir) {
- return nil
- }
- name := util.NormalizeAndResolve(util.ResolveLongestExistingParent(absPath))
- 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
-}
-
// CheckDocumentAddressingFileWrite 在创建目录、覆盖配置或调整时间之前检查待写内容。
func CheckDocumentAddressingFileWrite(absPath string, data []byte, directory bool) error {
- if err := checkDocumentAddressingLocalFile(absPath, false); err != nil {
- return err
- }
if err := CheckDocumentAddressingPath(absPath); err != nil {
return err
}
@@ -115,8 +90,7 @@ func CheckDocumentAddressingFileWrite(absPath string, data []byte, directory boo
if err != nil || len(paths) == 0 {
return err
}
- if err = documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,
- func(string) ([]byte, error) { return data, nil }); err != nil {
+ if err = documentaddressing.CheckPaths(paths, nil); err != nil {
return err
}
if isDocumentAddressingSource(paths) {
@@ -157,9 +131,6 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {
return relErr
}
dest := filepath.Join(destinations[i], rel)
- if err := checkDocumentAddressingLocalFile(dest, false); err != nil {
- return err
- }
if entry.IsDir() {
return CheckDocumentAddressingPath(dest)
}
@@ -190,8 +161,7 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {
for path := range upserts {
paths = append(paths, path)
}
- if err := documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,
- func(name string) ([]byte, error) { return filelock.ReadFile(upserts[name]) }); err != nil {
+ if err := documentaddressing.CheckPaths(paths, nil); err != nil {
return err
}
for _, document := range documents {
@@ -206,11 +176,8 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {
return nil
}
-// CheckDocumentAddressingFileRemoval 保留整本删除语义;部分删除不能抹去能力记录。
+// CheckDocumentAddressingFileRemoval 保留整本删除语义及规范路径校验。
func CheckDocumentAddressingFileRemoval(absPath string) error {
- if err := checkDocumentAddressingLocalFile(absPath, true); err != nil {
- return err
- }
var removes []string
err := filepath.WalkDir(absPath, func(name string, entry os.DirEntry, err error) error {
if errors.Is(err, os.ErrNotExist) {
@@ -229,5 +196,5 @@ func CheckDocumentAddressingFileRemoval(absPath string) error {
}
return CheckDocumentAddressingPath(absPath)
}
- return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, nil, removes, nil)
+ return documentaddressing.CheckPaths(nil, removes)
}
diff --git a/kernel/model/document_addressing_file_test.go b/kernel/model/document_addressing_file_test.go
index 507d999c90..784d246cb4 100644
--- a/kernel/model/document_addressing_file_test.go
+++ b/kernel/model/document_addressing_file_test.go
@@ -7,11 +7,11 @@ import (
"path/filepath"
"testing"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestDocumentAddressingSortRecoveryPreservesPendingWrite(t *testing.T) {
+func TestSortRecoveryIgnoresRetiredAddressingMarker(t *testing.T) {
initial := []byte(`{"` + appendSortOldID + `":7}`)
confPath := prepareSortConfAppendTest(t, initial)
previousConfDir := util.ConfDir
@@ -22,7 +22,6 @@ func TestDocumentAddressingSortRecoveryPreservesPendingWrite(t *testing.T) {
t.Fatal(err)
}
recordPath := saveSortConfAppendTestRecord(t, confPath, record)
- journal, _ := os.ReadFile(recordPath)
partial := append(bytes.Clone(initial[:record.Offset]), record.Suffix[:len(record.Suffix)/2]...)
if err = os.WriteFile(confPath, partial, 0600); err != nil {
t.Fatal(err)
@@ -30,25 +29,14 @@ func TestDocumentAddressingSortRecoveryPreservesPendingWrite(t *testing.T) {
if err = os.WriteFile(filepath.Join(filepath.Dir(confPath), "conf.json"), []byte(`{"documentAddressingVersion":3}`), 0600); err != nil {
t.Fatal(err)
}
- for _, operation := range []func() error{
- func() error { return recoverSortConfAppend(confPath) },
- func() error { _, err := readSortConfMap(confPath); return err },
- func() error { return writeSortConfMap(confPath, map[string]int{appendSortOldID: 99}) },
- func() error { return appendSortConfMap(confPath, initial, map[string]int{appendSortNewID: 9}) },
- func() error { _, err := recoverSortConfMap(confPath, partial); return err },
- } {
- if err = operation(); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("sort operation entered unsupported notebook: %v", err)
- }
+ if err := recoverSortConfAppend(confPath); err != nil {
+ t.Fatal("retired marker blocked sort recovery", err)
}
- if err = recoverSortConfAppends(); err != nil {
- t.Fatalf("unavailable notebook prevented startup: %v", err)
+ if _, err := os.Stat(recordPath); !os.IsNotExist(err) {
+ t.Fatal("completed recovery retained journal", err)
}
- for name, expected := range map[string][]byte{confPath: partial, recordPath: journal} {
- data, readErr := os.ReadFile(name)
- if readErr != nil || !bytes.Equal(data, expected) {
- t.Fatalf("sort recovery changed %s: %s, %v", name, data, readErr)
- }
+ if got, err := readSortConfMap(confPath); err != nil || got[appendSortOldID] != 7 || got[appendSortNewID] != 8 {
+ t.Fatal(got, err)
}
}
@@ -76,23 +64,18 @@ func documentAddressingRawPathAliases(t *testing.T, linkDirectory func(string, s
}
alias := filepath.Join(root, "alias")
linkDirectory(alias, box)
- if err := CheckDocumentAddressingFileWrite(filepath.Join(alias, "new", "child.sy"), []byte("raw"), false); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(alias, "20261026000001-parent1", "20261026000002-child01.sy"), []byte(`{"Spec":"999"}`), false); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("linked destination bypassed protection: %v", err)
}
outside := t.TempDir()
linkDirectory(filepath.Join(box, "outside"), outside)
- if err := CheckDocumentAddressingPath(filepath.Join(box, "outside", "new.sy")); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(box, "20261026000001-parent2", "20261026000002-child01.sy"), []byte(`{"Spec":"999"}`), false); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("logical notebook path bypassed protection: %v", err)
}
- confAlias := filepath.Join(root, "conf-alias")
- linkDirectory(confAlias, util.ConfDir)
- if err := CheckDocumentAddressingFileWrite(filepath.Join(confAlias, "document-addressing.json"), []byte(`{}`), false); !errors.Is(err, documentaddressing.ErrInvalid) {
- t.Fatalf("local capability alias bypassed protection: %v", err)
- }
dataAlias := filepath.Join(root, "data-alias")
linkDirectory(dataAlias, util.DataDir)
util.DataDir = dataAlias
- if err := CheckDocumentAddressingFileWrite(filepath.Join(box, "new.sy"), []byte("raw"), false); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err := CheckDocumentAddressingFileWrite(filepath.Join(box, "20261026000002-child01.sy"), []byte(`{"Spec":"999"}`), false); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("physical path of linked data directory bypassed protection: %v", err)
}
}
diff --git a/kernel/model/document_addressing_fts5_test.go b/kernel/model/document_addressing_fts5_test.go
index c205c9fedb..e31625bd61 100644
--- a/kernel/model/document_addressing_fts5_test.go
+++ b/kernel/model/document_addressing_fts5_test.go
@@ -22,7 +22,7 @@ func TestDocumentAddressingWholeNotebookDeletionRetainsRecoveryData(t *testing.T
t.Cleanup(func() { util.TempDir, util.HistoryDir, util.WorkspaceDir = oldTemp, oldHistory, oldWorkspace })
setupNotebookDocumentImportDatabase(t)
boxID := fixture.box.ID
- source := []byte("unparsed future source")
+ source := []byte(`{"Spec":"999","Properties":{"title":"Future"}}`)
config := []byte(`{"name":"future","closed":true,"documentAddressingVersion":3}`)
if err := os.WriteFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath), config, 0644); err != nil {
t.Fatal(err)
@@ -58,8 +58,8 @@ func TestDocumentAddressingWholeNotebookDeletionRetainsRecoveryData(t *testing.T
if data, readErr := os.ReadFile(sharedHistory); readErr != nil || !bytes.Equal(data, shared) {
t.Fatalf("shared database recovery data missing: %v", readErr)
}
- if err = filesys.CheckDocumentAddressing(boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("deletion discarded capability floor: %v", err)
+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {
+ t.Fatalf("retired mode blocked missing notebook: %v", err)
}
if _, err = os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {
t.Fatal("floor check recreated deleted notebook")
diff --git a/kernel/model/document_addressing_preflight_test.go b/kernel/model/document_addressing_preflight_test.go
index 655d57e2be..06e2c897f7 100644
--- a/kernel/model/document_addressing_preflight_test.go
+++ b/kernel/model/document_addressing_preflight_test.go
@@ -144,10 +144,6 @@ func TestDocumentAddressingCheckoutSourcePreflight(t *testing.T) {
future := `{"Spec":"999","Properties":{"title":"Future"}}`
title := `{"Spec":"2","Properties":{"title":{"format":"future"}}}`
slash := `{"Spec":"6","Properties":{"title":"Parent/Child"}}`
- var slashError error
- if documentaddressing.DefaultMode() < 2 {
- slashError = documentaddressing.ErrModeConflict
- }
for _, test := range []struct {
name, incoming, current, config, floor, document string
wantErr error
@@ -156,11 +152,11 @@ func TestDocumentAddressingCheckoutSourcePreflight(t *testing.T) {
{name: "incoming future title", incoming: title, current: ordinary, wantErr: documentaddressing.ErrInvalidTitle},
{name: "current future spec", incoming: ordinary, current: future, wantErr: treenode.ErrSpecTooNew},
{name: "current future title", incoming: ordinary, current: title, wantErr: documentaddressing.ErrInvalidTitle},
- {name: "mode before source", incoming: future, current: ordinary, config: `{"documentAddressingVersion":3}`, wantErr: documentaddressing.ErrUnsupported},
- {name: "floor before source", incoming: future, current: ordinary,
- floor: `{"version":1,"notebook":"` + checkoutSourceBox + `","minimumMode":3}`, wantErr: documentaddressing.ErrUnsupported},
+ {name: "retired mode does not bypass source", incoming: future, current: ordinary, config: `{"documentAddressingVersion":3}`, wantErr: treenode.ErrSpecTooNew},
+ {name: "retired floor does not bypass source", incoming: future, current: ordinary,
+ floor: `{"version":1,"notebook":"` + checkoutSourceBox + `","minimumMode":3}`, wantErr: treenode.ErrSpecTooNew},
{name: "ordinary", incoming: ordinary, current: `{"Spec":"2","Properties":{"title":"Old"}}`},
- {name: "literal slash", incoming: slash, current: ordinary, wantErr: slashError},
+ {name: "literal slash", incoming: slash, current: ordinary, wantErr: nil},
{name: "BOM source", incoming: "\xef\xbb\xbf" + ordinary, current: ordinary},
{name: "recover corrupt source", incoming: ordinary, current: `{"Spec":"2","Properties":`},
{name: "asset sy", incoming: future, current: ordinary, document: "assets/" + checkoutSourceDocument},
diff --git a/kernel/model/document_addressing_source_test.go b/kernel/model/document_addressing_source_test.go
index 5b720240cc..666d445e68 100644
--- a/kernel/model/document_addressing_source_test.go
+++ b/kernel/model/document_addressing_source_test.go
@@ -72,14 +72,14 @@ func TestDocumentAddressingRawSourceChanges(t *testing.T) {
t.Fatal(err)
}
writeDocumentAddressingSource(t, source, conflict)
- if err := copyDocumentAddressingFile(source, destination); !errors.Is(err, documentaddressing.ErrModeConflict) {
+ if err := copyDocumentAddressingFile(source, destination); !errors.Is(err, treenode.ErrDocumentTitleSpec) {
t.Fatal("copy used a source changed after batch preflight", err)
}
if actual, _ := os.ReadFile(destination); !bytes.Equal(actual, ordinary) {
t.Fatal("changed incoming source replaced the destination")
}
missing := filepath.Join(box, "20261022130000-parent1", "20261022130000-child01.sy")
- if err := CheckDocumentAddressingFileWrite(missing, conflict, false); !errors.Is(err, documentaddressing.ErrModeConflict) {
+ if err := CheckDocumentAddressingFileWrite(missing, conflict, false); !errors.Is(err, treenode.ErrDocumentTitleSpec) {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Dir(missing)); !os.IsNotExist(err) {
diff --git a/kernel/model/document_addressing_test.go b/kernel/model/document_addressing_test.go
index dde1d0ea86..9dffbba113 100644
--- a/kernel/model/document_addressing_test.go
+++ b/kernel/model/document_addressing_test.go
@@ -7,17 +7,10 @@ import (
"os"
"path/filepath"
"reflect"
- "strings"
"testing"
- "time"
"github.com/88250/gulu"
- "github.com/siyuan-note/dejavu"
- "github.com/siyuan-note/dejavu/cloud"
- "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/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -96,253 +89,6 @@ func TestDocumentAddressingImportTitlePreflight(t *testing.T) {
}
}
-func TestDocumentAddressingBlocksCachedAccessAndConfigRepair(t *testing.T) {
- fixture := setupFileOperationTest(t)
- previousConfDir := util.ConfDir
- util.ConfDir = t.TempDir()
- t.Cleanup(func() { util.ConfDir = previousConfDir })
- boxID := fixture.box.ID
- boxDir := filepath.Join(util.DataDir, boxID)
- configPath := filepath.Join(boxDir, documentaddressing.ConfigPath)
- docPath := filepath.Join(boxDir, fixture.sourcePath)
- source, err := os.ReadFile(docPath)
- if err != nil {
- t.Fatal(err)
- }
- if _, err = filesys.LoadTree(boxID, fixture.sourcePath, util.NewLute()); err != nil {
- t.Fatal(err)
- }
- cache.PutDocIALInBox(fixture.sourcePath, boxID, map[string]string{"title": "cached"})
- data := []byte(`{"name":"future","closed":false,"documentAddressingVersion":3}`)
- if err = os.WriteFile(configPath, data, 0644); err != nil {
- t.Fatal(err)
- }
- for _, removeConfig := range []bool{false, true} {
- if removeConfig {
- if err = os.Remove(configPath); err != nil {
- t.Fatal(err)
- }
- }
- boxes, listErr := listNotebooks(true)
- if listErr != nil || len(boxes) != 1 || !boxes[0].Closed {
- t.Fatalf("unsupported notebook opened: %+v, %v", boxes, listErr)
- }
- if properties := fixture.box.docIAL(fixture.sourcePath); properties != nil {
- t.Fatalf("returned cached properties: %v", properties)
- }
- if _, loadErr := filesys.LoadTree(boxID, fixture.sourcePath, util.NewLute()); !errors.Is(loadErr, documentaddressing.ErrUnsupported) {
- t.Fatal(loadErr)
- }
- if _, _, listErr = fixture.box.Ls("/"); !errors.Is(listErr, documentaddressing.ErrUnsupported) {
- t.Fatal(listErr)
- }
- if saveErr := fixture.box.SaveConf(conf.NewBoxConf()); !errors.Is(saveErr, documentaddressing.ErrUnsupported) {
- t.Fatal(saveErr)
- }
- if _, mountErr := mountBox(boxID); !errors.Is(mountErr, documentaddressing.ErrUnsupported) {
- t.Fatal(mountErr)
- }
- actual, readErr := os.ReadFile(configPath)
- if removeConfig {
- if !errors.Is(readErr, os.ErrNotExist) {
- t.Fatal("missing configuration was repaired")
- }
- } else if readErr != nil || !bytes.Equal(actual, data) {
- t.Fatal("source configuration changed")
- }
- }
- actual, err := os.ReadFile(docPath)
- if err != nil || !bytes.Equal(actual, source) {
- t.Fatal("document changed")
- }
-}
-
-func TestDocumentAddressingRejectsFutureConfigBeforeWrite(t *testing.T) {
- fixture := setupFileOperationTest(t)
- previousConfDir := util.ConfDir
- util.ConfDir = t.TempDir()
- t.Cleanup(func() { util.ConfDir = previousConfDir })
- name := filepath.Join(util.DataDir, fixture.box.ID, documentaddressing.ConfigPath)
- before, err := os.ReadFile(name)
- if err != nil {
- t.Fatal(err)
- }
- if err = fixture.box.saveConf0([]byte(`{"documentAddressingVersion":3}`)); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatal(err)
- }
- after, err := os.ReadFile(name)
- if err != nil || !bytes.Equal(before, after) {
- t.Fatal("rejected configuration was written")
- }
-}
-
-func TestDocumentAddressingSnapshotPreflight(t *testing.T) {
- previousConf := Conf
- Conf = &AppConf{Lang: "en"}
- t.Cleanup(func() { Conf = previousConf })
- for _, marker := range []string{"config", "floor"} {
- t.Run(marker, func(t *testing.T) {
- base := t.TempDir()
- oldConfDir := util.ConfDir
- util.ConfDir = filepath.Join(base, "conf")
- t.Cleanup(func() { util.ConfDir = oldConfDir })
- dataDir := filepath.Join(base, "data")
- repo, err := dejavu.NewRepoWithOptions(dejavu.Options{
- DataPath: dataDir, RepoPath: filepath.Join(base, "repo"), HistoryPath: filepath.Join(base, "history"), TempPath: filepath.Join(base, "temp"),
- DeviceID: "device", DeviceName: "device", DeviceOS: "windows", AESKey: []byte("0123456789abcdef0123456789abcdef"), HiddenDirectoryNames: []string{".siyuan"},
- })
- if err != nil {
- t.Fatal(err)
- }
- const boxID = "20260101120000-abcdefg"
- write := func(name, content string, tick int64) {
- t.Helper()
- name = filepath.Join(dataDir, boxID, name)
- if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(name, []byte(content), 0644); err != nil {
- t.Fatal(err)
- }
- stamp := time.Unix(1700000000+tick, 0)
- if err := os.Chtimes(name, stamp, stamp); err != nil {
- t.Fatal(err)
- }
- }
- config := `{"documentAddressingVersion":3}`
- if marker == "floor" {
- config = `{}`
- write(documentaddressing.FloorPath, `{"version":1,"notebook":"`+boxID+`","minimumMode":3}`, 10)
- }
- write(documentaddressing.ConfigPath, config, 10)
- write("existing.sy", "future source", 10)
- write("added.sy", "future addition", 10)
- snapshot, err := repo.Index("future", false, nil)
- if err != nil {
- t.Fatal(err)
- }
- write(documentaddressing.ConfigPath, `{"name":"legacy"}`, 20)
- write("existing.sy", "legacy source", 20)
- write("keep.sy", "must not be removed", 20)
- if err = os.Remove(filepath.Join(dataDir, boxID, "added.sy")); err != nil {
- t.Fatal(err)
- }
- if marker == "floor" {
- if err = os.Remove(filepath.Join(dataDir, boxID, documentaddressing.FloorPath)); err != nil {
- t.Fatal(err)
- }
- }
- repo.SetCheckoutHooks(documentAddressingCheckoutHooks(repo))
- if _, _, err = repo.Checkout(snapshot.ID, nil); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("preflight result: %v", err)
- }
- for name, want := range map[string]string{documentaddressing.ConfigPath: `{"name":"legacy"}`, "existing.sy": "legacy source", "keep.sy": "must not be removed"} {
- actual, readErr := os.ReadFile(filepath.Join(dataDir, boxID, name))
- if readErr != nil || string(actual) != want {
- t.Fatalf("source %s changed: %s, %v", name, actual, readErr)
- }
- }
- if _, err = os.Stat(filepath.Join(dataDir, boxID, "added.sy")); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("future document written")
- }
- if err = documentaddressing.CheckBox(dataDir, util.ConfDir, boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("incoming requirement not retained: %v", err)
- }
- })
- }
-}
-
-func TestDocumentAddressingSyncPreflightSurvivesTaskCleanup(t *testing.T) {
- full, partial, fullData := prepareAssetDownloadRepoTest(t)
- backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{
- Dir: "main", RepoPath: full.Path, AvailableSize: 1 << 30,
- Local: &cloud.ConfLocal{Endpoint: Conf.LoadSync().Local.Endpoint},
- }})
- remote, err := dejavu.NewRepoWithOptions(dejavu.Options{
- DataPath: full.DataPath, RepoPath: full.Path, HistoryPath: full.HistoryPath, TempPath: full.TempPath,
- DeviceID: full.DeviceID, DeviceName: full.DeviceName, DeviceOS: full.DeviceOS,
- AESKey: Conf.LoadRepo().Key, Cloud: backend, HiddenDirectoryNames: []string{".siyuan"},
- })
- if err != nil {
- t.Fatal(err)
- }
- const boxID = "20261022000100-abcdefg"
- write := func(name, data string, tick int64) {
- t.Helper()
- name = filepath.Join(fullData, boxID, name)
- if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(name, []byte(data), 0644); err != nil {
- t.Fatal(err)
- }
- stamp := time.Unix(1700000000+tick, 0)
- if err := os.Chtimes(name, stamp, stamp); err != nil {
- t.Fatal(err)
- }
- }
- write(documentaddressing.ConfigPath, `{}`, 10)
- write("existing.sy", "legacy", 10)
- write("keep.sy", "retained", 10)
- if _, err = remote.Index("legacy notebook", false, nil); err != nil {
- t.Fatal(err)
- }
- if _, _, err = remote.Sync(nil); err != nil {
- t.Fatal(err)
- }
- if _, _, err = partial.Sync(nil); err != nil {
- t.Fatal(err)
- }
- write(documentaddressing.ConfigPath, `{"documentAddressingVersion":3}`, 20)
- write("existing.sy", "future", 20)
- write("new.sy", "future addition", 20)
- if err = os.Remove(filepath.Join(fullData, boxID, "keep.sy")); err != nil {
- t.Fatal(err)
- }
- if _, err = remote.Index("future notebook", false, nil); err != nil {
- t.Fatal(err)
- }
- if _, _, err = remote.Sync(nil); err != nil {
- t.Fatal(err)
- }
- checkout := startSyncCheckout(partial)
- if checkout == nil {
- t.Fatal("missing checkout task")
- }
- finished := false
- t.Cleanup(func() {
- if !finished {
- var err error
- checkout.finish(partial, &err)
- }
- })
- _, _, err = partial.Sync(nil)
- if !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("task lost preflight: %v", err)
- }
- checkout.finish(partial, &err)
- finished = true
- if _, _, err = partial.RecoverAssetDownloads(nil); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("task cleanup lost preflight: %v", err)
- }
- reopened, err := newRepository()
- if err != nil {
- t.Fatal(err)
- }
- if _, _, err = reopened.RecoverAssetDownloads(nil); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("reopening pending recovery lost preflight: %v", err)
- }
- for name, want := range map[string]string{documentaddressing.ConfigPath: `{}`, "existing.sy": "legacy", "keep.sy": "retained"} {
- actual, readErr := os.ReadFile(filepath.Join(util.DataDir, boxID, name))
- if readErr != nil || string(actual) != want {
- t.Fatalf("rejected sync changed %s: %q, %v", name, actual, readErr)
- }
- }
- if _, err = os.Stat(filepath.Join(util.DataDir, boxID, "new.sy")); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("rejected sync wrote a new document")
- }
-}
-
func TestDocumentAddressingImportChecksBeforeRemapping(t *testing.T) {
fixture := setupFileOperationTest(t)
oldConfDir := util.ConfDir
@@ -366,7 +112,7 @@ func TestDocumentAddressingImportChecksBeforeRemapping(t *testing.T) {
if err = os.WriteFile(filepath.Join(metadata, boxDocMetaName), meta, 0644); err != nil {
t.Fatal(err)
}
- if err = os.WriteFile(filepath.Join(source, sourceBox+".sy"), []byte("unparsed future document"), 0644); err != nil {
+ if err = os.WriteFile(filepath.Join(source, sourceBox+".sy"), []byte(`{"Spec":"999","Properties":{"title":"Future"}}`), 0644); err != nil {
t.Fatal(err)
}
archive := filepath.Join(t.TempDir(), "future.sy.zip")
@@ -385,11 +131,11 @@ func TestDocumentAddressingImportChecksBeforeRemapping(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if _, err = importSY0(archive, fixture.box.ID, "/", whole, false, nil, false); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("import accepted future mode: %v", err)
+ if _, err = importSY0(archive, fixture.box.ID, "/", whole, false, nil, false); !errors.Is(err, treenode.ErrSpecTooNew) {
+ t.Fatalf("import accepted future Spec: %v", err)
}
- if _, err = inspectSYNotebookArchive(archive); !errors.Is(err, documentaddressing.ErrUnsupported) {
- t.Fatalf("bundle inspection accepted future mode: %v", err)
+ if _, err = inspectSYNotebookArchive(archive); err == nil {
+ t.Fatalf("bundle inspection accepted future Spec: %v", err)
}
after, err := os.ReadFile(archive)
if err != nil || !bytes.Equal(before, after) {
@@ -407,95 +153,26 @@ func TestDocumentAddressingImportChecksBeforeRemapping(t *testing.T) {
}
}
-func TestDocumentAddressingImportRemapsOnlyWholeNotebookFloor(t *testing.T) {
- oldData, oldConfDir := util.DataDir, util.ConfDir
- util.DataDir, util.ConfDir = t.TempDir(), t.TempDir()
- t.Cleanup(func() { util.DataDir, util.ConfDir = oldData, oldConfDir })
- const sourceBox, targetBox = "20260101120000-abcdefg", "20260101120001-hijklmn"
- for _, whole := range []bool{false, true} {
- source := t.TempDir()
- metaDir := filepath.Join(source, ".siyuan")
- if err := os.MkdirAll(metaDir, 0755); err != nil {
- t.Fatal(err)
- }
- data := []byte(`{"version":1,"notebook":"` + sourceBox + `","minimumMode":1}`)
- if err := os.WriteFile(filepath.Join(source, documentaddressing.FloorPath), data, 0644); err != nil {
- t.Fatal(err)
- }
- meta, err := json.Marshal(boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: sourceBox})
- if err != nil {
- t.Fatal(err)
- }
- if err = os.WriteFile(filepath.Join(metaDir, boxDocMetaName), meta, 0644); err != nil {
+func TestDocumentAddressingImportIgnoresRetiredFloor(t *testing.T) {
+ for _, source := range []string{`{}`, `{`, `{"minimumMode":999}`, `{"version":1,"notebook":"different","minimumMode":1}`} {
+ root := t.TempDir()
+ name := filepath.Join(root, documentaddressing.FloorPath)
+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
t.Fatal(err)
}
- if err = checkImportedDocumentAddressing(source); err != nil {
+ if err := os.WriteFile(name, []byte(source), 0644); err != nil {
t.Fatal(err)
}
- if err = prepareImportedDocumentAddressing(source, targetBox, whole); err != nil {
+ if err := checkImportedDocumentAddressing(root); err != nil {
t.Fatal(err)
}
- if whole {
- if err = documentaddressing.CheckSource(targetBox, source); err != nil {
- t.Fatalf("identity not remapped: %v", err)
- }
- if err = documentaddressing.CheckSource(sourceBox, source); !errors.Is(err, documentaddressing.ErrInvalid) {
- t.Fatalf("source identity retained: %v", err)
- }
- } else if _, err = os.Stat(filepath.Join(source, documentaddressing.FloorPath)); !errors.Is(err, os.ErrNotExist) {
- t.Fatal("partial import retained source floor")
+ data, err := os.ReadFile(name)
+ if err != nil || string(data) != source {
+ t.Fatal("retired notebook record changed", err)
}
}
}
-func TestDocumentAddressingImportFloorIdentity(t *testing.T) {
- oldData, oldConfDir := util.DataDir, util.ConfDir
- util.DataDir, util.ConfDir = t.TempDir(), t.TempDir()
- t.Cleanup(func() { util.DataDir, util.ConfDir = oldData, oldConfDir })
- const sourceID, otherID = "20260101120000-abcdefg", "20260101120001-hijklmn"
- valid := `{"version":1,"notebook":"` + sourceID + `","minimumMode":2}`
- for _, test := range []struct {
- name, directory, boxDocID, floor string
- wantErr error
- }{
- {name: "named export", directory: "Named notebook", floor: valid},
- {name: "ID directory", directory: sourceID, floor: valid},
- {name: "directory identity conflict", directory: otherID, floor: valid, wantErr: documentaddressing.ErrInvalid},
- {name: "box document identity conflict", directory: "Named notebook", boxDocID: otherID, floor: valid, wantErr: documentaddressing.ErrInvalid},
- {name: "invalid JSON", directory: "Named notebook", floor: `{`, wantErr: documentaddressing.ErrInvalid},
- {name: "invalid identity", directory: "Named notebook", floor: strings.ReplaceAll(valid, sourceID, "invalid"), wantErr: documentaddressing.ErrInvalid},
- {name: "unknown format", directory: "Named notebook", floor: strings.Replace(valid, `"version":1`, `"version":2`, 1), wantErr: documentaddressing.ErrInvalid},
- {name: "unsupported mode", directory: "Named notebook", floor: strings.Replace(valid, `"minimumMode":2`, `"minimumMode":3`, 1), wantErr: documentaddressing.ErrUnsupported},
- {name: "duplicate identity", directory: "Named notebook", floor: strings.Replace(valid, `"version":1`, `"version":1,"notebook":"`+otherID+`"`, 1), wantErr: documentaddressing.ErrInvalid},
- } {
- t.Run(test.name, func(t *testing.T) {
- root := filepath.Join(t.TempDir(), test.directory)
- if err := os.MkdirAll(filepath.Join(root, ".siyuan"), 0755); err != nil {
- t.Fatal(err)
- }
- floorPath := filepath.Join(root, documentaddressing.FloorPath)
- if err := os.WriteFile(floorPath, []byte(test.floor), 0644); err != nil {
- t.Fatal(err)
- }
- if test.boxDocID != "" {
- data, err := json.Marshal(boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: test.boxDocID})
- if err != nil {
- t.Fatal(err)
- }
- if err = os.WriteFile(filepath.Join(root, ".siyuan", boxDocMetaName), data, 0644); err != nil {
- t.Fatal(err)
- }
- }
- if err := checkImportedDocumentAddressing(root); !errors.Is(err, test.wantErr) {
- t.Fatalf("import identity: got %v, want %v", err, test.wantErr)
- }
- if data, err := os.ReadFile(floorPath); err != nil || string(data) != test.floor {
- t.Fatalf("source metadata changed: %q, %v", data, err)
- }
- })
- }
-}
-
func TestDocumentAddressingDataImportRejectsBeforeAnyWrite(t *testing.T) {
fixture := setupFileOperationTest(t)
oldConfDir := util.ConfDir
@@ -512,11 +189,12 @@ func TestDocumentAddressingDataImportRejectsBeforeAnyWrite(t *testing.T) {
if err := os.WriteFile(filepath.Join(install, "ordinary.txt"), []byte("other batch content"), 0644); err != nil {
t.Fatal(err)
}
- if _, err := validateImportedNotebookIdentities(install); !errors.Is(err, documentaddressing.ErrUnsupported) {
+
+ if err := os.WriteFile(filepath.Join(install, fixture.box.ID, "20261022120001-future1.sy"), []byte(`{"Spec":"999","Properties":{"title":"Future"}}`), 0644); err != nil {
t.Fatal(err)
}
err := applyDataImport(t.TempDir(), install, func(string, string) error { t.Fatal("batch began writing"); return nil })
- if !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatal(err)
}
}
@@ -526,12 +204,12 @@ func TestDocumentAddressingNotebookHistoryPreservesSource(t *testing.T) {
oldConfDir := util.ConfDir
util.ConfDir = t.TempDir()
t.Cleanup(func() { util.ConfDir = oldConfDir })
- name := filepath.Join(util.WorkspaceDir, historyPath, documentaddressing.ConfigPath)
- source := []byte(`{"name":"future","documentAddressingVersion":3}`)
+ name := filepath.Join(util.WorkspaceDir, historyPath, "20261022120001-future1.sy")
+ source := []byte(`{"Spec":"999","Properties":{"title":"Future"}}`)
if err := os.WriteFile(name, source, 0644); err != nil {
t.Fatal(err)
}
- if err := RollbackNotebookHistory(historyPath); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if err := RollbackNotebookHistory(historyPath); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {
@@ -543,7 +221,7 @@ func TestDocumentAddressingNotebookHistoryPreservesSource(t *testing.T) {
}
}
-func TestDocumentAddressingNativeExportPreservesFloor(t *testing.T) {
+func TestDocumentAddressingNativeExportLeavesRetiredFloor(t *testing.T) {
const boxID = "20260101120000-abcdefg"
setupExportRelatedTest(t, boxID)
name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)
@@ -560,9 +238,13 @@ func TestDocumentAddressingNativeExportPreservesFloor(t *testing.T) {
}
exported := ExportNotebookSY(boxID)
archive := openExportArchive(t, exported)
- data := readArchiveFile(t, archive, name+"/"+documentaddressing.FloorPath)
- if data != string(source) {
- t.Fatal("export lost capability floor")
+ for _, file := range archive.File {
+ if file.Name == name+"/"+documentaddressing.FloorPath {
+ t.Fatal("export regenerated a retired record")
+ }
+ }
+ if data, err := os.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)); err != nil || !bytes.Equal(data, source) {
+ t.Fatal("export changed notebook record", err)
}
archivePath, err := exportedFilePath(exported)
if err != nil {
diff --git a/kernel/model/document_create.go b/kernel/model/document_create.go
index 68b8a9af0f..6448914eab 100644
--- a/kernel/model/document_create.go
+++ b/kernel/model/document_create.go
@@ -14,7 +14,6 @@ import (
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
- "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"
@@ -62,8 +61,6 @@ func documentCreateFailure(err error, state, id, stage string, completed []strin
var addressingErr *DocumentAddressingError
if errors.As(err, &addressingErr) {
reason = addressingErr.Reason
- } else if errors.Is(err, documentaddressing.ErrModeConflict) {
- reason = "modeConflict"
}
return &DocumentCreateFailure{Reason: reason, CommitState: state, ID: id, Stage: stage,
Completed: completed, Cause: err}
diff --git a/kernel/model/document_legacy.go b/kernel/model/document_legacy.go
new file mode 100644
index 0000000000..1e40d81fdb
--- /dev/null
+++ b/kernel/model/document_legacy.go
@@ -0,0 +1,137 @@
+package model
+
+import (
+ "errors"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func legacyDocumentPathError(reason string, candidates *treenode.LegacyDocumentCandidates) error {
+ cause := documentaddressing.ErrPathAmbiguous
+ if reason == "legacyPathUnsupported" {
+ cause = documentaddressing.ErrLegacyPathUnsupported
+ }
+ ret := &DocumentAddressingError{Reason: reason, Cause: cause, CleanIDs: []string{}, UnsupportedIDs: []string{}}
+ for _, candidate := range candidates.Clean {
+ ret.CleanIDs = append(ret.CleanIDs, candidate.ID)
+ }
+ for _, candidate := range candidates.Unsupported {
+ ret.UnsupportedIDs = append(ret.UnsupportedIDs, candidate.ID)
+ }
+ return ret
+}
+
+func legacyDocumentCandidates(boxID string, hpaths []string) (map[string]*treenode.LegacyDocumentCandidates, error) {
+ if err := checkDocumentPathNotebook(boxID); err != nil {
+ return nil, err
+ }
+ ret, err := treenode.ClassifyLegacyDocumentPaths(boxID, hpaths)
+ if err != nil {
+ return nil, documentAddressingError("indexUnavailable", err)
+ }
+ return ret, nil
+}
+
+// ResolveLegacyDocumentPath requires one unambiguous, structurally clean target.
+// Root paths retain their existing meaning. Callers acting on the result must
+// still use the normal source-operation checks for moves, creates and reads.
+func ResolveLegacyDocumentPath(boxID, hpath string, create bool) (*treenode.BlockTree, error) {
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ return nil, err
+ }
+ defer ReleaseEncryptedBoxOperation(boxID)
+ hpathRefresh.Lock()
+ defer hpathRefresh.Unlock()
+ hpaths := []string{hpath}
+ if hpath == "/" {
+ hpaths = nil
+ }
+ groups, err := legacyDocumentCandidates(boxID, hpaths)
+ if err != nil {
+ return nil, err
+ }
+ if hpath == "/" {
+ return &treenode.BlockTree{BoxID: boxID, Path: "/", Type: "d"}, nil
+ }
+ candidates := groups[hpath]
+ if len(candidates.Unsupported) > 0 || len(candidates.Clean) > 1 {
+ if !create && len(candidates.Clean) == 0 {
+ return nil, legacyDocumentPathError("legacyPathUnsupported", candidates)
+ }
+ return nil, legacyDocumentPathError("pathAmbiguous", candidates)
+ }
+ if len(candidates.Clean) == 0 {
+ return nil, nil
+ }
+ return candidates.Clean[0], nil
+}
+
+// legacyDocumentCreationParents checks every requested parent prefix before any
+// source is created. A matching parent ID selects its real clean ancestor chain;
+// it never bypasses slash/empty-title conflicts. The caller holds hpathRefresh.
+func legacyDocumentCreationParents(boxID, hpath, parentID string) (map[string]*treenode.BlockTree, error) {
+ hpath = util.TrimSpaceInPath(strings.TrimSuffix(hpath, ".sy"))
+ parts := strings.Split(hpath, "/")[1:]
+ hpaths := []string{}
+ for i := 1; i < len(parts); i++ {
+ hpaths = append(hpaths, "/"+strings.Join(parts[:i], "/"))
+ }
+ groups, err := legacyDocumentCandidates(boxID, hpaths)
+ if err != nil {
+ return nil, err
+ }
+ ret := map[string]*treenode.BlockTree{}
+ var preferred *treenode.BlockTree
+ if len(hpaths) > 0 && !IsBoxDoc(boxID, parentID) {
+ for _, candidate := range groups[hpaths[len(hpaths)-1]].Clean {
+ if candidate.ID == parentID {
+ preferred = candidate
+ }
+ }
+ }
+ for _, hp := range hpaths {
+ candidates := groups[hp]
+ if len(candidates.Unsupported) > 0 {
+ return nil, legacyDocumentPathError("pathAmbiguous", candidates)
+ }
+ if preferred != nil {
+ for _, candidate := range candidates.Clean {
+ if candidate.ID == preferred.ID || strings.HasPrefix(preferred.Path, strings.TrimSuffix(candidate.Path, ".sy")+"/") {
+ ret[hp] = candidate
+ break
+ }
+ }
+ if ret[hp] == nil {
+ return nil, documentAddressingError("indexUnavailable", treenode.ErrDocumentMetadataUnavailable)
+ }
+ } else if len(candidates.Clean) > 1 {
+ return nil, legacyDocumentPathError("pathAmbiguous", candidates)
+ } else if len(candidates.Clean) == 1 {
+ ret[hp] = candidates.Clean[0]
+ }
+ }
+ return ret, nil
+}
+
+func cleanupRetiredDocumentAddressing() error {
+ if util.ReadOnly {
+ return nil
+ }
+ return documentaddressing.CleanupRetiredRecords(util.ConfDir)
+}
+
+// LegacyPathFailure exposes only addressing failures that the legacy HTTP
+// result types can represent. Other source/authentication errors remain errors.
+func LegacyPathFailure(err error) (*DocumentAddressingError, bool) {
+ var failure *DocumentAddressingError
+ if errors.As(err, &failure) {
+ switch failure.Reason {
+ case "pathAmbiguous", "legacyPathUnsupported", "indexUnavailable":
+ return failure, true
+ }
+ }
+ return nil, false
+}
diff --git a/kernel/model/document_legacy_cleanup_test.go b/kernel/model/document_legacy_cleanup_test.go
new file mode 100644
index 0000000000..7345c030ac
--- /dev/null
+++ b/kernel/model/document_legacy_cleanup_test.go
@@ -0,0 +1,49 @@
+package model
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestRetiredDocumentAddressingCleanupRespectsReadOnly(t *testing.T) {
+ previousConf, previousReadOnly := util.ConfDir, util.ReadOnly
+ util.ConfDir = t.TempDir()
+ t.Cleanup(func() { util.ConfDir, util.ReadOnly = previousConf, previousReadOnly })
+ file := filepath.Join(util.ConfDir, "document-addressing.json")
+ if err := os.WriteFile(file, []byte("original"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ util.ReadOnly = true
+ if err := cleanupRetiredDocumentAddressing(); err != nil {
+ t.Fatal(err)
+ }
+ if data, err := os.ReadFile(file); err != nil || string(data) != "original" {
+ t.Fatal("read-only startup changed workspace", err)
+ }
+ util.ReadOnly = false
+ if err := cleanupRetiredDocumentAddressing(); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(file); !os.IsNotExist(err) {
+ t.Fatal("startup did not retire local record", err)
+ }
+}
+
+func TestFixedDocumentAddressingMarkerPersists(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ name := filepath.Join(util.DataDir, fixture.box.ID, documentaddressing.ConfigPath)
+ configuration := fixture.box.GetConf()
+ if err := fixture.box.SaveConf(configuration); err != nil {
+ t.Fatal(err)
+ }
+ var fields map[string]json.RawMessage
+ data, err := os.ReadFile(name)
+ if err != nil || json.Unmarshal(data, &fields) != nil || string(fields["documentAddressingVersion"]) != "2" {
+ t.Fatal("configuration lost fixed addressing marker", err)
+ }
+}
diff --git a/kernel/model/document_legacy_create.go b/kernel/model/document_legacy_create.go
new file mode 100644
index 0000000000..037326c34c
--- /dev/null
+++ b/kernel/model/document_legacy_create.go
@@ -0,0 +1,63 @@
+package model
+
+import (
+ "os"
+ "path/filepath"
+
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// createLegacyDocuments keeps path selection and source commits inside the same
+// coordination boundary as identity creation. Raw source writers are checked
+// again under the source-write lock immediately before each document write.
+func createLegacyDocuments(boxID, hpath, content, parentID, id string, titleEmpty bool, attributes map[string]string) (string, error) {
+ flushLock.Lock()
+ defer flushLock.Unlock()
+ for _, queued := range takeQueuedTransactions() {
+ flushTx(queued)
+ }
+ hpathRefresh.Lock()
+ defer hpathRefresh.Unlock()
+ parents, err := legacyDocumentCreationParents(boxID, hpath, parentID)
+ if err != nil {
+ return "", err
+ }
+ return createDocsByHPath0(boxID, hpath, content, parentID, id, titleEmpty,
+ func(boxID, p, title, dom string, empty bool) (*parse.Tree, error) {
+ validation, err := validateCreateDoc(boxID, p, title, empty)
+ if err != nil {
+ return nil, err
+ }
+ var attrs map[string]string
+ if validation.id == id {
+ attrs = attributes
+ }
+ tree, err := buildCreateDocTree(boxID, validation, dom, attrs)
+ if err != nil {
+ return nil, err
+ }
+ tx := &Transaction{DoOperations: []*Operation{{Action: "create", Tree: tree}}, fromAPI: true}
+ tx.writeTransactionTree = func(source *parse.Tree) error {
+ return writeTreeUpsertQueueWithPreflight(source, tx.treeIndexChanges(source), func() error {
+ current, err := legacyDocumentCreationParents(boxID, hpath, parentID)
+ if err != nil {
+ return err
+ }
+ for hp, expected := range parents {
+ if actual := current[hp]; actual == nil || expected.ID != actual.ID || expected.Path != actual.Path {
+ return documentAddressingError("indexUnavailable", treenode.ErrDocumentMetadataUnavailable)
+ }
+ }
+ return nil
+ })
+ }
+ if err = performTxSyncLocked(tx); err != nil {
+ if _, statErr := os.Stat(filepath.Join(util.DataDir, boxID, p)); os.IsNotExist(statErr) {
+ treenode.RemoveBlockTreesByRootID(boxID, tree.ID)
+ }
+ }
+ return tree, err
+ }, parents)
+}
diff --git a/kernel/model/document_legacy_test.go b/kernel/model/document_legacy_test.go
new file mode 100644
index 0000000000..a2baac1cce
--- /dev/null
+++ b/kernel/model/document_legacy_test.go
@@ -0,0 +1,151 @@
+//go:build fts5
+
+package model
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path"
+ "reflect"
+ "strings"
+ "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/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestLegacyDocumentPaths(t *testing.T) {
+ if os.Getenv("SIYUAN_TEST_LEGACY_DOCUMENT_PATHS") != "1" {
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestLegacyDocumentPaths$", "-test.v")
+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_LEGACY_DOCUMENT_PATHS=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("%v\n%s", err, output)
+ }
+ return
+ }
+ prepareHPathRefreshTest(t)
+ t.Cleanup(backgroundRefreshWaitGroup.Wait)
+ box := &Box{ID: ast.NewNodeID()}
+ boxConf := conf.NewBoxConf()
+ boxConf.Name = "Legacy"
+ boxConf.Closed = false
+ if err := box.SaveConf(boxConf); err != nil {
+ t.Fatal(err)
+ }
+ plain := newHPathTestDoc(t, box.ID, "/", "Plain", 1)
+ parent := newHPathTestDoc(t, box.ID, "/", "A", 1)
+ child := newHPathTestDoc(t, box.ID, parent.Path, "B", 1)
+ literal := newHPathTestDoc(t, box.ID, "/", "A/B", 1)
+ newHPathTestDoc(t, box.ID, literal.Path, "C", 1)
+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ hp string
+ count int
+ want error
+ }{
+ {"/Plain", 1, nil}, {"/missing", 0, nil}, {"/A/B", 0, documentaddressing.ErrPathAmbiguous}, {"/A/B/C", 0, documentaddressing.ErrLegacyPathUnsupported},
+ } {
+ ids, err := GetIDsByHPath(test.hp, box.ID)
+ if !errors.Is(err, test.want) || len(ids) != test.count {
+ t.Fatalf("%s: %v %v", test.hp, ids, err)
+ }
+ }
+ before, err := archiveDirectoryFiles(util.DataDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, hp := range []string{"/A/B/New", "/A/B/C/M/New"} {
+ if _, err := CreateWithMarkdown("", box.ID, hp, "body", child.ID, ast.NewNodeID(), false, "", nil); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal("collision accepted", hp, err)
+ }
+ }
+ after, err := archiveDirectoryFiles(util.DataDir)
+ if err != nil || !reflect.DeepEqual(before, after) {
+ t.Fatal("rejected create wrote files", err)
+ }
+ if err := RenameDoc(box.ID, literal.Path, "Other/slash"); err != nil {
+ t.Fatal(err)
+ }
+ ids, err := GetIDsByHPath("/A/B", box.ID)
+ if err != nil || !reflect.DeepEqual(ids, []string{child.ID}) {
+ t.Fatal(ids, err)
+ }
+ before, _ = archiveDirectoryFiles(util.DataDir)
+ if _, err := CreateWithMarkdown("", box.ID, "/Other/slash/M/New", "", "", ast.NewNodeID(), false, "", nil); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal("missing early prefix bypassed slash collision", err)
+ }
+ after, _ = archiveDirectoryFiles(util.DataDir)
+ if !reflect.DeepEqual(before, after) {
+ t.Fatal("late prefix collision wrote files")
+ }
+ id, err := CreateWithMarkdown("", box.ID, "/Plain/Child", "body", "", ast.NewNodeID(), false, "", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bt := treenode.GetBlockTreeInExactBox(id, box.ID); bt == nil || path.Dir(bt.Path) != strings.TrimSuffix(plain.Path, ".sy") {
+ t.Fatal("clean parent changed", bt)
+ }
+ first := newHPathTestDoc(t, box.ID, "/", "Duplicate", 1)
+ second := newHPathTestDoc(t, box.ID, "/", "Duplicate", 1)
+ ids, err = GetIDsByHPath("/Duplicate", box.ID)
+ if err != nil || len(ids) != 2 {
+ t.Fatal(ids, err)
+ }
+ if _, err := ResolveLegacyDocumentPath(box.ID, "/Duplicate", false); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal("single-target lookup selected a duplicate", err)
+ }
+ if _, err := CreateWithMarkdown("", box.ID, "/Duplicate/Child", "", "", ast.NewNodeID(), false, "", nil); !errors.Is(err, documentaddressing.ErrPathAmbiguous) {
+ t.Fatal(err)
+ }
+ id, err = CreateWithMarkdown("", box.ID, "/Duplicate/Child", "", second.ID, ast.NewNodeID(), false, "", nil)
+ if err != nil {
+ t.Fatal("parent ID failed to disambiguate", err)
+ }
+ if bt := treenode.GetBlockTreeInExactBox(id, box.ID); bt == nil || path.Dir(bt.Path) != strings.TrimSuffix(second.Path, ".sy") {
+ t.Fatal("wrong duplicate parent", bt, first.ID)
+ }
+ fileTree := *Conf.FileTree.Load()
+ fileTree.BoxDocEnabled = true
+ Conf.FileTree.Store(&fileTree)
+ if ids, err := GetIDsByHPath("/", box.ID); err != nil || len(ids) != 1 || ids[0] != box.ID {
+ t.Fatal("logical notebook root changed", ids, err)
+ }
+ if root, err := ResolveLegacyDocumentPath(box.ID, "/", false); err != nil || root == nil || root.Path != "/" {
+ t.Fatal(root, err)
+ }
+ for _, state := range []string{"building", "pending"} {
+ if state == "building" {
+ if err := treenode.SetDocumentMetadataState(box.ID, "building"); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := treenode.BeginDocumentMetadataRecovery(treenode.GetBlockTreeInExactBox(plain.ID, box.ID)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before, _ = archiveDirectoryFiles(util.DataDir)
+ if ids, err := GetIDsByHPath("/missing", box.ID); err == nil || len(ids) != 0 {
+ t.Fatal("unready index was empty", ids, err)
+ }
+ if _, err := CreateWithMarkdown("", box.ID, "/New", "", "", ast.NewNodeID(), false, "", nil); err == nil {
+ t.Fatal("unready index admitted creation")
+ }
+ after, _ = archiveDirectoryFiles(util.DataDir)
+ if !reflect.DeepEqual(before, after) {
+ t.Fatal("unready index wrote files")
+ }
+ }
+}
diff --git a/kernel/model/document_move.go b/kernel/model/document_move.go
index 2da3f8aab2..867b982eef 100644
--- a/kernel/model/document_move.go
+++ b/kernel/model/document_move.go
@@ -27,7 +27,7 @@ func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenode
if err != nil {
return nil, err
}
- mode, err := filesys.DocumentAddressingMode(toBox)
+ _, err = filesys.DocumentAddressingMode(toBox)
if err != nil {
return nil, err
}
@@ -44,7 +44,7 @@ func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenode
var documents []*treenode.BlockTree
err = filesys.WalkTreeSnapshots(fromBox, paths, func(tree *parse.Tree) error {
sourcePath := tree.Path
- if err := treenode.CheckSpecForMode(tree, mode); err != nil {
+ if err := treenode.CheckSpec(tree); err != nil {
return documentAddressingError("targetModeUnsupported", err)
}
relative := strings.TrimPrefix(sourcePath, path.Dir(fromPath)+"/")
diff --git a/kernel/model/document_path.go b/kernel/model/document_path.go
index 552e7ffd01..ad0b5d7453 100644
--- a/kernel/model/document_path.go
+++ b/kernel/model/document_path.go
@@ -32,8 +32,10 @@ func documentParentDisplayPath(boxID, documentPath string) (string, error) {
}
type DocumentAddressingError struct {
- Reason string
- Cause error
+ Reason string
+ Cause error
+ CleanIDs []string
+ UnsupportedIDs []string
}
func (err *DocumentAddressingError) Error() string { return err.Cause.Error() }
@@ -121,9 +123,6 @@ func resolveDocumentPath(boxID string, parentID *string, segments []string) (*tr
}
func normalizeDocumentTitle(title string) string {
- if documentaddressing.DefaultMode() == 1 {
- return normalizeDocTitle(title)
- }
return normalizeTitleText(title)
}
@@ -138,18 +137,6 @@ func appendDocumentHPath(parent, title string) string {
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 校验新协议的完整输入,不通过截断、修剪或字符替换悄悄改变标题。
func ValidateDocumentTitle(format, text string) error {
if format != "plain" {
diff --git a/kernel/model/document_plan.go b/kernel/model/document_plan.go
index ba86b0b96a..40cdf12cee 100644
--- a/kernel/model/document_plan.go
+++ b/kernel/model/document_plan.go
@@ -10,7 +10,6 @@ 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"
)
@@ -58,7 +57,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 && documentaddressing.DefaultMode() == 1
+ ret.missing, ret.legacy = "create", false
if request.Now.IsZero() {
request.Now = time.Now()
}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 5ac8d1dffd..3c9fcf3450 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -2866,10 +2866,6 @@ func exportSYZipWithConfig(boxID, rootDirPath, baseFolderName string, docPaths [
logging.LogErrorf("write export notebook conf failed: %s", writeErr)
return
}
- if copyErr := copyExportedDocumentAddressing(boxID, exportDir); copyErr != nil {
- logging.LogErrorf("copy export notebook addressing metadata failed: %s", copyErr)
- return
- }
sourceBoxDocMetaPath := boxDocMetaPath(boxID)
if filelock.IsExist(sourceBoxDocMetaPath) {
if copyErr := filelock.Copy(sourceBoxDocMetaPath, filepath.Join(confDir, boxDocMetaName)); copyErr != nil {
diff --git a/kernel/model/file.go b/kernel/model/file.go
index ed9a03eddb..829086a7ee 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1373,9 +1373,10 @@ 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 {
+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {
return
}
+ defer ReleaseEncryptedBoxOperation(boxID)
createDocLock.Lock()
defer createDocLock.Unlock()
@@ -1413,14 +1414,7 @@ func CreateWithMarkdown(tags, boxID, hPath, md, parentID, id string, withMath bo
if id == "" {
id = ast.NewNodeID()
}
- retID, err = createDocsByHPath0(box.ID, hPath, dom, parentID, id, titleEmpty,
- func(boxID, p, title, content string, empty bool) (*parse.Tree, error) {
- var attrs map[string]string
- if tags != "" && strings.TrimSuffix(path.Base(p), ".sy") == id {
- attrs = map[string]string{"tags": tags}
- }
- return createDoc0(boxID, p, title, content, empty, true, attrs)
- })
+ retID, err = createLegacyDocuments(box.ID, hPath, dom, parentID, id, titleEmpty, map[string]string{"tags": tags})
if err != nil {
return
}
@@ -1627,29 +1621,38 @@ func GetFullHPathByID(id string) (hPath string, err error) {
return
}
-func GetIDsByHPath(hpath, boxID string) (ret []string, err error) {
- if err = CheckLegacyDocumentPath(boxID); err != nil {
- return
+// GetIDsByHPath returns every clean exact match and rejects slash/empty-title collisions.
+func GetIDsByHPath(hpath, boxID string) ([]string, error) {
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ return nil, err
}
- ret = []string{}
- if IsBoxDocEnabled() && "/" == hpath {
- if box := Conf.Box(boxID); nil != box {
- return []string{box.ID}, nil
- }
+ defer ReleaseEncryptedBoxOperation(boxID)
+ hpathRefresh.Lock()
+ defer hpathRefresh.Unlock()
+ hpaths := []string{hpath}
+ if IsBoxDocEnabled() && hpath == "/" {
+ hpaths = nil
}
- roots := treenode.GetBlockTreeRootsByHPath(boxID, hpath)
- if 1 > len(roots) {
- return
+ groups, err := legacyDocumentCandidates(boxID, hpaths)
+ if err != nil {
+ return nil, err
}
-
- for _, root := range roots {
- ret = append(ret, root.ID)
+ if IsBoxDocEnabled() && hpath == "/" {
+ return []string{boxID}, nil
}
- ret = gulu.Str.RemoveDuplicatedElem(ret)
- if 1 > len(ret) {
- ret = []string{}
+ candidates := groups[hpath]
+ if len(candidates.Unsupported) > 0 {
+ reason := "legacyPathUnsupported"
+ if len(candidates.Clean) > 0 {
+ reason = "pathAmbiguous"
+ }
+ return nil, legacyDocumentPathError(reason, candidates)
}
- return
+ ret := []string{}
+ for _, candidate := range candidates.Clean {
+ ret = append(ret, candidate.ID)
+ }
+ return ret, nil
}
type moveDocsRefreshKey struct {
diff --git a/kernel/model/heading.go b/kernel/model/heading.go
index 93bdea8a67..37f2be14cd 100644
--- a/kernel/model/heading.go
+++ b/kernel/model/heading.go
@@ -28,7 +28,6 @@ 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"
@@ -368,12 +367,7 @@ func Heading2Doc(srcHeadingID, targetBoxID, targetPath, previousPath string, toT
box := Conf.Box(targetBoxID)
headingText := getNodeRefText0(headingNode, Conf.Editor.Load().BlockRefDynamicAnchorTextMaxLen, true)
- if documentaddressing.DefaultMode() == 2 {
- headingText = normalizeDocumentTitle(headingText)
- } else if strings.Contains(headingText, "/") {
- headingText = strings.ReplaceAll(headingText, "/", "_")
- util.PushMsg(Conf.language(246), 7000)
- }
+ headingText = normalizeDocumentTitle(headingText)
moveToRoot := "/" == targetPath
toHP := "/" + headingText
diff --git a/kernel/model/import.go b/kernel/model/import.go
index 89e6adfee1..c27efc0b3e 100644
--- a/kernel/model/import.go
+++ b/kernel/model/import.go
@@ -29,7 +29,6 @@ import (
"image/png"
"io/fs"
"maps"
- "net/url"
"os"
"path"
"path/filepath"
@@ -53,7 +52,6 @@ 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"
@@ -577,9 +575,6 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s
} else {
createdBoxID = boxID
}
- if err = prepareImportedDocumentAddressing(unzipRootPath, boxID, createNotebook); err != nil {
- return
- }
encryptedTarget := IsEncryptedBox(boxID)
toPath = normalizeBoxDocTarget(boxID, toPath)
@@ -1637,11 +1632,6 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
if "" != yfmTitle {
title = yfmTitle
}
- if documentaddressing.DefaultMode() == 1 {
- if unescapedTitle, unescapeErr := url.PathUnescape(title); unescapeErr == nil {
- title = unescapedTitle
- }
- }
parentDisplay := baseHPath
if curRelPath != "/" {
parentDisplay = appendDocumentHPath(baseHPath, strings.TrimPrefix(path.Dir(externalPath), "/"))
@@ -1795,11 +1785,6 @@ func importFromLocalPath(boxID, localPath string, toPath string, skipRoot bool)
if "" != yfmTitle {
title = yfmTitle
}
- if documentaddressing.DefaultMode() == 1 {
- if unescapedTitle, unescapeErr := url.PathUnescape(title); unescapeErr == nil {
- title = unescapedTitle
- }
- }
updated := yfmUpdated
fname := path.Base(targetPath)
targetPath = strings.ReplaceAll(targetPath, fname, id+".sy")
diff --git a/kernel/model/listitem.go b/kernel/model/listitem.go
index 8a4ca14763..5a30b2b5ea 100644
--- a/kernel/model/listitem.go
+++ b/kernel/model/listitem.go
@@ -22,7 +22,6 @@ 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"
@@ -47,11 +46,7 @@ func ListItem2Doc(srcListItemID, targetBoxID, targetPath, previousPath string, t
box := Conf.Box(targetBoxID)
listItemText := sql.GetContainerText(listItemNode)
- if documentaddressing.DefaultMode() == 2 {
- listItemText = normalizeDocumentTitle(listItemText)
- } else {
- listItemText = util.FilterFileName(listItemText)
- }
+ listItemText = normalizeDocumentTitle(listItemText)
moveToRoot := "/" == targetPath
toHP := "/" + listItemText
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index 9aa587f914..cc2928bcc4 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -284,15 +284,6 @@ func RemoveBox(boxID string) (err error) {
if statErr != nil && localExists {
return statErr
}
- unsupportedAddressing := false
- // 目录已删除时只清理运行时状态,不用本机下界记录重新创建笔记本。
- if localExists {
- addressingErr := filesys.CheckDocumentAddressing(boxID)
- unsupportedAddressing = errors.Is(addressingErr, documentaddressing.ErrUnsupported)
- if addressingErr != nil && !unsupportedAddressing {
- return addressingErr
- }
- }
if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {
err = errors.New(Conf.language(239))
return
@@ -347,10 +338,8 @@ func RemoveBox(boxID string) (err error) {
defer databaseIndexDataLock.Unlock()
createDocLock.Lock()
defer createDocLock.Unlock()
- if !unsupportedAddressing {
- if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {
- return
- }
+ if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {
+ return
}
if !isEncrypted {
unmount0(boxID)
@@ -374,12 +363,7 @@ func RemoveBox(boxID string) (err error) {
logging.LogErrorf("gen sync history failed: %s", err)
return
}
- if !isEncrypted && unsupportedAddressing {
- if err = backupUnsupportedNotebookAttributeViews(historyDir); err != nil {
- return
- }
- }
- if !isEncrypted && !unsupportedAddressing {
+ if !isEncrypted {
pages, walkErr := pagedPathsWithError(localPath, 32)
if walkErr != nil {
return walkErr
@@ -387,6 +371,12 @@ func RemoveBox(boxID string) (err error) {
for _, paths := range pages {
for _, filename := range paths {
tree, loadErr := loadTree(filename, util.NewLute())
+ if errors.Is(loadErr, treenode.ErrSpecTooNew) || errors.Is(loadErr, documentaddressing.ErrInvalidTitle) {
+ if err = backupUnsupportedNotebookAttributeViews(historyDir); err != nil {
+ return err
+ }
+ continue
+ }
if loadErr != nil {
return loadErr
}
@@ -658,19 +648,18 @@ func mountBox(boxID string) (alreadyMount bool, err error) {
var userGuideIDs = []string{"20210808180117-6v0mkxr", "20210808180117-czj9bvb", "20211226090932-5lcq56f", "20240530133126-axarxgx"}
func checkMountDocumentAddressing(boxID string) error {
- if !IsUserGuide(boxID) {
- return filesys.CheckDocumentAddressing(boxID)
+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {
+ return err
}
- // 用户显式重开已删除的指南时,先校验内置副本及本机能力下界,复制后再迁移。
- // 已存在的指南仍须先通过源数据检查,不能借恢复流程覆盖不兼容或损坏的数据。
- if _, err := os.Lstat(filepath.Join(util.DataDir, boxID)); err == nil {
- if err = filesys.CheckDocumentAddressing(boxID); err != nil {
+ if IsUserGuide(boxID) {
+ source := filepath.Join(util.WorkingDir, "guide", boxID)
+ if _, err := os.Stat(source); err == nil {
+ return checkDocumentAddressingCopy(source, boxID)
+ } else if !os.IsNotExist(err) {
return err
}
- } else if !os.IsNotExist(err) {
- return err
}
- return documentaddressing.CheckImport(util.DataDir, util.ConfDir, boxID, filepath.Join(util.WorkingDir, "guide", boxID))
+ return nil
}
func IsUserGuide(boxID string) bool {
diff --git a/kernel/model/mount_user_guide_test.go b/kernel/model/mount_user_guide_test.go
index d39013f003..13186ee2ec 100644
--- a/kernel/model/mount_user_guide_test.go
+++ b/kernel/model/mount_user_guide_test.go
@@ -15,6 +15,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/task"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -73,8 +74,8 @@ func TestMountUserGuideAfterDeletion(t *testing.T) {
}
data, err = os.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath))
var fields map[string]any
- if err != nil || json.Unmarshal(data, &fields) != nil || fields["documentAddressingVersion"] != float64(2) {
- t.Fatalf("restored guide was not migrated: %s, %v", data, err)
+ if err != nil || json.Unmarshal(data, &fields) != nil || fields["documentAddressingVersion"] != nil && fields["documentAddressingVersion"] != float64(2) {
+ t.Fatalf("restored guide configuration is invalid: %s, %v", data, err)
}
if Conf.Box(boxID) == nil {
t.Fatal("restored guide was not mounted")
@@ -83,10 +84,10 @@ func TestMountUserGuideAfterDeletion(t *testing.T) {
task.ExecTaskJob()
}
// 来源不兼容时,无论本地副本是否存在,都不能覆盖或创建副本。
- if err := os.WriteFile(config, []byte(`{"documentAddressingVersion":99}`), 0644); err != nil {
+ if err := os.WriteFile(filepath.Join(source, "20261026000000-future1.sy"), []byte(`{"Spec":"999","Properties":{"title":"Future"}}`), 0644); err != nil {
t.Fatal(err)
}
- if _, err := Mount(boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if _, err := Mount(boxID); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("incompatible bundled guide was accepted: %v", err)
}
if actual, err := os.ReadFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath)); err != nil || string(actual) != string(data) {
@@ -95,7 +96,7 @@ func TestMountUserGuideAfterDeletion(t *testing.T) {
if err := RemoveBox(boxID); err != nil {
t.Fatal(err)
}
- if _, err := Mount(boxID); !errors.Is(err, documentaddressing.ErrUnsupported) {
+ if _, err := Mount(boxID); !errors.Is(err, treenode.ErrSpecTooNew) {
t.Fatalf("missing guide bypassed source check: %v", err)
}
if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {
@@ -118,7 +119,7 @@ func TestMountUserGuideAfterDeletion(t *testing.T) {
if err := removeBoxDir(ordinaryDir); err != nil {
t.Fatal(err)
}
- if _, err := Mount(ordinaryBox); !errors.Is(err, os.ErrNotExist) {
+ if _, err := Mount(ordinaryBox); err == nil {
t.Fatalf("ordinary notebook bypassed missing-source check: %v", err)
}
if err := RemoveBox(ordinaryBox); err != nil {
diff --git a/kernel/model/notebook_archive_import.go b/kernel/model/notebook_archive_import.go
index 0e87ae7a4c..f03f983d1d 100644
--- a/kernel/model/notebook_archive_import.go
+++ b/kernel/model/notebook_archive_import.go
@@ -16,7 +16,6 @@ import (
"github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/conf"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -90,11 +89,6 @@ func ImportNotebookArchive(archivePath, password string, keyData []byte) error {
return err
}
defer zeroAndClear(kek)
- for _, root := range notebookArchiveBoxRoots(manifest) {
- if err = documentaddressing.CheckImport(util.DataDir, util.ConfDir, path.Base(root), filepath.Join(payload, filepath.FromSlash(root))); err != nil {
- return err
- }
- }
install := filepath.Join(directory, "install")
roots, err := stageNotebookArchiveImport(payload, install, manifest)
if err != nil {
diff --git a/kernel/model/notebook_bundle_fts5_test.go b/kernel/model/notebook_bundle_fts5_test.go
index 704e9fe874..c9958ddb70 100644
--- a/kernel/model/notebook_bundle_fts5_test.go
+++ b/kernel/model/notebook_bundle_fts5_test.go
@@ -70,7 +70,7 @@ func TestImportNotebooksSYWithAddressingFloor(t *testing.T) {
t.Fatal("import reused a source notebook identity")
}
root := filepath.Join(util.DataDir, boxID)
- if err = documentaddressing.CheckSource(boxID, root); err != nil {
+ if err = checkImportedDocumentAddressing(root); err != nil {
t.Fatal("imported addressing floor does not match the new notebook", err)
}
entries, readErr := os.ReadDir(root)
diff --git a/kernel/model/path.go b/kernel/model/path.go
index 7e9a8f8bd0..4df1714c12 100644
--- a/kernel/model/path.go
+++ b/kernel/model/path.go
@@ -40,7 +40,7 @@ func createDocsByHPathSync(boxID, hPath, content, parentID, id string, titleEmpt
}
func createDocsByHPath0(boxID, hPath, content, parentID, id string, titleEmpty bool,
- createDocFn func(boxID, p, title, dom string, titleEmpty bool) (*parse.Tree, error)) (retID string, err error) {
+ createDocFn func(boxID, p, title, dom string, titleEmpty bool) (*parse.Tree, error), checkedParents ...map[string]*treenode.BlockTree) (retID string, err error) {
if "" == id {
id = ast.NewNodeID()
}
@@ -52,7 +52,7 @@ func createDocsByHPath0(boxID, hPath, content, parentID, id string, titleEmpty b
// 笔记本顶层文档是用户可见的逻辑根,完整路径应从笔记本根目录解析。
parentID = ""
}
- if "" != parentID {
+ if "" != parentID && len(checkedParents) == 0 {
// 存在同名文档时通过父文档 ID 精确定位 https://github.com/siyuan-note/siyuan/issues/8138
parentHPath, name := path.Split(hPath)
parentHPath = strings.TrimSuffix(parentHPath, "/")
@@ -72,20 +72,24 @@ func createDocsByHPath0(boxID, hPath, content, parentID, id string, titleEmpty b
parts := strings.Split(hPath, "/")[1:]
// The subdoc creation path is unstable when a parent doc with the same name exists https://github.com/siyuan-note/siyuan/issues/9322
// 存在同名父文档时子文档创建路径不稳定,这里需要按照完整的 hpath 映射,不能在下面的循环中边构建 hpath 边构建 path,否则虽然 hpath 相同,但是会导致 path 组装错位
- for i, part := range parts {
- if i == len(parts)-1 {
- break
- }
+ if len(checkedParents) > 0 {
+ hpathBtMap = checkedParents[0]
+ } else {
+ for i, part := range parts {
+ if i == len(parts)-1 {
+ break
+ }
- hPathBuilder.WriteString("/")
- hPathBuilder.WriteString(part)
- hp := hPathBuilder.String()
- root := treenode.GetBlockTreeRootByHPath(boxID, hp)
- if nil == root {
- break
- }
+ hPathBuilder.WriteString("/")
+ hPathBuilder.WriteString(part)
+ hp := hPathBuilder.String()
+ root := treenode.GetBlockTreeRootByHPath(boxID, hp)
+ if nil == root {
+ break
+ }
- hpathBtMap[hp] = root
+ hpathBtMap[hp] = root
+ }
}
pathBuilder := bytes.Buffer{}
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 3c416cea95..ee8935b90e 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -25,7 +25,6 @@ import (
"maps"
"math"
"os"
- "path"
"path/filepath"
"regexp"
"slices"
@@ -46,7 +45,6 @@ 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"
@@ -575,14 +573,9 @@ func SearchRefBlockInBox(id, rootID, keyword string, beforeLen int, isSquareBrac
if !isDatabase {
// 如果非数据库中搜索块引,则不允许新建重名文档
if block := treenode.GetBlockTreeInBox(id, boxID); nil != block {
- 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)
- }
+ parentID := block.RootID
+ resolved, resolveErr := ResolveDocPath(block.BoxID, "document", &parentID, []string{keyword})
+ newDoc = resolveErr == nil && resolved.Status == "missing"
}
} else { // 如果是数据库中搜索绑定块,则允许新建重名文档 https://github.com/siyuan-note/siyuan/issues/11713
newDoc = true
@@ -599,12 +592,8 @@ func filterSelfHPath(blocks []*Block) {
for _, b := range blocks {
if b.IsDoc() {
- 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)
+ if metadata, err := treenode.GetDocumentMetadata(b.Box, b.RootID); err == nil {
+ b.HPath = trimDocumentTitleHPath(b.HPath, metadata.Title.Text)
}
}
}
diff --git a/kernel/model/sort_conf_append.go b/kernel/model/sort_conf_append.go
index f0c4047f54..89b5459645 100644
--- a/kernel/model/sort_conf_append.go
+++ b/kernel/model/sort_conf_append.go
@@ -310,7 +310,7 @@ func recoverSortConfAppends() error {
return fmt.Errorf("invalid sort recovery notebook [%s]", boxID)
}
if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {
- if errors.Is(err, documentaddressing.ErrUnsupported) || errors.Is(err, documentaddressing.ErrInvalid) {
+ if errors.Is(err, documentaddressing.ErrInvalid) {
logging.LogWarnf("keep sort recovery for unavailable notebook [%s]: %s", boxID, err)
continue
}
diff --git a/kernel/model/structured_titles_crypto_test.go b/kernel/model/structured_titles_crypto_test.go
index 600bd5413a..d105bd66e9 100644
--- a/kernel/model/structured_titles_crypto_test.go
+++ b/kernel/model/structured_titles_crypto_test.go
@@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"os"
"os/exec"
"path/filepath"
@@ -16,6 +17,7 @@ import (
"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/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -109,6 +111,12 @@ func TestStructuredTitlesEncryptedLockAndHistory(t *testing.T) {
if literal.DisplayPath != child.DisplayPath || literal.Depth != 1 || child.Depth != 2 {
t.Fatal("encrypted display path collision changed document identity")
}
+ if ids, err := GetIDsByHPath("/A", box); err != nil || len(ids) != 1 || ids[0] != parent.ID {
+ t.Fatal("clean encrypted legacy path failed", ids, err)
+ }
+ if ids, err := GetIDsByHPath("/A/B", box); !errors.Is(err, documentaddressing.ErrPathAmbiguous) || len(ids) != 0 {
+ t.Fatal("encrypted collision accepted", ids, err)
+ }
literalSource := structuredTitlesCiphertext(t, literal)
childSource := structuredTitlesCiphertext(t, child)
keys, err := json.Marshal(currentNotebookCrypto())
@@ -125,6 +133,9 @@ func TestStructuredTitlesEncryptedLockAndHistory(t *testing.T) {
t.Fatal(err)
}
LockBox(box)
+ if ids, err := GetIDsByHPath("/A/B", box); err == nil || len(ids) != 0 {
+ t.Fatal("locked notebook exposed legacy candidates", ids, err)
+ }
if _, _, err = GetDocPaths(box, []string{literal.ID, child.ID}); err == nil {
t.Fatal("locked notebook exposed structured titles")
}
diff --git a/kernel/model/structured_titles_test.go b/kernel/model/structured_titles_test.go
index d606798ea0..9888bd263f 100644
--- a/kernel/model/structured_titles_test.go
+++ b/kernel/model/structured_titles_test.go
@@ -5,7 +5,6 @@ package model
import (
"bytes"
"context"
- "errors"
"os"
"os/exec"
"path/filepath"
@@ -14,7 +13,6 @@ import (
"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/sql"
"github.com/siyuan-note/siyuan/kernel/treenode"
@@ -99,10 +97,10 @@ func TestStructuredTitlesCreationAndIdentity(t *testing.T) {
paths[0].Title.Text != leaf.Title.Text {
t.Fatal(paths, missing, err)
}
- if _, err = GetIDsByHPath("/A/B", box.ID); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {
+ if ids, err := GetIDsByHPath("/A/B", box.ID); err != nil || len(ids) != 1 || ids[0] != child.ID {
t.Fatal(err)
}
- if _, err = CreateWithMarkdown("", box.ID, "/Plain", "", parent.ID, ast.NewNodeID(), false, "", nil); !errors.Is(err, documentaddressing.ErrLegacyPathUnsupported) {
+ if _, err = CreateWithMarkdown("", box.ID, "/Plain", "", parent.ID, ast.NewNodeID(), false, "", nil); err != nil {
t.Fatal(err)
}
newSource, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, ordinary.Path))
diff --git a/kernel/model/structured_titles_upgrade_test.go b/kernel/model/structured_titles_upgrade_test.go
index 088915ab8f..2cc9c850d9 100644
--- a/kernel/model/structured_titles_upgrade_test.go
+++ b/kernel/model/structured_titles_upgrade_test.go
@@ -179,13 +179,13 @@ func TestStructuredTitlesReleasedDataUpgradeAndRestart(t *testing.T) {
}
}
-func TestStructuredTitlesSyncAndSnapshotRetainUpgradedMode(t *testing.T) {
+func TestStructuredTitlesSyncAndSnapshotKeepFixedCapabilities(t *testing.T) {
const helper = "SIYUAN_TEST_RELEASED_TITLES_SYNC"
if os.Getenv(helper) != "1" {
// 同步事件及笔记本生命周期是进程级状态,不能继承其他模型用例的后台任务。
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
- command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStructuredTitlesSyncAndSnapshotRetainUpgradedMode$", "-test.v")
+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStructuredTitlesSyncAndSnapshotKeepFixedCapabilities$", "-test.v")
command.Env = append(os.Environ(), helper+"=1")
if output, err := command.CombinedOutput(); err != nil {
t.Fatalf("released-data sync: %v\n%s", err, output)
@@ -247,8 +247,8 @@ func TestStructuredTitlesSyncAndSnapshotRetainUpgradedMode(t *testing.T) {
t.Fatal(err)
}
snapshot, err := documentaddressing.InspectBox(receiver.DataPath, util.ConfDir, box)
- if err != nil || snapshot.Mode != 2 || !snapshot.RecordsConsistent {
- t.Fatal("sync or snapshot lowered a confirmed capability", snapshot, err)
+ if err != nil || snapshot.Mode != 2 {
+ t.Fatal("sync or snapshot changed the fixed addressing version", snapshot, err)
}
}
for _, document := range fixture.Documents {
@@ -279,14 +279,11 @@ func TestStructuredTitlesSyncAndSnapshotRetainUpgradedMode(t *testing.T) {
if err = os.Chtimes(name, stamp, stamp); err != nil {
t.Fatal(err)
}
- if err = os.Remove(filepath.Join(sender.DataPath, box, documentaddressing.FloorPath)); err != nil {
- t.Fatal(err)
- }
}
synchronize(sender, "stale notebook configuration", receiver)
for box := range boxes {
if _, err = os.Stat(filepath.Join(receiver.DataPath, box, documentaddressing.FloorPath)); !os.IsNotExist(err) {
- t.Fatal("the stale remote deletion was not exercised", err)
+ t.Fatal("sync regenerated a retired notebook record", err)
}
}
assertUpgraded()
diff --git a/kernel/treenode/document_legacy.go b/kernel/treenode/document_legacy.go
new file mode 100644
index 0000000000..f8dcb285cd
--- /dev/null
+++ b/kernel/treenode/document_legacy.go
@@ -0,0 +1,148 @@
+package treenode
+
+import (
+ "encoding/json"
+ "path"
+ "strings"
+
+ "github.com/88250/gulu"
+)
+
+// LegacyDocumentCandidates separates exact display-path matches by their real ancestry.
+// Unsupported includes slash titles, empty titles and empty-title placeholders.
+type LegacyDocumentCandidates struct {
+ Clean []*BlockTree
+ Unsupported []*BlockTree
+}
+
+// Seed from the already selected IDs rather than rescanning notebook paths.
+// json_each avoids a SQL-variable limit on large legacy result sets; UNION
+// bounds corrupt cycles. Joins retain the same identity indexes as structured paths.
+const legacyAncestorMetadataQuery = `WITH RECURSIVE ancestors(id) AS (
+ SELECT value FROM json_each(?)
+ UNION SELECT m.parent_id FROM ancestors a JOIN document_metadata m ON m.id=a.id AND m.box_id=?
+ WHERE m.parent_id IS NOT NULL)
+ SELECT ` + documentMetadataColumns + ` FROM ancestors a
+ LEFT JOIN document_metadata m ON m.id=a.id AND m.box_id=?
+ LEFT JOIN blocktrees b INDEXED BY idx_blocktrees_id ON b.box_id=m.box_id AND b.id=m.id AND b.type='d'`
+
+// ClassifyLegacyDocumentPaths reads readiness, candidates and all ancestors in one
+// database snapshot. It never reads document sources or falls back to another box.
+func ClassifyLegacyDocumentPaths(boxID string, hpaths []string) (map[string]*LegacyDocumentCandidates, error) {
+ tx, err := beginTxForBox(boxID)
+ if err != nil {
+ return nil, err
+ }
+ defer tx.Rollback()
+ var state string
+ var pending bool
+ if err = tx.QueryRow("SELECT state FROM document_metadata_state WHERE box_id=? AND version=1", boxID).Scan(&state); err != nil || state != "ready" {
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ if err = tx.QueryRow("SELECT EXISTS(SELECT 1 FROM document_metadata_pending WHERE box_id=?)", boxID).Scan(&pending); err != nil || pending {
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ ret := map[string]*LegacyDocumentCandidates{}
+ var candidates []*BlockTree
+ seenCandidates := map[string]bool{}
+ for _, hpath := range hpaths {
+ if _, exists := ret[hpath]; exists {
+ continue
+ }
+ ret[hpath] = &LegacyDocumentCandidates{Clean: []*BlockTree{}, Unsupported: []*BlockTree{}}
+ rows, queryErr := tx.Query("SELECT * FROM blocktrees WHERE box_id=? AND hpath=? AND type='d' ORDER BY id", boxID, gulu.Str.RemoveInvisible(hpath))
+ if queryErr != nil {
+ return nil, queryErr
+ }
+ for rows.Next() {
+ block := &BlockTree{}
+ if err = rows.Scan(&block.ID, &block.RootID, &block.ParentID, &block.BoxID, &block.Path, &block.HPath, &block.Updated, &block.Type); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ // Keep the requested lookup key separate from the stored display path.
+ if !seenCandidates[block.ID] {
+ candidates = append(candidates, block)
+ seenCandidates[block.ID] = true
+ }
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return nil, err
+ }
+ }
+ if len(candidates) == 0 {
+ return ret, nil
+ }
+ ids := make([]string, 0, len(candidates))
+ for _, candidate := range candidates {
+ ids = append(ids, candidate.ID)
+ }
+ encodedIDs, err := json.Marshal(ids)
+ if err != nil {
+ return nil, err
+ }
+ rows, err := tx.Query(legacyAncestorMetadataQuery, string(encodedIDs), boxID, boxID)
+ if err != nil {
+ return nil, err
+ }
+ metadata := map[string]*DocumentMetadata{}
+ for rows.Next() {
+ meta, scanErr := scanDocumentMetadata(rows)
+ if scanErr != nil {
+ rows.Close()
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ metadata[meta.ID] = meta
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return nil, err
+ }
+ for _, candidate := range candidates {
+ unsupported := false
+ seen := map[string]bool{}
+ var titles []string
+ currentID, childPath := candidate.ID, ""
+ for {
+ meta := metadata[currentID]
+ if meta == nil || seen[currentID] || childPath != "" &&
+ (currentID == boxID || strings.TrimSuffix(meta.Path, ".sy") != path.Dir(childPath)) {
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ seen[currentID] = true
+ if meta.Title.Text == "" || meta.Title.Empty || strings.Contains(meta.Title.Text, "/") {
+ unsupported = true
+ }
+ titles = append(titles, meta.Title.Text)
+ if meta.ParentID == nil {
+ if path.Dir(meta.Path) != "/" {
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ break
+ }
+ currentID, childPath = *meta.ParentID, meta.Path
+ }
+ if !unsupported {
+ for i, j := 0, len(titles)-1; i < j; i, j = i+1, j-1 {
+ titles[i], titles[j] = titles[j], titles[i]
+ }
+ if candidate.HPath != "/"+strings.Join(titles, "/") {
+ return nil, ErrDocumentMetadataUnavailable
+ }
+ }
+ for hpath := range ret {
+ if candidate.HPath != gulu.Str.RemoveInvisible(hpath) {
+ continue
+ }
+ if unsupported {
+ ret[hpath].Unsupported = append(ret[hpath].Unsupported, candidate)
+ } else {
+ ret[hpath].Clean = append(ret[hpath].Clean, candidate)
+ }
+ }
+ }
+ return ret, nil
+}
diff --git a/kernel/treenode/document_legacy_test.go b/kernel/treenode/document_legacy_test.go
new file mode 100644
index 0000000000..60d748b4fc
--- /dev/null
+++ b/kernel/treenode/document_legacy_test.go
@@ -0,0 +1,155 @@
+package treenode
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/parse"
+)
+
+func TestLegacyDocumentCandidatesClassifyRealAncestorChains(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
+ box := withDocumentMetadataDB(t, encrypted)
+ parent := NewTree(box, "/20261026000001-parent1.sy", "/A", "A")
+ clean := NewTree(box, "/20261026000001-parent1/20261026000002-clean01.sy", "/A/B", "B")
+ slash := NewTree(box, "/20261026000003-slash01.sy", "/A/B", "A/B")
+ leaf := NewTree(box, "/20261026000003-slash01/20261026000004-leaf001.sy", "/A/B/C", "C")
+ empty := NewTree(box, "/20261026000001-parent1/20261026000005-empty01.sy", "/A", "")
+ placeholder := NewTree(box, "/20261026000006-place01.sy", "/Untitled", "Untitled")
+ placeholder.Root.SetIALAttr(DocumentTitleEmptyAttr, "true")
+ literal := NewTree(box, "/20261026000007-entity1.sy", "/A&#47;B", "A&#47;B")
+ for _, tree := range []*parse.Tree{parent, clean, slash, leaf, empty, placeholder, literal} {
+ UpsertBlockTree(tree)
+ }
+ if _, err := execForBox(box, "UPDATE blocktrees SET hpath='/A' WHERE id=?", empty.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := SetDocumentMetadataState(box, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ paths := []string{"/A/B", "/A/B/C", "/A", "/Untitled", "/A&#47;B", "/missing"}
+ groups, err := ClassifyLegacyDocumentPaths(box, paths)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for hp, want := range map[string][2]int{"/A/B": {1, 1}, "/A/B/C": {0, 1}, "/A": {1, 1}, "/Untitled": {0, 1}, "/A&#47;B": {1, 0}, "/missing": {0, 0}} {
+ if got := groups[hp]; len(got.Clean) != want[0] || len(got.Unsupported) != want[1] {
+ t.Fatalf("%s: %+v", hp, got)
+ }
+ }
+ RemoveBlockTree(box, slash.ID)
+ RemoveBlockTree(box, leaf.ID)
+ groups, err = ClassifyLegacyDocumentPaths(box, []string{"/A/B"})
+ if err != nil || len(groups["/A/B"].Clean) != 1 || len(groups["/A/B"].Unsupported) != 0 {
+ t.Fatal(groups, err)
+ }
+ })
+ }
+}
+
+func TestLegacyDocumentAncestorReadsUseIdentityIndexes(t *testing.T) {
+ for _, encrypted := range []bool{false, true} {
+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {
+ box := withDocumentMetadataDB(t, encrypted)
+ rows, err := queryForBox(box, "EXPLAIN QUERY PLAN "+legacyAncestorMetadataQuery, "[]", box, box)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var plan strings.Builder
+ for rows.Next() {
+ var id, parent, unused int
+ var detail string
+ if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
+ t.Fatal(err)
+ }
+ plan.WriteString(detail + "\n")
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(plan.String(), "SEARCH b USING INDEX idx_blocktrees_id (id=?)") || !strings.Contains(plan.String(), "SEARCH m USING INDEX sqlite_autoindex_document_metadata_1 (box_id=? AND id=?)") {
+ t.Fatal("ancestor lookup scans unrelated documents", plan.String())
+ }
+ })
+ }
+}
+
+func TestLegacyDocumentCandidatesFailClosed(t *testing.T) {
+ for _, state := range []string{"missing", "building", "pending", "missing ancestor", "corrupt revision", "stale hpath", "cycle", "database error"} {
+ t.Run(state, func(t *testing.T) {
+ box := withDocumentMetadataDB(t, false)
+ parent := NewTree(box, "/20261026000001-parent1.sy", "/A", "A")
+ child := NewTree(box, "/20261026000001-parent1/20261026000002-child01.sy", "/A/B", "B")
+ UpsertBlockTree(parent)
+ UpsertBlockTree(child)
+ if state != "missing" {
+ if err := SetDocumentMetadataState(box, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var err error
+ switch state {
+ case "building":
+ err = SetDocumentMetadataState(box, "building")
+ case "pending":
+ _, err = BeginDocumentMetadataRecovery(GetBlockTreeInExactBox(parent.ID, box))
+ case "missing ancestor":
+ _, err = db.Exec("DELETE FROM document_metadata WHERE id=?", parent.ID)
+ case "corrupt revision":
+ _, err = db.Exec("UPDATE document_metadata SET revision='corrupt' WHERE id=?", parent.ID)
+ case "stale hpath":
+ _, err = db.Exec("UPDATE blocktrees SET hpath='/old/B' WHERE id=?", child.ID)
+ case "cycle":
+ parent.Path = "/" + child.ID + "/" + parent.ID + ".sy"
+ UpsertBlockTree(parent)
+ case "database error":
+ err = db.Close()
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ hp := "/A/B"
+ if state == "stale hpath" {
+ hp = "/old/B"
+ }
+ if _, err := ClassifyLegacyDocumentPaths(box, []string{hp}); err == nil {
+ t.Fatal("unproven chain accepted")
+ }
+ if state == "pending" {
+ if _, err := ClassifyLegacyDocumentPaths(box, []string{"/not-found"}); !errors.Is(err, ErrDocumentMetadataUnavailable) {
+ t.Fatal("pending index treated as empty", err)
+ }
+ }
+ })
+ }
+}
+
+func TestLegacyDocumentCandidatesAfterSourceMetadataCommit(t *testing.T) {
+ box := withDocumentMetadataDB(t, false)
+ parent := NewTree(box, "/20261026000001-parent1.sy", "/Old", "Old")
+ child := NewTree(box, "/20261026000001-parent1/20261026000002-child01.sy", "/Old/C", "C")
+ other := NewTree(box, "/20261026000003-other01.sy", "/A", "A")
+ otherChild := NewTree(box, "/20261026000003-other01/20261026000004-other02.sy", "/A/B", "B")
+ collision := NewTree(box, "/20261026000003-other01/20261026000004-other02/20261026000005-other03.sy", "/A/B/C", "C")
+ for _, tree := range []*parse.Tree{parent, child, other, otherChild, collision} {
+ UpsertBlockTree(tree)
+ }
+ if err := SetDocumentMetadataState(box, "ready"); err != nil {
+ t.Fatal(err)
+ }
+ parent.Root.SetIALAttr("title", "A/B")
+ parent.HPath = "/A/B"
+ if _, err := BeginDocumentMetadataWrite(parent); err != nil {
+ t.Fatal(err)
+ }
+ if err := CommitDocumentMetadataWrite(parent); err != nil {
+ t.Fatal(err)
+ }
+ groups, err := ClassifyLegacyDocumentPaths(box, []string{"/A/B/C"})
+ if err != nil || len(groups["/A/B/C"].Clean) != 1 || len(groups["/A/B/C"].Unsupported) != 1 {
+ t.Fatal("source metadata commit missed a new collision", groups, err)
+ }
+}
diff --git a/kernel/treenode/document_metadata.go b/kernel/treenode/document_metadata.go
index 64a741e066..807d17a29a 100644
--- a/kernel/treenode/document_metadata.go
+++ b/kernel/treenode/document_metadata.go
@@ -212,12 +212,28 @@ func BeginDocumentMetadataRecovery(doc *BlockTree) (bool, error) {
func CommitDocumentMetadataWrite(tree *parse.Tree) error {
indexBlockTreeLock.Lock()
defer indexBlockTreeLock.Unlock()
+ docs, err := DocHPaths(tree.Box, tree.Path)
+ if err != nil {
+ return err
+ }
tx, err := beginTxForBox(tree.Box)
if err != nil {
return err
}
defer tx.Rollback()
execInsertBlocktrees(tx, tree, []*ast.Node{tree.Root})
+ var state string
+ if stateErr := tx.QueryRow("SELECT state FROM document_metadata_state WHERE box_id=? AND version=1", tree.Box).Scan(&state); stateErr != nil && !errors.Is(stateErr, sql.ErrNoRows) {
+ return stateErr
+ }
+ // Rebuilds may not yet have descendant summaries. They cannot serve legacy
+ // queries until the existing full rebuild publishes ready.
+ if state == "ready" {
+ if err = refreshDocumentHPathsInTx(tx, tree, docs); err != nil {
+ return err
+ }
+ }
+
if _, err = tx.Exec("DELETE FROM document_metadata_pending WHERE box_id=? AND id=? AND revision=?",
tree.Box, tree.ID, documentMetadataFromTree(tree).Revision); err != nil {
return err
diff --git a/kernel/treenode/document_source.go b/kernel/treenode/document_source.go
index 18d600ae1d..571b360015 100644
--- a/kernel/treenode/document_source.go
+++ b/kernel/treenode/document_source.go
@@ -40,16 +40,13 @@ type documentTitleSpecProperties struct {
}
func (properties *documentTitleSpecProperties) UnmarshalJSON(data []byte) error {
- err := documentaddressing.CheckTitleProperties(data, 1)
- if errors.Is(err, documentaddressing.ErrModeConflict) {
- properties.requiresStructured = true
- return nil
- }
+ requiresSpec, err := documentaddressing.CheckTitleProperties(data)
+ properties.requiresStructured = properties.requiresStructured || requiresSpec
return err
}
// checkDocumentSourceJSON 保留重复字段中遇到的兼容错误,在容错解析前确定标题和源版本能否处理。
-func checkDocumentSourceJSON(data []byte, mode int) (string, error) {
+func checkDocumentSourceJSON(data []byte) (string, error) {
if !bytes.HasPrefix(bytes.TrimSpace(data), []byte("{")) {
return "", errors.New("invalid document source")
}
@@ -57,13 +54,9 @@ func checkDocumentSourceJSON(data []byte, mode int) (string, error) {
Spec documentSourceSpec
Properties documentSourceProperties
}
- root.Properties.mode = mode
if err := json.Unmarshal(data, &root); err != nil {
return "", err
}
- if errors.Is(root.Properties.err, documentaddressing.ErrModeConflict) {
- return "", root.Properties.err
- }
if root.Spec.err != nil {
return "", root.Spec.err
}
@@ -91,13 +84,12 @@ func (spec *documentSourceSpec) UnmarshalJSON(data []byte) error {
}
type documentSourceProperties struct {
- err error
- mode int
+ err error
}
func (properties *documentSourceProperties) UnmarshalJSON(data []byte) error {
- if err := documentaddressing.CheckTitleProperties(data, properties.mode); err != nil {
- if properties.err == nil || errors.Is(err, documentaddressing.ErrModeConflict) {
+ if _, err := documentaddressing.CheckTitleProperties(data); err != nil {
+ if properties.err == nil {
properties.err = err
}
}
diff --git a/kernel/treenode/document_source_test.go b/kernel/treenode/document_source_test.go
index f5f77567d1..83b21b0d90 100644
--- a/kernel/treenode/document_source_test.go
+++ b/kernel/treenode/document_source_test.go
@@ -2,39 +2,12 @@ package treenode
import (
"errors"
- "strings"
"testing"
"github.com/88250/lute/ast"
"github.com/88250/lute/parse"
- "github.com/siyuan-note/siyuan/kernel/documentaddressing"
)
-func TestDocumentAddressingLegacySourceTitleConflict(t *testing.T) {
- for _, source := range []string{
- `{"Spec":"2","Properties":{"title":"A/B"}}`,
- `{"Spec":"2","Properties":{"title":"A\u002fB"}}`,
- `{"Spec":"2","Properties":{"title":"A&#47;B"}}`,
- `{"Spec":"2","Properties":{"title":"A/B","title":"Legacy"}}`,
- `{"Spec":"2","Properties":{"title":"A/B"},"Properties":{"title":"Legacy"}}`,
- `{"Spec":"999","Properties":{"title":"private/title"}}`,
- `{"Properties":{"title":"private/title"},"Spec":"999"}`,
- } {
- if err := CheckSpecJSONForMode([]byte(source), 1); !errors.Is(err, documentaddressing.ErrModeConflict) {
- t.Errorf("source title conflict was not retained: %v", err)
- } else if strings.Contains(err.Error(), "private") {
- t.Fatal("source title leaked into error")
- }
- }
- for _, title := range []string{"A/B", "A&#47;B"} {
- root := &ast.Node{Type: ast.NodeDocument, Spec: "2"}
- root.KramdownIAL = [][]string{{"title", title}}
- if err := CheckSpecForMode(&parse.Tree{Root: root}, 1); !errors.Is(err, documentaddressing.ErrModeConflict) {
- t.Fatalf("in-memory source title was accepted: %v", err)
- }
- }
-}
-
func TestDocumentAddressingSourcePreservesOrdinaryTitles(t *testing.T) {
root := &ast.Node{Type: ast.NodeDocument, Spec: "2"}
root.SetIALAttr("title", "A&#47;B")
@@ -82,7 +55,7 @@ func TestDocumentTitleWriteSpec(t *testing.T) {
`{"Spec":"2","Properties":{"title":"A/B"},"Properties":{"title":"Ordinary"}}`,
`{"Spec":"6","Spec":"2","Properties":{"title":"A/B"}}`,
} {
- if err := CheckSpecJSONForMode([]byte(source), 2); err != nil {
+ if err := CheckSpecJSON([]byte(source)); err != nil {
t.Fatalf("existing low-spec source is no longer readable: %v", err)
}
if err := CheckDocumentTitleWriteSpecJSON([]byte(source)); !errors.Is(err, ErrDocumentTitleSpec) {
diff --git a/kernel/treenode/hpath.go b/kernel/treenode/hpath.go
index d528e71574..0b2b4aa1a8 100644
--- a/kernel/treenode/hpath.go
+++ b/kernel/treenode/hpath.go
@@ -65,6 +65,15 @@ func RefreshDocHPaths(tree *parse.Tree) (err error) {
return err
}
defer tx.Rollback()
+ if err = refreshDocumentHPathsInTx(tx, tree, docs); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// refreshDocumentHPathsInTx publishes document display paths with source metadata.
+// Content-block copies remain on the existing background refresh queue.
+func refreshDocumentHPathsInTx(tx *sql.Tx, tree *parse.Tree, docs []*BlockTree) (err error) {
if err = upsertDocumentMetadata(tx, tree); err != nil {
return err
}
@@ -111,7 +120,7 @@ func RefreshDocHPaths(tree *parse.Tree) (err error) {
if _, err = tx.Exec("UPDATE blocktrees SET updated = ? WHERE id = ? AND box_id = ? AND type = 'd'", tree.Root.IALAttr("updated"), tree.ID, tree.Box); err != nil {
return err
}
- return tx.Commit()
+ return nil
}
// CurrentTreeHPath 使排队期间加载的树使用最新文档路径,避免旧索引操作写回重命名前的路径。
diff --git a/kernel/treenode/tree.go b/kernel/treenode/tree.go
index 4a9d2d17d9..5d850b00e2 100644
--- a/kernel/treenode/tree.go
+++ b/kernel/treenode/tree.go
@@ -158,14 +158,10 @@ var CurrentSpec = DocumentTitleSpec
var ErrSpecTooNew = fmt.Errorf("the document spec is too new")
-// CheckSpecJSON 按当前发行版能力校验独立源(如导入和历史),不能代替笔记本模式与授权预检。
+// CheckSpecJSON 按当前发行版能力校验独立源(如导入和历史),不能代替授权与认证预检。
// 在解析节点之前检查,避免未知节点被容错解析后覆盖原始内容。
func CheckSpecJSON(data []byte) error {
- return CheckSpecJSONForMode(data, documentaddressing.DefaultMode())
-}
-
-func CheckSpecJSONForMode(data []byte, mode int) error {
- spec, err := checkDocumentSourceJSON(data, mode)
+ spec, err := checkDocumentSourceJSON(data)
if err != nil {
return err
}
@@ -173,13 +169,6 @@ func CheckSpecJSONForMode(data []byte, mode int) error {
}
func CheckSpec(tree *parse.Tree) (err error) {
- 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 = nil
if err = ValidateTableCellRich(tree.Root); nil != err {
return
@@ -237,7 +226,7 @@ func UpgradeSpec(tree *parse.Tree) (upgraded bool) {
})
}
if documentTitleSpecUpgradeRequired(tree.Root.Spec) &&
- documentaddressing.CheckLegacyTitle(tree.Root.IALAttr("title")) != nil {
+ documentaddressing.TitleRequiresSpec(tree.Root.IALAttr("title")) {
tree.Root.Spec = DocumentTitleSpec
}
return oldSpec != tree.Root.Spec