An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Guard notebook document addressing modes https://github.com/siyuan-note/siyuan/issues/19938
Danield3378a44e72d
diff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.mdindex 9770d8045f..18681a82e7 100644--- a/docs/DOCUMENT-ADDRESSING.md+++ b/docs/DOCUMENT-ADDRESSING.md@@ -372,6 +372,8 @@ Mode `2` has no direct switch back to `1`. Even after current titles no longer cActivation 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 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.+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.diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.mdindex 01786f5512..70942a9f9d 100644--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md@@ -372,6 +372,8 @@启用时在笔记本 `.siyuan/document-addressing.json` 写入独立的能力下界记录 `{version: 1, notebook, minimumMode: 2}`,只含身份及版本,随原生笔记本导出、备份和同步保存。本机另在工作空间 `conf/document-addressing.json` 保留按笔记本 ID 索引的已确认最低模式;它参与工作空间配置备份,不作为标题或密钥的存储位置。有效模式取合法笔记本配置、能力下界记录和本机已确认记录中最严格的要求。记录不是密文认证凭据;未知记录版本、无效字段或身份不匹配必须保留原文件并拒绝处理,不能按缺省模式 `1` 继续。+本机记录采用 `{version: 1, notebooks: {"<notebookID>": 2}}`,省略尚无较高要求的笔记本;普通兼容模式读取不创建记录或改写源数据。记录写入必须原子替换,合并时逐个身份取最大值,不能用较旧记录整体覆盖。本机或同步、快照预检已经读到合法的较高要求时,即使本次批次因能力不足被拒绝,也保留该要求,防止下一次读取旧的本地配置时恢复普通写入;记住能力要求不等于启用结构化标题。导入时尚未采用的独立原生笔记本身份不因此写入本机记录。+保护版本同时识别配置及能力下界记录;不支持的模式在实际处理源文件前拒绝。同步应用和快照恢复先核对受影响笔记本的能力要求,再替换配置或文件。已确认模式 `2` 时,传入旧配置、缺少新字段或删除能力记录都不能降低有效模式;恢复配置投影和下界记录后再开放访问。若只能在文件落盘后检查,或依赖层不能在应用前提供所需配置数据,阶段 A 尚未完成,须先补齐同步和恢复入口,不能以重建索引代替前置保护。删除整个笔记本仍按现有语义执行,不为补齐能力记录而重新创建已删除的笔记本;本机保留该身份的已确认下界,恢复同一身份时继续生效。完整笔记本的原生导入先校验源身份与能力记录,再按既有导入规则分配或复用目标身份,并将能力下界绑定到目标身份;不得借身份重映射降低源笔记本已确认的模式。向既有笔记本导入部分文档则按前述完整操作集合检查,不直接复制源笔记本的模式配置。diff --git a/kernel/documentaddressing/mode.go b/kernel/documentaddressing/mode.gonew file mode 100644index 0000000000..e21cd4b91b--- /dev/null+++ b/kernel/documentaddressing/mode.go@@ -0,0 +1,369 @@+// 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++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"+ supportedMode = 1+)++var (+ ErrInvalid = errors.New("invalid document addressing metadata")+ ErrUnsupported = errors.New("unsupported document addressing mode")+ storeLock sync.Mutex+)++// 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"], ¬ebook) != nil || !ast.IsNodeIDPattern(notebook) || notebook != 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+ }+ return checkSupported(boxID, max(mode, store.Notebooks[boxID]))+}++// CheckBox 在任何源数据修复、索引和读写前确认能力下界。合法的较高要求只升不降。+func CheckBox(dataDir, confDir, boxID string) error {+ if !ast.IsNodeIDPattern(boxID) {+ return ErrInvalid+ }+ storeLock.Lock()+ defer storeLock.Unlock()+ store, err := loadStore(dataDir, confDir)+ if err != nil {+ return err+ }+ mode, err := ReadMode(boxID, directoryReader(filepath.Join(dataDir, boxID)))+ if err != nil {+ return fmt.Errorf("notebook [%s]: %w", boxID, err)+ }+ mode = store.confirm(boxID, mode)+ if err = store.save(); err != nil {+ return err+ }+ return checkSupported(boxID, mode)+}++// 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)+ 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 > supportedMode {+ 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)) }+}++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")}+ data, err := filelock.ReadFile(ret.path)+ if errors.Is(err, os.ErrNotExist) {+ return ret, nil+ }+ if err != nil {+ return nil, err+ }+ 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+ }+ for id, value := range notebooks {+ if !ast.IsNodeIDPattern(id) {+ return nil, ErrInvalid+ }+ mode, err := positiveInt(value)+ if err != nil {+ return nil, err+ }+ ret.Notebooks[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 {+ 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 filelock.WriteFile(store.path, data)+}diff --git a/kernel/documentaddressing/mode_test.go b/kernel/documentaddressing/mode_test.gonew file mode 100644index 0000000000..d5dac7eb8e--- /dev/null+++ b/kernel/documentaddressing/mode_test.go@@ -0,0 +1,269 @@+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) {+ 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 TestCheckBoxDoesNotMigrateLegacyData(t *testing.T) {+ 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) {+ 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")+ }+ })+ }+}++func TestCheckBatchUsesIncomingModeAndRetainsObservedFloor(t *testing.T) {+ 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) {+ 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) {+ 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) {+ 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)+ }+}++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)+ }+ })+ }+}diff --git a/kernel/filesys/document_addressing.go b/kernel/filesys/document_addressing.gonew file mode 100644index 0000000000..f2bd6f4056--- /dev/null+++ b/kernel/filesys/document_addressing.go@@ -0,0 +1,11 @@+package filesys++import (+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// CheckDocumentAddressing 在读取缓存或修改笔记本源数据之前检查寻址能力。+func CheckDocumentAddressing(boxID string) error {+ return documentaddressing.CheckBox(util.DataDir, util.ConfDir, boxID)+}diff --git a/kernel/filesys/document_addressing_test.go b/kernel/filesys/document_addressing_test.gonew file mode 100644index 0000000000..0d792afcaf--- /dev/null+++ b/kernel/filesys/document_addressing_test.go@@ -0,0 +1,73 @@+package filesys++import (+ "bytes"+ "errors"+ "os"+ "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 TestDocumentAddressingPreservesPlainAndEncryptedSources(t *testing.T) {+ legacy, err := os.ReadFile("../treenode/testdata/table-cell-legacy.sy")+ if err != nil {+ t.Fatal(err)+ }+ for _, encrypted := range []bool{false, true} {+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {+ oldData, oldConf := util.DataDir, util.ConfDir+ oldProvider, oldAcquire, oldRelease := DEKProvider, DEKLockAcquire, DEKLockRelease+ util.DataDir, util.ConfDir = t.TempDir(), t.TempDir()+ DEKLockAcquire, DEKLockRelease = nil, nil+ t.Cleanup(func() {+ util.DataDir, util.ConfDir = oldData, oldConf+ DEKProvider, DEKLockAcquire, DEKLockRelease = oldProvider, oldAcquire, oldRelease+ })+ const boxID = "20261022000000-abcdefg"+ const document = "/20261022000001-hijklmn/20261022000002-opqrstu.sy"+ var dek []byte+ if encrypted {+ dek = bytes.Repeat([]byte{23}, 32)+ }+ decryptCalls := 0+ DEKProvider = func(string) ([]byte, error) { decryptCalls++; return bytes.Clone(dek), nil }+ source, err := encryptDataWithDEK(boxID, document, legacy, dek)+ if err != nil {+ t.Fatal(err)+ }+ absPath := writeStalePathFixture(t, boxID, document, source)+ writeStalePathFixture(t, boxID, documentaddressing.ConfigPath, []byte(`{"documentAddressingVersion":2}`))+ readers := map[string]func() error{+ "properties": func() error { _, err := DocIAL(absPath); return err },+ "parent properties": func() error { _, err := readParentDocIAL(absPath); return err },+ "path": func() error { _, _, err := ReadDocHPath(boxID, document); return err },+ "tree": func() error { _, err := LoadTree(boxID, document, util.NewLute()); return err },+ "decoded tree": func() error { _, err := LoadTreeByData(legacy, boxID, document, util.NewLute()); return err },+ "write": func() error {+ _, err := WriteTree(treenode.NewTree(boxID, document, "/Parent/Child", "Child"))+ return err+ },+ }+ for name, read := range readers {+ if err := read(); !errors.Is(err, documentaddressing.ErrUnsupported) {+ t.Fatalf("%s: %v", name, err)+ }+ }+ if decryptCalls != 0 {+ t.Fatal("unsupported notebook reached decryption")+ }+ actual, err := os.ReadFile(absPath)+ if err != nil || !bytes.Equal(actual, source) {+ t.Fatal("source changed")+ }+ parent := filepath.Join(util.DataDir, boxID, "20261022000001-hijklmn.sy")+ if _, err = os.Stat(parent); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("parent was repaired")+ }+ })+ }+}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex f6cced5caf..215f3dbe3a 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -187,12 +187,12 @@ func validateTreePath(boxID, p string) error {return fmt.Errorf("invalid document path [%s]", p)}}- return nil+ return CheckDocumentAddressing(boxID)}func LoadTreeWithFix(boxID, p string, luteEngine *lute.Lute) (ret *parse.Tree, needFix bool, err error) {if err = validateTreePath(boxID, p); err != nil {- logging.LogErrorf("invalid tree path [%s] for box [%s]: %s", p, boxID, err)+ logging.LogErrorf("cannot load tree [%s] for box [%s]: %s", p, boxID, err)return}@@ -355,6 +355,11 @@ func readParentDocIAL(absPath string) (map[string]string, error) {func readDocIAL(absPath string, strict bool) (map[string]string, error) {boxID := docIALBoxID(absPath)+ if boxID != "" {+ if err := CheckDocumentAddressing(boxID); err != nil {+ return nil, err+ }+ }dek, _, release, err := acquireCryptoLease(boxID)if err != nil {return nil, err@@ -402,6 +407,11 @@ func DocIAL(absPath string) (ret map[string]string, err error) {// 加密笔记本的 .sy 是密文,流式 jsoniter 解析无法处理,需先整体读+解密。// 反推 boxID:路径形如 <DataDir>/<boxID>/...;非加密笔记本走原流式逻辑。boxID := docIALBoxID(absPath)+ if boxID != "" {+ if err = CheckDocumentAddressing(boxID); err != nil {+ return nil, err+ }+ }if boxID != "" && DEKProvider != nil {dek, encrypted, releaseCryptoLease, leaseErr := acquireCryptoLease(boxID)if leaseErr != nil {diff --git a/kernel/go.mod b/kernel/go.modindex 53b1db5b25..c23131525b 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -75,7 +75,7 @@ require (github.com/sashabaranov/go-openai v1.42.0github.com/shirou/gopsutil/v4 v4.26.7github.com/siyuan-note/dataparser v0.0.0-20260115084335-b57cb8bc7c17- github.com/siyuan-note/dejavu v0.0.0-20261021030846-925a87301674+ github.com/siyuan-note/dejavu v0.0.0-20261022130950-71be2217abb3github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dcegithub.com/siyuan-note/filelock v0.0.0-20260831011452-393425122aaadiff --git a/kernel/go.sum b/kernel/go.sumindex d5d9dc0a57..80048a5660 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -567,6 +567,8 @@ github.com/siyuan-note/dejavu v0.0.0-20261020151424-5697b06616f2 h1:i4CD3LjVb2eLgithub.com/siyuan-note/dejavu v0.0.0-20261020151424-5697b06616f2/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/dejavu v0.0.0-20261021030846-925a87301674 h1:SLsLvDU9Js7yuLAyVAHnU5A+FcqObh8BPyiKuF6JDlA=github.com/siyuan-note/dejavu v0.0.0-20261021030846-925a87301674/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=+github.com/siyuan-note/dejavu v0.0.0-20261022130950-71be2217abb3 h1:n35AM98bbsgHX1iUu0P0YmfG/iLKU5kaUHeITpZ5X+U=+github.com/siyuan-note/dejavu v0.0.0-20261022130950-71be2217abb3/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044 h1:b1/Q4DSREDvGh1/NbzR9873EKrjakdoUtsNlghWxUOI=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044/go.mod h1:t6jXpJdrXzRsdQF+XGaw35f16JVZcDyIkk5/6//ywnY=github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dce h1:356bfC3pucxXuYpZIwaQ3viVCbq5RbRuvBhb4xtoBR0=diff --git a/kernel/model/box.go b/kernel/model/box.goindex d30aef3844..be8ab4f02a 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -127,6 +127,12 @@ func listNotebooks(repairMissingConf bool) (ret []*Box, err error) {boxConf := conf.NewBoxConf()boxDirPath := filepath.Join(util.DataDir, id)boxConfPath := filepath.Join(boxDirPath, ".siyuan", "conf.json")+ if addressingErr := filesys.CheckDocumentAddressing(id); addressingErr != nil {+ // 只展示关闭的笔记本;不能进入配置修复、解密元数据或索引流程。+ logging.LogWarnf("notebook [%s] is unavailable: %s", id, addressingErr)+ ret = append(ret, &Box{ID: id, Name: id, Closed: true, Encrypted: IsEncryptedBox(id)})+ continue+ }isExistConf := filelock.IsExist(boxConfPath)missingEncryptedIdentity := falseif !isExistConf {@@ -344,6 +350,9 @@ func (box *Box) SaveConfAndSync(conf *conf.BoxConf) error {}func (box *Box) saveConf(conf *conf.BoxConf, syncChange bool) error {+ if err := filesys.CheckDocumentAddressing(box.ID); err != nil {+ return err+ }confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json")persisted, err := prepareBoxConfForSave(box.ID, conf)if err != nil {@@ -392,6 +401,9 @@ func (box *Box) saveConf0(data []byte) error {if !ast.IsNodeIDPattern(box.ID) {return fmt.Errorf("invalid box ID [%s]", box.ID)}+ if err := checkDocumentAddressingConf(box.ID, data); err != nil {+ return err+ }confPath := filepath.Join(util.DataDir, box.ID, ".siyuan/conf.json")if err := os.MkdirAll(filepath.Join(util.DataDir, box.ID, ".siyuan"), 0755); err != nil {@@ -407,7 +419,11 @@ func (box *Box) saveConf0(data []byte) error {// validateBoxPath 校验 box 内相对路径,拒绝 .. 和绝对路径,确保最终路径在 <DataDir>/<boxID>/ 内。func (box *Box) validateBoxPath(p string) (string, error) {- return filesys.ValidateBoxRelativePath(box.ID, p)+ rel, err := filesys.ValidateBoxRelativePath(box.ID, p)+ if err != nil {+ return "", err+ }+ return rel, filesys.CheckDocumentAddressing(box.ID)}func (box *Box) Ls(p string) (ret []*FileInfo, totals int, err error) {diff --git a/kernel/model/document_addressing.go b/kernel/model/document_addressing.gonew file mode 100644index 0000000000..4db7aca24d--- /dev/null+++ b/kernel/model/document_addressing.go@@ -0,0 +1,161 @@+package model++import (+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/dejavu"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "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 })+}++// documentAddressingPreflight 读取待恢复快照中的记录,在整批写入和删除前检查能力。+func documentAddressingPreflight(repo *dejavu.Repo) func(*dejavu.CheckoutPlan) error {+ return func(plan *dejavu.CheckoutPlan) error {+ upserts := make([]string, 0, len(plan.Upserts))+ removes := make([]string, 0, len(plan.Removes))+ paths := map[string]string{}+ for _, file := range plan.Upserts {+ upserts = append(upserts, file.Path)+ paths[strings.TrimPrefix(file.Path, "/")] = file.Path+ }+ for _, file := range plan.Removes {+ removes = append(removes, file.Path)+ }+ return documentaddressing.CheckBatch(repo.DataPath, util.ConfDir, upserts, removes,+ func(name string) ([]byte, error) { return plan.ReadFile(paths[name]) })+ }+}++func documentAddressingCheckoutHooks(repo *dejavu.Repo) dejavu.CheckoutHooks {+ return dejavu.CheckoutHooks{Preflight: documentAddressingPreflight(repo)}+}++// 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+ }+ if err == nil {+ var meta boxDocMeta+ if json.Unmarshal(data, &meta) != nil || meta.Spec != boxDocMetaSpec || !ast.IsNodeIDPattern(meta.BoxDocID) {+ return documentaddressing.ErrInvalid+ }+ boxID = meta.BoxDocID+ }+ 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)+}++// checkDocumentAddressingCopy 在整批导入或历史恢复开始复制前检查源配置及目标已确认的下界。+func checkDocumentAddressingCopy(sourceRoot, boxID string) error {+ var upserts []string+ err := filepath.WalkDir(sourceRoot, func(name string, entry os.DirEntry, err error) error {+ if err != nil {+ return err+ }+ if entry.IsDir() {+ return nil+ }+ rel, err := filepath.Rel(sourceRoot, name)+ if err != nil {+ return err+ }+ if boxID != "" {+ rel = filepath.Join(boxID, rel)+ }+ upserts = append(upserts, filepath.ToSlash(rel))+ return nil+ })+ if err != nil {+ return err+ }+ return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, upserts, nil, func(name string) ([]byte, error) {+ if boxID != "" {+ name = strings.TrimPrefix(name, boxID+"/")+ }+ 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)+}++// backupUnsupportedNotebookAttributeViews 无法解析源文档时保留共享数据库的原始快照,避免丢失恢复材料。+func backupUnsupportedNotebookAttributeViews(historyDir string) error {+ directory := filepath.Join(util.DataDir, "storage", "av")+ entries, err := os.ReadDir(directory)+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ continue+ }+ dest := filepath.Join(historyDir, "storage", "av", entry.Name())+ if _, err = os.Stat(dest); err == nil {+ continue+ } else if !errors.Is(err, os.ErrNotExist) {+ return err+ }+ if err = filelock.Copy(filepath.Join(directory, entry.Name()), dest); err != nil {+ return err+ }+ }+ return nil+}diff --git a/kernel/model/document_addressing_fts5_test.go b/kernel/model/document_addressing_fts5_test.gonew file mode 100644index 0000000000..17f6464eea--- /dev/null+++ b/kernel/model/document_addressing_fts5_test.go@@ -0,0 +1,67 @@+//go:build fts5++package model++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentAddressingWholeNotebookDeletionRetainsRecoveryData(t *testing.T) {+ fixture := setupFileOperationTest(t)+ oldTemp, oldHistory, oldWorkspace := util.TempDir, util.HistoryDir, util.WorkspaceDir+ util.TempDir, util.HistoryDir = t.TempDir(), t.TempDir()+ util.WorkspaceDir = filepath.Dir(util.DataDir)+ t.Cleanup(func() { util.TempDir, util.HistoryDir, util.WorkspaceDir = oldTemp, oldHistory, oldWorkspace })+ setupNotebookDocumentImportDatabase(t)+ boxID := fixture.box.ID+ source := []byte("unparsed future source")+ config := []byte(`{"name":"future","closed":true,"documentAddressingVersion":2}`)+ if err := os.WriteFile(filepath.Join(util.DataDir, boxID, documentaddressing.ConfigPath), config, 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(util.DataDir, boxID, fixture.sourcePath), source, 0644); err != nil {+ t.Fatal(err)+ }+ sharedDir := filepath.Join(util.DataDir, "storage", "av")+ if err := os.MkdirAll(sharedDir, 0755); err != nil {+ t.Fatal(err)+ }+ shared := []byte("unparsed shared database")+ if err := os.WriteFile(filepath.Join(sharedDir, "20261022000200-abcdefg.json"), shared, 0644); err != nil {+ t.Fatal(err)+ }+ if err := RemoveBox(boxID); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("notebook was not deleted")+ }+ paths, err := filepath.Glob(filepath.Join(util.HistoryDir, "*-delete", boxID))+ if err != nil || len(paths) != 1 {+ t.Fatalf("missing recovery data: %v, %v", paths, err)+ }+ for name, want := range map[string][]byte{documentaddressing.ConfigPath: config, fixture.sourcePath: source} {+ actual, readErr := os.ReadFile(filepath.Join(paths[0], name))+ if readErr != nil || !bytes.Equal(actual, want) {+ t.Fatalf("history changed %s: %q, %v", name, actual, readErr)+ }+ }+ sharedHistory := filepath.Join(filepath.Dir(paths[0]), "storage", "av", "20261022000200-abcdefg.json")+ 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 = 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_test.go b/kernel/model/document_addressing_test.gonew file mode 100644index 0000000000..9e498ca8a2--- /dev/null+++ b/kernel/model/document_addressing_test.go@@ -0,0 +1,434 @@+package model++import (+ "bytes"+ "encoding/json"+ "errors"+ "os"+ "path/filepath"+ "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/util"+)++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":2}`)+ 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 TestDocumentAddressingRejectsConfigActivationBeforeWrite(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":2}`)); !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":2}`+ if marker == "floor" {+ config = `{}`+ write(documentaddressing.FloorPath, `{"version":1,"notebook":"`+boxID+`","minimumMode":2}`, 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":2}`, 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+ util.ConfDir = t.TempDir()+ t.Cleanup(func() { util.ConfDir = oldConfDir })+ const sourceBox = "20260101120000-abcdefg"+ for _, whole := range []bool{false, true} {+ root := t.TempDir()+ source := filepath.Join(root, "Notebook")+ metadata := filepath.Join(source, ".siyuan")+ if err := os.MkdirAll(metadata, 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(metadata, "conf.json"), []byte(`{"name":"future","documentAddressingVersion":2}`), 0644); err != nil {+ t.Fatal(err)+ }+ meta, err := json.Marshal(boxDocMeta{Spec: boxDocMetaSpec, BoxDocID: sourceBox})+ if err != nil {+ t.Fatal(err)+ }+ 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 {+ t.Fatal(err)+ }+ archive := filepath.Join(t.TempDir(), "future.sy.zip")+ writer, err := gulu.Zip.Create(archive)+ if err != nil {+ t.Fatal(err)+ }+ if err = writer.AddDirectory("Notebook", source); err != nil {+ _ = writer.Close()+ t.Fatal(err)+ }+ if err = writer.Close(); err != nil {+ t.Fatal(err)+ }+ before, err := os.ReadFile(archive)+ 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 = inspectSYNotebookArchive(archive); !errors.Is(err, documentaddressing.ErrUnsupported) {+ t.Fatalf("bundle inspection accepted future mode: %v", err)+ }+ after, err := os.ReadFile(archive)+ if err != nil || !bytes.Equal(before, after) {+ t.Fatal("archive changed")+ }+ boxes, err := os.ReadDir(util.DataDir)+ if err != nil {+ t.Fatal(err)+ }+ for _, box := range boxes {+ if box.IsDir() && len(box.Name()) == len(sourceBox) && box.Name() != fixture.box.ID {+ t.Fatalf("created notebook before validation: %s", box.Name())+ }+ }+ }+}++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 {+ t.Fatal(err)+ }+ if err = checkImportedDocumentAddressing(source); err != nil {+ t.Fatal(err)+ }+ if err = prepareImportedDocumentAddressing(source, targetBox, whole); 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")+ }+ }+}++func TestDocumentAddressingDataImportRejectsBeforeAnyWrite(t *testing.T) {+ fixture := setupFileOperationTest(t)+ oldConfDir := util.ConfDir+ util.ConfDir = t.TempDir()+ t.Cleanup(func() { util.ConfDir = oldConfDir })+ install := t.TempDir()+ metaDir := filepath.Join(install, fixture.box.ID, ".siyuan")+ if err := os.MkdirAll(metaDir, 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(metaDir, "conf.json"), []byte(`{"documentAddressingVersion":2}`), 0644); err != nil {+ t.Fatal(err)+ }+ 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) {+ 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) {+ t.Fatal(err)+ }+}++func TestDocumentAddressingNotebookHistoryPreservesSource(t *testing.T) {+ historyPath, boxID := setupNotebookHistoryRollbackTest(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":2}`)+ if err := os.WriteFile(name, source, 0644); err != nil {+ t.Fatal(err)+ }+ if err := RollbackNotebookHistory(historyPath); !errors.Is(err, documentaddressing.ErrUnsupported) {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, boxID)); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("restoration created notebook before validation")+ }+ data, err := os.ReadFile(name)+ if err != nil || !bytes.Equal(data, source) {+ t.Fatal("history source changed")+ }+}++func TestDocumentAddressingNativeExportPreservesFloor(t *testing.T) {+ const boxID = "20260101120000-abcdefg"+ setupExportRelatedTest(t, boxID)+ name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)+ source := []byte(`{"version":1,"notebook":"` + boxID + `","minimumMode":1}`)+ if err := os.WriteFile(name, source, 0644); err != nil {+ t.Fatal(err)+ }+ archive := openExportArchive(t, ExportNotebookSY(boxID))+ data := readArchiveFile(t, archive, boxID+"/"+documentaddressing.FloorPath)+ if data != string(source) {+ t.Fatal("export lost capability floor")+ }+}diff --git a/kernel/model/export.go b/kernel/model/export.goindex 155e8b096f..741ddace5f 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -2784,6 +2784,10 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, i}func exportSYZipWithConfig(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool, config conf.Export) (zipPath string) {+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {+ util.PushErrMsg(err.Error(), 7000)+ return+ }confFlashcardSnapshot := Conf.LoadFlashcard()defer util.ClearPushProgress(100)@@ -2863,6 +2867,10 @@ 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/history.go b/kernel/model/history.goindex 61c0e519e3..23b98ca7f8 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -687,6 +687,9 @@ func RollbackNotebookHistory(historyPath string) (err error) {if filelock.IsExist(to) {return errors.New(Conf.Language(371))}+ if err = checkDocumentAddressingCopy(from, boxID); err != nil {+ return+ }boundRecovery := &Transaction{trees: map[string]*parse.Tree{}}defer func() { boundRecovery.finishAttributeViewMutation(err != nil) }()if err = boundRecovery.restoreNotebookAttributeViewHistory(from, boxID); err != nil {diff --git a/kernel/model/import.go b/kernel/model/import.goindex edc86ae674..28c0cec33b 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -443,6 +443,9 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, sreturn}unzipRootPath := filepath.Join(unzipPath, entries[0].Name())+ if err = checkImportedDocumentAddressing(unzipRootPath); err != nil {+ return+ }name := filepath.Base(unzipRootPath)if strings.HasPrefix(name, "data-20") && len("data-20230321175442") == len(name) {logging.LogErrorf("invalid .sy.zip [unzipRootPath=%s, baseName=%s]", unzipRootPath, name)@@ -563,6 +566,9 @@ 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)@@ -1284,6 +1290,9 @@ func writeImportedTree(boxID, syPath, newSyPath, relPath string, data []byte) er}func validateImportedNotebookIdentities(tmpDataPath string) ([]string, error) {+ if err := checkDocumentAddressingCopy(tmpDataPath, ""); err != nil {+ return nil, err+ }identities, err := inspectDataImportNotebooks(tmpDataPath)if err != nil {return nil, errdiff --git a/kernel/model/import_data_transaction.go b/kernel/model/import_data_transaction.goindex 8e18bd2a8f..3603512fdc 100644--- a/kernel/model/import_data_transaction.go+++ b/kernel/model/import_data_transaction.go@@ -104,6 +104,9 @@ func dataImportTarget(name string) (string, error) {// applyDataImport 先备份全部待覆盖文件,再登记提交日志;任何写入失败都补偿已安装的路径。func applyDataImport(directory, install string, write func(string, string) error) error {+ if err := checkDocumentAddressingCopy(install, ""); err != nil {+ return err+ }files, err := archiveDirectoryFiles(install)if err != nil {return errdiff --git a/kernel/model/mount.go b/kernel/model/mount.goindex 65fd56fee5..dd9be1b077 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -34,6 +34,8 @@ import ("github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/cache"+ "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""github.com/siyuan-note/siyuan/kernel/treenode"@@ -271,6 +273,11 @@ func RemoveBox(boxID string) (err error) {if !ast.IsNodeIDPattern(boxID) {return errors.New("invalid notebook ID")}+ 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@@ -326,8 +333,10 @@ func RemoveBox(boxID string) (err error) {defer databaseIndexDataLock.Unlock()createDocLock.Lock()defer createDocLock.Unlock()- if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {- return+ if !unsupportedAddressing {+ if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {+ return+ }}if !isEncrypted {unmount0(boxID)@@ -351,7 +360,12 @@ func RemoveBox(boxID string) (err error) {logging.LogErrorf("gen sync history failed: %s", err)return}- if !isEncrypted {+ if !isEncrypted && unsupportedAddressing {+ if err = backupUnsupportedNotebookAttributeViews(historyDir); err != nil {+ return+ }+ }+ if !isEncrypted && !unsupportedAddressing {pages, walkErr := pagedPathsWithError(localPath, 32)if walkErr != nil {return walkErr@@ -506,6 +520,9 @@ func Mount(boxID string) (alreadyMount bool, err error) {}func mountBox(boxID string) (alreadyMount bool, err error) {+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {+ return+ }confFileTreeSnapshot := Conf.LoadFileTree()if _, loaded := boxLock.LoadOrStore(boxID, true); loaded {diff --git a/kernel/model/notebook_bundle.go b/kernel/model/notebook_bundle.goindex d2be6113e9..33f5aa564d 100644--- a/kernel/model/notebook_bundle.go+++ b/kernel/model/notebook_bundle.go@@ -334,6 +334,9 @@ func inspectSYNotebookArchive(zipPath string) (ret *inspectedSYNotebook, err errreturn nil, errors.New(Conf.Language(199))}rootPath := filepath.Join(unzipPath, entries[0].Name())+ if err = checkImportedDocumentAddressing(rootPath); err != nil {+ return nil, err+ }ret = &inspectedSYNotebook{archivePath: zipPath, name: entries[0].Name()}confPath := filepath.Join(rootPath, ".siyuan", "conf.json")hasNotebookMetadata := filelock.IsExist(confPath)diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex d94bef3ade..05bbdbd1b6 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -3171,6 +3171,7 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {scope = stored}}+ ret.SetCheckoutHooks(documentAddressingCheckoutHooks(ret))err = ret.ConfigureAssetDownloads(confSyncSnapshot.AssetDownloadMode == 1, assetDownloadStatePath(), scope)return}diff --git a/kernel/model/sync_checkout.go b/kernel/model/sync_checkout.goindex 09463b5254..d4faf00f01 100644--- a/kernel/model/sync_checkout.go+++ b/kernel/model/sync_checkout.go@@ -62,6 +62,7 @@ func startSyncCheckout(repo *dejavu.Repo) *syncCheckoutTask {activeSyncCheckout.Unlock()repo.SetCheckoutHooks(dejavu.CheckoutHooks{Context: ctx, Apply: task.prepareApply, Applied: task.completeApply, Before: checkCheckoutSpace, Cleaned: notifyCheckoutCleanup,+ Preflight: documentAddressingPreflight(repo),Progress: func(progress dejavu.CheckoutProgress) {task.Lock()newFile := task.progress.Path != progress.Path@@ -232,7 +233,7 @@ func (task *syncCheckoutTask) finish(repo *dejavu.Repo, syncErr *error) {close(task.done)task.worker.Wait()task.cancel()- repo.SetCheckoutHooks(dejavu.CheckoutHooks{})+ repo.SetCheckoutHooks(documentAddressingCheckoutHooks(repo))if task.releaseWrites != nil {task.releaseWrites()task.releaseWrites = nil