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: Command Line Interface https://github.com/siyuan-note/siyuan/issues/17674
Danielb0177c4aa187
diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex 95c7755025..d8369b7aac 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -87,7 +87,7 @@ var documentCreateCmd = &cobra.Command{if err != nil {return err}- model.AppendPushEntry("create", notebook, docPath)+ model.AppendPushCreateEntry(notebook, docPath)fmt.Println(id)return nil},@@ -152,7 +152,11 @@ var documentRemoveCmd = &cobra.Command{return err}model.RemoveDoc(tree.Box, tree.Path)- model.AppendPushEntry("reloadFiletree", "", "")+ model.AppendPushRemoveEntry(tree.Box, tree.Path, id)+ parentPath := path.Dir(tree.Path) + ".sy"+ if parentPath != "/.sy" {+ model.AppendPushReloadDocInfoEntry(tree.Box, parentPath)+ }fmt.Println(id)return nil},@@ -177,7 +181,7 @@ var documentRenameCmd = &cobra.Command{if err := model.RenameDoc(tree.Box, tree.Path, title); err != nil {return err}- model.AppendPushEntry("reloadFiletree", "", "")+ model.AppendPushRenameEntry(tree.Box, tree.Path, title)return nil},}diff --git a/kernel/cli/cmd/root.go b/kernel/cli/cmd/root.goindex 5216119330..d50f1110fd 100644--- a/kernel/cli/cmd/root.go+++ b/kernel/cli/cmd/root.go@@ -67,10 +67,12 @@ var rootCmd = &cobra.Command{util.ConfDir = filepath.Join(workspacePath, "conf")util.DataDir = filepath.Join(workspacePath, "data")util.TempDir = filepath.Join(workspacePath, "temp")+ util.QueueDir = filepath.Join(util.TempDir, "queue")util.DBPath = filepath.Join(util.TempDir, "siyuan.db")util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")os.MkdirAll(util.TempDir, 0755)+ os.MkdirAll(util.QueueDir, 0755)logging.SetLogPath(filepath.Join(util.TempDir, "siyuan-cli.log"))logging.SetLogToStdout(false)diff --git a/kernel/job/cron.go b/kernel/job/cron.goindex 8f19abe1dd..42f4096580 100644--- a/kernel/job/cron.go+++ b/kernel/job/cron.go@@ -39,7 +39,7 @@ func StartCron() {go every(util.SQLFlushInterval, sql.FlushTxJob)go every(util.SQLFlushInterval, sql.FlushHistoryTxJob)go every(util.SQLFlushInterval, sql.FlushAssetContentTxJob)- go every(util.SQLFlushInterval, sql.PollWAL)+ go every(util.SQLFlushInterval, sql.PollIndexQueue)go every(50*time.Microsecond, model.PollPushQueue)go every(10*time.Minute, model.IndexEmbedBlockJob)go every(10*time.Minute, model.CacheVirtualBlockRefJob)diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 121513502a..d1a3131b9b 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -600,8 +600,8 @@ func InitConf() {Conf.AccessAuthCode = strings.TrimSpace(Conf.AccessAuthCode)if 1 == Conf.DataIndexState {- // 上次未正常完成数据索引,后续会由 recoverWAL() 恢复- logging.LogInfof("data index state is [%d], will recover through WAL", Conf.DataIndexState)+ // 上次未正常完成数据索引,后续会由 recoverIndexQueue() 恢复+ logging.LogInfof("data index state is [%d], will recover through index queue", Conf.DataIndexState)}Conf.DataIndexState = 0@@ -786,6 +786,7 @@ func Close(force, setCurrentWorkspace bool, execInstallPkg int) (exitCode int) {Conf.Close()sql.CloseDatabase()+ closePushQueue()util.SaveAssetsTexts()clearWorkspaceTemp()clearCorruptedNotebooks()@@ -1201,6 +1202,10 @@ func clearWorkspaceTemp() {os.RemoveAll(filepath.Join(util.DataDir, "%")) // v3.0.6 生成的错误历史文件夹os.RemoveAll(filepath.Join(util.TempDir, "blocktree")) // v3.1.0 前旧版的块树数据+ // v3.7.0-dev 开发版数据索引队列,后面改成 index.queue 了+ os.RemoveAll(filepath.Join(util.TempDir, "queue.wal"))+ os.RemoveAll(filepath.Join(util.TempDir, "queue.wal.lock"))+logging.LogInfof("cleared workspace temp")}diff --git a/kernel/model/push_queue.go b/kernel/model/push_queue.goindex 72d795b8a9..083b5658db 100644--- a/kernel/model/push_queue.go+++ b/kernel/model/push_queue.go@@ -23,8 +23,11 @@ import ("path/filepath""sync"+ "github.com/88250/lute"+ "github.com/88250/lute/render""github.com/gofrs/flock""github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/util")@@ -32,6 +35,8 @@ type pushEntry struct {Action string `json:"action"`Box string `json:"box,omitempty"`Path string `json:"path,omitempty"`+ ID string `json:"id,omitempty"`+ Title string `json:"title,omitempty"`}var (@@ -44,14 +49,30 @@ func ensurePushQueue() {if "" != pushQueuePath {return}- pushQueuePath = filepath.Join(util.TempDir, "push.queue")+ pushQueuePath = filepath.Join(util.QueueDir, "push.queue")+ os.MkdirAll(util.QueueDir, 0755)pushFlock = flock.New(pushQueuePath + ".lock")}-func AppendPushEntry(action, box, p string) {+func AppendPushCreateEntry(box, p string) {+ appendPushEntry(pushEntry{Action: "create", Box: box, Path: p})+}++func AppendPushRemoveEntry(box, p, id string) {+ appendPushEntry(pushEntry{Action: "remove", Box: box, Path: p, ID: id})+}++func AppendPushRenameEntry(box, p, title string) {+ appendPushEntry(pushEntry{Action: "rename", Box: box, Path: p, Title: title})+}++func AppendPushReloadDocInfoEntry(box, p string) {+ appendPushEntry(pushEntry{Action: "reloadDocInfo", Box: box, Path: p})+}++func appendPushEntry(entry pushEntry) {ensurePushQueue()- entry := pushEntry{Action: action, Box: box, Path: p}data, err := json.Marshal(entry)if err != nil {logging.LogErrorf("marshal push entry failed: %s", err)@@ -59,12 +80,12 @@ func AppendPushEntry(action, box, p string) {}data = append(data, '\n')- pushMu.Lock()- defer pushMu.Unlock()-_ = pushFlock.Lock()defer func() { _ = pushFlock.Unlock() }()+ pushMu.Lock()+ defer pushMu.Unlock()+f, err := os.OpenFile(pushQueuePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)if err != nil {logging.LogErrorf("open push queue for append failed: %s", err)@@ -99,8 +120,26 @@ func PollPushQueue() {continue}PushCreate(box, e.Path, nil)- case "reloadFiletree":- util.BroadcastByType("filetree", "reloadFiletree", 0, "", nil)+ case "remove":+ evt := util.NewCmdResult("removeDoc", 0, util.PushModeBroadcast)+ evt.Data = map[string]any{"ids": []string{e.ID}}+ util.PushEvent(evt)+ case "rename":+ util.BroadcastByType("filetree", "rename", 0, "", map[string]any{+ "box": e.Box,+ "path": e.Path,+ "title": e.Title,+ })+ case "reloadDocInfo":+ luteEngine := lute.New()+ tree, err := filesys.LoadTree(e.Box, e.Path, luteEngine)+ if err != nil {+ logging.LogWarnf("push queue reloadDocInfo: load tree [%s/%s] failed: %s", e.Box, e.Path, err)+ continue+ }+ renderer := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)+ size := uint64(len(renderer.Render()))+ refreshDocInfo0(tree, size)}}@@ -146,3 +185,7 @@ func clearPushQueue() {}}}++func closePushQueue() {+ os.Remove(filepath.Join(util.QueueDir, "push.queue.lock"))+}diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex e7117fdea3..951e7ddcd6 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -87,17 +87,17 @@ func initDatabase(forceRebuild bool) {}initDBConnection()- initQueueWAL()+ initIndexQueue()treenode.InitBlockTree(forceRebuild)if !forceRebuild {// 检查数据库结构版本,如果版本不一致的话说明改过表结构,需要重建if util.DatabaseVer == getDatabaseVer() {- recoverWAL()+ recoverIndexQueue()return}logging.LogInfof("the database structure is changed, rebuilding database...")- clearWALEntries()+ clearIndexQueueEntries()}// 不存在库或者版本不一致都会走到这里@@ -1321,7 +1321,7 @@ func batchUpdateHPath(tx *sql.Tx, tree *parse.Tree, context map[string]any) (err}func CloseDatabase() {- closeQueueWAL()+ closeIndexQueue()if err := db.Close(); err != nil {logging.LogErrorf("close database failed: %s", err)}diff --git a/kernel/sql/queue_wal.go b/kernel/sql/index_queue.gosimilarity index 54%rename from kernel/sql/queue_wal.gorename to kernel/sql/index_queue.goindex ec0a32f6fa..25c31e50fe 100644--- a/kernel/sql/queue_wal.go+++ b/kernel/sql/index_queue.go@@ -35,13 +35,13 @@ import ()var (- walMu sync.Mutex- walSize atomic.Int64- skipWALAppend atomic.Bool- walFlock *flock.Flock+ indexMu sync.Mutex+ indexQueueSize atomic.Int64+ skipIndexAppend atomic.Bool+ indexFlock *flock.Flock)-type walEntry struct {+type indexEntry struct {Action string `json:"action"`ID string `json:"id,omitempty"`IDs []string `json:"ids,omitempty"`@@ -50,107 +50,113 @@ type walEntry struct {Hashes []string `json:"hashes,omitempty"`}-func initQueueWAL() {- walPath := filepath.Join(util.TempDir, "queue.wal")- walFlock = flock.New(walPath + ".lock")- fi, err := os.Stat(walPath)+func initIndexQueue() {+ indexQueuePath := filepath.Join(util.QueueDir, "index.queue")+ os.MkdirAll(util.QueueDir, 0755)+ indexFlock = flock.New(indexQueuePath + ".lock")+ fi, err := os.Stat(indexQueuePath)if err != nil {if !os.IsNotExist(err) {- logging.LogErrorf("stat WAL file [%s] failed: %s", walPath, err)+ logging.LogErrorf("stat index queue file [%s] failed: %s", indexQueuePath, err)}return}- walSize.Store(fi.Size())+ indexQueueSize.Store(fi.Size())}-func closeQueueWAL() {}+func closeIndexQueue() {+ os.Remove(filepath.Join(util.QueueDir, "index.queue.lock"))+}-func appendToWAL(op *dbQueueOperation) {- if skipWALAppend.Load() {+func appendToIndexQueue(op *dbQueueOperation) {+ if skipIndexAppend.Load() {return}- entry := dbOpToWALEntry(op)+ entry := dbOpToIndexEntry(op)if nil == entry {return}data, err := json.Marshal(entry)if err != nil {- logging.LogErrorf("marshal WAL entry failed: %s", err)+ logging.LogErrorf("marshal index queue entry failed: %s", err)return}data = append(data, '\n')- walMu.Lock()- defer walMu.Unlock()+ _ = indexFlock.Lock()+ defer func() { _ = indexFlock.Unlock() }()- _ = walFlock.Lock()- defer func() { _ = walFlock.Unlock() }()+ indexMu.Lock()+ defer indexMu.Unlock()- walPath := filepath.Join(util.TempDir, "queue.wal")- f, err := os.OpenFile(walPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)+ indexQueuePath := filepath.Join(util.QueueDir, "index.queue")+ f, err := os.OpenFile(indexQueuePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)if err != nil {- logging.LogErrorf("open WAL for append failed: %s", err)+ logging.LogErrorf("open index queue for append failed: %s", err)return}n, err := f.Write(data)f.Close()if err != nil {- logging.LogErrorf("write WAL failed: %s", err)+ logging.LogErrorf("write index queue failed: %s", err)return}- walSize.Add(int64(n))+ indexQueueSize.Add(int64(n))}-func dbOpToWALEntry(op *dbQueueOperation) *walEntry {+func dbOpToIndexEntry(op *dbQueueOperation) *indexEntry {switch op.action {case "upsert":- return &walEntry{Action: "upsert", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}+ return &indexEntry{Action: "upsert", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}case "index":- return &walEntry{Action: "index", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}+ return &indexEntry{Action: "index", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}case "rename":- return &walEntry{Action: "rename", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}+ return &indexEntry{Action: "rename", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}case "move":- return &walEntry{Action: "move", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}+ return &indexEntry{Action: "move", ID: op.indexTree.ID, Box: op.indexTree.Box, Path: op.indexTree.Path}case "update_refs":- return &walEntry{Action: "update_refs", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}+ return &indexEntry{Action: "update_refs", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}case "delete_refs":- return &walEntry{Action: "delete_refs", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}+ return &indexEntry{Action: "delete_refs", ID: op.upsertTree.ID, Box: op.upsertTree.Box, Path: op.upsertTree.Path}case "delete":- return &walEntry{Action: "delete", Box: op.removeTreeBox, Path: op.removeTreePath}+ return &indexEntry{Action: "delete", Box: op.removeTreeBox, Path: op.removeTreePath}case "delete_id":- return &walEntry{Action: "delete_id", ID: op.removeTreeID}+ return &indexEntry{Action: "delete_id", ID: op.removeTreeID}case "delete_ids":- return &walEntry{Action: "delete_ids", IDs: op.removeTreeIDs}+ return &indexEntry{Action: "delete_ids", IDs: op.removeTreeIDs}case "delete_box":- return &walEntry{Action: "delete_box", Box: op.box}+ return &indexEntry{Action: "delete_box", Box: op.box}case "delete_box_refs":- return &walEntry{Action: "delete_box_refs", Box: op.box}+ return &indexEntry{Action: "delete_box_refs", Box: op.box}case "delete_assets":- return &walEntry{Action: "delete_assets", Hashes: op.removeAssetHashes}+ return &indexEntry{Action: "delete_assets", Hashes: op.removeAssetHashes}case "index_node":- return &walEntry{Action: "index_node", ID: op.id}+ return &indexEntry{Action: "index_node", ID: op.id}default:return nil}}-func clearWAL(snapshotSize int64) {- walMu.Lock()- defer walMu.Unlock()+func clearIndexQueue(snapshotSize int64) {+ _ = indexFlock.Lock()+ defer func() { _ = indexFlock.Unlock() }()++ indexMu.Lock()+ defer indexMu.Unlock()- walPath := filepath.Join(util.TempDir, "queue.wal")+ indexQueuePath := filepath.Join(util.QueueDir, "index.queue")- var preserved []walEntry- fi, err := os.Stat(walPath)+ var preserved []indexEntry+ fi, err := os.Stat(indexQueuePath)if err == nil && fi.Size() > snapshotSize {- preserved = readWALEntriesFrom(walPath, snapshotSize)+ preserved = readIndexEntriesFrom(indexQueuePath, snapshotSize)}- f, err := os.Create(walPath)+ f, err := os.Create(indexQueuePath)if err != nil {- logging.LogErrorf("create WAL file failed: %s", err)+ logging.LogErrorf("create index queue file failed: %s", err)return}@@ -162,11 +168,11 @@ func clearWAL(snapshotSize int64) {newSize += int64(n)}f.Close()- walSize.Store(newSize)+ indexQueueSize.Store(newSize)}-func readWALEntriesFrom(walPath string, offset int64) (entries []walEntry) {- f, err := os.Open(walPath)+func readIndexEntriesFrom(indexQueuePath string, offset int64) (entries []indexEntry) {+ f, err := os.Open(indexQueuePath)if err != nil {return}@@ -182,7 +188,7 @@ func readWALEntriesFrom(walPath string, offset int64) (entries []walEntry) {if 0 == len(line) {continue}- var entry walEntry+ var entry indexEntryif nil == json.Unmarshal(line, &entry) {entries = append(entries, entry)}@@ -190,46 +196,46 @@ func readWALEntriesFrom(walPath string, offset int64) (entries []walEntry) {return}-func clearWALEntries() {- walMu.Lock()- defer walMu.Unlock()+func clearIndexQueueEntries() {+ indexMu.Lock()+ defer indexMu.Unlock()- walPath := filepath.Join(util.TempDir, "queue.wal")- if gulu.File.IsExist(walPath) {- if err := os.Truncate(walPath, 0); err != nil {- logging.LogErrorf("clear WAL failed: %s", err)+ indexQueuePath := filepath.Join(util.QueueDir, "index.queue")+ if gulu.File.IsExist(indexQueuePath) {+ if err := os.Truncate(indexQueuePath, 0); err != nil {+ logging.LogErrorf("clear index queue failed: %s", err)}}- walSize.Store(0)+ indexQueueSize.Store(0)}-func PollWAL() {- if skipWALAppend.Load() {+func PollIndexQueue() {+ if skipIndexAppend.Load() {return}- _ = walFlock.Lock()- defer func() { _ = walFlock.Unlock() }()+ _ = indexFlock.Lock()+ defer func() { _ = indexFlock.Unlock() }()- entries := loadWAL()+ entries := loadIndexQueue()if 1 > len(entries) {return}- skipWALAppend.Store(true)- defer skipWALAppend.Store(false)+ skipIndexAppend.Store(true)+ defer skipIndexAppend.Store(false)- logging.LogInfof("polling [%d] external WAL operations", len(entries))- processWALEntries(entries, "poll WAL")- clearWALEntries()+ logging.LogInfof("polling [%d] external index queue operations", len(entries))+ processIndexEntries(entries, "poll index queue")+ clearIndexQueueEntries()}-func loadWAL() (entries []walEntry) {- walPath := filepath.Join(util.TempDir, "queue.wal")- f, err := os.Open(walPath)+func loadIndexQueue() (entries []indexEntry) {+ indexQueuePath := filepath.Join(util.QueueDir, "index.queue")+ f, err := os.Open(indexQueuePath)if err != nil {if !os.IsNotExist(err) {- logging.LogErrorf("open WAL for reading failed: %s", err)+ logging.LogErrorf("open index queue for reading failed: %s", err)}return}@@ -241,31 +247,31 @@ func loadWAL() (entries []walEntry) {if 0 == len(line) {continue}- var entry walEntry+ var entry indexEntryif err = json.Unmarshal(line, &entry); err != nil {- logging.LogWarnf("skip corrupted WAL line: %s", err)+ logging.LogWarnf("skip corrupted index queue line: %s", err)continue}entries = append(entries, entry)}if err = scanner.Err(); err != nil {- logging.LogErrorf("scan WAL failed: %s", err)+ logging.LogErrorf("scan index queue failed: %s", err)}return}-func recoverWAL() {- entries := loadWAL()+func recoverIndexQueue() {+ entries := loadIndexQueue()if 1 > len(entries) {return}- logging.LogInfof("recovering [%d] WAL operations", len(entries))- processWALEntries(entries, "recover WAL")- logging.LogInfof("recovered [%d] WAL operations, will be flushed soon", len(entries))+ logging.LogInfof("recovering [%d] index queue operations", len(entries))+ processIndexEntries(entries, "recover index queue")+ logging.LogInfof("recovered [%d] index queue operations, will be flushed soon", len(entries))}-func processWALEntries(entries []walEntry, prefix string) {+func processIndexEntries(entries []indexEntry, prefix string) {luteEngine := lute.New()for _, e := range entries {switch e.Action {diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex 7a22eb4c34..efecaf1b5c 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -96,7 +96,7 @@ func ClearQueue() {dbQueueLock.Lock()defer dbQueueLock.Unlock()operationQueue = nil- clearWALEntries()+ clearIndexQueueEntries()}var flushingTx = atomic.Bool{}@@ -105,7 +105,7 @@ func FlushQueue() {initDatabaseLock.Lock()defer initDatabaseLock.Unlock()- ops, walSnapshot := getOperations()+ ops, indexSnapshot := getOperations()total := len(ops)if 1 > total && !flushingTx.Load() {return@@ -204,7 +204,7 @@ func FlushQueue() {eventbus.Publish(eventbus.EvtSQLIndexFlushed)- clearWAL(walSnapshot)+ clearIndexQueue(indexSnapshot)}func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error) {@@ -450,18 +450,18 @@ func RemoveTreePathQueue(treeBox, treePathPrefix string) {appendOperation(newOp)}-func getOperations() (ops []*dbQueueOperation, walSnapshot int64) {+func getOperations() (ops []*dbQueueOperation, indexSnapshot int64) {dbQueueLock.Lock()defer dbQueueLock.Unlock()ops = operationQueueoperationQueue = nil- walSnapshot = walSize.Load()+ indexSnapshot = indexQueueSize.Load()return}func appendOperation(op *dbQueueOperation) {operationQueue = append(operationQueue, op)- appendToWAL(op)+ appendToIndexQueue(op)eventbus.Publish(eventbus.EvtSQLIndexChanged)}diff --git a/kernel/util/working.go b/kernel/util/working.goindex 91a8e1b0ba..03b33bc08f 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -228,6 +228,7 @@ var (RepoDir string // 仓库目录路径HistoryDir string // 数据历史目录路径TempDir string // 临时目录路径+ QueueDir string // 队列目录路径LogPath string // 配置目录下的日志文件 siyuan.log 路径DBName = "siyuan.db" // SQLite 数据库文件名DBPath string // SQLite 数据库文件路径@@ -303,6 +304,7 @@ func initWorkspaceDir(workspaceArg string) {RepoDir = filepath.Join(WorkspaceDir, "repo")HistoryDir = filepath.Join(WorkspaceDir, "history")TempDir = filepath.Join(WorkspaceDir, "temp")+ QueueDir = filepath.Join(TempDir, "queue")osTmpDir := filepath.Join(TempDir, "os")os.RemoveAll(osTmpDir)if err := os.MkdirAll(osTmpDir, 0755); err != nil {