@imliulian/dsh-zeromem 0.1.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/NOTICE +17 -0
- package/README.md +44 -13
- package/README.zh.md +44 -13
- package/assets/panel.js +110 -4
- package/bin/dsh-zeromem.mjs +187 -0
- package/lib/contracts.mjs +253 -2
- package/lib/expiry.mjs +105 -1
- package/lib/hooks.mjs +29 -6
- package/lib/index.mjs +4 -1
- package/lib/llm.mjs +6 -2
- package/lib/memory.mjs +263 -5
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +268 -28
- package/lib/tools.mjs +101 -7
- package/lib/web.mjs +86 -8
- package/package.json +8 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `@imliulian/dsh-zeromem` will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.2.1] - 2026-11-27
|
|
6
|
+
|
|
7
|
+
### Fixed & Improved
|
|
8
|
+
- **Pure Native Pre-Write Admission + Gated Standalone Supersession (`lib/contracts.mjs`, `lib/memory.mjs`)**:
|
|
9
|
+
- Restored `_admitWindow` to the 100% pure native 3-field `FACT_ADMISSION_SYSTEM` prompt (removing out-of-distribution `prior_facts` and 4-field JSON Schema pollution during admission that caused admission drift and noisy supersession edges in v0.2.0).
|
|
10
|
+
- Extracted supersession linking into a lightweight gated standalone pass (`FACT_SUPERSESSION_SYSTEM` + `buildSupersessionSchema`, `num_predict = 128`) that triggers only on admitted & guarded facts containing explicit state-change/migration cues (`hasSupersessionCue`) and passing size-independent token-overlap and boilerplate-echo filters (`FACT_ADMISSION_SUPERSEDE_ADDENDUM` kept as a compatibility export).
|
|
11
|
+
- **No-Op Revision Isolation (`isNoopRevision`)**:
|
|
12
|
+
- Intercepts `decision === "revise"` outputs that return empty strings or materially unchanged copies of the candidate (ignoring whitespace, casing, and trailing `| Involving:` suffixes) and routes them into `hold` isolation rather than storing stale/leaked facts.
|
|
13
|
+
- **Recall Evidence Deduplication & Verbatim Folding (`deduplicateRecallEvidence`, `isEvidenceVerbatimInFact`, `lib/hooks.mjs`, `lib/tools.mjs`)**:
|
|
14
|
+
- Deduplicates shared `(doc_id, seg_id)` evidence segments across recall hits and folds segments already contained verbatim inside the fact text into compact segment references in both `formatRecallInjection` (`agent/pre-step` auto-injection) and `zeromem_recall` tool output—while preserving full lossless `hit.evidence` on underlying engine/store APIs.
|
|
15
|
+
- **Full Python Parity & 52k-Char Ablation Verification**:
|
|
16
|
+
- Keeps `schema_version = 1`, `SCHEMA_SIG = 42e7ab99494de6a6b4e88eb2`, `APP_FORMAT_ID = 0x494D4C4C`, and all 5 native DSH tool names unchanged (100% cross-runtime interoperable with Python `zeromem` v0.2.1).
|
|
17
|
+
- Verified on the controlled 52k-char (71 docs × 12 Qs) ablation benchmark (`L3 v0.2.0 -> L3-FIX v0.2.1`): deterministic rule defect rate `1.07% -> 0.00%`, prior template leaks `4/6 -> 0/0`, full-DB combined error rate `8.31% -> 6.79%`, supersession false positives `-83.3%` (`12 -> 3` with core TP `sig_05 -> sig_02` lifting Top-1 hit rate `90% -> 100%`), context characters `-17.0%` (`12/12` questions reduced), and single-step cloud input tokens `-13.9%`.
|
|
18
|
+
|
|
19
|
+
## [0.2.0] - 2026-11-26
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
- **Timeline Evolution & Supersession Lineage (`fact_supersessions`)**: Full feature and SQLite schema parity with Python [ZeroMem](https://github.com/IMLIULIAN/zeromem) (`schema_version = 1`, `SCHEMA_SIG = 42e7ab99494de6a6b4e88eb2`, `APP_FORMAT_ID = 0x494D4C4C` unchanged). Before admission, same-namespace active facts are recalled via `<1ms` FTS5 as `prior_facts` with Ollama JSON Schema constraints (`supersedes_fact_id`) to link replacements without breaking existing records.
|
|
23
|
+
- **Event Time Interval Filtering (`occurred_from` / `occurred_to` / `include_superseded`)**: Supports `YYYY`, `YYYY-MM`, and `YYYY-MM-DD` bounds with fail-closed validation across `SQLiteMemoryStore.search()`, `ZeroMemEngine.recall()`, `zeromem_recall` tool, `/dsh-zeromem/api/memories`, and the CLI; active facts automatically rank ahead of superseded history; `guardFact` adds conservative single-date grounding backfill without leaking record dates or `until:` tags.
|
|
24
|
+
- **Read-Only Markdown Export (`exportMarkdown` / `dsh-zeromem export --md` / `GET /dsh-zeromem/api/export.md`)**: 100% read-only SQLite access (`readOnly: true` + `PRAGMA query_only = ON`), zero LLM calls, supporting stdout, single file (`-o`), or per-namespace Obsidian/Git directory (`--dir` with `INDEX.md`), preserving YAML frontmatter, bound original evidence quotes, supersession badges, and `until:` expiry labels.
|
|
25
|
+
- **SQLite Online Safe Backup (`backupDatabase` / `dsh-zeromem backup` / `POST /dsh-zeromem/api/backup`)**: Powered by Node's built-in `node:sqlite` Online Backup API (`backup()`), safely snapshots live WAL databases, flattens snapshots to `journal_mode = DELETE` (zero `-wal`/`-shm` sidecars for OneDrive/BaiduSyncdisk/iCloud), verifies `PRAGMA integrity_check == ok`, and optionally writes `.sha256` checksum files.
|
|
26
|
+
- **Lossless Soft-Eviction & Restore Lineage Parity**: `softEvict` / `restoreEvicted` now snapshot and restore `fact_supersessions` edges with canonical JSON SHA-256 parity across Python and Node runtimes.
|
|
27
|
+
- **Zero-Dependency CLI & Workbench Controls**: Added `dsh-zeromem` CLI (`search` / `export` / `backup` / `stats`) and compact icon controls in the embedded Shadow DOM workbench for timeline date filtering, one-click Markdown export download, and one-click online snapshot backup.
|
|
28
|
+
|
|
5
29
|
## [0.1.0] - 2026-11-23
|
|
6
30
|
|
|
7
31
|
### Added
|
package/NOTICE
CHANGED
|
@@ -15,3 +15,20 @@ This plugin is the official DeepSeek Harness integration for ZeroMem
|
|
|
15
15
|
evidence-grounded extraction/admission protocol. Companion local model
|
|
16
16
|
weights Qwen3.5-4B-Memory-V2 (derived from Qwen/Qwen3.5-4B) are distributed
|
|
17
17
|
separately under Apache-2.0.
|
|
18
|
+
|
|
19
|
+
Schema Lineage & Third-Party Ecosystem Compatibility:
|
|
20
|
+
The structured fact-extraction and pre-write admission schema conventions shared
|
|
21
|
+
with ZeroMem (including bank/namespace partitioning, fact types
|
|
22
|
+
"world" / "experience" / "observation", temporal fields occurred_start /
|
|
23
|
+
occurred_end / mentioned_at, and where / entities metadata) are inspired by and
|
|
24
|
+
conceptually compatible with Vectorize Hindsight
|
|
25
|
+
(https://github.com/vectorize-io/hindsight, MIT License). This plugin's
|
|
26
|
+
node:sqlite dual-track FTS5 store, admission/guardrail pipeline, governance and
|
|
27
|
+
lossless restore layer, and DSH integration are independent clean-room
|
|
28
|
+
implementations containing no Hindsight source code.
|
|
29
|
+
|
|
30
|
+
Name Disambiguation:
|
|
31
|
+
ZeroMem (零忆) and @imliulian/dsh-zeromem (by IMLIULIAN / B站IM榴莲 / ZeroZoneX)
|
|
32
|
+
are independent open-source local memory projects and are not affiliated with,
|
|
33
|
+
derived from, or related to the academic paper "Zero-Mem: Zero-Token Memory
|
|
34
|
+
Operations for LLM Agents" (Yilin Xiao et al., arXiv:2607.29377, July 2026).
|
package/README.md
CHANGED
|
@@ -18,24 +18,36 @@
|
|
|
18
18
|
- Zero third-party runtime dependencies and zero `postinstall` build scripts — installs cleanly under `pnpm >= 10`.
|
|
19
19
|
- **100% Fail-Open**: even if Ollama or your cloud API is offline, DSH startup and chat are never blocked and local FTS5 search remains available.
|
|
20
20
|
|
|
21
|
-
2. **Evidence-Grounded Extraction + Pre-Write Admission
|
|
22
|
-
- Uses a
|
|
23
|
-
- Every stored fact remains **hard-bound to original evidence segments** (`evidence_ids`), eliminating black-box drift and allowing instant verification against the source text.
|
|
21
|
+
2. **Evidence-Grounded Extraction + Pure Native Pre-Write Admission**
|
|
22
|
+
- Uses a decoupled pipeline (**short-window chunking → structured extraction → pure native 3-field admission check with no-op `revise` isolation → deterministic guard**) tuned for the open-source 4B specialist model **[Qwen3.5-4B-Memory-V2](https://huggingface.co/IMLIULIAN/qwen3.5-4b-memory-v2)** (runs 100% locally via Ollama at $0 cloud cost).
|
|
23
|
+
- Every stored fact remains **hard-bound to original evidence segments** (`evidence_ids`), eliminating black-box drift and allowing instant verification against the source text. At injection/tool rendering time, shared `(doc_id, seg_id)` evidence segments are deduplicated and verbatim-contained segments are folded into compact references without altering lossless underlying `hit.evidence`.
|
|
24
24
|
- **Automatic Pre-Send Credential Redaction**: common secrets (`sk-...`, `ghp_...`, `AKIA...`, `Bearer ...`, etc.) are masked to `[REDACTED]` *before* extraction or storage — including when using external APIs.
|
|
25
25
|
|
|
26
|
-
3. **Long-Horizon Memory Governance (Anti-Decay & Reversible)**
|
|
26
|
+
3. **Long-Horizon Memory Governance & Gated Timeline Evolution (Anti-Decay & Reversible)**
|
|
27
|
+
- **Gated Standalone Timeline Supersession (`fact_supersessions`)**: Rather than polluting pre-write admission with out-of-distribution `prior_facts`, ZeroMem runs a lightweight standalone supersession pass (`num_predict=128`, JSON Schema constrained) *only* on admitted facts carrying explicit state-change/migration cues that pass token-overlap and boilerplate-echo filters—ranking active facts ahead of superseded history while keeping full auditability.
|
|
28
|
+
- **Event Time Interval Filtering (`occurred_from` / `occurred_to`)**: Filter memories by `YYYY`, `YYYY-MM`, or `YYYY-MM-DD` event windows (`occurred_from`, `occurred_to`, `include_superseded`) across the engine, `zeromem_recall` tool, Web workbench, and CLI.
|
|
27
29
|
- **Time-Expiry Demotion (`until:YYYY-MM-DD`)**: expired temporary rules/plans are strictly calendar-validated and non-destructively demoted to the tail of search results instead of polluting active context.
|
|
28
30
|
- **Adaptive `2–8` Relative-Score Gating**: dynamically trims low-relevance tail noise based on relative BM25 score ratio (`0.35`, toggleable).
|
|
29
|
-
- **Lossless Soft-Eviction & SHA-256 Tamper-Checked Restore**: deleting a memory archives its facts, segments, and canonical SHA-256 fingerprint into the `evicted_records` side table; restoring verifies integrity before atomically rebuilding FTS5 indexes.
|
|
31
|
+
- **Lossless Soft-Eviction & SHA-256 Tamper-Checked Restore**: deleting a memory archives its facts, segments, supersession edges, and canonical SHA-256 fingerprint into the `evicted_records` side table; restoring verifies integrity before atomically rebuilding FTS5 indexes and lineage edges.
|
|
30
32
|
|
|
31
|
-
4. **
|
|
33
|
+
4. **Read-Only Markdown Export & SQLite Online Safe Backup (Obsidian / Cloud-Drive Friendly)**
|
|
34
|
+
- **100% Read-Only Markdown Export** (`dsh-zeromem export --md` / `GET /dsh-zeromem/api/export.md` / `exportMarkdown()`): opens SQLite read-only (`PRAGMA query_only = ON`) with zero LLM calls, exporting to stdout, a single file (`-o`), or an Obsidian/Git per-namespace vault directory (`--dir` with `INDEX.md`) complete with YAML frontmatter, bound original evidence quotes, supersession links, and `until:` annotations.
|
|
35
|
+
- **WAL-Safe Online Backup** (`dsh-zeromem backup` / `POST /dsh-zeromem/api/backup` / `backupDatabase()`): uses Node's built-in `node:sqlite` Online Backup API to snapshot live WAL databases without locking writers, flattens snapshots to `journal_mode = DELETE` (zero `-wal`/`-shm` sidecars for OneDrive/iCloud/BaiduSyncdisk), verifies `PRAGMA integrity_check == ok`, and optionally writes `.sha256` checksums.
|
|
36
|
+
|
|
37
|
+
5. **Flexible Dual Backend (Local Ollama ↔ OpenAI-Compatible API)**
|
|
32
38
|
- **Local Ollama (Default)**: connects directly to `127.0.0.1:11434` (bypassing system proxy for loopback), auto-detects local Ollama / `Qwen3.5-4B-Memory-V2`, and supports one-click background model pulling (`Q8_0` / `Q4_K_M`) with confirmation.
|
|
33
39
|
- **Cloud / Custom OpenAI-Compatible API**: switch live anytime without restarting DSH — built-in presets for DeepSeek, OpenAI, SiliconFlow, OpenRouter, plus persistent **Custom API** (Base URL + Model ID) for vLLM, LM Studio, or private gateways. API keys stay strictly local (`~/.zeromem/dsh-zeromem.json`, mode `0600`) and are never echoed to the browser.
|
|
34
40
|
|
|
35
|
-
|
|
36
|
-
- **5 Native DSH Tools** (strict lossless JSON): `zeromem_recall
|
|
41
|
+
6. **Native DSH Integration, CLI & Cross-Tool Interop**
|
|
42
|
+
- **5 Native DSH Tools** (strict lossless JSON): `zeromem_recall` (with `occurred_from` / `occurred_to` / `include_superseded`), `zeromem_remember` (with `link_supersessions`), `zeromem_stats`, `zeromem_evict`, `zeromem_restore`.
|
|
37
43
|
- **Automatic Session Lifecycle Hooks** (live-toggleable): `agent/pre-step` (`<1ms` recall with anti-loop markers) and `agent/turn-stopping` (non-blocking background extraction, automatically skips subagents).
|
|
38
|
-
- **Shared Database with Python ZeroMem**: reads and writes the exact same `~/.zeromem/memory.db` (`schema_version = 1`) as [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem), sharing local memory seamlessly across DSH, Cursor, Claude Code, and Codex.
|
|
44
|
+
- **Shared Database with Python ZeroMem**: reads and writes the exact same `~/.zeromem/memory.db` (`schema_version = 1`, `SCHEMA_SIG = 42e7ab99494de6a6b4e88eb2`, `APP_FORMAT_ID = 0x494D4C4C`, including `fact_supersessions` and `evicted_records`) as [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem), sharing local memory seamlessly across DSH, Cursor, Claude Code, and Codex.
|
|
45
|
+
|
|
46
|
+
### Verified v0.2.1 Upgrade Highlights (52k-Char Controlled Ablation)
|
|
47
|
+
Sharing the exact same engine logic and database contract with Python ZeroMem v0.2.1, the three v0.2.1 upgrades (pure native admission + gated standalone supersession, no-op `revise` → `hold` isolation, and recall evidence deduplication/folding) were verified on a controlled 52k-char (71 docs × 12 Qs) ablation benchmark (`Qwen3.5-4B-Memory-V2` local write at ¥0 + live `deepseek-flash`, 560 unique facts audited by rules ∪ judge):
|
|
48
|
+
- **Fact Integrity**: deterministic rule defects `1.07% -> 0.00%` (`0/368`), prior template leaks `4/6 -> 0/0`, full-DB combined error rate `8.31% -> 6.79%` (`-29.6%` vs raw 4B extraction), plaintext cloud secret leaks `0` (vs `8` on raw FTS5 / unguarded tiers).
|
|
49
|
+
- **Timeline Precision**: only `5/71` docs triggered the gated supersession pass, cutting false-positive edges by `-83.3%` (`12 -> 3` including the core reversal TP) and restoring Top-1 hit rate from `9/10` to `10/10` (`100%`).
|
|
50
|
+
- **Context Compactness**: rendered context characters dropped on `12/12` questions (`-17.0%` avg), cutting single-step cloud input tokens by `-13.9%` (`-94.6%` vs full-context stuffing across all 12 Qs). Full tables and bilingual charts are available in [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem).
|
|
39
51
|
|
|
40
52
|
---
|
|
41
53
|
|
|
@@ -95,12 +107,29 @@ Default config path: `~/.zeromem/dsh-zeromem.json` (`0600` on POSIX). Supports `
|
|
|
95
107
|
|
|
96
108
|
As an optional convenience on top of the local memory engine, the plugin injects a lightweight Shadow DOM management panel in DSH Web and DSH Desktop (automatically skipped in headless profiles, protected by loopback + same-origin security fences):
|
|
97
109
|
|
|
98
|
-
- Browse and search local facts, filter by namespace, expand bound original evidence, and
|
|
110
|
+
- Browse and search local facts, filter by namespace or event date range (`occurred_from` / `occurred_to`), inspect supersession badges (`替代 #N` / `已被 #M 替代`), expand bound original evidence, and highlight `[REDACTED]` tokens.
|
|
111
|
+
- One-click **Export Markdown** (read-only `.md` download) and **Online Backup** (WAL-flattened snapshot in `~/.zeromem/backups/` with `.sha256`).
|
|
99
112
|
- Manually write facts, soft-evict outdated entries (with recycle bin preview & SHA-256 restore), and clear expired `until:` records.
|
|
100
113
|
- Switch Local Ollama / Cloud API live, test connectivity, and optionally toggle light/dark frosted-glass styling or custom wallpaper.
|
|
101
114
|
|
|
102
115
|
---
|
|
103
116
|
|
|
117
|
+
## CLI (`dsh-zeromem`)
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
# Search with event time range & hide superseded historical facts
|
|
121
|
+
npx @imliulian/dsh-zeromem search "database" --occurred-from 2026-01-01 --hide-superseded
|
|
122
|
+
|
|
123
|
+
# Read-only Markdown export (single file or Obsidian/Git per-namespace directory)
|
|
124
|
+
npx @imliulian/dsh-zeromem export --md -o ./zeromem.md
|
|
125
|
+
npx @imliulian/dsh-zeromem export --md --dir ./obsidian-vault/zeromem
|
|
126
|
+
|
|
127
|
+
# WAL-safe SQLite Online Backup (single file, journal_mode=DELETE, integrity_check=ok)
|
|
128
|
+
npx @imliulian/dsh-zeromem backup ./backups/ --sha256
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
104
133
|
## Testing
|
|
105
134
|
|
|
106
135
|
```bash
|
|
@@ -108,6 +137,8 @@ npm run check
|
|
|
108
137
|
npm test
|
|
109
138
|
```
|
|
110
139
|
|
|
111
|
-
## License &
|
|
112
|
-
- **GNU Affero General Public License v3.0 (`AGPL-3.0-only`)** — see [LICENSE](LICENSE) and [NOTICE](NOTICE). Any redistributed modifications or network-accessible deployments derived from this plugin must remain open-source under AGPL-3.0 with original copyright notices preserved.
|
|
113
|
-
- Companion
|
|
140
|
+
## License, Attribution & Disambiguation
|
|
141
|
+
- **License**: **GNU Affero General Public License v3.0 (`AGPL-3.0-only`)** — see [LICENSE](LICENSE) and [NOTICE](NOTICE). Any redistributed modifications or network-accessible deployments derived from this plugin must remain open-source under AGPL-3.0 with original copyright notices preserved.
|
|
142
|
+
- **Author & Companion Projects**: **IMLIULIAN (B站IM榴莲)** · **ZeroZoneX** — [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem) · [Qwen3.5-4B-Memory-V2 (Hugging Face, separately Apache-2.0)](https://huggingface.co/IMLIULIAN/qwen3.5-4b-memory-v2)
|
|
143
|
+
- **Schema Lineage & Compatibility**: The fact schema conventions shared with ZeroMem (`bank`, `type: world | experience | observation`, `occurred_start` / `occurred_end` / `mentioned_at`, `where`, `entities`) are inspired by and conceptually compatible with [**Vectorize Hindsight**](https://github.com/vectorize-io/hindsight) (MIT License). This plugin's `node:sqlite` + dual-track FTS5 engine, pre-write admission guardrails, governance/restore layer, and DSH UI/hooks are independent implementations containing no Hindsight source code.
|
|
144
|
+
- **Name Disambiguation**: **ZeroMem (零忆)** / `@imliulian/dsh-zeromem` is an independent local memory system and is **not** affiliated with or derived from the academic paper *Zero-Mem: Zero-Token Memory Operations for LLM Agents* (Yilin Xiao et al., [arXiv:2607.29377](https://arxiv.org/abs/2607.29377), July 2026).
|
package/README.zh.md
CHANGED
|
@@ -18,24 +18,36 @@
|
|
|
18
18
|
- **零第三方运行时依赖、零 `postinstall` 编译脚本**,完美兼容 `pnpm >= 10` 默认安全策略,秒装即用。
|
|
19
19
|
- **100% Fail-Open 容错**:即使本地 Ollama 或云端 API 离线,也绝不阻塞 DSH 启动与正常对话,历史记忆本地 FTS5 检索始终可用。
|
|
20
20
|
|
|
21
|
-
2. **证据绑定 +
|
|
22
|
-
- 内置**短窗切块 → 结构化抽取 →
|
|
23
|
-
- 每一条入库事实均**强制绑定原始证据片段**(`evidence_ids
|
|
21
|
+
2. **证据绑定 + 纯净原生写前审校(拒绝黑盒幻觉)**
|
|
22
|
+
- 内置**短窗切块 → 结构化抽取 → 纯净原生 3 字段审校(含空转 `revise` 转 `hold` 拦截)→ 确定性规则守卫**解耦流水线,针对开源 4B 记忆专项微调模型 **[Qwen3.5-4B-Memory-V2](https://huggingface.co/IMLIULIAN/qwen3.5-4b-memory-v2)** 深度打磨(通过 Ollama 100% 离线运行,写入 ¥0 云端费)。
|
|
23
|
+
- 每一条入库事实均**强制绑定原始证据片段**(`evidence_ids`),随时可回溯原文核对,避免摘要漂移与无中生有;在自动注入与工具返回渲染层会对共享 `(doc_id, seg_id)` 原文段去重并对已逐字包含在事实正文内的原文段折叠为紧凑引用(底层 `hit.evidence` 保持完整无损)。
|
|
24
24
|
- **离开本机前自动密钥脱敏**:常见密钥与凭据(`sk-...`、`ghp_...`、`AKIA...`、`Bearer ...` 等)在送往模型与写入数据库前自动替换为 `[REDACTED]`,切换云端 API 时同样受保护。
|
|
25
25
|
|
|
26
|
-
3.
|
|
26
|
+
3. **面向长周期演进的门控时间线演化与记忆治理机制**
|
|
27
|
+
- **门控独立时间线替代链(`fact_supersessions`)**:写前审校保持 100% 原生 3 字段无污染;仅对通过审校与规则守卫且含显式状态变更/迁移线索、并通过词元重叠与模板复读过滤的极少数事实,才发起轻量独立替代链判定(`num_predict=128` + JSON Schema 约束),召回时活跃事实自动优先于被替代历史事实排序,同时完整保留历史可溯源链。
|
|
28
|
+
- **事件时间区间过滤(`occurred_from` / `occurred_to`)**:支持 `YYYY`、`YYYY-MM`、`YYYY-MM-DD` 区间重叠检索与 `include_superseded` 控制,覆盖引擎、`zeromem_recall` 工具、Web 工作台与 CLI。
|
|
27
29
|
- **`until:YYYY-MM-DD` 过期自动后移**:严格日历校验临时规则/阶段性计划,过期记录无损后移至召回尾部并附带结构化过期标记,不污染当前有效记忆。
|
|
28
30
|
- **`2–8` 动态相对分数门槛**:按头名相关性比值(默认 `0.35`,可开关)自动截断尾部低相关噪音,减少无效上下文占用。
|
|
29
|
-
- **无损软淘汰 + `SHA-256`
|
|
31
|
+
- **无损软淘汰 + `SHA-256` 防篡改原子恢复**:删除的记忆连同原文片段、替代链边与规范化 `SHA-256` 指纹一并归档至同库 `evicted_records` 边表;恢复时先做完整性校验,再原子写回并重建 FTS5 索引与演化边表。
|
|
30
32
|
|
|
31
|
-
4.
|
|
33
|
+
4. **只读 Markdown 导出与 SQLite 在线安全备份(适配 Obsidian / Git / 网盘)**
|
|
34
|
+
- **100% 只读 Markdown 导出**(`dsh-zeromem export --md` / `GET /dsh-zeromem/api/export.md` / `exportMarkdown()`):只读模式打开数据库(`PRAGMA query_only = ON`),零 LLM 调用,支持标准输出、单文件(`-o`)及按空间拆分的 Obsidian/Git 目录(`--dir`,附 `INDEX.md`),保留 YAML frontmatter、原文引用块、替代链与 `until:` 过期标注。
|
|
35
|
+
- **WAL 安全在线热备**(`dsh-zeromem backup` / `POST /dsh-zeromem/api/backup` / `backupDatabase()`):直接调用 Node 内置 `node:sqlite` Online Backup API,不阻塞并发读写,自动将快照拍平为 `journal_mode = DELETE`(无 `-wal`/`-shm` 伴生文件,安全适配 OneDrive/百度网盘/iCloud),内置 `PRAGMA integrity_check` 与可选 `.sha256` 校验文件。
|
|
36
|
+
|
|
37
|
+
5. **本地模型 ↔ 云端 API 自由切换(无独显也能用)**
|
|
32
38
|
- **本地模型(Ollama,默认)**:回环地址直连 `127.0.0.1:11434`(自动绕过系统代理),自动检测本机 Ollama 与 `Qwen3.5-4B-Memory-V2`,支持按需一键拉取 `Q8_0` / `Q4_K_M` 版本(均带二次确认)。
|
|
33
39
|
- **云端 / 自定义 OpenAI 兼容 API**:无需重启 DSH 实时切换,内置 DeepSeek / OpenAI / SiliconFlow / OpenRouter 预设,并支持持久化保存**自定义 API**(Base URL + Model ID,适配 vLLM、LM Studio 或私有网关)。API Key 仅保存在本机 `~/.zeromem/dsh-zeromem.json`(POSIX `0600`),绝不向浏览器回显明文。
|
|
34
40
|
|
|
35
|
-
|
|
36
|
-
- **5 个原生 DSH 工具**(严格无损 JSON):`zeromem_recall
|
|
41
|
+
6. **DSH 原生闭环、命令行工具 & 跨工具数据库互通**
|
|
42
|
+
- **5 个原生 DSH 工具**(严格无损 JSON):`zeromem_recall`(支持 `occurred_from` / `occurred_to` / `include_superseded`)、`zeromem_remember`(支持 `link_supersessions`)、`zeromem_stats`、`zeromem_evict`、`zeromem_restore`。
|
|
37
43
|
- **会话生命周期自动闭环**(均支持热开关):`agent/pre-step`(发消息前 `<1ms` 带防回环标记自动召回)与 `agent/turn-stopping`(每轮结束后后台异步沉淀,自动跳过 subagent)。
|
|
38
|
-
- **与 Python 版 ZeroMem 数据互通**:共用同一份 `~/.zeromem/memory.db`(`schema_version = 1`),与 [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem) 在 DSH、Cursor、Claude Code、Codex 之间无缝共享同一套本地记忆库。
|
|
44
|
+
- **与 Python 版 ZeroMem 100% 数据互通**:共用同一份 `~/.zeromem/memory.db`(`schema_version = 1`、`SCHEMA_SIG = 42e7ab99494de6a6b4e88eb2`、`APP_FORMAT_ID = 0x494D4C4C`,完整互通 `fact_supersessions` 与 `evicted_records`),与 [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem) 在 DSH、Cursor、Claude Code、Codex 之间无缝共享同一套本地记忆库。
|
|
45
|
+
|
|
46
|
+
### v0.2.1 升级实证摘要(5.2 万字受控消融复测)
|
|
47
|
+
与 Python ZeroMem v0.2.1 保持 100% 同构的三项引擎修复(纯净原生验收 + 门控独立替代链、空转 `revise` 拦截转 `hold`、召回共享/同文原文段去重折叠),在 71 篇合成工程文档(51,947 字)× 12 题四档消融复测中(本机 `Qwen3.5-4B-Memory-V2` 写入云端费 `¥0` + `deepseek-flash` 真机盲测 + 560 唯一事实规则∪裁判全库审计):
|
|
48
|
+
- **入库保真与安全**:确定性规则缺陷率 `1.07% → 0.00%`(`0/368`),先验模板泄漏(规则/裁判)双归零(`4/6 → 0/0`),全库联合错误率 `8.31% → 6.79%`(相对无验收抽取降 `-29.6%`);云端明文密钥外泄维持 `0`(对照未脱敏裸搜/抽取档均为 `8` 次)。
|
|
49
|
+
- **替代链精准度**:71 篇仅 `5` 篇触发轻量门控调用,假阳性边骤降 `-83.3%`(`12 → 3`,含核心架构反转真阳),直接带动 10 道有答案题 Top-1 命中率由 `9/10` 回升至 `10/10 (100%)`。
|
|
50
|
+
- **上下文瘦身**:12/12 题注入上下文字符全线下降(均值 `-17.0%`),11 道单步题云端输入 Token 实省 `-13.9%`(全 12 题相对全量历史注入省 `94.6%`)。完整消融对照表与双语高清图表见 [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem)。
|
|
39
51
|
|
|
40
52
|
---
|
|
41
53
|
|
|
@@ -96,12 +108,29 @@ ollama pull hf.co/IMLIULIAN/qwen3.5-4b-memory-v2:Q4_K_M
|
|
|
96
108
|
|
|
97
109
|
在本地记忆引擎之上,插件额外附带了一个轻量的 Shadow DOM 内嵌侧滑工作台(仅在带界面的 DSH Web / 桌面端注入,Headless 环境自动跳过,受本机回环 + 同源双层安全栅栏保护),方便可视化日常打理:
|
|
98
110
|
|
|
99
|
-
-
|
|
111
|
+
- 快速检索、按空间或事件日期区间筛选、查看替代链徽章(`替代 #N` / `已被 #M 替代`)、点击记忆展开原始绑定证据、高亮查看 `[REDACTED]` 脱敏标记。
|
|
112
|
+
- 一键**导出只读 Markdown(`.md`)**与**在线安全备份**(自动生成拍平 WAL 的单文件快照及 `.sha256` 至 `~/.zeromem/backups/`)。
|
|
100
113
|
- 手动写入记忆、软淘汰至回收站、按批次预览与 `SHA-256` 校验一键恢复、一键清理已过期 `until:` 记忆。
|
|
101
114
|
- 实时切换本地 Ollama / 云端 API、一键测试连接,附带亮/暗毛玻璃主题与自定义壁纸等轻量交互体验。
|
|
102
115
|
|
|
103
116
|
---
|
|
104
117
|
|
|
118
|
+
## 命令行工具(`dsh-zeromem`)
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
# 按事件时间区间检索并隐藏被替代的历史事实
|
|
122
|
+
npx @imliulian/dsh-zeromem search "架构方案" --occurred-from 2026-01-01 --hide-superseded
|
|
123
|
+
|
|
124
|
+
# 只读导出为单文件 Markdown 或 Obsidian/Git 分空间目录
|
|
125
|
+
npx @imliulian/dsh-zeromem export --md -o ./zeromem.md
|
|
126
|
+
npx @imliulian/dsh-zeromem export --md --dir ./obsidian-vault/zeromem
|
|
127
|
+
|
|
128
|
+
# WAL 安全在线备份(拍平为无 -wal/-shm 单文件快照 + integrity_check + .sha256)
|
|
129
|
+
npx @imliulian/dsh-zeromem backup ./backups/ --sha256
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
105
134
|
## 开发与测试
|
|
106
135
|
|
|
107
136
|
```bash
|
|
@@ -109,6 +138,8 @@ npm run check
|
|
|
109
138
|
npm test
|
|
110
139
|
```
|
|
111
140
|
|
|
112
|
-
##
|
|
113
|
-
-
|
|
114
|
-
-
|
|
141
|
+
## 许可、血缘归属与同名消歧
|
|
142
|
+
- **开源协议**:**GNU Affero General Public License v3.0(`AGPL-3.0-only`)**,详见 [LICENSE](LICENSE) 与 [NOTICE](NOTICE)。任何基于本插件的二次修改分发或网络服务部署均须以 AGPL-3.0 同等开源并保留原作者署名与版权声明。
|
|
143
|
+
- **作者与关联项目**:**B站IM榴莲(IMLIULIAN)** · **ZeroZoneX** — [IMLIULIAN/zeromem](https://github.com/IMLIULIAN/zeromem) · [Qwen3.5-4B-Memory-V2(Hugging Face,模型权重单独采用 Apache-2.0)](https://huggingface.co/IMLIULIAN/qwen3.5-4b-memory-v2)
|
|
144
|
+
- **Schema 血缘与兼容致谢**:本插件与 ZeroMem 共用的结构化事实字段协议(`bank`、`type: world | experience | observation`、`occurred_start` / `occurred_end` / `mentioned_at`、`where`、`entities`)受开源项目 [**Vectorize Hindsight**](https://github.com/vectorize-io/hindsight)(MIT License)启发并保持概念/Schema 兼容;本插件基于 `node:sqlite` 的双轨 FTS5 引擎、写前审校守卫、过期/软淘汰与 SHA-256 恢复机制及 DSH 集成代码均为独立从零实现,不含 Hindsight 源码。
|
|
145
|
+
- **同名论文消歧**:**ZeroMem(零忆)** 与 `@imliulian/dsh-zeromem` 是独立开发的纯本地记忆系统,与学术论文 *Zero-Mem: Zero-Token Memory Operations for LLM Agents*(Yilin Xiao et al., [arXiv:2607.29377](https://arxiv.org/abs/2607.29377), 2026 年 7 月)名称相近,但两者完全独立,无作者、代码、模型或隶属关系。
|
package/assets/panel.js
CHANGED
|
@@ -50,6 +50,12 @@
|
|
|
50
50
|
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>',
|
|
51
51
|
chevron:
|
|
52
52
|
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',
|
|
53
|
+
calendar:
|
|
54
|
+
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M16 2v4M8 2v4M3 10h18"/></svg>',
|
|
55
|
+
fileMd:
|
|
56
|
+
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/><path d="M12 18v-6"/><path d="m9 15 3 3 3-3"/></svg>',
|
|
57
|
+
backup:
|
|
58
|
+
'<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14a9 3 0 0 0 18 0V5"/><path d="M3 12a9 3 0 0 0 18 0"/></svg>',
|
|
53
59
|
};
|
|
54
60
|
|
|
55
61
|
const NOISE_URI =
|
|
@@ -671,6 +677,22 @@
|
|
|
671
677
|
}
|
|
672
678
|
.zm-tag.rev { background: var(--zm-rev-bg); color: var(--zm-rev-text); border-color: var(--zm-rev-border); }
|
|
673
679
|
.zm-tag.exp { background: var(--zm-exp-bg); color: var(--zm-exp-text); border-color: var(--zm-exp-border); }
|
|
680
|
+
.zm-tag.sup-new { background: rgba(16, 185, 129, 0.12); color: #059669; border-color: rgba(16, 185, 129, 0.28); }
|
|
681
|
+
.zm-tag.sup-old { background: rgba(148, 163, 184, 0.16); color: var(--zm-muted); border-color: var(--zm-divider); text-decoration: line-through; }
|
|
682
|
+
.zm-card.sup-muted { opacity: 0.78; }
|
|
683
|
+
.zm-time-bar {
|
|
684
|
+
display: none; align-items: center; gap: 6px; flex-wrap: wrap;
|
|
685
|
+
padding: 7px 9px; border-radius: 12px; background: var(--zm-surface);
|
|
686
|
+
border: 1px solid var(--zm-surface-border);
|
|
687
|
+
}
|
|
688
|
+
.zm-time-bar.open { display: flex; }
|
|
689
|
+
.zm-date-in {
|
|
690
|
+
height: 28px; min-width: 108px; flex: 1 1 108px; padding: 0 8px;
|
|
691
|
+
border-radius: 8px; border: 1px solid var(--zm-input-border);
|
|
692
|
+
background: var(--zm-input-bg); color: var(--zm-text); font-size: 11.5px; outline: none;
|
|
693
|
+
}
|
|
694
|
+
.zm-date-in:focus { border-color: var(--zm-accent-border); }
|
|
695
|
+
.zm-icon-btn.active { border-color: var(--zm-accent-border); color: var(--zm-accent); }
|
|
674
696
|
|
|
675
697
|
.zm-fact-text {
|
|
676
698
|
font-size: 12.8px; line-height: 1.56; color: var(--zm-text); word-break: break-word; cursor: pointer;
|
|
@@ -985,6 +1007,18 @@
|
|
|
985
1007
|
</button>
|
|
986
1008
|
<div class="zm-ns-menu" id="zmNsMenu" role="listbox" aria-label="空间筛选"></div>
|
|
987
1009
|
</div>
|
|
1010
|
+
<button class="zm-icon-btn square" id="zmTimeToggleBtn" type="button" aria-label="时间线筛选" title="按事件日期与替代链筛选">${ICONS.calendar}</button>
|
|
1011
|
+
<button class="zm-icon-btn square" id="zmExportMdBtn" type="button" aria-label="导出 Markdown" title="只读导出 Markdown (.md)">${ICONS.fileMd}</button>
|
|
1012
|
+
<button class="zm-icon-btn square" id="zmBackupBtn" type="button" aria-label="在线安全备份" title="SQLite 在线安全备份(无 WAL)">${ICONS.backup}</button>
|
|
1013
|
+
</div>
|
|
1014
|
+
<div class="zm-time-bar" id="zmTimeBar">
|
|
1015
|
+
<input class="zm-date-in" id="zmFromDate" type="text" placeholder="起始 YYYY-MM-DD" aria-label="事件起始日期" title="事件起始日期(支持 YYYY / YYYY-MM / YYYY-MM-DD)" />
|
|
1016
|
+
<input class="zm-date-in" id="zmToDate" type="text" placeholder="截止 YYYY-MM-DD" aria-label="事件截止日期" title="事件截止日期(支持 YYYY / YYYY-MM / YYYY-MM-DD)" />
|
|
1017
|
+
<label class="zm-switch" style="padding:0 6px;" title="隐藏已被更新事实替代的历史记录">
|
|
1018
|
+
<span>仅有效</span>
|
|
1019
|
+
<input type="checkbox" id="zmHideSup" />
|
|
1020
|
+
</label>
|
|
1021
|
+
<button class="zm-icon-btn square" id="zmTimeClearBtn" type="button" aria-label="清空时间筛选" title="清空时间线筛选">${ICONS.close}</button>
|
|
988
1022
|
</div>
|
|
989
1023
|
<div class="zm-meta-row">
|
|
990
1024
|
<span id="zmSearchMeta">就绪</span>
|
|
@@ -2287,17 +2321,35 @@
|
|
|
2287
2321
|
});
|
|
2288
2322
|
}
|
|
2289
2323
|
|
|
2290
|
-
|
|
2324
|
+
function buildMemoryQueryParams({ includeLimit = true } = {}) {
|
|
2291
2325
|
const q = $("zmSearchInput").value.trim();
|
|
2292
2326
|
const ns = state.selectedNs;
|
|
2293
|
-
const
|
|
2327
|
+
const occurredFrom = $("zmFromDate")?.value.trim() || "";
|
|
2328
|
+
const occurredTo = $("zmToDate")?.value.trim() || "";
|
|
2329
|
+
const hideSup = Boolean($("zmHideSup")?.checked);
|
|
2330
|
+
const qs = new URLSearchParams();
|
|
2331
|
+
if (includeLimit) {
|
|
2332
|
+
qs.set("q", q);
|
|
2333
|
+
qs.set("limit", "50");
|
|
2334
|
+
}
|
|
2294
2335
|
if (ns) qs.set("ns", ns);
|
|
2336
|
+
if (occurredFrom) qs.set("occurred_from", occurredFrom);
|
|
2337
|
+
if (occurredTo) qs.set("occurred_to", occurredTo);
|
|
2338
|
+
if (hideSup) qs.set("include_superseded", "0");
|
|
2339
|
+
return { qs, q, hasFilter: Boolean(occurredFrom || occurredTo || hideSup) };
|
|
2340
|
+
}
|
|
2341
|
+
|
|
2342
|
+
async function loadMemories() {
|
|
2343
|
+
const { qs, q, hasFilter } = buildMemoryQueryParams({ includeLimit: true });
|
|
2344
|
+
$("zmTimeToggleBtn")?.classList.toggle("active", hasFilter);
|
|
2295
2345
|
try {
|
|
2296
2346
|
const data = await api(`/memories?${qs.toString()}`);
|
|
2297
2347
|
const list = $("zmList");
|
|
2298
2348
|
$("zmSearchMeta").textContent = q
|
|
2299
2349
|
? `命中 ${data.count} 条 · ${data.elapsed_ms}ms`
|
|
2300
|
-
:
|
|
2350
|
+
: hasFilter
|
|
2351
|
+
? `筛选 ${data.count} 条 · ${data.elapsed_ms}ms`
|
|
2352
|
+
: `最新 ${data.count} 条`;
|
|
2301
2353
|
|
|
2302
2354
|
if (!data.items || !data.items.length) {
|
|
2303
2355
|
list.innerHTML = '<div class="zm-empty">暂无匹配记忆<br/>点右上角「写入」或在对话中自然沉淀</div>';
|
|
@@ -2309,13 +2361,22 @@
|
|
|
2309
2361
|
const evHtml = (item.evidence || [])
|
|
2310
2362
|
.map((ev) => `<div class="zm-ev-item"><span class="zm-ev-id">${esc(ev.id)}</span>${highlightRedacted(ev.text)}</div>`)
|
|
2311
2363
|
.join("");
|
|
2364
|
+
const isSupOld = Array.isArray(item.superseded_by) && item.superseded_by.length > 0;
|
|
2365
|
+
const occLabel = item.occurred_start
|
|
2366
|
+
? item.occurred_end && item.occurred_end !== item.occurred_start
|
|
2367
|
+
? `${item.occurred_start}~${item.occurred_end}`
|
|
2368
|
+
: item.occurred_start
|
|
2369
|
+
: "";
|
|
2312
2370
|
return `
|
|
2313
|
-
<article class="zm-card">
|
|
2371
|
+
<article class="zm-card${isSupOld ? " sup-muted" : ""}">
|
|
2314
2372
|
<div class="zm-card-top">
|
|
2315
2373
|
<div class="zm-tags">
|
|
2316
2374
|
<span class="zm-tag">#${item.fact_id}</span>
|
|
2317
2375
|
<span class="zm-tag">${esc(item.namespace)}</span>
|
|
2376
|
+
${occLabel ? `<span class="zm-tag">${esc(occLabel)}</span>` : ""}
|
|
2318
2377
|
${item.action === "revise" ? '<span class="zm-tag rev">已纠错</span>' : ""}
|
|
2378
|
+
${item.supersedes_fact_id ? `<span class="zm-tag sup-new">替代 #${item.supersedes_fact_id}</span>` : ""}
|
|
2379
|
+
${isSupOld ? `<span class="zm-tag sup-old">已被 ${item.superseded_by.map((x) => `#${x}`).join(",")} 替代</span>` : ""}
|
|
2319
2380
|
${item.until_expiry ? `<span class="zm-tag exp">${esc(item.until_expiry.label)}</span>` : ""}
|
|
2320
2381
|
</div>
|
|
2321
2382
|
<button class="zm-icon-btn square danger zm-evict-btn" data-fid="${item.fact_id}" type="button" aria-label="移入回收站" title="软淘汰至回收站(可恢复)">${ICONS.trash}</button>
|
|
@@ -2790,6 +2851,51 @@
|
|
|
2790
2851
|
});
|
|
2791
2852
|
});
|
|
2792
2853
|
|
|
2854
|
+
$("zmTimeToggleBtn").addEventListener("click", () => {
|
|
2855
|
+
$("zmTimeBar").classList.toggle("open");
|
|
2856
|
+
});
|
|
2857
|
+
for (const id of ["zmFromDate", "zmToDate"]) {
|
|
2858
|
+
$(id).addEventListener("change", () => loadMemories());
|
|
2859
|
+
$(id).addEventListener("keydown", (e) => {
|
|
2860
|
+
if (e.key === "Enter") loadMemories();
|
|
2861
|
+
});
|
|
2862
|
+
}
|
|
2863
|
+
$("zmHideSup").addEventListener("change", () => loadMemories());
|
|
2864
|
+
$("zmTimeClearBtn").addEventListener("click", () => {
|
|
2865
|
+
$("zmFromDate").value = "";
|
|
2866
|
+
$("zmToDate").value = "";
|
|
2867
|
+
$("zmHideSup").checked = false;
|
|
2868
|
+
loadMemories();
|
|
2869
|
+
});
|
|
2870
|
+
$("zmExportMdBtn").addEventListener("click", () => {
|
|
2871
|
+
const { qs } = buildMemoryQueryParams({ includeLimit: false });
|
|
2872
|
+
qs.set("download", "1");
|
|
2873
|
+
const a = document.createElement("a");
|
|
2874
|
+
a.href = `${API_BASE}/export.md?${qs.toString()}`;
|
|
2875
|
+
a.download = "";
|
|
2876
|
+
a.click();
|
|
2877
|
+
showToast("已触发只读 Markdown 导出");
|
|
2878
|
+
});
|
|
2879
|
+
$("zmBackupBtn").addEventListener("click", async () => {
|
|
2880
|
+
const btn = $("zmBackupBtn");
|
|
2881
|
+
btn.disabled = true;
|
|
2882
|
+
await withUiBusy("备份中", async () => {
|
|
2883
|
+
try {
|
|
2884
|
+
const res = await api("/backup", {
|
|
2885
|
+
method: "POST",
|
|
2886
|
+
body: JSON.stringify({ sha256: true, verify: true }),
|
|
2887
|
+
});
|
|
2888
|
+
const rc = res.receipt || {};
|
|
2889
|
+
const name = String(rc.backup_path || "").split(/[\\/]/).pop() || "backup.db";
|
|
2890
|
+
showToast(`已备份 ${name} (${formatBytes(rc.size_bytes)} · ${String(rc.sha256 || "").slice(0, 8)})`);
|
|
2891
|
+
} catch (err) {
|
|
2892
|
+
showToast(`备份失败:${err.message}`, false);
|
|
2893
|
+
} finally {
|
|
2894
|
+
btn.disabled = false;
|
|
2895
|
+
}
|
|
2896
|
+
});
|
|
2897
|
+
});
|
|
2898
|
+
|
|
2793
2899
|
$("zmPickOllama").addEventListener("click", () => {
|
|
2794
2900
|
state.providerDraft = "ollama";
|
|
2795
2901
|
renderProviderFields();
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Zero-dependency CLI for @imliulian/dsh-zeromem:
|
|
4
|
+
* dsh-zeromem search <query> [--db PATH] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--hide-superseded] [--limit N] [--json]
|
|
5
|
+
* dsh-zeromem export --md [--db PATH] [-o FILE | --dir DIR] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--as-of DATE] [--hide-superseded] [--include-evicted] [--no-frontmatter] [--json]
|
|
6
|
+
* dsh-zeromem backup [OUT] [--db PATH] [-o OUT] [--overwrite] [--no-verify] [--sha256] [--json]
|
|
7
|
+
* dsh-zeromem stats [--db PATH] [--ns NS] [--json]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { defaultDbPath, expandHome } from "../lib/config.mjs";
|
|
11
|
+
import { backupDatabase, exportMarkdown } from "../lib/portability.mjs";
|
|
12
|
+
import { SQLiteMemoryStore } from "../lib/store.mjs";
|
|
13
|
+
|
|
14
|
+
function printHelp() {
|
|
15
|
+
console.log(`dsh-zeromem — ZeroMem (零忆) local SQLite memory CLI
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
dsh-zeromem search [query] [--db PATH] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--hide-superseded] [--limit N] [--json]
|
|
19
|
+
dsh-zeromem export --md [--db PATH] [-o FILE | --dir DIR] [--ns NS] [--occurred-from DATE] [--occurred-to DATE] [--as-of DATE] [--hide-superseded] [--include-evicted] [--no-frontmatter] [--json]
|
|
20
|
+
dsh-zeromem backup [OUT] [--db PATH] [-o OUT] [--overwrite] [--no-verify] [--sha256] [--json]
|
|
21
|
+
dsh-zeromem stats [--db PATH] [--ns NS] [--json]
|
|
22
|
+
`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function parseArgs(argv) {
|
|
26
|
+
const flags = {};
|
|
27
|
+
const positionals = [];
|
|
28
|
+
const valueFlags = new Set([
|
|
29
|
+
"--db",
|
|
30
|
+
"--ns",
|
|
31
|
+
"--namespace",
|
|
32
|
+
"--limit",
|
|
33
|
+
"--as-of",
|
|
34
|
+
"--occurred-from",
|
|
35
|
+
"--occurred-to",
|
|
36
|
+
"-o",
|
|
37
|
+
"--output",
|
|
38
|
+
"--dir",
|
|
39
|
+
]);
|
|
40
|
+
for (let i = 0; i < argv.length; i++) {
|
|
41
|
+
const arg = argv[i];
|
|
42
|
+
if (arg === "-h" || arg === "--help") {
|
|
43
|
+
flags.help = true;
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
if (valueFlags.has(arg)) {
|
|
47
|
+
const next = argv[i + 1];
|
|
48
|
+
if (next === undefined) throw new Error(`Missing value for ${arg}`);
|
|
49
|
+
flags[arg] = next;
|
|
50
|
+
i += 1;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (arg.startsWith("--") && arg.includes("=")) {
|
|
54
|
+
const idx = arg.indexOf("=");
|
|
55
|
+
flags[arg.slice(0, idx)] = arg.slice(idx + 1);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (arg.startsWith("-")) {
|
|
59
|
+
flags[arg] = true;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
positionals.push(arg);
|
|
63
|
+
}
|
|
64
|
+
return { flags, positionals };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function runCli(argv = process.argv.slice(2)) {
|
|
68
|
+
const { flags, positionals } = parseArgs(argv);
|
|
69
|
+
const cmd = positionals[0];
|
|
70
|
+
if (!cmd || flags.help) {
|
|
71
|
+
printHelp();
|
|
72
|
+
return 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const dbPath = flags["--db"] ? expandHome(flags["--db"]) : defaultDbPath();
|
|
76
|
+
const ns = flags["--ns"] || flags["--namespace"] || null;
|
|
77
|
+
const asJson = Boolean(flags["--json"]);
|
|
78
|
+
|
|
79
|
+
if (cmd === "stats") {
|
|
80
|
+
const store = new SQLiteMemoryStore(dbPath);
|
|
81
|
+
const st = store.stats(ns);
|
|
82
|
+
if (asJson) {
|
|
83
|
+
console.log(JSON.stringify(st, null, 2));
|
|
84
|
+
} else {
|
|
85
|
+
console.log(`DB: ${st.db_path}`);
|
|
86
|
+
console.log(
|
|
87
|
+
`Documents: ${st.documents} | Segments: ${st.segments} | Facts: ${st.facts} (revised ${st.revised_facts}) | Supersessions: ${st.supersessions} | Evicted: ${st.evicted_records}`
|
|
88
|
+
);
|
|
89
|
+
console.log(`Namespaces: ${st.namespaces.length ? st.namespaces.join(", ") : "(none)"}`);
|
|
90
|
+
}
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (cmd === "search") {
|
|
95
|
+
const query = positionals.slice(1).join(" ");
|
|
96
|
+
const store = new SQLiteMemoryStore(dbPath);
|
|
97
|
+
const hits = store.search(query, {
|
|
98
|
+
namespace: ns,
|
|
99
|
+
limit: flags["--limit"] ? Number(flags["--limit"]) : null,
|
|
100
|
+
asOf: flags["--as-of"] || null,
|
|
101
|
+
occurredFrom: flags["--occurred-from"] || null,
|
|
102
|
+
occurredTo: flags["--occurred-to"] || null,
|
|
103
|
+
includeSuperseded: !flags["--hide-superseded"],
|
|
104
|
+
});
|
|
105
|
+
if (asJson) {
|
|
106
|
+
console.log(JSON.stringify(hits, null, 2));
|
|
107
|
+
} else if (!hits.length) {
|
|
108
|
+
console.log("(no matching memories)");
|
|
109
|
+
} else {
|
|
110
|
+
for (let i = 0; i < hits.length; i++) {
|
|
111
|
+
const h = hits[i];
|
|
112
|
+
const badges = [];
|
|
113
|
+
if (h.occurred_start) badges.push(h.occurred_start);
|
|
114
|
+
if (h.supersedes_fact_id) badges.push(`替代 #${h.supersedes_fact_id}`);
|
|
115
|
+
if (h.superseded_by?.length) badges.push(`已被 ${h.superseded_by.map((x) => `#${x}`).join(",")} 替代`);
|
|
116
|
+
if (h.until_expiry?.label) badges.push(h.until_expiry.label);
|
|
117
|
+
const badgeStr = badges.length ? ` [${badges.join(" | ")}]` : "";
|
|
118
|
+
console.log(`${i + 1}. (#${h.fact_id} · ${h.namespace}${badgeStr}) ${h.text}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (cmd === "export") {
|
|
125
|
+
const outputPath = flags["-o"] || flags["--output"] || null;
|
|
126
|
+
const outputDir = flags["--dir"] || null;
|
|
127
|
+
const res = exportMarkdown({
|
|
128
|
+
dbPath,
|
|
129
|
+
outputPath,
|
|
130
|
+
outputDir,
|
|
131
|
+
namespace: ns,
|
|
132
|
+
occurredFrom: flags["--occurred-from"] || null,
|
|
133
|
+
occurredTo: flags["--occurred-to"] || null,
|
|
134
|
+
asOf: flags["--as-of"] || null,
|
|
135
|
+
includeSuperseded: !flags["--hide-superseded"],
|
|
136
|
+
includeEvicted: Boolean(flags["--include-evicted"]),
|
|
137
|
+
frontmatter: !flags["--no-frontmatter"],
|
|
138
|
+
});
|
|
139
|
+
if (res.mode === "stdout" && !asJson) {
|
|
140
|
+
process.stdout.write(res.markdown || "");
|
|
141
|
+
} else if (asJson) {
|
|
142
|
+
const out = { ...res };
|
|
143
|
+
if (out.mode !== "stdout") delete out.markdown;
|
|
144
|
+
console.log(JSON.stringify(out, null, 2));
|
|
145
|
+
} else {
|
|
146
|
+
console.log(
|
|
147
|
+
`Exported ${res.facts_exported} facts (${res.documents_referenced} docs) -> ${res.output_dir || res.output_path}`
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
return 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (cmd === "backup") {
|
|
154
|
+
const outTarget = flags["-o"] || flags["--output"] || positionals[1] || null;
|
|
155
|
+
const receipt = await backupDatabase({
|
|
156
|
+
dbPath,
|
|
157
|
+
outputPath: outTarget,
|
|
158
|
+
overwrite: Boolean(flags["--overwrite"]),
|
|
159
|
+
verify: !flags["--no-verify"],
|
|
160
|
+
writeSha256: Boolean(flags["--sha256"]),
|
|
161
|
+
});
|
|
162
|
+
if (asJson) {
|
|
163
|
+
console.log(JSON.stringify(receipt, null, 2));
|
|
164
|
+
} else {
|
|
165
|
+
console.log(
|
|
166
|
+
`Backup OK (${receipt.journal_mode}, integrity=${receipt.integrity_check}, ${receipt.size_bytes} B): ${receipt.backup_path}`
|
|
167
|
+
);
|
|
168
|
+
console.log(`SHA-256: ${receipt.sha256}`);
|
|
169
|
+
}
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
throw new Error(`Unknown command: ${cmd}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, "/").split("/").pop());
|
|
177
|
+
if (isMain) {
|
|
178
|
+
runCli().then(
|
|
179
|
+
(code) => {
|
|
180
|
+
process.exitCode = code;
|
|
181
|
+
},
|
|
182
|
+
(err) => {
|
|
183
|
+
console.error(`dsh-zeromem error: ${err?.message || err}`);
|
|
184
|
+
process.exitCode = 1;
|
|
185
|
+
}
|
|
186
|
+
);
|
|
187
|
+
}
|