An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:memo: Clarify document addressing compatibility and recovery https://github.com/siyuan-note/siyuan/issues/19938
Danielb78d90d11d3d
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.mdindex 8902dcee00..902b6207f2 100644--- a/docs/DOCUMENT-ADDRESSING.md+++ b/docs/DOCUMENT-ADDRESSING.md@@ -2,7 +2,7 @@[中文](DOCUMENT-ADDRESSING.zh-CN.md)-Related issue: [Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938)+Related issues: [Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938), [Improve content preservation when converting headings to documents](https://github.com/siyuan-note/siyuan/issues/19235)This is an implementation design draft defining document titles, hierarchy addressing, readable paths, APIs, and migration behavior. The new fields, endpoints, and version mechanisms below are proposed contracts, not capabilities already supported by the current release. See [Document rename and path indexes](DOCUMENT-HPATH.md) (Chinese) for the current rename and index update mechanism.@@ -109,6 +109,12 @@ Render ordinary titles as text through existing escaping or text-node mechanismsBlock references, dynamic anchor text, links, tags, and assets need additional rules for dependency updates, click behavior, reference and asset ownership, cycles, ID remapping during copying and import, and encryption boundaries. This design preserves representation space for those capabilities without committing to enabling every inline element at once. The later rich title implementation must also cover input methods, selection, undo, mobile interaction, history, sync, and export.+### Conversion between headings and documents++Currently, `Heading2Doc` uses `headingDocParagraph` to move inline nodes that the document name cannot fully represent into a body paragraph, including images, links, formatting, and original text altered by normalization or truncation. Foundational separation preserves that behavior. Once titles allow `/`, a preservation paragraph needed solely because of slash replacement may become unnecessary, but other content must not be discarded. Evaluate title text extraction separately from preservation of the original nodes.++Use #19235 as a later inline-title round-trip acceptance case: supported inline elements and asset references become title source content; unsupported elements remain in the body. Reverse conversion or merging back into a document preserves node content, asset ownership, and references, restoring heading levels under explicit rules. Equal plain text does not prove that a body paragraph duplicates the title and cannot justify deleting user content. Automatic merging requires verifiable conversion provenance and content revisions; retain content when provenance is uncertain or the user has edited it, rather than blindly deduplicating. Existing ordinary documents do not automatically move their first paragraph into the title.+Acceptance of this decoupling must establish that adding a title representation does not change addressing or hierarchy rules, that existing ordinary titles retain their literal content, and that consumers obtain titles through the defined access boundary instead of guessing title syntax independently.## Creation and path templates@@ -139,11 +145,15 @@ Creating a hierarchy by name requires an explicit starting location and a titleA `/` within a structured title segment does not create another level, and `.` or `..` does not navigate. Moving up a level, starting from the notebook root, and anchoring at the current document require separate representations. An empty segment array means the starting location itself. An empty string cannot automatically match an empty-title parent, while creation can explicitly submit an empty final title. The caller's `onMissingParent` policy determines whether missing ancestors may be created.+Name matches and parent path revisions are separate commit conditions. `nameConditions` records `{parentID, title, expectedID}`: `parentID` is a parent document ID or `null` for the logical root, and nonempty `title` uses the shared exact plain-text matching rules. `expectedID: null` means no same-named child may yet exist; a document ID means the sole match must still be that document. Omitting `expectedID` is invalid. Accept at most 128 conditions, limited to the destination notebook, the actual ancestor chain, and the final parent, without enumerating unrelated locations. Normalize a notebook document ID to the logical root first, excluding the notebook document itself and empty-title placeholders from name queries.++Creation of a missing ancestor must submit its absence condition and retain the unique-identity conditions for ancestors previously matched by name. The kernel rechecks them under coordination shared with creation, rename, move, and deletion, holding that coordination through source and metadata commits. Any mismatch returns `planChanged`; callers resolve again instead of automatically reusing a newly appeared document. If two callers concurrently create the same missing ancestor, at most one satisfies the original absence condition. Ordinary final-document creation may omit name conditions and still allow duplicate sibling titles; do not add a unique title index. `expectedParentRevision` does not replace these conditions.+### Commits, partial failures, and retries-The first implementation does not add a general atomic multi-file creation API. Kernel workflows use creation plans; plugins compose the resolver and single-document creation endpoint. Before writing, a plan validates predictable title, depth, ambiguity, template, and authorization errors and assigns a fixed ID to each document to be created. Matched ancestors retain their identities and revisions. Recheck matches and revisions during execution; concurrently introduced same-named candidates require replanning instead of silently selecting another document.+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.-Each creation step commits independently. A success response requires synchronous persistence of the source document and required body and attribute changes, with readable document metadata; full-text indexing can remain asynchronous. Preserve the workflow's template, footnote, math, clipping-source, tag, sorting, and refresh-notification behavior when separating addressing.+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.Keep documents already persisted when a later step fails. Error data distinguishes `commitState: "none"`, `"committed"`, and `"unknown"` and includes confirmed document IDs, the failed stage, and completed steps. `committed` means the source document was committed, not that all subsequent actions succeeded. If persistence cannot be determined, return `unknown` rather than claiming no write occurred. Multi-level workflows retain the original plan and completed IDs and show where processing can continue.@@ -151,11 +161,15 @@ Callers retain allocated IDs before sending requests. After a lost response or uRecovery handles only unfinished steps and does not automatically delete successfully created parent documents. Non-repeatable follow-up actions such as clearing source data require all necessary workflow steps to succeed. Partial success or merely receiving a document ID cannot trigger deletion of shorthand source data.+After successful template document tree creation, undo and redo retain the existing grouping and ID-remapping semantics for parent edits and documents created by that operation. After partial failure, recovery and undo records reflect actual completed steps and must not act on uncommitted documents. Redo uses retained plan snapshots instead of reevaluating time-sensitive templates. Subsequent edits to existing or newly created documents remain subject to transaction conflict checks and cannot be deleted merely to clean up a failed plan. If side-effect completion cannot be established, stop automatic continuation and present confirmed results; an index recovery marker is not proof of business success.+### Template versionsLegacy 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. Compatibility compilation preserves grammar, not arbitrary selection of a same-named parent; unknown ancestors still require ambiguity checks.+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.++Legacy workflows and string templates in mode `1` retain existing duplicate-name selection and `parentID` fallback behavior. Internal identity-based implementations must pass legacy regressions rather than silently returning ambiguity errors because they share a strict resolver. New structured APIs apply strict ambiguity checks in both modes. Built-in mode `2` workflows use strict plans even for legacy templates and never select an arbitrary same-named parent; disclose that behavior change at explicit activation. A cross-notebook target used through the new protocol remains strict even when the destination uses mode `1`.New configuration uses `docCreateTarget`, `refCreateTarget`, and `dailyNoteTarget` alongside the original string save-path fields. Initially, these objects are available only in the configuration of notebooks with mode `2` enabled. Global settings retain legacy string templates and existing inheritance rules, avoiding configuration unknown to old clients before notebook activation. Each object requires `version: 2`, specifying the destination notebook, anchor, number of upward steps, ancestor segments, final title, and missing-parent policy. Each segment reuses the existing save-path template evaluator. The example's `{{now | date ...}}` syntax is for save-path templates and must not be confused with body-template syntax.@@ -177,6 +191,8 @@ New templates establish segment boundaries before rendering and evaluate each tiWhen 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.+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.+### Workflow migration| Entry point | Preserved behavior and migration focus |@@ -185,7 +201,7 @@ When a new object exists, it is the sole authoritative configuration for that cr| Daily notes | Reuse by the daily-note date attribute first; retain template-target preference for multiple matches and ID ordering otherwise; do not reapply body templates to existing notes || 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, and insertion order; validate preview revisions on commit and expose partial completion |+| 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 || 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.@@ -206,6 +222,16 @@ Renames still invalidate display paths, ancestor text search data, and related c## Import and export+### Cross-mode moves and recovery++Cross-notebook moves, copies, native imports, and history restoration preflight the entire operation set before the first write, including every descendant of each root document. Check destination mode, title formats and original text, source-format readability, destination depth, and existing encryption boundaries, not just top-level titles. If any document requires a title capability not enabled at the destination, reject the entire operation with `targetModeUnsupported`, returning conflicting document IDs only within authorized scope. Do not move directories, rewrite titles, delete sources, or automatically enable the destination mode.++After the user explicitly enables the destination mode and recovery completes, replan and revalidate the operation. Imports creating a notebook also obtain an explicit mode choice before committing documents. Required title capabilities derive from the title representation and actual content. The `.sy` version expresses source-reader requirements; not every version higher than `DocumentTitleSpec` implies mode `2`, and source versions must not be lowered to pass checks. Ordinary titles satisfying destination rules may move from a mode `2` notebook into mode `1`.++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.++### Filename and link mapping+Export first assigns a unique relative file path to each document identity, then uses the same mapping to write files and generate inter-document links. The mapping must handle slashes in titles, invalid filename characters, duplicate names, case-insensitive collisions, length limits, and duplicate names across notebooks. Overwrite checks and link generation cannot independently choose filenames while processing individual items.The allocator determines export directories from ID relationships, then converts each filename independently. Preserve existing unambiguous filenames; use safe names for reserved or empty names, `.`, `..`, trailing spaces or dots, and similar cases. Append a stable document ID on collision and the notebook ID if also necessary. Compare names under the destination filesystem's case and naming rules, retaining the unique suffix and extension when truncating. After allocating all names, recheck uniqueness and destination-directory boundaries before writing files and links. A `/` within a title affects only its filename conversion and never creates a directory.@@ -230,7 +256,9 @@ Each `DocumentPath` contains titles and ancestors from one verifiable revision.`/api/filetree/resolveDocPath` accepts `notebook`, `start`, and `segments`. `start` is `{kind: "root"}` or `{kind: "document", id: string}`; `segments` is an array of independent title strings. The endpoint only resolves, never creates. An empty array returns the starting location; otherwise, lookup proceeds one level at a time by exact name without interpreting navigation characters inside strings.-Results contain `status`, `start`, `resolved`, `nextIndex`, `candidates`, and `candidatesTruncated`. `start` returns the starting identity and revision; `resolved` and `candidates` use `DocumentPath`. `nextIndex` is the zero-based index of the next segment. `status: "resolved"` means all segments matched; `"missing"` means no document exists from that segment onward; `"ambiguous"` means that segment has multiple candidates. Return at most 128 candidates ordered by ID, setting `candidatesTruncated` if more exist. Reaching the limit still reports ambiguity: callers must use an explicit parent ID, never default to the first truncated candidate.+Results contain `status`, `start`, `resolved`, `nextIndex`, `candidates`, `candidatesTruncated`, and `nameConditions`. `start` returns the starting identity and revision; `resolved` and `candidates` use `DocumentPath`. `nextIndex` is the zero-based index of the next segment. `status: "resolved"` means all segments matched; `"missing"` means no document exists from that segment onward; `"ambiguous"` means that segment has multiple candidates. Return at most 128 candidates ordered by ID, setting `candidatesTruncated` if more exist. Reaching the limit still reports ambiguity: callers must use an explicit parent ID, never default to the first truncated candidate.++`nameConditions` contains a condition for each uniquely matched segment. A missing result also includes the first missing segment's absence condition; an ambiguous result does not generate a successful condition for the ambiguous segment. An empty segment array returns an empty condition array. The chain and conditions come from one verifiable snapshot and still require revalidation on commit. After creating the first missing ancestor, plugins resolve again using the original start and complete original segment array so subsequent conditions use confirmed parent IDs. One missing result does not reserve the entire nonexistent path.Resolution accepts at most 128 segments, each within the title length limit; actual creation still enforces the user's document depth restriction. Empty string segments fail; existing empty-title parents require ID selection. A root result uses an explicit root location, not an invented document ID. Root revisions cover notebook identity and relevant configuration, without invalidation by unrelated child changes. The notebook document ID, when used as a root alias, also uses root revision validation. Errors and candidates must not expose another notebook's titles.@@ -256,38 +284,44 @@ The minimal request for `/api/filetree/createDocByParent` follows. This example| `title` | Required; initially accepts only a plain title object; empty text differs from omission || `markdown` | Required; an empty string is valid || `expectedParentRevision` | Optional validation of the parent path revision when submitting a preview; use the resolver's root revision for a root target |+| `nameConditions` | Optional array of at most 128 name-match conditions; required when creating a missing ancestor, with its absence condition matching this creation's nonempty title and parent |+| `expectedTarget` | Optional configuration source `notebook`, `purpose`, and `revision`; required when submitting a preview derived from save-path configuration || `tags`, `withMath`, `clippingHref` | Optional, retaining the corresponding Markdown creation behavior || `sorts`, `sortTargetID`, `sortPosition` | Optional, preserving sort validation; relative targets must still be sibling documents, and conflicting sort specifications fail || `docCreateTemplatePath`, `listDocTree` | Optional, retaining existing body-template and document-tree refresh semantics |Reject additional targeting fields such as `path` and `hPath` to avoid competing location sources. A parent mismatch fails directly without falling back to name resolution. Success returns `{id, document: DocumentPath}`; clients use the returned ID to open, reference, or append to the document.-Business errors use `code: -1` with a stable `data.reason`. `msg` is for human readers, not plugin branching. Contract declarations retain error data carrying commit state and recovery information. Authentication, role, locking, and general request-validation failures continue using their middleware contracts rather than replacing every existing error format.+Name conditions, parent path revisions, and configuration revisions are checked separately and do not replace one another. Omitting conditions means direct creation by known identity, without a guarantee that an earlier name- or configuration-derived preview remains valid. Conditions grant no authority; the kernel still validates access, ownership, and leases. Multi-level plans check applicable conditions before each commit and report actual commit states for the current and preceding steps on failure, without selecting another parent.++Business errors use `code: -1` with a stable `data.reason`. `msg` is for human readers, not plugin branching. The table collects reasons used across this design; each creation, move, import, or recovery endpoint declares only applicable error variants, retaining the corresponding commit state and recovery information. Authentication, role, locking, and general request-validation failures continue using their middleware contracts rather than replacing every existing error format.| Reason | Meaning and caller action || --- | --- || `invalidTitle` | Invalid title representation, characters, or length; correct the input || `parentUnavailable` | Parent absent or outside the target notebook; do not search another notebook |-| `planChanged` | Location, title revision, or preview dependencies changed; resolve and confirm the target again |+| `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 || `indexUnavailable` | Structured metadata is not ready; wait for recovery without falling back to display paths || `unsupportedTitleFormat` | Client or endpoint cannot handle the title format; upgrade or use an endpoint supporting that format |+| `targetModeUnsupported` | The complete move, copy, import, or recovery set exceeds destination mode capabilities; explicitly enable the destination before replanning |+| `modeConflict` | Notebook mode records conflict with source title capabilities; enter controlled recovery instead of continuing compatibility-mode writes || `writeFailed` | A write or later processing failed; recover using `commitState` and the reported stage |### 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 endpoint only reads configuration; it neither evaluates templates nor guesses the current document or date. Callers supply context when generating the plan afterward.+`/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` retains its response while the effective configuration is a legacy template. When a new object is active, it returns `code: -1`, `data: {reason: "structuredTemplateRequired"}` instead of returning the obsolete old path. Declare that error variant on the legacy contract. Both built-in consumers and plugins use the new reader to avoid reimplementing configuration inheritance independently.+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.### Capability discovery and activation-Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `structuredPaths` means the server implements the new protocol; `indexState` indicates this notebook's readiness. These are distinct. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with a ready index.+Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.`revision` is the configuration revision relevant to activation, not an individual document's path revision. Capability declarations grant no access; closed or locked notebooks retain existing restrictions, and status reads expose neither titles nor protected template content. When an older server omits the object, plugins use only legacy capabilities. Authorization, locking, and network errors must not be interpreted as unsupported capabilities or trigger fallback writes.-`/api/notebook/enableStructuredTitles` accepts `notebook` and `expectedRevision`. It checks the configuration revision, index state, and local client compatibility, persists mode `2`, and returns current `documentCapabilities`. If already enabled with a matching revision, it may return the current state. The endpoint cannot prove that every offline sync client has upgraded; the activation UI explains the minimum version and plugin adaptation requirements, and the user explicitly enables the mode. General configuration updates cannot bypass this activation flow, and old requests omitting new fields cannot reset the mode to `1`.+`/api/notebook/enableStructuredTitles` accepts `notebook` and `expectedRevision`. Normal activation from compatibility mode checks the configuration revision, ready index, and local client compatibility before persisting mode `2`. Mode conflicts use the dedicated recovery flow below, without first requiring a ready index in the conflicting state. The endpoint returns current `documentCapabilities`; `recovering` means only that the activation decision is durable, while writes still await recovery. If already enabled with a matching revision, it may return the current state. The endpoint cannot prove that every offline sync client has upgraded; the activation UI explains the minimum version and plugin adaptation requirements, and the user explicitly enables the mode. General configuration updates cannot bypass this activation flow, and old requests omitting new fields cannot reset the mode to `1`.### Contract and declaration maintenance@@ -295,11 +329,11 @@ Implementation follows [Kernel API type contracts](API-CONTRACTS.md): define dec## API and plugin compatibility-Mode `1` is compatibility mode; mode `2` is explicitly enabled structured title mode. An old notebook without the field reads as `1`. The mode determines availability of legacy protocols, not a guess based on whether a particular request happens to contain `/`.+Mode `1` is compatibility mode; mode `2` is explicitly enabled structured title mode. An old notebook with neither the field nor a higher capability record reads as `1`; a missing field cannot override an established capability floor. The mode determines availability of legacy protocols, not a guess based on whether a particular request happens to contain `/`.| Use case | Compatibility mode `1` | Structured title mode `2` | Plugin migration || --- | --- | --- | --- |-| Reads, moves, and deletion by ID | Preserve existing contracts | Preserve identity, authorization, and response variants | Keep using IDs; reread location after moves |+| 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 |@@ -307,8 +341,8 @@ Mode `1` is compatibility mode; mode `2` is explicitly enabled structured title| `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 | Run with original grammar | Compile internally into structured plans | Explicitly use version `2` templates when `/` in a variable must remain within one segment |-| `getDocCreateSavePath` | Preserve legacy configuration results | Preserve results for old templates; return `structuredTemplateRequired` for new templates | Use `getDocCreateTarget` for the effective versioned configuration |+| 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 |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.@@ -322,18 +356,32 @@ Plugins migrate through capability discovery, reading known targets by ID, resol### Mixed-version access-Notebook configuration adds `documentAddressingVersion`: absent or `1` means compatibility mode, and `2` means structured title mode. This is independent of encryption-envelope versions and must not reuse `BoxCrypt.Spec`. Enabling the mode does not rewrite existing document titles or IDs in bulk; it changes subsequent operation eligibility and representation rules for new content.+Notebook configuration adds `documentAddressingVersion`: an absent field or `1` denotes compatibility mode, and `2` denotes structured title mode. Effective mode also considers the capability floor records below instead of relying only on this field. This is independent of encryption-envelope versions and must not reuse `BoxCrypt.Spec`. Enabling the mode does not rewrite existing document titles or IDs in bulk; it changes subsequent operation eligibility and representation rules for new content.Even if `.sy` continues storing a string title, older clients can remove `/` or interpret title text as hierarchy. Release in two steps: first a protective version that recognizes notebook capability markers and safely rejects unsupported modes, then a feature version that allows enabling mode `2`. The protective version rejects unsupported modes before mounting, indexing, repairing, editing, or applying sync changes; it must not modify data before requesting an upgrade.Documents actually using new title capabilities adopt a new `DocumentTitleSpec`. Allocate its numeric value against the `.sy` versions in use at implementation time, rather than reserving a number in this draft. Enabling a notebook does not rewrite every document that does not use the capability. Future rich representations also need explicit format versions, and tolerant parsing must never overwrite unknown content.-Version protection covers full reads, attribute-only reads, read-only path recovery, import, history, backups, and sync. Currently, the non-strict `readDocIAL` branch does not execute the same `CheckSpecJSON` validation as the strict branch; checking only ordinary editor loads is insufficient. A source version requiring mode `2` in a mode `1` notebook produces a mode conflict first. Import continues only after explicit activation, never by silently cleaning titles to fit the old mode.+Version protection covers full reads, attribute-only reads, read-only path recovery, import, history, backups, and sync. Currently, the non-strict `readDocIAL` branch does not execute the same `CheckSpecJSON` validation as the strict branch; checking only ordinary editor loads is insufficient. If the source title format or actual content requires mode `2` while the notebook's effective mode is `1`, return `modeConflict` first. Import continues only after explicit activation, never by silently cleaning titles to fit the old mode. Other newer body features do not automatically require structured title mode.Determine the minimum compatible version through read, write, and rejection tests against actual releases. Clients predating the protective release that ignore capability markers cannot be constrained automatically by new fields and are outside the safe mixed-version promise. All sync devices must upgrade before activation. Offline device state cannot be proven and must be explained. If a supported version still has a path that rewrites data, keep the capability disabled rather than substituting documentation for necessary protection.Mode `2` has no direct switch back to `1`. Even after current titles no longer contain `/`, history and backups can retain new formats. Older clients may use a verified compatible export copy or a complete pre-activation backup restored into a separate workspace; do not overwrite the original workspace with old configuration and continue syncing. Any future downgrade converter requires its own conversion manifest, conflict policy, and recovery design while preserving original data.+### Mode records and conflict recovery++Activation writes a separate capability floor record `{version: 1, notebook, minimumMode: 2}` to the notebook's `.siyuan/document-addressing.json`. It contains only identity and version information and accompanies native notebook exports, backups, and sync. The workspace also retains confirmed minimum modes keyed by notebook ID in `conf/document-addressing.json`; include it in workspace configuration backups without storing titles or keys there. The effective mode is the strictest requirement from valid notebook configuration, the capability floor record, and the local confirmed record. A record is not proof of ciphertext authentication. Unknown record versions, invalid fields, or mismatched identities preserve the original files and refuse processing rather than defaulting to mode `1`.++The protective release recognizes both configuration and capability floor records, rejecting unsupported modes 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.++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.++Normal activation coordinates the local floor, notebook floor, and configuration writes through a durable record containing only identity and stage information. After interruption, complete the confirmed activation decision without retracting a mode requirement already written. Enter `modeState: "structured"` only once indexes and records are consistent. The configuration revision covers these activation states and records rather than just ordinary configuration modification time.++If a valid activation record exists but configuration lags, recovery may proceed automatically under the confirmed mode. Without a valid activation record, finding source titles that require mode `2` enters `modeState: "conflict"` and rejects ordinary writes. Under authorization and encrypted-notebook leases, administrators can inspect source formats and required capabilities through an independent read-only scan. That scan does not depend on derived indexes, modify source files, or tolerate unknown formats or unauthenticated ciphertext.++After the user explicitly chooses recovery to mode `2`, `enableStructuredTitles` validates the latest `expectedRevision`, local compatibility, and source inspection results. It first persists the activation decision, then enters `modeState: "recovering"` to build indexes; this recovery path does not require the original index to be `ready`. Success enters `structured`. Scan, authentication, or build failure preserves source files, keys, and recovery records, blocks ordinary writes, and reports the error. Retrying continues the same recovery decision instead of downgrading or recreating the notebook. Unknown source formats still require a reader upgrade; explicit activation never bypasses format validation.+### 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.@@ -350,18 +398,22 @@ To cover a crash after the source write but before recovery work is registered,Existing encrypted data is the compatibility baseline, subject to the authenticated-read, isolation, and recovery requirements in [Encrypted notebooks](ENCRYPTED-NOTEBOOK.md). Title sources, plain-text titles, and ancestor chains are protected document content. Reads, caches, and responses must remain within the notebook's authorization scope and operation lease, with cleanup on lock following the existing lifecycle.+In encrypted notebooks, `docCreateTarget`, `refCreateTarget`, and `dailyNoteTarget` are protected configuration and must not be persisted directly as plaintext `BoxConf` fields. The current encrypted `BoxCrypt.Metadata` payload contains only icon and sorting metadata. Define an independent `version: 2` for this payload, retaining `icon`, `sort`, and `sortMode` and adding `documentTargets` for the three optional target objects. Authenticate and read existing payloads without `version` as version `1`; ordinary configuration saves remain compatible with them. Generate version `2` when writing new target objects and do not downgrade that payload after removing the objects. Interpret this version separately from `BoxCrypt.Spec`, target-object `version`, and `.sy` versions.++While unlocked, the configuration reader projects target objects into authorized administrator responses under a lease. Before persistence, clear them from the plaintext configuration copy and retain only authenticated ciphertext. Clear corresponding plaintext caches on lock, and omit these objects from locked status and configuration responses and from non-administrator responses. Omitted or filtered fields do not request deletion. Ordinary configuration saves while locked preserve existing ciphertext verbatim; creating or changing target objects requires unlocking first. Cover old payload fixtures in new-payload reads, password-change rewrapping, import/export, historical configuration, and backup recovery. Reject interpretation or overwriting on unknown payload versions or authentication failure; unrecognized struct fields must not cause new configuration to be discarded.+Derived indexes can be rebuilt only after authenticating source ciphertext and validating the document format. Unknown formats, corruption, and authentication failures must preserve original data and return errors, without falling back to plaintext, cross-notebook queries, or unauthenticated old indexes. Rebuilding ordinary indexes does not establish authentication of encrypted source data.-Internal decoupling does not require changes to encryption envelopes, AAD, or key derivation. Any later change to those formats requires a separate explicit version, authenticated migration, and interruption recovery design that retains matching keys and backup material. Never regenerate `MasterSalt`, discard keys, or require users to recreate existing encrypted notebooks to avoid incompatibility. Supported formats in documents, history, backups, and sync snapshots must remain recoverable.+The versioned configuration-payload extension retains the existing authenticated container, `siyuan/box-metadata` subkey purpose, and notebook-bound AAD without changing encryption envelopes, AAD semantics, or key derivation. Any later change to those formats requires a separate explicit version, authenticated migration, and interruption recovery design that retains matching keys and backup material. Never regenerate `MasterSalt`, discard keys, or require users to recreate existing encrypted notebooks to avoid incompatibility. Supported formats in documents, history, backups, and sync snapshots must remain recoverable.## Implementation stages and activation gates| Stage | Deliverables | Completion criteria || --- | --- | --- |-| A: Compatibility protection | Notebook capability markers, unknown-mode and source-version protection, existing behavior fixtures | Protective version released; unsupported modes safely rejected at every write and repair entry point |+| A: Compatibility protection | Notebook capability floors and conflict detection, unknown-mode and source-version protection, existing behavior fixtures | Protective release shipped; modes checked before sync and snapshot application, unsupported modes safely refused at every write and repair entry point || B: Internal separation | Shared title access, document metadata, ID hierarchy calculations, path refresh, and recovery | Ordinary titles retain behavior; structure is no longer derived from display strings; encrypted indexes rebuild from authenticated sources |-| C: APIs and consumers | New read, resolve, and create APIs, version `2` templates, built-in workflow and platform migration | New and old contracts verified; partial failures recoverable; daily-note and other business behavior retained |-| D: New characters | Mode activation, legacy API rejection rules, plugin migration guidance, import/export and cross-version verification | Allow explicit user activation of `/` only after all gates pass |+| C: APIs and consumers | New read, resolve, and conditional-create APIs, version `2` templates and encrypted payloads, built-in workflow and platform migration | Name and configuration conditions and old/new contracts verified; partial failures and undo recoverable; daily-note and other business behavior retained |+| D: New characters | Mode activation and conflict recovery, legacy API rejection, plugin migration guidance, cross-mode operations, and import/export checks | Whole-subtree preflight, mode recovery, and all activation gates pass before explicit user activation of `/` || E: Inline titles | Separate source-format, editing, and rendering design | Retain this design's identity APIs and deliver separately after format and old-writer protection |Stages B and C may ship while retaining legacy title restrictions. New characters require all relevant conditions in A through D. Stage E is not a prerequisite for the foundational separation, but A through D must not reintroduce assumptions that titles will permanently have plain-text sources.@@ -378,14 +430,14 @@ Implementation still needs actual release version numbers, an available `.sy` ve| --- | --- || 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; parent deletion, cross-notebook moves, closure, or locking; lost responses, partial commits, fixed-ID conflicts, and multi-level recovery |-| Templates | All legacy syntax boundaries, segment-by-segment rendering, variables containing `/`, relative operations, one time snapshot, and daily note, shorthand, and related entry points |+| 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 || 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 and export | Duplicate names, invalid filenames, case collisions, path escape, relative links, cross-notebook references, title metadata, and lossless round-trip guarantees |-| Legacy APIs and plugins | Unchanged mode `1` responses; notebook-wide legacy-addressing rejection in mode `2`; SQL display collisions, structured replacements, and missing capabilities distinguished from request errors |-| Older clients and encryption | Supported historical format fixtures, mixed-version sync, 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 |+| 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 |+| Older clients and encryption | Supported historical source and configuration payload fixtures; mixed-version 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 |+| 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 |### Essential regression cases@@ -394,6 +446,14 @@ Retain `TestCreateDocsByHPathUsesParentIDForDuplicateHPath` and `TestCreateDocsBCreate a root document `A/B`, a root document `A` with child `B`, a root document `A/B`, and a root document `A%2FB` together. The first two may share a display path, but must retain correct IDs, `segments`, `depth`, subtree scope, and export links. Neither of the latter two may be converted into the former structures. Add repeated slashes, dot segments, empty titles, case differences, and different title formats with identical plain text.+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. Moves, copies, imports, and recovery into mode `1` all fail before the first write, and descendant changes after preflight are detected. Retry successfully after explicit destination activation without relaxing encryption boundaries. Documents with other newer body features but compatible titles must not be misclassified as requiring mode `2`.++Simulate old-configuration replacement, missing or corrupt capability records, interrupted sync, and source documents already requiring mode `2` while indexes remain unavailable. Verify that effective mode never decreases, unknown formats preserve original data, explicit activation can enter independent recovery, and restart resumes the original recovery decision. Cover deletion followed by restoration of the same notebook identity, and preservation of capability floors when whole-notebook imports remap identities. Inspect new configuration payload persistence and locked responses and caches for absence of plaintext target objects, and verify old payload reads and recovery after backups and password changes.++Retain `TestHeadingDocParagraph` and `TestHeadingDocParagraphTextMark` so foundational separation continues covering images, links, and original heading content preserved in the body. Stage E additionally verifies supported nodes in title sources and both conversion directions without deleting user paragraphs based on equal plain text. Template document trees cover grouped undo and redo, partial commits, name or ID conflicts on redo, and user edits after creation, not just successful creation.+Actual HTTP regressions verify strict request types, required fields versus `null`, result ordering, truncated candidates, error data, administrator and writable access, encrypted response leases, and published-visitor rejection. Assert old compatibility behavior separately from new endpoints instead of replacing legacy expectations. Frontend tests cover old template configuration round-trips, new segment evaluation, one time snapshot, partial-success presentation, and mobile entry points.Fault injection covers at least the boundaries before and after source persistence, before and after metadata transactions, interrupted content-index batches, lost success responses, and locking during response serialization. Use real fixtures from supported historical formats for reads, export, history, backup, and recovery, and verify safe rejection of new formats by the protective release. Testing only files generated by the current version does not establish backward compatibility.@@ -426,4 +486,6 @@ Change CI filters or maintenance guides only if existing discovery would miss ne| Daily-note reuse and legacy creation regressions | [`model/daily_note.go`](../kernel/model/daily_note.go), [`model/file_test.go`](../kernel/model/file_test.go) || Import and export | [`model/import.go`](../kernel/model/import.go), [`model/import_obsidian.go`](../kernel/model/import_obsidian.go), [`model/export.go`](../kernel/model/export.go) || Reusable rich-source validation pattern | [`treenode/table_cell_rich.go`](../kernel/treenode/table_cell_rich.go) |+| Heading/document conversion | [`model/heading.go`](../kernel/model/heading.go), [`model/heading_doc_test.go`](../kernel/model/heading_doc_test.go) |+| Configuration encryption and sync application | [`model/box_conf_crypto.go`](../kernel/model/box_conf_crypto.go), [`model/repository.go`](../kernel/model/repository.go), [`model/sync_checkout.go`](../kernel/model/sync_checkout.go) || Document versions | [`treenode/tree.go`](../kernel/treenode/tree.go), [`.sy` file structure](SY-FORMAT.md) |diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.mdindex a2aa226f9e..11d1248802 100644--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md@@ -2,7 +2,7 @@[English](DOCUMENT-ADDRESSING.md)-关联问题:[Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938)+关联问题:[Improve hPath by separating display text from document addressing](https://github.com/siyuan-note/siyuan/issues/19938)、[Improve content preservation when converting headings to documents](https://github.com/siyuan-note/siyuan/issues/19235)本文为实施设计草案,规定文档标题、层级定位、可读路径、接口及迁移的目标行为。下文新增的字段、接口和版本机制均为拟实现契约,不表示当前版本已经支持。当前重命名与路径索引的更新机制见 [文档重命名与路径索引](DOCUMENT-HPATH.md)。@@ -109,6 +109,12 @@块引用、动态锚文本、链接、标签和资源需要进一步定义依赖更新、点击行为、引用及资源归属、循环引用处理、复制与导入时的 ID 重映射,以及加密边界。本方案保留这些能力的表示空间,不表示所有行级元素都会同时开放。后续富文本标题实现还必须覆盖输入法、选区、撤销、移动端交互、历史、同步和导出。+### 标题块与文档转换++当前 `Heading2Doc` 通过 `headingDocParagraph` 将文档名无法完整表达的行内节点移入正文段落,包括图片、链接、样式以及被规范化或截断的原文字。基础解耦必须保留这一行为;允许标题中的 `/` 后,仅因斜杠替换而产生的保留段落可以不再需要,但不能因此丢弃其他内容。文档标题的文本提取与原节点内容保留分别判断。++将 #19235 作为后续行级标题的双向转换验收:支持的行级元素连同资源引用进入标题源内容;暂不支持的元素继续保留在正文。反向转换或合并回正文时,保留节点内容、资源归属和引用关系,并按明确规则恢复标题层级。相同纯文本不证明正文段落是标题副本,不能据此删除用户内容。若提供自动合并,须记录可校验的转换来源及内容版本;无法确认或用户已编辑时保留内容,不能盲目去重。现有普通文档不自动将首段迁入标题。+本次解耦的验收必须确认:增加一种标题表示时,寻址和层级规则无须改变;现有普通标题的字面内容保持不变;消费者通过约定的标题读取边界获取内容,不能各自猜测标题语法。## 创建与路径模板@@ -139,11 +145,15 @@结构化标题段中的 `/` 不拆分层级,`.`、`..` 不执行导航。向上一级、从笔记本根开始和以当前文档为起点需要独立表达。空段数组表示起点自身,空字符串不能用来自动匹配空标题父文档;最终创建的空标题仍可显式提交。是否允许创建缺失祖先,由调用方的 `onMissingParent` 策略决定。+名称匹配结果与父路径版本是不同的提交条件。`nameConditions` 记录 `{parentID, title, expectedID}`:`parentID` 为父文档 ID 或逻辑根的 `null`,非空 `title` 按统一纯文本规则精确匹配;`expectedID: null` 表示仍不存在同名子文档,文档 ID 则表示唯一匹配仍为该文档。省略 `expectedID` 无效。条件最多 128 项,只能涉及本次目标所在笔记本、其实际祖先链及最终父级,不能用来枚举无关位置。笔记本文档 ID 先规范化为逻辑根,查询排除笔记本文档自身及空标题占位值。++创建缺失祖先必须提交相应的不存在条件,并保留此前按名称匹配祖先的唯一身份条件。内核在与创建、重命名、移动、删除共用的协调范围内重新查询,并保持到源文档及元数据提交完成;任一条件不成立返回 `planChanged`,调用方重新解析,不自动复用刚出现的同名文档。两个调用方同时创建同名祖先时,至多一个满足原不存在条件。普通最终文档创建可以省略名称条件,继续允许同父同名,不给标题添加唯一索引。`expectedParentRevision` 不能代替这些条件。+### 提交、部分失败与重试-首版不新增通用的跨文件原子创建接口。内核业务使用创建计划,插件通过解析接口及单文档创建接口组合操作。计划在写入前校验所有可预知的标题、深度、歧义、模板及权限错误,并为待创建的每篇文档分配固定 ID;已匹配祖先记录身份和版本。执行时重新检查匹配和版本,并发出现同名候选时要求重新规划,不能悄悄改用另一篇文档。+首版不新增通用的跨文件原子创建接口。内核业务使用创建计划,插件通过解析接口及单文档创建接口组合操作。新协议及模式 `2` 的计划在写入前校验所有可预知的标题、深度、歧义、模板及权限错误,并为待创建的每篇文档分配固定 ID;已匹配祖先记录身份和版本。执行时重新检查匹配和版本,并发出现同名候选时要求重新规划,不能悄悄改用另一篇文档。模式 `1` 的旧业务按下文兼容规则保持原选择语义。-每个创建步骤独立提交。成功响应要求源文档及本次必需的正文、属性修改已同步持久化,文档元数据已可读取;搜索全文索引可按现有机制异步更新。模板、脚注、数学内容、剪藏来源、标签、排序及刷新通知按原业务语义执行,不能因拆分定位逻辑而丢失。+通用多级创建按文档分别提交;已有模板文档树仍保留父文档编辑与子文档创建共用的事务及撤销分组,不能因迁移定位逻辑而拆成互不相关的用户操作。成功响应要求源文档及本次必需的正文、属性修改已同步持久化,文档元数据已可读取;搜索全文索引可按现有机制异步更新。模板、脚注、数学内容、剪藏来源、标签、排序及刷新通知按原业务语义执行,不能因拆分定位逻辑而丢失。写入途中失败时保留已落盘文档。错误数据区分 `commitState: "none"`、`"committed"`、`"unknown"`,并返回可确认的文档 ID、失败阶段及已完成步骤;`committed` 仅表示源文档已提交,不表示所有后续动作成功。落盘状态无法确认时必须返回 `unknown`,不得声称未写入。多级业务同时保留原计划及已完成 ID,向用户提供继续处理的位置。@@ -151,11 +161,15 @@恢复只处理未完成步骤,不自动删除已经成功创建的父文档。源数据清理等不可重复的后续操作,仅在业务所需步骤全部成功后进行;部分成功和单纯收到文档 ID 都不足以触发速记源数据删除。+模板文档树正常完成后,撤销和重做保持父文档修改与本次创建文档的原有分组及 ID 重映射语义。部分失败时,恢复与撤销记录必须依据实际完成步骤,不能操作未提交的文档;重做使用已保存的计划快照,不重新执行时间敏感的模板。已有文档或已创建文档发生后续修改时,沿用事务冲突检查,不能以清理失败计划为由删除这些修改。无法确认副作用是否完成时停止自动续作并展示已确认结果,不把索引恢复标记当作业务成功凭据。+### 模板版本旧字符串保存路径继续使用原有解释规则,包括绝对与相对路径、`..`、末尾 `/`、空模板、跨笔记本上下文,以及显式名称替换末段的行为。新建语法必须有可识别的版本,不能自动将已有配置按新规则重解释。-旧模板由兼容编译器按原语法求值,再输出结构化创建计划;另行传入的新标题保持独立,不重新拼入路径字符串。相对起点和向上导航使用当前文档 ID 及父关系,不能先把当前文档的显示路径拆成旧模板段。该内部适配不调用被新模式禁用的公开字符串寻址接口,因此已有日记等配置仍可工作。旧模板内变量产生 `/` 时继续按旧语法分层,只有显式改用新模板后才保留为单段。兼容编译保留语法,不保留任意选取同名父文档的做法;未知祖先仍执行歧义检查。+旧模板由兼容编译器按原语法求值,再输出结构化创建计划;另行传入的新标题保持独立,不重新拼入路径字符串。相对起点和向上导航使用当前文档 ID 及父关系,不能先把当前文档的显示路径拆成旧模板段。该内部适配不调用被新模式禁用的公开字符串寻址接口,因此已有日记等配置仍可工作。旧模板内变量产生 `/` 时继续按旧语法分层,只有显式改用新模板后才保留为单段。++模式 `1` 的旧业务入口及旧字符串模板保留既有同名选择和 `parentID` 回退行为;内部实现改用身份后仍须通过旧行为回归,不能因共享严格解析器而悄悄改成歧义错误。新结构化接口在两个模式中均执行严格歧义检查。模式 `2` 的内置业务使用严格计划,即使输入来自旧模板也不得任取同名父文档;这是显式启用时需要说明的行为变化。跨笔记本目标使用新协议时同样保持严格规则,不因目标为模式 `1` 而恢复任取行为。新配置分别使用 `docCreateTarget`、`refCreateTarget`、`dailyNoteTarget`,与原保存路径字符串字段并存。首版仅在已启用模式 `2` 的笔记本配置中开放这三个对象,全局配置继续保留旧字符串模板及现有继承规则,避免未经笔记本启用便引入旧客户端无法识别的配置。对象必须带 `version: 2`,指定目标笔记本、起点、向上层数、祖先段、最终标题和缺失祖先策略;各段继续复用现有保存路径模板求值器。示例中的 `{{now | date ...}}` 是保存路径模板语法,不能与正文模板语法混淆。@@ -177,6 +191,8 @@新对象存在时,它是相应创建目标的唯一权威配置;旧字符串仅保留为原配置记录。修改旧字段为不同值时必须返回明确的配置冲突,不能静默覆盖新对象;原样回传旧字段仍可接受。显式移除新对象后可重新使用旧模板,但不会将笔记本降回兼容模式。未配置新对象时沿用现有笔记本及全局配置选择顺序。跨笔记本的目标仍按目标笔记本模式校验标题,不能因为来源已启用模式 `2` 而绕过目标限制。+由配置生成的预览保存配置来源笔记本、业务用途、有效配置版本及已求值上下文。提交时使用 `expectedTarget: {notebook, purpose, revision}` 校验配置,其中 `notebook` 是读取配置的来源笔记本,可能不同于创建请求的目标笔记本。版本覆盖生效目标、参与继承的配置及选中的正文模板路径;无关设置不使预览失效。内核在配置更新与文档变更共同遵守的协调范围内重新解析有效配置,校验版本和目标笔记本后提交;配置变化返回 `planChanged`,即使父路径未变也不能继续。模板正文预览另保存已渲染内容及依赖快照,不能用配置版本代替正文快照校验。+### 业务入口迁移| 入口 | 保持的业务行为与迁移重点 |@@ -185,7 +201,7 @@| 日记 | 先按日记日期属性复用;多个匹配时保留现有模板目标优先、否则按 ID 排序的规则,已有日记不重新应用正文模板 || 速记 | 明确追加目标或新建目标;目标持久化成功后才清理来源 || 数据库新建条目 | 保留属性值、绑定关系和排序;创建计划保存最终文档 ID |-| 模板文档树 | 保留预览、ID 重映射和插入顺序,提交校验预览版本并展示部分完成结果 |+| 模板文档树 | 保留预览、ID 重映射、插入顺序及整组撤销和重做;提交校验路径、名称与配置条件并展示部分完成结果 || 桌面、浏览器和移动端 | 分别检查菜单、快捷键、对话框及事件处理;共享工具函数迁移不能代替各端验证 |日记的既有复用策略是明确的业务规则,不因通用解析器拒绝歧义而改成所有同日期情况均报错;模板目标优先匹配改为结构化身份链比较。@@ -206,6 +222,16 @@## 导入与导出+### 跨模式移动与恢复++跨笔记本移动、复制、原生导入及历史恢复在首次写入前检查完整操作集合,包括每个根文档的所有后代。检查目标模式、标题格式和原文、源格式可读性、目标深度及既有加密边界;不能仅检查顶层标题。只要任一文档需要目标尚未启用的标题能力,整次操作返回 `targetModeUnsupported`,并提供授权范围内的冲突文档 ID;不移动目录、不改写标题、不删除来源,也不自动启用目标模式。++用户明确启用目标模式并完成恢复后,重新规划和校验操作。新建目标笔记本的导入流程也先取得明确的模式选择,再提交文档。需要的标题能力由标题格式及实际内容决定;`.sy` 版本表示源格式的读取要求,不把所有高于 `DocumentTitleSpec` 的版本都等同于需要模式 `2`,也不为通过检查而降低源版本。符合目标规则的普通标题可以从模式 `2` 的笔记本进入模式 `1`。++已就绪元数据可用于检查完整子树,导入和历史使用对应的已认证源快照;缺失或过期索引先恢复,不用旧 `hPath` 推断能力。预检记录整个操作集合的身份、成员及标题和位置版本,提交在变更协调范围内复核,防止预检后后代改名或新增。可预知的不兼容必须在任何写入前拒绝;实际 I/O 失败沿用部分提交记录及恢复规则,不承诺跨文件原子移动。普通与加密笔记本之间、不同加密笔记本之间的既有隔离规则保持不变。++### 文件名与链接映射+导出先为每个文档身份分配唯一的相对文件路径,再用同一份映射写文件及生成文档间链接。映射必须处理标题中的斜杠、非法文件名字符、同名文档、大小写不敏感冲突、长度限制和跨笔记本同名;文件覆盖检查与链接生成不能各自临时决定文件名。分配器先按 ID 关系确定导出目录,再独立转换每个文件名。兼容已有无冲突文件名;遇到保留名称、空名称、`.`、`..`、尾部空格或点等情况时使用安全名称,冲突时附加稳定的文档 ID,必要时再加笔记本 ID。按目标文件系统规则比较大小写和名称,截断时保留唯一后缀及扩展名。所有名称分配完成后再次校验相对路径唯一性及目标目录边界,随后写文件和链接。标题中的 `/` 只影响单个文件名转换,不产生新目录。@@ -230,7 +256,9 @@`/api/filetree/resolveDocPath` 接收 `notebook`、`start` 与 `segments`。`start` 为 `{kind: "root"}` 或 `{kind: "document", id: string}`,`segments` 为独立标题字符串数组。接口只解析,不创建。空数组返回起点;非空数组按精确名称逐级查找,不解析字符串中的导航字符。-结果包含 `status`、`start`、`resolved`、`nextIndex`、`candidates` 和 `candidatesTruncated`。`start` 返回起点身份及版本,`resolved` 和 `candidates` 使用 `DocumentPath`;`nextIndex` 是下一待处理段的零基索引。`status: "resolved"` 表示全部命中,`"missing"` 表示从该段开始没有文档,`"ambiguous"` 表示该段存在多个候选。候选按 ID 排序,最多返回 128 个,并用 `candidatesTruncated` 表示仍有更多结果;达到上限仍必须报告歧义,调用方改用明确父 ID,不能从截断结果中默认选择第一项。+结果包含 `status`、`start`、`resolved`、`nextIndex`、`candidates`、`candidatesTruncated` 和 `nameConditions`。`start` 返回起点身份及版本,`resolved` 和 `candidates` 使用 `DocumentPath`;`nextIndex` 是下一待处理段的零基索引。`status: "resolved"` 表示全部命中,`"missing"` 表示从该段开始没有文档,`"ambiguous"` 表示该段存在多个候选。候选按 ID 排序,最多返回 128 个,并用 `candidatesTruncated` 表示仍有更多结果;达到上限仍必须报告歧义,调用方改用明确父 ID,不能从截断结果中默认选择第一项。++`nameConditions` 包含已经唯一匹配的各段条件;缺失结果再包含首个缺失段的不存在条件,歧义结果不为歧义段生成成功条件。空段数组返回空条件数组。解析的链和条件来自同一可验证快照,提交时仍须重新检查。插件创建首个缺失祖先后按原起点及完整的原始段数组重新解析,使后续条件引用已确认的父 ID;不能把一次缺失结果当成对整条尚不存在路径的预留。解析最多接受 128 段,每段遵守标题长度限制,实际创建仍执行用户的文档深度限制。空字符串段失败,名称为空的已有父文档需按 ID 选定。笔记本根作为解析结果时使用明确的根位置,不伪造文档 ID;根版本覆盖笔记本身份及相关配置,不因无关子文档变化而失效。作为根位置别名的笔记本文档 ID 也使用根版本校验。错误和候选不得泄露其他笔记本的标题。@@ -256,38 +284,44 @@| `title` | 必填,首版仅接受普通标题对象;空字符串与缺省值不同 || `markdown` | 必填,允许空字符串 || `expectedParentRevision` | 可选,提交预览时用于校验父路径版本;根位置使用解析接口返回的根版本 |+| `nameConditions` | 可选,至多 128 项名称匹配条件;创建缺失祖先必传,不存在条件对应本次创建的非空标题与父级 |+| `expectedTarget` | 可选,包含来源 `notebook`、`purpose` 和配置 `revision`;从保存路径配置生成的预览提交必须携带 || `tags`、`withMath`、`clippingHref` | 可选,复用现有 Markdown 创建流程对应的处理规则 || `sorts`、`sortTargetID`、`sortPosition` | 可选,保持排序校验;相对排序目标必须仍是同一父级下的文档,冲突排序方式报错 || `docCreateTemplatePath`、`listDocTree` | 可选,沿用现有正文模板与文档树刷新语义 |接口拒绝额外提交的 `path`、`hPath` 等目标字段,避免两个位置来源互相覆盖。父文档不匹配时直接失败,不能退回名称寻址。成功返回 `{id, document: DocumentPath}`;客户端直接使用返回 ID 打开、引用或追加内容。-业务错误使用 `code: -1`,`data.reason` 提供稳定原因;`msg` 用于人类阅读,不作为插件分支条件。契约声明保留错误数据,以传递提交状态和恢复信息。认证、角色、锁定及通用请求校验错误继续使用相应中间件契约,不强行改写所有既有错误格式。+名称条件、父路径版本和配置版本分别校验,不能相互替代;缺省条件表示直接按已知身份创建,不承诺保持先前按名称或配置得到的预览。条件均不是授权凭据,内核仍验证权限、归属和租约。多级计划每次提交前校验其适用条件,失败时返回本次及此前步骤的真实提交状态,不重选父文档。++业务错误使用 `code: -1`,`data.reason` 提供稳定原因;`msg` 用于人类阅读,不作为插件分支条件。下表汇总本方案涉及的原因,各创建、移动、导入或恢复接口仅声明适用的错误变体,并保留相应提交状态和恢复信息。认证、角色、锁定及通用请求校验错误继续使用相应中间件契约,不强行改写所有既有错误格式。| 原因 | 含义及调用方处理 || --- | --- || `invalidTitle` | 标题格式、字符或长度无效,修改输入后提交 || `parentUnavailable` | 父文档不存在或不属于目标笔记本,不跨笔记本查找 |-| `planChanged` | 位置、标题版本或预览依赖变化,重新解析并确认目标 |+| `planChanged` | 位置、标题版本、名称匹配或配置等预览依赖变化,重新解析并确认目标 || `documentIDConflict` | ID 已存在,核对原请求结果,不覆盖或直接换 ID 重试 || `legacyPathUnsupported` | 目标笔记本禁用旧字符串寻址,改用新接口 || `indexUnavailable` | 结构化元数据未就绪,等待恢复,不回退到显示路径 || `unsupportedTitleFormat` | 客户端或接口不能处理标题格式,升级或改用对应格式接口 |+| `targetModeUnsupported` | 移动、复制、导入或恢复的完整操作集合超出目标模式;明确启用目标后重新规划 |+| `modeConflict` | 笔记本模式记录与源标题能力不一致,进入受控恢复,不按兼容模式继续写入 || `writeFailed` | 写入或后续处理失败,依据 `commitState` 及阶段恢复 |### 读取有效创建目标-`/api/filetree/getDocCreateTarget` 接收当前 `notebook` 与 `purpose: "document" | "reference" | "dailyNote"`,复用各业务现有的配置优先级,返回生效的 `target`、`docCreateTemplatePath` 和配置 `revision`。`target` 为带 `version` 的联合类型:旧模板返回 `{version: 1, notebook, path}`,新模板返回上文完整的版本 `2` 对象。接口只读取配置,不执行模板、不猜测当前文档或当前日期;调用方随后提供上下文生成计划。+`/api/filetree/getDocCreateTarget` 接收当前 `notebook` 与 `purpose: "document" | "reference" | "dailyNote"`,复用各业务现有的配置优先级,返回生效的 `target`、`docCreateTemplatePath` 和配置 `revision`。`target` 为带 `version` 的联合类型:旧模板返回 `{version: 1, notebook, path}`,新模板返回上文完整的版本 `2` 对象。返回字段 `docCreateTemplatePath` 表示该业务的有效正文模板:普通新建按现有继承规则选择,日记取 `DailyNoteTemplatePath`,块引用新建保持当前不自动应用正文模板的行为并返回空字符串。接口只读取配置,不执行模板、不猜测当前文档或当前日期;调用方随后提供上下文生成计划,并将来源、用途及 `revision` 放入提交条件。-旧 `/api/filetree/getDocCreateSavePath` 在生效配置仍为旧模板时保持原响应;新对象生效时返回 `code: -1`、`data: {reason: "structuredTemplateRequired"}`,不返回已经失效的旧路径。该错误变体在旧契约中明确声明。新增读取入口同时服务内置调用方和插件,避免各自重复实现配置继承规则。+旧 `/api/filetree/getDocCreateSavePath` 与 `/api/filetree/getRefCreateSavePath` 在各自生效配置仍为旧模板时保持原响应;对应的新对象生效时均返回 `code: -1`、`data: {reason: "structuredTemplateRequired"}`,不返回已经失效的旧路径。判断依据是配置来源及对应业务,不取决于旧路径或新目标指向哪个笔记本;旧目标仍为模式 `1` 也不能放行历史配置。两个错误变体分别在旧契约中声明。新增读取入口同时服务内置调用方和插件,避免各自重复实现配置继承规则。### 能力探测与启用-在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`structuredPaths` 表示服务端实现了新协议,`indexState` 表示该笔记本是否可用;两者不能混为一谈。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2` 且索引就绪时为 `true`。+在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`modeState`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`modeState` 为 `legacy`、`structured`、`conflict` 或 `recovering`;`structuredPaths` 表示服务端实现了新协议,`indexState` 表示派生索引状态,均不代替模式状态。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2`、`modeState: "structured"` 且索引就绪时为 `true`。`revision` 是启用流程相关的配置版本;它不等同于某篇文档的路径版本。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。-`/api/notebook/enableStructuredTitles` 接收 `notebook` 与 `expectedRevision`,核查当前配置版本、索引状态和客户端本地兼容能力后持久化模式 `2`,返回最新 `documentCapabilities`。已经启用且版本匹配时可直接返回当前状态。此接口不能证明所有离线同步客户端都已升级;启用界面需要说明最低版本和插件适配要求,由用户明确启用。通用配置更新不能绕过此流程切换模式,省略新字段的旧请求也不能将模式重置为 `1`。+`/api/notebook/enableStructuredTitles` 接收 `notebook` 与 `expectedRevision`。正常从兼容模式启用时,先核查当前配置版本、就绪索引及客户端本地兼容能力,再持久化模式 `2`;模式冲突恢复按后文专门流程执行,不要求冲突状态下先有就绪索引。接口返回最新 `documentCapabilities`,`recovering` 只表示启用决定已持久化,写入仍等待恢复完成。已经启用且版本匹配时可直接返回当前状态。此接口不能证明所有离线同步客户端都已升级;启用界面需要说明最低版本和插件适配要求,由用户明确启用。通用配置更新不能绕过此流程切换模式,省略新字段的旧请求也不能将模式重置为 `1`。### 契约及声明维护@@ -295,11 +329,11 @@## 接口与插件兼容-模式 `1` 为兼容模式;模式 `2` 为显式启用的结构化标题模式。没有模式字段的旧笔记本按 `1` 读取。模式决定旧协议是否可用,不根据某一次请求是否恰好包含 `/` 猜测。+模式 `1` 为兼容模式;模式 `2` 为显式启用的结构化标题模式。没有模式字段且没有更高能力记录的旧笔记本按 `1` 读取;已有能力下界不能被缺省字段覆盖。模式决定旧协议是否可用,不根据某一次请求是否恰好包含 `/` 猜测。| 使用场景 | 兼容模式 `1` | 结构化标题模式 `2` | 插件迁移方式 || --- | --- | --- | --- |-| 按 ID 读取、移动及删除 | 保持现有契约 | 保持身份、权限及返回变体 | 继续使用 ID,移动后重新读取当前位置 |+| 按 ID 读取、移动及删除 | 保持现有契约;移入内容先满足目标模式 | 保持身份及权限;跨模式移动增加整棵子树的准入检查 | 继续使用 ID;处理 `targetModeUnsupported`,移动后重新读取当前位置 || 按 ID 重命名及 ID 数据路径创建 | 保持现有标题规则 | 普通标题可保留 `/`,仍验证模式和标题格式 | 标题与位置分开传递;未知富文本格式不能用纯文本覆盖 || `getIDsByHPath` | 保留原名称路径语法 | 整个笔记本拒绝,返回 `legacyPathUnsupported` | 已知 ID 直接使用;未知位置调用 `resolveDocPath` || `createDocWithMd` | 保留旧语法及 `parentID` 回退行为 | 整个笔记本拒绝,即使传入 `parentID` | 改用 `createDocByParent`,不提交字符串路径 |@@ -307,8 +341,8 @@| `getFullHPathByID` | 保留含笔记本名称的输出及空值规则 | 仍显示笔记本名称,不能反向定位 | 笔记本名称与文档段分别展示 || `blocks.hpath`、`blocktrees.hpath` | 保留列类型及原行为 | 仍是字符串,可能包含无法区分的标题斜杠 | 子树查询使用 ID `path`,标题读取文档行 `content`,父级及深度通过结构化接口取得 || `Criterion.hPath`、`SearchPath`、搜索结果 | 保留既有配置和高亮语义 | 显示文字仍可检索,范围与层级使用 ID | 不把高亮文本或路径显示值重新提交为位置 |-| 旧保存路径模板 | 原语法运行 | 通过内部兼容编译器生成结构化计划 | 需要变量中的 `/` 保持单段时显式使用版本 `2` 模板 |-| `getDocCreateSavePath` | 保留旧配置结果 | 旧模板仍返回原结果,新模板返回 `structuredTemplateRequired` | 通过 `getDocCreateTarget` 读取生效的带版本配置 |+| 旧保存路径模板 | 保留原语法及旧入口的同名选择行为 | 内部兼容编译器生成严格计划,未知祖先有歧义时拒绝 | 需要变量中的 `/` 保持单段时显式使用版本 `2` 模板 |+| `getDocCreateSavePath`、`getRefCreateSavePath` | 保留旧配置结果 | 对应业务的旧模板仍返回原结果,新对象生效时返回 `structuredTemplateRequired` | 通过 `getDocCreateTarget` 读取生效的带版本配置 |不改变旧字段的数据类型,不删除旧 API,也不把模式 `2` 的显示路径编码后伪装成可兼容地址。新模式下两个不同结构可以显示为相同字符串;SQL 的等值 `hpath` 查询也可能返回两种结构。继续按分隔符计数、取末段或做前缀子树查询的插件必须适配,这是启用能力的兼容成本。@@ -322,18 +356,32 @@### 混合版本访问-笔记本配置新增 `documentAddressingVersion`,缺省或 `1` 为兼容模式,`2` 为结构化标题模式。该字段与加密信封版本独立,不能复用 `BoxCrypt.Spec`。新旧模式不批量改写已有文档标题或 ID;开启能力只改变后续操作准入和新内容的表示规则。+笔记本配置新增 `documentAddressingVersion`,字段缺省或 `1` 表示兼容模式,`2` 表示结构化标题模式;有效模式还须结合后文的能力下界记录,不能只读取这个字段。该字段与加密信封版本独立,不能复用 `BoxCrypt.Spec`。新旧模式不批量改写已有文档标题或 ID;开启能力只改变后续操作准入和新内容的表示规则。即使 `.sy` 仍保存字符串标题,旧客户端也可能移除 `/`,或把标题文字当作层级。发布分两步:先发布理解笔记本能力标记、能够安全拒绝未知模式的保护版本,再发布允许启用模式 `2` 的功能版本。保护版本在挂载、索引、修复、编辑及同步应用入口拒绝处理不支持的模式,不能先修改数据再提示升级。真正使用新标题能力的文档采用新的 `DocumentTitleSpec`;具体数值在实现时按当时已使用的 `.sy` 版本分配,不在草案中预占某个数字。未使用新能力的文档不因笔记本启用而全部改写。未来富文本表示还需对应的明确格式版本,未知内容不得被容错解析后覆盖。-版本保护必须覆盖完整读取、仅属性读取、只读路径恢复、导入、历史、备份及同步。当前 `readDocIAL` 的非严格分支不会执行与严格分支相同的 `CheckSpecJSON` 检查,不能仅在普通编辑加载处添加检查就认为完整受保护。源文档版本要求模式 `2` 而配置仍为 `1` 时,先报告模式冲突;导入只能在明确选择启用后继续,不能偷偷清理标题以适配旧模式。+版本保护必须覆盖完整读取、仅属性读取、只读路径恢复、导入、历史、备份及同步。当前 `readDocIAL` 的非严格分支不会执行与严格分支相同的 `CheckSpecJSON` 检查,不能仅在普通编辑加载处添加检查就认为完整受保护。源标题格式或实际内容要求模式 `2` 而笔记本有效模式仍为 `1` 时,先返回 `modeConflict`;导入只能在明确选择启用后继续,不能偷偷清理标题以适配旧模式。版本较新的其他正文功能不自动要求结构化标题模式。最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。启用前要求所有同步设备升级;系统无法证明离线设备状态,应明确说明这一限制。如果已支持版本仍存在会改写数据的路径,保持新能力关闭,不能以文档提示代替必要保护。模式 `2` 启用后不提供直接改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复启用前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。+### 模式记录与冲突恢复++启用时在笔记本 `.siyuan/document-addressing.json` 写入独立的能力下界记录 `{version: 1, notebook, minimumMode: 2}`,只含身份及版本,随原生笔记本导出、备份和同步保存。本机另在工作空间 `conf/document-addressing.json` 保留按笔记本 ID 索引的已确认最低模式;它参与工作空间配置备份,不作为标题或密钥的存储位置。有效模式取合法笔记本配置、能力下界记录和本机已确认记录中最严格的要求。记录不是密文认证凭据;未知记录版本、无效字段或身份不匹配必须保留原文件并拒绝处理,不能按缺省模式 `1` 继续。++保护版本同时识别配置及能力下界记录;不支持的模式在实际处理源文件前拒绝。同步应用和快照恢复先核对受影响笔记本的能力要求,再替换配置或文件。已确认模式 `2` 时,传入旧配置、缺少新字段或删除能力记录都不能降低有效模式;恢复配置投影和下界记录后再开放访问。若只能在文件落盘后检查,或依赖层不能在应用前提供所需配置数据,阶段 A 尚未完成,须先补齐同步和恢复入口,不能以重建索引代替前置保护。++删除整个笔记本仍按现有语义执行,不为补齐能力记录而重新创建已删除的笔记本;本机保留该身份的已确认下界,恢复同一身份时继续生效。完整笔记本的原生导入先校验源身份与能力记录,再按既有导入规则分配或复用目标身份,并将能力下界绑定到目标身份;不得借身份重映射降低源笔记本已确认的模式。向既有笔记本导入部分文档则按前述完整操作集合检查,不直接复制源笔记本的模式配置。++正常启用通过仅含身份和阶段的持久化记录协调本机下界、笔记本下界及配置写入;任一步骤中断后继续完成已确认的启用决定,不撤回已经写入的模式要求。索引完成、记录一致后才进入 `modeState: "structured"`。配置版本覆盖这些启用状态及记录,不能仅取普通配置的修改时间。++已有有效启用记录而配置落后时,可以按已确认的模式自动恢复。没有有效启用记录、但发现源标题需要模式 `2` 时,进入 `modeState: "conflict"`,拒绝普通写入。管理员可在授权和加密租约内通过独立只读扫描检查源格式及所需能力;该扫描不依赖派生索引,不更改源文件,也不容错接受未知格式或未认证密文。++用户明确选择恢复为模式 `2` 后,通过 `enableStructuredTitles` 校验最新 `expectedRevision`、本地兼容能力和源检查结果,先持久化启用决定,再进入 `modeState: "recovering"` 构建索引;这条恢复路径不以原索引 `ready` 为前置条件。成功后进入 `structured`;扫描、认证或构建失败时保留源文件、密钥和恢复记录,停止普通写入并报告错误。重试继续同一恢复决定,不能为了消除错误而降级或重建笔记本。未知源格式仍须升级读取器,明确启用不等于允许跳过格式检查。+### 索引与任务恢复`document_metadata` 使用独立的派生索引版本及笔记本状态 `missing`、`building`、`ready`、`error`。新建表后从源文档和 ID 位置构建,不从旧 `hPath` 推测段边界。构建期间记录增量变更并在切换前追平;只有全量扫描和增量校验完成,才将对应代次标记为 `ready`。@@ -350,18 +398,22 @@已有加密数据是兼容基线,遵循 [加密笔记本](ENCRYPTED-NOTEBOOK.zh-CN.md) 的认证读取、隔离及恢复要求。标题源内容、纯文本标题和祖先链都属于受保护的文档内容;读取、缓存和响应必须处于对应笔记本的授权范围及操作租约内,锁定后按现有生命周期清理。+`docCreateTarget`、`refCreateTarget`、`dailyNoteTarget` 在加密笔记本中按受保护配置保存,不能直接作为明文字段落入 `BoxConf`。当前 `BoxCrypt.Metadata` 的加密载荷只包含图标及排序;新方案为该载荷定义独立的 `version: 2`,保留 `icon`、`sort`、`sortMode`,并以 `documentTargets` 保存三个可选目标对象。现有无 `version` 的载荷按版本 `1` 认证读取,普通配置保存继续兼容旧载荷;写入新对象时才生成版本 `2`,以后移除对象也不退回旧载荷版本。该版本与 `BoxCrypt.Spec`、目标对象的 `version` 和 `.sy` 版本分别解释。++已解锁时,配置读取器在租约内将目标对象投影到授权管理接口;写盘前必须从明文配置副本清除这些对象,只保存认证密文。锁定后清除相应明文缓存,状态及配置响应不返回这些对象;非管理员同样不能读取它们。省略或被过滤的字段不是删除请求,锁定时的普通配置保存保持既有密文原样,新增或修改目标对象必须先解锁。新载荷读取、改密重新包络、导入导出、历史配置及备份恢复覆盖旧版本样本;未知载荷版本和认证失败拒绝解读或覆盖,不能因结构体不认识字段而丢弃新配置。+重建派生索引之前必须认证源密文并验证文档格式。未知格式、损坏和认证失败必须保留原始数据并返回错误,不能回退到明文、跨笔记本查询或未认证的旧索引。普通索引重建不代表加密源数据已经通过认证。-本方案的内部解耦不要求更改加密信封、AAD 或密钥派生。后续若涉及这些格式,必须另有显式版本、认证迁移和中断恢复设计,并保留匹配的密钥与备份材料。不得重新生成 `MasterSalt`、丢弃密钥或要求用户重建已有加密笔记本来规避兼容问题。文档、历史、备份和同步快照中的受支持格式必须持续可恢复。+配置载荷的版本化扩展沿用现有认证加密容器、`siyuan/box-metadata` 子密钥用途及笔记本绑定 AAD,不修改加密信封、AAD 语义或密钥派生。后续若涉及这些格式,必须另有显式版本、认证迁移和中断恢复设计,并保留匹配的密钥与备份材料。不得重新生成 `MasterSalt`、丢弃密钥或要求用户重建已有加密笔记本来规避兼容问题。文档、历史、备份和同步快照中的受支持格式必须持续可恢复。## 实施拆分与开放条件| 阶段 | 交付内容 | 完成条件 || --- | --- | --- |-| A:兼容保护 | 笔记本能力标记、未知模式及源版本保护、旧行为回归样本 | 已发布保护版本;未知模式在所有写入与修复入口安全拒绝 |+| A:兼容保护 | 笔记本能力下界及冲突识别、未知模式及源版本保护、旧行为回归样本 | 已发布保护版本;同步及快照应用前验证模式,所有写入与修复入口安全拒绝未知模式 || B:内部解耦 | 统一标题读取、文档元数据、ID 层级计算、路径刷新及恢复 | 普通标题行为不变;结构不再从显示字符串推导,加密索引可认证重建 |-| C:接口与调用方 | 新读取、解析、创建接口,版本 `2` 模板,内置业务及各端迁移 | 新旧契约通过验证,部分失败可恢复,日记等业务行为保持 |-| D:开放新字符 | 模式启用入口、旧接口拒绝规则、插件迁移说明、导入导出和跨版本验证 | 全部开放条件满足后才允许用户显式启用 `/` |+| C:接口与调用方 | 新读取、解析、条件创建接口,版本 `2` 模板及加密载荷,内置业务及各端迁移 | 名称与配置并发条件、新旧契约通过验证,部分失败及撤销可恢复,日记等业务行为保持 |+| D:开放新字符 | 模式启用与冲突恢复入口、旧接口拒绝规则、插件迁移说明、跨模式操作及导入导出验证 | 完整子树预检、模式恢复和全部开放条件满足后才允许用户显式启用 `/` || E:行级标题 | 独立的源格式、编辑及渲染设计 | 保持本方案身份接口,完成格式及旧写入保护后另行交付 |阶段 B、C 可以在保留旧标题限制时先行交付;新字符的开放必须等待 A 至 D 所需条件全部成立。阶段 E 不作为基础解耦的前置依赖,也不能在 A 至 D 中重新引入只接受永久纯文本来源的假设。@@ -378,14 +430,14 @@| --- | --- || 标题内容 | `/`、`/`、连续斜杠、`%2F`、`.`、`..`、空标题、Unicode 和长度边界;原字符不发生未经约定的转换 || 身份与层级 | 单标题 `A/B` 与两级 `A`、`B`,同父同名、不同父同名、重复 ID 的归属校验、根位置及笔记本文档 |-| 创建与并发 | 直接按 ID 跟随父位置及带版本请求拒绝过期预览;父文档删除、跨笔记本移动、关闭或锁定;响应丢失、部分提交、固定 ID 冲突及多级恢复 |-| 模板 | 旧语法全部边界、新语法逐段渲染、变量包含 `/`、相对操作、同一时间快照、日记与速记等入口 |+| 创建与并发 | 直接按 ID 跟随父位置及带版本请求拒绝过期预览;同名祖先并发创建、匹配集合及配置变化;父文档删除、跨笔记本移动、关闭或锁定;响应丢失、部分提交、固定 ID 冲突及多级恢复 |+| 模板 | 旧语法全部边界及模式 `1` 的旧同名行为、新语法逐段渲染、变量包含 `/`、相对操作、同一时间快照、配置继承及正文模板选择、日记与速记等入口、模板文档树整组撤销和重做 || 搜索与展示 | 原始标题字符检索、祖先文字检索、ID 范围过滤、标题高亮、面包屑段边界、复制文字与 ID 链接 || 索引与恢复 | 深层子树、父子连续重命名、旧编辑快照、批次中断、重启、移动、删除、同步及普通与加密索引迁移 |-| 导入导出 | 重名、非法文件名、大小写冲突、路径越界、相对链接、跨笔记本引用、标题元数据及无损往返承诺 |-| 旧接口与插件 | 模式 `1` 旧返回不变;模式 `2` 整个笔记本拒绝旧寻址;SQL 显示字符串碰撞、结构化替代接口、能力缺失与请求失败的区别 |-| 旧客户端与加密 | 支持的历史格式样本、混合版本同步、认证失败、锁定期间的缓存和响应、历史及备份恢复、密钥材料保留 |-| 行级元素扩展 | 现有 Markdown 样式文字保持字面含义;标题表示变化不影响身份与层级;纯文本相同不合并文档;格式与纯文本来源单向派生 |+| 导入导出及跨模式操作 | 重名、非法文件名、大小写冲突、路径越界、相对链接、跨笔记本引用、标题元数据及无损往返承诺;移动、复制和恢复预检全部后代,拒绝时不产生部分写入 |+| 旧接口与插件 | 模式 `1` 旧返回不变;模式 `2` 整个笔记本拒绝旧寻址;两个旧目标读取接口拒绝失效配置,即使旧目标仍为模式 `1`;SQL 显示字符串碰撞、结构化替代接口、能力缺失与请求失败的区别 |+| 旧客户端与加密 | 支持的历史格式及配置载荷样本、混合版本同步、能力下界不降级、无就绪索引的模式冲突恢复、认证失败、锁定期间的缓存和响应、历史及备份恢复、密钥材料保留 |+| 行级元素扩展 | 现有 Markdown 样式文字保持字面含义;标题表示变化不影响身份与层级;纯文本相同不合并文档;格式与纯文本来源单向派生;#19235 的图片及链接双向转换保留、资源引用和防重复要求 || 跨端与性能 | 桌面、浏览器和移动端创建及重命名;大子树下的前台延迟、数据库批次时间、内存、CPU 和磁盘读写 |### 关键回归用例@@ -394,6 +446,14 @@同时建立根文档 `A/B`、根文档 `A` 及其子文档 `B`、根文档 `A/B`、根文档 `A%2FB`。前两者允许相同显示路径,但 ID、`segments`、`depth`、子树范围和导出链接必须各自正确;后两者不得被转换成前两者。增加重复斜杠、点段、空标题、大小写差异和相同纯文本不同标题格式的样本。+两个请求同时解析缺失祖先并提交同一不存在条件,验证只成功一次,另一次返回 `planChanged`;普通同名最终文档仍可分别创建。已匹配祖先出现第二个同名文档时,唯一身份条件失败。配置预览后改变目标笔记本、继承配置或正文模板路径,即使父路径版本相同也须拒绝;重命名与配置更新发生在最后校验和提交之间的竞争也需覆盖。++构造标题普通但后代包含 `/` 或新标题格式的子树,向模式 `1` 移动、复制、导入和恢复均在首次写入前拒绝;预检后后代变化也须被发现。目标明确启用后重新执行成功,既有加密边界不放宽。仅使用其他新版正文功能而标题仍兼容的文档不得被误判为需要模式 `2`。++模拟旧配置覆盖、能力记录缺失或损坏、同步中断,以及源文档已经需要模式 `2` 但索引尚不可用的场景。验证有效模式不下降、未知格式保留原数据、明确启用可进入独立恢复流程、重启继续原恢复决定。覆盖整本删除后按同一身份恢复,以及完整导入重映射笔记本身份时保留能力下界。对新配置载荷检查磁盘及锁定后的接口和缓存均无新目标对象明文,并验证旧载荷读取及备份、改密后的恢复。++保留 `TestHeadingDocParagraph` 与 `TestHeadingDocParagraphTextMark`,基础解耦继续覆盖图片、链接和原标题内容进入正文的行为;阶段 E 再验证支持的节点进入标题源内容及双向转换,不按纯文本相等删除用户段落。模板文档树覆盖整组撤销和重做、部分提交、重做时的名称或 ID 冲突及创建后用户编辑,不能只测试新建成功。+实际 HTTP 回归检查严格请求类型、必填与 `null` 区别、返回顺序、候选截断、错误数据、管理员与可写保护、加密响应租约及发布访问拒绝。旧接口的兼容回归与新接口回归分开断言,避免用新预期覆盖旧行为。前端验证旧模板配置往返、新模板逐段求值、同一时间快照、部分成功提示以及移动端入口。故障注入至少覆盖源文档落盘前后、元数据事务前后、内容索引批次中断、成功响应丢失及锁定发生在响应输出期间。使用受支持历史格式的真实样本验证读取、导出、历史、备份及恢复,同时验证保护版本安全拒绝新格式;仅测试当前版本生成的文件不能证明向后兼容。@@ -426,4 +486,6 @@| 日记复用及旧创建回归 | [`model/daily_note.go`](../kernel/model/daily_note.go)、[`model/file_test.go`](../kernel/model/file_test.go) || 导入与导出 | [`model/import.go`](../kernel/model/import.go)、[`model/import_obsidian.go`](../kernel/model/import_obsidian.go)、[`model/export.go`](../kernel/model/export.go) || 可复用的富文本来源校验模式 | [`treenode/table_cell_rich.go`](../kernel/treenode/table_cell_rich.go) |+| 标题块与文档转换 | [`model/heading.go`](../kernel/model/heading.go)、[`model/heading_doc_test.go`](../kernel/model/heading_doc_test.go) |+| 配置加密及同步应用 | [`model/box_conf_crypto.go`](../kernel/model/box_conf_crypto.go)、[`model/repository.go`](../kernel/model/repository.go)、[`model/sync_checkout.go`](../kernel/model/sync_checkout.go) || 文档版本 | [`treenode/tree.go`](../kernel/treenode/tree.go)、[`.sy` 文件结构](SY-FORMAT.zh-CN.md) |