@fonlan/dsh-gitmemo 0.1.5 → 0.3.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/README.md CHANGED
@@ -3,33 +3,34 @@
3
3
  **English** | [**简体中文**](README.zh.md)
4
4
 
5
5
  **Git-backed long-term memory for DeepSeek Harness (dsh)** — a Cordis plugin mirroring
6
- [GitMemo](https://github.com/fonlan/gitmemo). The agent stores completed task outcomes as
7
- markdown entries in a local **`.mem`** Git repository and searches them before starting new
8
- work. Git is the only dependency, and no manual memory commands are ever needed.
6
+ [GitMemo](https://github.com/fonlan/gitmemo). The root agent stores completed task outcomes as
7
+ **immutable** markdown entries in a local **`.mem`** Git repository (a single `main` branch with
8
+ structured commit messages) and searches them before starting new work. Git is the only
9
+ dependency, and no manual memory commands are ever needed.
9
10
 
10
11
  ## Key Characteristics
11
12
 
12
13
  - **Extremely simple** — once installed, no manual memory commands in day-to-day tasks
13
- - **Fully automated** — the agent runs `init`, `search`, `read`, `write`, `delete` as part of its normal task flow
14
+ - **Fully automated** — the root agent runs `search`, `read`, `write`, `delete`, `replace` as part of its normal task flow
14
15
  - **Local-only & offline** — memory lives in a local `.mem` Git repository; no cloud dependency
15
16
  - **Git-only** — no runtime dependency beyond the `git` CLI
16
- - **Token-efficient** — reuses prior conclusions via `mem_search` instead of re-injecting context
17
- - **Prevents context bloat** — search-first workflow; the skill caps reads at 5 relevant memories
18
- - **Auditable** — every memory action is a commit in `.mem`'s Git history
19
- - **Traceable** — each memory can be traced and replayed from commit history
20
- - **Branch-aligned** — the `.mem` branch follows the project's current branch on writes
17
+ - **Token-efficient** — reuses prior conclusions via `mem_search`; subagents carry neither the workflow rules nor the tool schemas
18
+ - **Immutable entries** — every write creates a new file; corrections use `mem_replace` (one commit deletes the old file and adds the new one), withdrawal uses `mem_delete`
19
+ - **Structured search** — commit messages carry `GitMemo-*` trailers (keywords, digest, search-text projections); search is `git log --grep --fixed-strings` over commit messages only — entry bodies are never scanned
20
+ - **Auditable** — every memory action is a commit in `.mem`'s Git history; replaced/deleted entries stay readable by hash
21
+ - **Crash-safe** — write/delete/replace run under a cross-process lock with a journal written before entry mutation; migration uses a sibling swap journal so an interrupted directory exchange is recovered before automatic initialization
22
+ - **Single-branch** — `.mem` permanently stays on `main`; the code branch/SHA is recorded as entry metadata only
21
23
 
22
24
  ## What the Plugin Provides
23
25
 
24
26
  | Piece | Description |
25
27
  | --- | --- |
26
- | `mem_init` | Initialize the `.mem` repository (all other tools auto-initialize) |
27
- | `mem_search` | Search memories: `keywords` (comma-separated), `skip` (pagination), `mode` (`and` / `or` / `auto` — AND first, OR fallback). Returns up to 20 hits as `hash\|title\|date` |
28
- | `mem_read` | Read one memory entry by commit hash (full markdown) |
29
- | `mem_write` | Store a task outcome: `title` + `content` (or `content_file` / `file`), optional inline `body` (commit body; engine API still supports `body_file`). Commits `.mem/entries/<timestamp>-<slug>.md` and aligns the `.mem` branch |
30
- | `mem_delete` | Delete a memory entry by commit hash (then redo and rewrite) |
31
- | Always-on rules section | The complete workflow rules (gitmemo's `agents-template.md` equivalent) are injected into **every** session's system prompt — no skill load needed |
32
- | Session-start injection | On every new **root** agent session, the N most recent memory titles (`hash\|title\|date`) are automatically injected into that session's system prompt, so prior-session context is visible before any tool call; subagents are skipped and the lookup never creates `.mem` |
28
+ | `mem_search` | Search memories: `keywords` (array of 1–12, 中英文同义词), `skip` + `snapshot` (stable pagination). Returns up to 20 scored hits with `summary` / `keywords` / `matched_keywords` |
29
+ | `mem_read` | Read one memory entry by create/replace commit hash (full markdown; historical hashes stay readable) |
30
+ | `mem_write` | Store a task outcome: `title` + `summary` + `keywords` (2–12) + `content` (engine generates front matter), optional `related_branches` / `related_paths`. One ADD commit per immutable file |
31
+ | `mem_delete` | Withdraw an obsolete conclusion (requires `commit_hash` + `reason`) |
32
+ | `mem_replace` | Correct an outdated conclusion in ONE atomic commit (D old + A new) — never delete-then-write |
33
+ | Scoped rules | The workflow rules + the five tools are registered into **root agents only** (`delegationDepth === 0`) at `agent/created`; subagents carry neither |
33
34
 
34
35
  ## Installation
35
36
 
@@ -48,7 +49,7 @@ dsh plugin --profile web add /path/to/dsh-gitmemo
48
49
  ```
49
50
 
50
51
  Then restart the dsh profile (e.g. restart the `dsh web` process). The plugin registers on the
51
- host plane, so every agent session in that profile sees the tools and the skill.
52
+ host plane, so every new **root** agent session in that profile sees the tools and the rules.
52
53
 
53
54
  ### Configuration
54
55
 
@@ -58,80 +59,77 @@ The bundle patch ships with sensible defaults; override them in the profile's
58
59
  ```yaml
59
60
  - id: dsh-gitmemo
60
61
  config:
61
- memDirName: .mem # memory repo directory name at the project root
62
- searchLimit: 20 # max hits per mem_search call
63
- branchAlign: true # .mem branch follows the project branch on write
64
- recentContextLimit: 5 # recent memory titles injected into each new session's system prompt (0 disables)
62
+ searchLimit: 20 # max hits per mem_search call (page size)
63
+ lockTimeoutMs: 30000 # cross-process lock wait timeout
65
64
  projectRoot: null # optional explicit project root (defaults to the session cwd)
66
65
  ```
67
66
 
68
- ## Memory Location
67
+ ## Memory Location & Format
69
68
 
70
69
  The `.mem` repository lives at the **project root** of the calling session's workspace
71
- (`git rev-parse --show-toplevel`, falling back to the working directory). Entries are
72
- markdown files under `.mem/entries/`; every operation is a commit, so the whole memory is
73
- readable with plain `git`:
70
+ (`git rev-parse --show-toplevel`, falling back to the working directory; an explicit
71
+ `projectRoot` config wins). The repo layout:
72
+
73
+ ```text
74
+ .mem/
75
+ ├── .git/
76
+ ├── .gitmemo-format # schema version marker, e.g. "2"
77
+ └── entries/ # one immutable file per active memory
78
+ └── <utc-ms>-<digest-prefix>-<slug>.md
79
+ ```
80
+
81
+ - `.mem` is initialized on its own `main` branch; initialization writes `.mem/` and the lock
82
+ file path into the parent repo's `.git/info/exclude` (never into a version-controlled
83
+ `.gitignore`), and refuses to run when the parent repo already tracks `.mem` content.
84
+ - Every write creates a brand-new file with an exclusive create (never overwrites), commits
85
+ one ADD commit with structured trailers, and records the code branch/SHA/related paths in
86
+ the entry front matter.
87
+
88
+ The whole memory stays readable with plain `git`:
74
89
 
75
90
  ```bash
76
91
  git -C .mem log --oneline
77
92
  git -C .mem show <commit-hash>
78
93
  ```
79
94
 
80
- > Tip: add `.mem/` to your project's `.gitignore` so the memory repository never mixes into project commits.
81
-
82
- ## Agent Workflow (always-on rules)
83
-
84
- 1. **Before work — search.** Extract 3-5 keywords from the request → `mem_search`. If more
85
- than 5 hits are relevant, read only the 5 most likely (`mem_read`). Paginate with `skip`
86
- 20, 40, … when nothing relevant appears.
87
- 2. **User unsatisfied — delete and rewrite.** `mem_delete <hash>` → redo from feedback →
88
- `mem_write` a corrected entry.
89
- 3. **End-of-session checkpoint — the only write path.** When the conversation is ending, review
90
- the whole session and `mem_write` every completed repo-related task that still lacks a memory
91
- and whose outcome is **valuable/reusable** (or was explicitly asked to be remembered). Never
92
- duplicate an already-written entry; if a stored outcome is outdated, `mem_delete` it first,
93
- then write the corrected entry. Never write for pure Q&A, incomplete tasks, non-repo work, or
94
- purely operational git actions. Write all pending memories before closing the conversation.
95
-
96
- ## Entry Format
97
-
98
- ```markdown
99
- ---
100
- date: 2026-02-19T15:10:10Z
101
- status: done
102
- repo_branch: main
103
- repo_commit: 9f3e1a2
104
- mem_branch: main
105
- related_paths: [src/auth/login.ts]
106
- tags: [auth, security]
107
- ---
108
- ### Original User Request
109
- (verbatim)
110
- ### AI Understanding
111
- - Goal: / Constraints: / Out of scope:
112
- ### Final Outcome
113
- - Changes/outputs summary
114
- ```
95
+ ## Agent Workflow (always-on rules, root agents)
96
+
97
+ 1. **Before work — search.** For repo-related tasks, extract 1–12 中英文关键词 → `mem_search`.
98
+ Pure chat and general Q&A need no search.
99
+ 2. **Preselect results.** Based on `title` / `summary` / `keywords` / `score` /
100
+ `matched_keywords`, `mem_read` at most 5 most relevant memories; paginate with `skip` +
101
+ the returned `snapshot`.
102
+ 3. **End-of-session checkpoint — the only write path.** When the conversation is ending,
103
+ `mem_write` every completed repo-related task that still lacks a memory and whose outcome is
104
+ **valuable/reusable** (or was explicitly asked to be remembered). Never duplicate an
105
+ already-written entry. Never write for pure Q&A, incomplete tasks, non-repo work, or purely
106
+ operational git actions.
107
+ 4. **User correction.** If a stored conclusion is outdated and a replacement exists →
108
+ `mem_replace` (never delete-then-write). If it is obsolete with no replacement →
109
+ `mem_delete` with a `reason`.
110
+ 5. **Subagent results.** Only the root agent decides whether a session-level memory is written.
115
111
 
116
112
  ## Development
117
113
 
118
114
  ```bash
119
115
  npm install
120
116
  npm run build # tsc → lib/
121
- npm test # build + engine/plugin unit tests (node:test)
117
+ npm test # build + engine/plugin/migration unit tests (node:test)
122
118
  ```
123
119
 
124
120
  ## Layout
125
121
 
126
122
  ```
127
123
  dsh-gitmemo/
128
- ├── package.json # npm package; dsh.bundle.patch wires the profile layer
124
+ ├── package.json # npm package; dsh.bundle.patch wires the profile layer; bin: dsh-gitmemo
129
125
  ├── cordis.patch.yml # composition layer: the dsh-gitmemo row
130
126
  ├── src/
131
- │ ├── index.ts # Cordis plugin: mem_* tools + gitmemo skill + prompt section
132
- │ └── mem.ts # core engine (port of gitmemo scripts/mem.sh)
127
+ │ ├── index.ts # Cordis plugin: root-agent-scoped mem_* tools + workflow section
128
+ │ ├── mem.ts # core engine (protocol, lock/journal, search, write/read/delete/replace)
129
+ │ ├── migrate.ts # legacy migration (dry-run/apply, backup refs, CAS swap)
130
+ │ └── cli.ts # `dsh-gitmemo migrate` CLI entry
133
131
  ├── lib/ # built output (committed; used by file:/git installs)
134
- └── test/mem.test.mjs # engine + plugin unit tests
132
+ └── test/mem.test.mjs # engine + plugin + migration unit tests
135
133
  ```
136
134
 
137
135
  ## License
package/README.zh.md CHANGED
@@ -3,33 +3,33 @@
3
3
  [**English**](README.md) | **简体中文**
4
4
 
5
5
  **基于 Git 的 DeepSeek Harness (dsh) 长期记忆插件** —— 一个镜像
6
- [GitMemo](https://github.com/fonlan/gitmemo) 功能的 Cordis 插件。Agent 会把已完成任务的结论以
7
- markdown 条目存入项目根目录的本地 **`.mem`** Git 仓库,并在开始新任务前先搜索既往记忆。唯一依赖
8
- 是 Git,日常使用完全无需手动记忆命令。
6
+ [GitMemo](https://github.com/fonlan/gitmemo) 功能的 Cordis 插件。根 Agent 会把已完成任务的结论以
7
+ **不可变** markdown 条目存入项目根目录的本地 **`.mem`** Git 仓库(单一 `main` 分支 + 结构化提交信息),
8
+ 并在开始新任务前先搜索既往记忆。唯一依赖是 Git,日常使用完全无需手动记忆命令。
9
9
 
10
10
  ## 核心特性
11
11
 
12
12
  - **极其简单** —— 安装后日常任务无需任何手动记忆命令
13
- - **全自动** —— Agent 在正常任务流程中自动执行 `init` / `search` / `read` / `write` / `delete`
13
+ - **全自动** —— 根 Agent 在正常任务流程中自动执行 `search` / `read` / `write` / `delete` / `replace`
14
14
  - **纯本地、可离线** —— 记忆存于本地 `.mem` Git 仓库,无云端依赖
15
15
  - **仅依赖 Git** —— 除 `git` CLI 外无任何运行时依赖
16
- - **省 token** —— 通过 `mem_search` 复用既有结论,而非反复注入上下文
17
- - **防止上下文膨胀** —— 先搜索后工作的流程,技能规定最多只读 5 条最相关记忆
18
- - **可审计** —— 每次记忆操作都是 `.mem` Git 历史中的一次提交
19
- - **可追溯** —— 每条记忆都能从提交历史中回溯与重放
20
- - **分支对齐** —— 写入时 `.mem` 分支跟随项目当前分支
16
+ - **省 token** —— 通过 `mem_search` 复用既有结论;子代理既不携带工作流规则也不携带工具 schema
17
+ - **条目不可变** —— 每次写入都创建新文件;更正用 `mem_replace`(一个提交同时删除旧文件、新增新文件),作废用 `mem_delete`
18
+ - **结构化搜索** —— commit message 携带 `GitMemo-*` trailers(keywords、digest、search-text 投影);搜索只对 commit message 执行 `git log --grep --fixed-strings`,绝不扫描条目正文
19
+ - **可审计** —— 每次记忆操作都是 `.mem` Git 历史中的一次提交;被替换/删除的条目仍可按哈希读取
20
+ - **崩溃安全** —— write/delete/replace 在修改条目前先写事务 journal;迁移另用 sibling swap journal,目录交换中断后会在自动初始化前恢复
21
+ - **单分支** —— `.mem` 永远停留在 `main`;代码分支/SHA 只作为条目元数据记录
21
22
 
22
23
  ## 插件提供的内容
23
24
 
24
25
  | 内容 | 说明 |
25
26
  | --- | --- |
26
- | `mem_init` | 初始化 `.mem` 仓库(其余工具都会自动初始化) |
27
- | `mem_search` | 搜索记忆:`keywords`(逗号分隔)、`skip`(分页)、`mode`(`and` / `or` / `auto`,auto 先 AND 后 OR 兜底)。每次最多返回 20 条 `hash\|title\|date` |
28
- | `mem_read` | 按提交哈希读取一条记忆的完整 markdown |
29
- | `mem_write` | 存储任务结论:`title` + `content`(或 `content_file` / `file`),可选内联 `body`(commit body;引擎 API 仍支持 `body_file`)。提交为 `.mem/entries/<时间戳>-<slug>.md` 并对齐 `.mem` 分支 |
30
- | `mem_delete` | 按提交哈希删除记忆条目(然后重做并重写) |
31
- | 常驻规则片段 | 完整工作流规则(相当于 gitmemo 的 `agents-template.md`)注入**每个**会话的系统提示词——无需加载技能即可生效 |
32
- | 会话开始注入 | 每个新**根** Agent 会话开始时,自动把最近 N 条记忆标题(`hash\|title\|date`)注入该系统提示词,跨会话上下文在调用任何工具前即可见;子代理被跳过,且该查询只读、绝不创建 `.mem` |
27
+ | `mem_search` | 搜索记忆:`keywords`(1–12 个关键词数组,建议中英文同义词)、`skip` + `snapshot`(稳定分页)。每次最多返回 20 条带 `summary` / `keywords` / `matched_keywords` 的评分结果 |
28
+ | `mem_read` | 按创建/替换提交哈希读取一条记忆的完整 markdown(历史哈希仍可读) |
29
+ | `mem_write` | 存储任务结论:`title` + `summary` + `keywords`(2–12)+ `content`(front matter 由引擎生成),可选 `related_branches` / `related_paths`。每个不可变文件对应一个 ADD 提交 |
30
+ | `mem_delete` | 作废无替代结论(需要 `commit_hash` + `reason`) |
31
+ | `mem_replace` | 一个原子提交内更正旧结论(D 旧文件 + A 新文件)—— 禁止先删后写 |
32
+ | 作用域规则 | 工作流规则与五个工具只在 `agent/created` 时注册进**根 Agent**(`delegationDepth === 0`);子代理两者皆无 |
33
33
 
34
34
  ## 安装
35
35
 
@@ -47,8 +47,8 @@ dsh plugin --profile web add @fonlan/dsh-gitmemo
47
47
  dsh plugin --profile web add /path/to/dsh-gitmemo
48
48
  ```
49
49
 
50
- 然后重启对应的 dsh profile(例如重启 `dsh web` 进程)。插件注册在宿主平面,该 profile 下所有
51
- Agent 会话都能看到这些工具与技能。
50
+ 然后重启对应的 dsh profile(例如重启 `dsh web` 进程)。插件注册在宿主平面,该 profile 下每个新
51
+ **根** Agent 会话都能看到这些工具与规则。
52
52
 
53
53
  ### 配置
54
54
 
@@ -57,75 +57,69 @@ bundle patch 自带合理默认值,可在 profile 的 `cordis.patch.yml` 中
57
57
  ```yaml
58
58
  - id: dsh-gitmemo
59
59
  config:
60
- memDirName: .mem # 项目根目录下记忆仓库的目录名
61
- searchLimit: 20 # 每次 mem_search 返回的最大条数
62
- branchAlign: true # 写入时 .mem 分支跟随项目分支
63
- recentContextLimit: 5 # 注入每个新会话系统提示词的最近记忆条数(0 表示关闭)
60
+ searchLimit: 20 # 每次 mem_search 返回的最大条数(每页大小)
61
+ lockTimeoutMs: 30000 # 跨进程锁等待超时
64
62
  projectRoot: null # 可选:显式项目根目录(默认取会话工作目录)
65
63
  ```
66
64
 
67
- ## 记忆存放位置
65
+ ## 记忆存放位置与格式
68
66
 
69
67
  `.mem` 仓库位于调用会话工作区的**项目根目录**(`git rev-parse --show-toplevel`,找不到时退回
70
- 工作目录)。条目是 `.mem/entries/` 下的 markdown 文件;每次操作都是一次提交,整个记忆可以用
71
- 普通 `git` 命令查看:
68
+ 工作目录;显式配置 `projectRoot` 优先)。仓库结构:
69
+
70
+ ```text
71
+ .mem/
72
+ ├── .git/
73
+ ├── .gitmemo-format # schema 版本标记,如 "2"
74
+ └── entries/ # 每个活跃记忆一个不可变文件
75
+ └── <utc-ms>-<digest-prefix>-<slug>.md
76
+ ```
77
+
78
+ - `.mem` 初始化在自己的 `main` 分支上;初始化时把 `.mem/` 与锁文件路径写入父仓库的
79
+ `.git/info/exclude`(绝不写入受版本控制的 `.gitignore`),且当父仓库已跟踪 `.mem` 内容时拒绝初始化。
80
+ - 每次写入都用独占创建生成全新文件(绝不覆盖),以带结构化 trailers 的 ADD 提交落库,并把代码
81
+ 分支/SHA/相关路径记录在条目 front matter 中。
82
+
83
+ 整个记忆可以用普通 `git` 命令查看:
72
84
 
73
85
  ```bash
74
86
  git -C .mem log --oneline
75
87
  git -C .mem show <commit-hash>
76
88
  ```
77
89
 
78
- > 提示:建议把 `.mem/` 加入项目的 `.gitignore`,避免记忆仓库混入项目提交。
79
-
80
- ## Agent 工作流(常驻规则)
81
-
82
- 1. **开工前 —— 搜索。** 从请求中提取 3-5 个关键词 → `mem_search`。若相关结果超过 5 条,只
83
- `mem_read` 最可能相关的 5 条。无相关结果时用 `skip` 20、40… 翻页。
84
- 2. **用户不满意 —— 删除重写。** `mem_delete <hash>` → 按反馈重做 → `mem_write` 更正后的条目。
85
- 3. **会话结束检查点 —— 唯一的写入路径。** 对话即将结束时,回顾整个会话,用 `mem_write` 写入
86
- **每一条**已完成、与仓库相关、且结论**有价值/可复用**(或用户明确要求记住)但还没有记忆的任务。
87
- 绝不重复写已存在的条目;若已存结论已过时,先 `mem_delete` 再写更正条目。纯问答、未完成任务、
88
- 与仓库无关的工作、纯操作性的 git 动作一律不写。关闭会话前写完所有待写记忆。
89
-
90
- ## 条目格式
91
-
92
- ```markdown
93
- ---
94
- date: 2026-02-19T15:10:10Z
95
- status: done
96
- repo_branch: main
97
- repo_commit: 9f3e1a2
98
- mem_branch: main
99
- related_paths: [src/auth/login.ts]
100
- tags: [auth, security]
101
- ---
102
- ### Original User Request
103
- (verbatim)
104
- ### AI Understanding
105
- - Goal: / Constraints: / Out of scope:
106
- ### Final Outcome
107
- - Changes/outputs summary
108
- ```
90
+ ## Agent 工作流(常驻规则,仅根 Agent)
91
+
92
+ 1. **开工前 —— 搜索。** 仓库相关任务开始前提取 1–12 个中英文关键词 → `mem_search`。纯闲聊和通用问答无需搜索。
93
+ 2. **结果预筛。** 根据 `title` / `summary` / `keywords` / `score` / `matched_keywords` 最多
94
+ `mem_read` 5 条最相关记忆;用 `skip` + 返回的 `snapshot` 翻页。
95
+ 3. **会话结束检查点 —— 唯一的写入路径。** 对话即将结束时,`mem_write` **每一条**已完成、与仓库
96
+ 相关、且结论**有价值/可复用**(或用户明确要求记住)但还没有记忆的任务。绝不重复写已存在的条目。
97
+ 纯问答、未完成任务、与仓库无关的工作、纯操作性的 git 动作一律不写。
98
+ 4. **用户更正。** 已存结论过时且有替代结论 → `mem_replace`(禁止先 delete 再 write);结论作废且无
99
+ 替代 → 带 `reason` 的 `mem_delete`。
100
+ 5. **子代理结果。** 是否形成一条会话级记忆,由根 Agent 汇总后决定。
109
101
 
110
102
  ## 开发
111
103
 
112
104
  ```bash
113
105
  npm install
114
106
  npm run build # tsc → lib/
115
- npm test # 构建 + 引擎/插件单元测试(node:test)
107
+ npm test # 构建 + 引擎/插件/迁移单元测试(node:test)
116
108
  ```
117
109
 
118
110
  ## 目录结构
119
111
 
120
112
  ```
121
113
  dsh-gitmemo/
122
- ├── package.json # npm 包;dsh.bundle.patch 接入 profile 层
114
+ ├── package.json # npm 包;dsh.bundle.patch 接入 profile 层;bin: dsh-gitmemo
123
115
  ├── cordis.patch.yml # 组合层:dsh-gitmemo 行
124
116
  ├── src/
125
- │ ├── index.ts # Cordis 插件:mem_* 工具 + gitmemo 技能 + 提示词片段
126
- │ └── mem.ts # 核心引擎(gitmemo scripts/mem.sh 的移植)
117
+ │ ├── index.ts # Cordis 插件:仅根 Agent 的 mem_* 工具 + 工作流片段
118
+ │ ├── mem.ts # 核心引擎(协议、锁/journal、搜索、write/read/delete/replace)
119
+ │ ├── migrate.ts # 旧格式迁移(dry-run/apply、backup refs、CAS 交换)
120
+ │ └── cli.ts # `dsh-gitmemo migrate` CLI 入口
127
121
  ├── lib/ # 构建产物(已提交,供 file:/git 安装使用)
128
- └── test/mem.test.mjs # 引擎 + 插件单元测试
122
+ └── test/mem.test.mjs # 引擎 + 插件 + 迁移单元测试
129
123
  ```
130
124
 
131
125
  ## License
package/cordis.patch.yml CHANGED
@@ -3,9 +3,15 @@
3
3
  # Installing this package into a profile (`dsh plugin --profile <name> add @fonlan/dsh-gitmemo`)
4
4
  # appends it to `dsh.profile.bundles`; this patch is then applied as that
5
5
  # bundle's layer. The row below loads the package's main entry as a host-plane
6
- # plugin: it registers the `mem_init` / `mem_search` / `mem_read` /
7
- # `mem_write` / `mem_delete` tools on the shared tool registry, a runtime
8
- # `gitmemo` skill, and a system-prompt section pointing at the memory workflow.
6
+ # plugin: at every ROOT-agent creation it scopes the
7
+ # `mem_search` / `mem_read` / `mem_write` / `mem_delete` / `mem_replace`
8
+ # tools plus the memory workflow system-prompt section into that agent
9
+ # (subagents get neither). No session-start scanning, no Git I/O at
10
+ # registration time.
11
+ #
12
+ # `memDirName` / `branchAlign` / `recentContextLimit` are deprecated and kept
13
+ # only for one compatibility version (they are parsed but have no effect;
14
+ # `.mem` is fixed at <projectRoot>/.mem and always stays on main).
9
15
  - insert:
10
16
  - id: dsh-gitmemo
11
17
  # Node-resolvable package name — must stay in sync with package.json
@@ -15,3 +21,4 @@
15
21
  config:
16
22
  memDirName: .mem
17
23
  searchLimit: 20
24
+ lockTimeoutMs: 30000
package/lib/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/lib/cli.js ADDED
@@ -0,0 +1,178 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-gitmemo CLI — explicit legacy migration (plan 10).
4
+ *
5
+ * dsh-gitmemo migrate --project-root <path> [--dry-run|--apply]
6
+ * [--source <legacy-mem-dir>] [--out <baseline-file>] [--baseline <file>]
7
+ *
8
+ * Migration is AUTOMATIC inside the engine (the first operation on a legacy
9
+ * `.mem` repo migrates it in place). This CLI remains for explicit control:
10
+ * non-default --source directories, baseline review, and repos where
11
+ * automatic migration is blocked (conflicts, dirty worktree, ...).
12
+ *
13
+ * Dry-run scans the legacy `.mem` repo without touching any ref/index/work
14
+ * tree state and prints the plan (dedupe, conflicts, estimated commits).
15
+ * `--apply` re-verifies the baseline refs, then migrates inside the
16
+ * cross-process lock; the original `.mem` is only replaced after the new
17
+ * canonical main is fully built and verified.
18
+ *
19
+ * @module dsh-gitmemo/cli
20
+ */
21
+ import { readFile, writeFile } from "node:fs/promises";
22
+ import { resolve } from "node:path";
23
+ import { GitMemoError } from "./mem.js";
24
+ import { migrateApply, migrateDryRun } from "./migrate.js";
25
+ function usage() {
26
+ return [
27
+ "usage: dsh-gitmemo migrate --project-root <path> [--dry-run|--apply]",
28
+ " [--source <legacy-mem-dir>] [--out <baseline-file>] [--baseline <file>]",
29
+ "",
30
+ " --project-root <path> code project root (the .mem sibling lives here)",
31
+ " --dry-run scan the legacy repo and print the migration plan (default)",
32
+ " --apply execute migration (uses --baseline, or performs a fresh dry-run first)",
33
+ " --source <dir> legacy memory dir (default <projectRoot>/.mem)",
34
+ " --out <file> write the dry-run baseline JSON to a file",
35
+ " --baseline <file> baseline JSON produced by a previous --dry-run",
36
+ " --help, -h show this help"
37
+ ].join("\n");
38
+ }
39
+ function parseArgs(argv) {
40
+ const args = { projectRoot: "", action: "dry-run" };
41
+ // optional subcommand token: `dsh-gitmemo migrate --project-root ...`
42
+ if (argv[0] === "migrate")
43
+ argv = argv.slice(1);
44
+ for (let i = 0; i < argv.length; i += 1) {
45
+ const arg = argv[i];
46
+ switch (arg) {
47
+ case "--project-root":
48
+ case "--projectRoot": {
49
+ const value = argv[i + 1];
50
+ if (value === undefined)
51
+ throw new GitMemoError("gitmemo: --project-root requires a path");
52
+ args.projectRoot = value;
53
+ i += 1;
54
+ break;
55
+ }
56
+ case "--dry-run":
57
+ args.action = "dry-run";
58
+ break;
59
+ case "--apply":
60
+ args.action = "apply";
61
+ break;
62
+ case "--source":
63
+ case "--sourceDir": {
64
+ const value = argv[i + 1];
65
+ if (value === undefined)
66
+ throw new GitMemoError("gitmemo: --source requires a path");
67
+ args.source = value;
68
+ i += 1;
69
+ break;
70
+ }
71
+ case "--out": {
72
+ const value = argv[i + 1];
73
+ if (value === undefined)
74
+ throw new GitMemoError("gitmemo: --out requires a file path");
75
+ args.out = value;
76
+ i += 1;
77
+ break;
78
+ }
79
+ case "--baseline": {
80
+ const value = argv[i + 1];
81
+ if (value === undefined)
82
+ throw new GitMemoError("gitmemo: --baseline requires a file path");
83
+ args.baseline = value;
84
+ i += 1;
85
+ break;
86
+ }
87
+ case "--help":
88
+ case "-h":
89
+ console.log(usage());
90
+ process.exit(0);
91
+ break;
92
+ default:
93
+ throw new GitMemoError("gitmemo: unknown argument: " + arg + "\n" + usage());
94
+ }
95
+ }
96
+ if (args.projectRoot.length === 0) {
97
+ throw new GitMemoError("gitmemo: --project-root is required\n" + usage());
98
+ }
99
+ return args;
100
+ }
101
+ function printDryRun(root, report) {
102
+ if (report.alreadyNewFormat === true) {
103
+ console.log(`gitmemo: ${report.baseline.memDir} is already in new format — nothing to migrate.`);
104
+ return;
105
+ }
106
+ const lines = [
107
+ `gitmemo migration dry-run for ${root}`,
108
+ ` source: ${report.baseline.memDir}`,
109
+ ` legacy branches: ${report.branches.join(", ") || "(none)"}`,
110
+ ` active legacy entries: ${report.oldEntryCount}`,
111
+ ` unique entries: ${report.uniqueEntryCount}`,
112
+ ` conflicts: ${report.conflictCount}`,
113
+ ` estimated main commits: ${report.estimatedMainCommits} (1 init + ${report.uniqueEntryCount} entries)`
114
+ ];
115
+ if (report.conflictCount > 0) {
116
+ lines.push(" conflict manifest:");
117
+ for (const conflict of report.baseline.conflicts) {
118
+ const variants = conflict.variants.map((v) => `${v.branch}@${v.hash.slice(0, 12)}`).join(", ");
119
+ lines.push(` ${conflict.path}: [${variants}]`);
120
+ }
121
+ lines.push(" → resolve the conflicts, then re-run --dry-run to produce a clean baseline.");
122
+ }
123
+ for (const warning of report.warnings)
124
+ lines.push(" warning: " + warning);
125
+ lines.push("Next: review and run `dsh-gitmemo migrate --project-root <path> --apply` (or pass a saved --baseline file).");
126
+ console.log(lines.join("\n"));
127
+ }
128
+ async function main() {
129
+ const args = parseArgs(process.argv.slice(2));
130
+ const root = resolve(args.projectRoot);
131
+ if (args.action === "dry-run") {
132
+ const report = await migrateDryRun(root, { source: args.source });
133
+ printDryRun(root, report);
134
+ if (args.out !== undefined) {
135
+ await writeFile(args.out, JSON.stringify(report.baseline, null, 2) + "\n", "utf8");
136
+ console.log(`baseline written to ${args.out}`);
137
+ }
138
+ return;
139
+ }
140
+ let baseline;
141
+ if (args.baseline !== undefined) {
142
+ try {
143
+ baseline = JSON.parse(await readFile(args.baseline, "utf8"));
144
+ }
145
+ catch (error) {
146
+ throw new GitMemoError("gitmemo: cannot read baseline file " + args.baseline + ": " + String(error));
147
+ }
148
+ }
149
+ else {
150
+ const report = await migrateDryRun(root, { source: args.source });
151
+ if (report.alreadyNewFormat === true) {
152
+ console.log(`gitmemo: ${report.baseline.memDir} is already in new format — nothing to migrate.`);
153
+ return;
154
+ }
155
+ if (report.conflictCount > 0) {
156
+ printDryRun(root, report);
157
+ throw new GitMemoError("gitmemo: migration has conflicts — resolve them before --apply");
158
+ }
159
+ baseline = report.baseline;
160
+ }
161
+ const report = await migrateApply(root, baseline, { source: args.source });
162
+ if (report.alreadyMigrated === true) {
163
+ console.log(`gitmemo: ${baseline.memDir} is already in new format — nothing to migrate.`);
164
+ return;
165
+ }
166
+ console.log([
167
+ `gitmemo migration applied for ${root}`,
168
+ ` entries reimported: ${report.entries}`,
169
+ ` old branches backed up: ${report.oldBranches.join(", ")}`,
170
+ ` backup refs: ${report.backupRefPrefix}<branch> (kept permanently; old hashes stay readable)`,
171
+ ` new main: ${report.newMain}`
172
+ ].join("\n"));
173
+ }
174
+ main().catch((error) => {
175
+ const message = error instanceof GitMemoError ? error.message : String(error);
176
+ console.error("gitmemo: " + message);
177
+ process.exit(1);
178
+ });