dsh-plain-memory 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.en.md +72 -0
- package/README.md +146 -2
- package/cards.js +69 -0
- package/cordis.patch.yml +5 -0
- package/git.js +119 -0
- package/index.js +686 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/memory.js +396 -0
- package/package.json +46 -4
- package/prompts/daily-consolidate.md +28 -0
- package/template/README.md +39 -0
- package/template/self.md +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Simin Yuan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.en.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# dsh-plain-memory
|
|
2
|
+
|
|
3
|
+
[中文](README.md) | English
|
|
4
|
+
|
|
5
|
+
Plain memory for DeepSeek Harness. **Remove it and DSH is unchanged; install it and DSH remembers you and recalls what matters.**
|
|
6
|
+
|
|
7
|
+
Memory is plain Markdown in your own Git repository. The plugin is 1,141 lines, imports only Node built-ins, calls no model, and runs no periodic timer.
|
|
8
|
+
|
|
9
|
+
## What it does
|
|
10
|
+
|
|
11
|
+
1. **Asset** — memory lives as Markdown in your private repo; the plugin pulls at session start, commits each write immediately, and pushes in a detached process.
|
|
12
|
+
2. **Multiple windows (experimental, off by default)** — enable with `cards: true`; sessions then exchange a short delta when their cues match. Off by default because a stale card from an already-closed window was observed being pushed back.
|
|
13
|
+
3. **Recall** — each memory carries cue words; every turn matches the user message locally (BM25 over Chinese bigrams plus a small hand-written concept bridge) and injects at most three entries, only above threshold.
|
|
14
|
+
|
|
15
|
+
## Measured properties
|
|
16
|
+
|
|
17
|
+
| Property | Value |
|
|
18
|
+
|---|---|
|
|
19
|
+
| Plugin source | **1,045 lines** (excluding tests) |
|
|
20
|
+
| Runtime dependencies | **0** |
|
|
21
|
+
| Model calls inside the plugin | **0** |
|
|
22
|
+
| Periodic timers / resident processes | **0** |
|
|
23
|
+
| Fixed per-session injection | **≈596 tokens** (four tool schemas) |
|
|
24
|
+
| Injection when nothing matches | **zero** |
|
|
25
|
+
| One recalled entry | **≈124 tokens** |
|
|
26
|
+
| Uninstall | DSH boots normally; the memory repo is untouched byte for byte |
|
|
27
|
+
|
|
28
|
+
Measured against a real `headless` profile with a scripted mock model server, from the actual `/v1/messages` request bodies. See `test/e2e/measure.mjs`. Token counts are estimates, not a provider tokenizer.
|
|
29
|
+
|
|
30
|
+
## Verification
|
|
31
|
+
|
|
32
|
+
- **Prompt cache**: over three consecutive turns in one session, turn 2's message array is a byte-identical prefix of turn 3's; injection only appends.
|
|
33
|
+
- **Cross-domain recall**: 5/5 probes hit, 0 false recalls on 6 unrelated questions — note that probes and concept bridge share an author, so this is not independent validation.
|
|
34
|
+
- **Git does not block**: with an unreachable remote the turn takes 3,051 ms vs 2,989 ms baseline (−62 ms); push runs in a detached child.
|
|
35
|
+
- **Concurrency**: two processes writing ten entries each land 20/20, one commit, clean tree.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
dsh plugin --profile desktop add <path-or-git-url>
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Then add one row to the profile's `cordis.patch.yml`:
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
- insert:
|
|
47
|
+
- id: plain-memory
|
|
48
|
+
name: 'dsh-plain-memory'
|
|
49
|
+
config:
|
|
50
|
+
repoPath: 'C:/Users/you/memory-repo'
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Restart DSH. **Rollback**: delete that row, `dsh plugin --profile desktop remove dsh-plain-memory`, restart.
|
|
54
|
+
|
|
55
|
+
## Self layer
|
|
56
|
+
|
|
57
|
+
`self.md` is mirrored into a managed block inside `$DSH_HOME/AGENTS.md`, so identity and preferences are present from the first turn. Only the marked block is touched. A preference the user explicitly asked to remember is written directly; a preference the model inferred becomes a proposal until the user confirms it.
|
|
58
|
+
|
|
59
|
+
## Limits
|
|
60
|
+
|
|
61
|
+
- The concept bridge is a hand-written word list (23 groups, capped at 50), not a semantic model.
|
|
62
|
+
- Status cards only travel between sessions on the same Git branch or sharing changed files.
|
|
63
|
+
- Consolidation is a DSH `schedule` task you create yourself; the plugin has no background logic.
|
|
64
|
+
- Chinese is tokenised into character bigrams; no dictionary or segmenter.
|
|
65
|
+
|
|
66
|
+
## Tools
|
|
67
|
+
|
|
68
|
+
`memory_write`, `memory_confirm`, `memory_card`, `memory_recall`.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,3 +1,147 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-plain-memory · 原味记忆
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[English](README.en.md) | 中文
|
|
4
|
+
|
|
5
|
+
DSH 原生的轻记忆。**拔掉它,DSH 一点没变;装上它,DSH 记得你、需要时想得起来。**
|
|
6
|
+
|
|
7
|
+
记忆是纯 Markdown,放在你自己的 Git 仓库里。插件本体 1,141 行,只 import Node 内置模块,不调用任何模型,不起任何周期定时器。插件页显示名为「原味记忆」(`locale/zh.json`),包名与仓库名仍是 `dsh-plain-memory`。
|
|
8
|
+
|
|
9
|
+
## 为什么又做一个记忆插件
|
|
10
|
+
|
|
11
|
+
我读过主流的一批 DSH 记忆插件(只读、未安装)。它们大多在往「更重」的方向走:几万行代码、内置模型调用、后台巩固、SQLite 或向量库。而这里做的是**减法**——留两件核心事,外加一个实验功能,其余全部留给 DSH 自己:
|
|
12
|
+
|
|
13
|
+
1. **资产**:记忆是纯 Markdown,存在你自己的 Git 仓库;会话开头自动 pull,写入当场提交,推送在后台,不挡对话。
|
|
14
|
+
2. **唤起**:写记忆时顺手写线索词;之后用用户消息在本地做 BM25 匹配,命中才注入。
|
|
15
|
+
|
|
16
|
+
**实验功能:多窗口状态卡(默认关闭,`cards: true` 才开)**——每个会话写一张状态卡,别的窗口用同一套线索匹配去查,过阈值才推 1–2 行增量。卡 24 小时过期。已知问题见「边界」,默认不开。
|
|
17
|
+
|
|
18
|
+
## 硬指标(实测,非估算)
|
|
19
|
+
|
|
20
|
+
| 指标 | 实测 |
|
|
21
|
+
|---|---|
|
|
22
|
+
| 插件源码 | **1,141 行**(`index.js` 634 + `memory.js` 347 + `git.js` 101 + `cards.js` 59,不含测试);统计命令见文末 |
|
|
23
|
+
| 运行时依赖 | **0**(只 import `node:fs` / `node:path` / `node:os` / `node:crypto` / `node:child_process` / `node:url`) |
|
|
24
|
+
| 插件内模型调用 | **0**(全仓无 LLM 客户端、无 `fetch`、无 API 调用) |
|
|
25
|
+
| 周期定时器 / 常驻进程 | **0**(只有 `index.lock` 退避时的一次性 sleep;push 是分离子进程,不是常驻) |
|
|
26
|
+
| 每会话固定注入 | **≈487 token**(4 个工具 schema,约为单轮请求的 2.8%) |
|
|
27
|
+
| 自我层 | 取决于你自己的条目:实测 4 条约 347 token(约 2.0%) |
|
|
28
|
+
| 无相关内容时 | **零注入**(空记忆仓、无窗口更新时,请求体里没有任何注入消息) |
|
|
29
|
+
| 单次召回注入 | 1 条实测 **≈124 token**;上限 3 条,整块裁剪到 700 token 以内 |
|
|
30
|
+
| 卸载 | 去掉 patch 后正常启动,记忆仓一个字节不变 |
|
|
31
|
+
|
|
32
|
+
测量方法:真 DSH `headless` profile + 真 agent loop + 脚本化的假模型服务器(零 token 成本),从实际发出的 `/v1/messages` 请求体里量。见 `test/e2e/measure.mjs`。token 数是估算(中文按 1 字 1 token、ASCII 按 4 字符 1 token),不是提供方分词器。
|
|
33
|
+
|
|
34
|
+
## 四项验证
|
|
35
|
+
|
|
36
|
+
| 验证 | 结果 |
|
|
37
|
+
|---|---|
|
|
38
|
+
| **提示缓存**:同一会话连续 3 轮,比较请求里的消息数组 | 第二轮 3 条是第三轮 5 条的**逐字节前缀**;注入只追加在末尾,历史一条不改 |
|
|
39
|
+
| **跨领域唤起**:5 组「经历一套词、提问另一套词」 | **5/5 命中**,6 条无关提问**误召回 0**。注意:用例与概念桥是同一作者写的,这**不是**独立验证 |
|
|
40
|
+
| **git 卡死**:远端指向不可达地址(TEST-NET-1) | 基线 3,051 ms / 不可达远端 2,989 ms(差 −62 ms);回合照常结束,push 不挡对话 |
|
|
41
|
+
| **并发写入**:两个进程同时各写 10 条 | **20/20 落盘**,无报错,1 个提交覆盖两边,工作区干净 |
|
|
42
|
+
|
|
43
|
+
命令:`node test/e2e/cache.mjs`、`cross-domain.mjs`、`git-block.mjs`、`concurrency.mjs`(前两个需要 `DSH_APP_HOME`)。
|
|
44
|
+
|
|
45
|
+
## 它怎么工作
|
|
46
|
+
|
|
47
|
+
**注入方式**:每轮只往消息末尾**追加**一条 user message(`agent/pre-step` 瀑布),不改 system prompt、不改历史前缀,所以提供方的提示缓存不整段失效。非首步不重复注入;没命中就什么都不加;同一条记忆在同一窗口只注入一次。
|
|
48
|
+
|
|
49
|
+
**自我层**:`self.md` 的内容同步进 `$DSH_HOME/AGENTS.md` 里一段带标记的托管块,DSH 原生在每个会话开始加载它,所以「你是谁、你的偏好」开局就在,不需要先命中一次。托管块只改标记之间那一段,`AGENTS.md` 里你自己的内容不会被碰。
|
|
50
|
+
|
|
51
|
+
**多窗口(实验性,默认关闭,`cards: true` 才开)**:每个会话写一张状态卡(工作线、改过的文件、本轮首句目标)。别的窗口**用和召回记忆同一套线索匹配**去查这些卡:本轮消息按句切分,逐句和卡的目标/结论/文件名比,**过阈值(默认 0.3)才注入** 1–2 行增量;同分支、同文件只是 +0.15 的加分项。同一张卡在同一窗口只出现一次,内容变了才再推送;**24 小时没更新的卡直接过期**。改到同一批文件是硬碰撞,仍会无条件提醒一次;目标几乎就是本轮这句话的「回声卡」不推。
|
|
52
|
+
|
|
53
|
+
> 为什么默认关闭:2026-11-14 的真机实测里,B 窗口问「另一个窗口的报价说明写到哪了?」,实际收到的是**上一次测试遗留的同句卡片**(回声),而不是 A 窗口的工作卡——A 的卡对这句话只重合「报价说明」一个概念,分数不够。回声过滤能挡住逐字重复,挡不住「已关闭窗口留下的过时卡」。「不打扰」是最核心的承诺,所以这一项默认不开。
|
|
54
|
+
|
|
55
|
+
**跨领域唤起**:写记忆时写 `cues`(线索词),会话结束或每日巩固时把它们写得更抽象。之后每轮用用户消息做本地匹配:中文二元组 + 23 组手写概念桥(评委/评审、转圈/卡住、换电脑/迁移)+ 停用词,0–1 归一分,默认阈值 0.3。长消息按句切开分别召回,避免十个问题挤一条时被稀释。
|
|
56
|
+
|
|
57
|
+
**git 不挡对话**:拉取最多 5 秒、提交最多 5 秒、撞上另一个窗口的 `index.lock` 退避重试 3 次;写完记忆**当场提交**,推送在分离子进程里跑,回合不等它;失败只记日志,改动留在工作区,下次会话开头补交补推。所有 git 调用带 `GIT_TERMINAL_PROMPT=0`,不会弹凭证窗口。
|
|
58
|
+
|
|
59
|
+
**自检**:如果注入被宿主拒绝,或 `agent/pre-step` 一次都没触发,插件会在控制台、logger 和 `.state/health.log` 各留一条告警,不静默失效。
|
|
60
|
+
|
|
61
|
+
**巩固不在插件里**:合并重复、解决冲突、遗忘过时、提炼线索词,交给 DSH 原生的 `schedule` 每天跑一次**普通会话**,提示词见 [`prompts/daily-consolidate.md`](prompts/daily-consolidate.md)。提示词开头有闸门:没有新增情景记忆就直接结束,不做任何 git 操作。
|
|
62
|
+
|
|
63
|
+
## 安装
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
dsh plugin --profile desktop add <本仓库路径或 git URL>
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
然后在 profile 的 `cordis.patch.yml` 加一行(或依赖包自带的 `cordis.patch.yml` 自动插入):
|
|
70
|
+
|
|
71
|
+
```yaml
|
|
72
|
+
- insert:
|
|
73
|
+
- id: plain-memory
|
|
74
|
+
name: 'dsh-plain-memory'
|
|
75
|
+
config:
|
|
76
|
+
repoPath: 'C:/Users/you/memory-repo' # 你的记忆仓本地 clone
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
重启 DSH。插件会在 `repoPath` 不存在时创建最小骨架(`README.md` + `self.md`),但**不会**替你建仓库或加远端。
|
|
80
|
+
|
|
81
|
+
**回滚**:从 `cordis.patch.yml` 删掉 `id: plain-memory` 那一行,再 `dsh plugin --profile desktop remove dsh-plain-memory`,重启。记忆仓保留,DSH 行为与装之前完全一致。
|
|
82
|
+
|
|
83
|
+
## 记忆仓
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
mkdir my-memory && cd my-memory && git init
|
|
87
|
+
git remote add origin <你的私有仓库>
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
目录与格式见 [`template/README.md`](template/README.md)。三层:
|
|
91
|
+
|
|
92
|
+
- `self.md` 自我层——身份、偏好、长期约束。用户亲口说「记住」时直接写入;模型自己推断的偏好只生成待确认提案,用户同意后才写。
|
|
93
|
+
- `episodic/<日期>-<标题>-<短id>.md` 情景层——哪天做了什么、结论是什么。
|
|
94
|
+
- `semantic/<日期>-<标题>-<短id>.md` 语义层——跨会话可复用的事实与方法。
|
|
95
|
+
- `.state/` 运行时(状态卡、观察日志、待确认提案),被 gitignore。
|
|
96
|
+
|
|
97
|
+
一条记忆一个文件,两个窗口同时写不同记忆不会互相覆盖。
|
|
98
|
+
|
|
99
|
+
## 接每日巩固
|
|
100
|
+
|
|
101
|
+
把 [`prompts/daily-consolidate.md`](prompts/daily-consolidate.md) 作为 DSH `schedule` 任务的提示词,每天清晨跑一次。它跑在普通会话里,插件不参与任何巩固代码。代价:新领悟要到第二天才进入索引。
|
|
102
|
+
|
|
103
|
+
## 工具
|
|
104
|
+
|
|
105
|
+
| 工具 | 作用 |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `memory_write` | 写一条记忆(semantic / episodic / self) |
|
|
108
|
+
| `memory_confirm` | 用户确认后,把自我层提案写入 `self.md` |
|
|
109
|
+
| `memory_card` | 更新本窗口状态卡:目标、结论、工作线 |
|
|
110
|
+
| `memory_recall` | 按关键词读取记忆全文(只读;注入被截断时用它) |
|
|
111
|
+
|
|
112
|
+
## 边界(诚实说明)
|
|
113
|
+
|
|
114
|
+
- **概念桥是手写词表,不是语义模型。** 23 组,上限 50 组;词表里没有的说法接不住。这是为了不引入向量模型、推理进程和下载。真需要更强的召回,应该改线索词的写法,或换掉整条检索路径。
|
|
115
|
+
- **多窗口默认关闭。** 打开后仍有两个已知问题:①目标几乎等于本轮消息的「回声卡」会被过滤,但**已关闭窗口留下的旧卡照样可能冒出来**;②A 的卡对 B 的问法可能分数不够(只重合一个概念)。要转正,得先测「没问也该知道」的场景。
|
|
116
|
+
- **一条记忆默认一个线索就算命中,可以调到两个。** 把 `minCues` 设成 2 会明显更安静(单个泛词触发不了),但实测会把跨领域召回从 5/5 压到 2/5;要开它,先靠巩固把线索词写扎实。
|
|
117
|
+
- **「记住」的判定偏宽**:消息里出现「记住 / 记下 / 以后都 / 以后不要 / 别再」就当作已确认,直接写自我层。
|
|
118
|
+
- **概念桥是手写词表,覆盖有限**:比如「电脑 / 笔记本」这一组就没收,这类漏召回时模型可以自己调 `memory_recall` 补查。
|
|
119
|
+
- **巩固要你自己建定时任务。** 插件里没有任何后台逻辑。
|
|
120
|
+
- **中文用二元组切词**,不引入词典或分词器。
|
|
121
|
+
- 检索阈值和条数可配(`minScore` 默认 0.3、`maxRecall` 默认 3),但默认值只在有限场景里调过。
|
|
122
|
+
|
|
123
|
+
## 测试
|
|
124
|
+
|
|
125
|
+
```sh
|
|
126
|
+
node test/core.test.mjs # 记忆仓内核:解析、BM25、概念桥、一跳、写入
|
|
127
|
+
node test/plugin.test.mjs # 插件装配:注入、卡片、自我层、去重、提交、重启恢复
|
|
128
|
+
node test/selfblock.test.mjs # 自我层 → AGENTS.md 托管块
|
|
129
|
+
node test/e2e/cross-domain.mjs # 5 组跨领域用例 + 6 条无关提问
|
|
130
|
+
DSH_APP_HOME=<DSH 安装目录> node test/e2e/run.mjs # 真 DSH 端到端
|
|
131
|
+
DSH_APP_HOME=<DSH 安装目录> node test/e2e/measure.mjs # 硬指标实测
|
|
132
|
+
DSH_APP_HOME=<DSH 安装目录> node test/e2e/cache.mjs # 3 轮提示缓存前缀
|
|
133
|
+
DSH_APP_HOME=<DSH 安装目录> node test/e2e/git-block.mjs # 不可达远端不挡回合
|
|
134
|
+
node test/e2e/concurrency.mjs # 两进程并发写
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
端到端需要先在该目录 `npm install`(只装假模型服务器,和插件运行时无关)。
|
|
138
|
+
|
|
139
|
+
## 行数统计
|
|
140
|
+
|
|
141
|
+
```sh
|
|
142
|
+
node -e "const fs=require('fs');for(const f of ['index.js','memory.js','git.js','cards.js']){const t=fs.readFileSync(f,'utf8');console.log(f,'总行',t.split('\n').length,'非空行',t.split('\n').filter(l=>l.trim()).length)}"
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## License
|
|
146
|
+
|
|
147
|
+
MIT
|
package/cards.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 窗口状态卡:每个活跃 DSH 会话一张,落在记忆仓的 .state/cards/ 下。
|
|
3
|
+
* 卡片是运行时协调数据,不是记忆资产,所以被 .state/.gitignore 排除,不进 git。
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
|
|
9
|
+
const CARD_VERSION = 1
|
|
10
|
+
|
|
11
|
+
function stateDir(repo) {
|
|
12
|
+
return join(repo, '.state')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** 确保 .state 存在且被 git 忽略。 */
|
|
16
|
+
export function ensureState(repo) {
|
|
17
|
+
const dir = stateDir(repo)
|
|
18
|
+
mkdirSync(join(dir, 'cards'), { recursive: true })
|
|
19
|
+
mkdirSync(join(dir, 'pending'), { recursive: true })
|
|
20
|
+
const ignore = join(dir, '.gitignore')
|
|
21
|
+
if (!existsSync(ignore)) writeFileSync(ignore, '*\n', 'utf8')
|
|
22
|
+
return dir
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function cardFile(repo, sessionId) {
|
|
26
|
+
return join(stateDir(repo), 'cards', `${String(sessionId).replace(/[^\w.-]/g, '_')}.json`)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function clip(text, max) {
|
|
30
|
+
const s = String(text || '').replace(/\s+/g, ' ').trim()
|
|
31
|
+
return s.length > max ? s.slice(0, max - 1) : s
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 写一张状态卡(原子替换)。 */
|
|
35
|
+
export function writeCard(repo, card) {
|
|
36
|
+
const dir = ensureState(repo)
|
|
37
|
+
const file = cardFile(repo, card.session)
|
|
38
|
+
const value = {
|
|
39
|
+
v: CARD_VERSION,
|
|
40
|
+
session: String(card.session),
|
|
41
|
+
cwd: clip(card.cwd, 200),
|
|
42
|
+
line: clip(card.line, 80),
|
|
43
|
+
lineExplicit: card.lineExplicit === true,
|
|
44
|
+
files: (card.files || []).slice(0, 12).map((f) => clip(f, 160)),
|
|
45
|
+
objective: clip(card.objective, 300),
|
|
46
|
+
conclusion: clip(card.conclusion, 300),
|
|
47
|
+
updatedAt: Number(card.updatedAt) || Date.now(),
|
|
48
|
+
}
|
|
49
|
+
const tmp = `${file}.${process.pid}.tmp`
|
|
50
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, 'utf8')
|
|
51
|
+
try { renameSync(tmp, file) } catch { writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8') }
|
|
52
|
+
return dir
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 读全部状态卡;坏文件直接跳过。 */
|
|
56
|
+
export function readCards(repo) {
|
|
57
|
+
const dir = join(stateDir(repo), 'cards')
|
|
58
|
+
let names = []
|
|
59
|
+
try { names = readdirSync(dir) } catch { return [] }
|
|
60
|
+
const out = []
|
|
61
|
+
for (const name of names) {
|
|
62
|
+
if (!name.endsWith('.json')) continue
|
|
63
|
+
try {
|
|
64
|
+
const card = JSON.parse(readFileSync(join(dir, name), 'utf8'))
|
|
65
|
+
if (card && typeof card.session === 'string') out.push(card)
|
|
66
|
+
} catch { /* 半写入的卡片下一轮会被覆盖 */ }
|
|
67
|
+
}
|
|
68
|
+
return out
|
|
69
|
+
}
|
package/cordis.patch.yml
ADDED
package/git.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 最小 git 封装:只做记忆仓需要的 pull / commit / push。
|
|
3
|
+
*
|
|
4
|
+
* 三条纪律,都是为了「不挡回合、不打断对话」:
|
|
5
|
+
* 1. 所有调用都有超时,且禁止交互(GIT_TERMINAL_PROMPT=0、GCM_INTERACTIVE=never)。
|
|
6
|
+
* 2. 提交遇到 index.lock 时退避重试;仍失败就把改动留在工作区,下次提交带上。
|
|
7
|
+
* 3. 推送在后台跑,回合不等它;失败只记日志,下次再补推。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execFile, spawn } from 'node:child_process'
|
|
11
|
+
|
|
12
|
+
const PULL_MS = 5_000
|
|
13
|
+
const COMMIT_MS = 5_000
|
|
14
|
+
const PUSH_MS = 15_000
|
|
15
|
+
|
|
16
|
+
function gitEnv() {
|
|
17
|
+
return {
|
|
18
|
+
...process.env,
|
|
19
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
20
|
+
GCM_INTERACTIVE: 'never',
|
|
21
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 跑一条 git 命令;永远 resolve,不抛。 */
|
|
26
|
+
export function runGit(repo, args, timeoutMs = COMMIT_MS) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
execFile(
|
|
29
|
+
'git',
|
|
30
|
+
['-C', repo, ...args],
|
|
31
|
+
{ timeout: timeoutMs, windowsHide: true, maxBuffer: 4 * 1024 * 1024, env: gitEnv() },
|
|
32
|
+
(error, stdout, stderr) => {
|
|
33
|
+
resolve({
|
|
34
|
+
ok: error === null,
|
|
35
|
+
code: typeof error?.code === 'number' ? error.code : error === null ? 0 : 1,
|
|
36
|
+
out: String(stdout || '').trim(),
|
|
37
|
+
err: String(stderr || '').trim(),
|
|
38
|
+
timedOut: error?.killed === true,
|
|
39
|
+
})
|
|
40
|
+
},
|
|
41
|
+
)
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms) })
|
|
46
|
+
|
|
47
|
+
/** 是否是一个 git 工作树。 */
|
|
48
|
+
export async function isRepo(repo) {
|
|
49
|
+
const r = await runGit(repo, ['rev-parse', '--is-inside-work-tree'], 4_000)
|
|
50
|
+
return r.ok && r.out === 'true'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 工作树根目录。 */
|
|
54
|
+
export async function topLevel(repo) {
|
|
55
|
+
const r = await runGit(repo, ['rev-parse', '--show-toplevel'], 4_000)
|
|
56
|
+
return r.ok ? r.out : ''
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 目录所在的 git 分支;不是仓库(或 detached)就返回空串。用它当「工作线」。 */
|
|
60
|
+
export async function branchOf(dir) {
|
|
61
|
+
const r = await runGit(dir, ['symbolic-ref', '--short', 'HEAD'], 4_000)
|
|
62
|
+
return r.ok ? r.out : ''
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 是否有未提交改动。 */
|
|
66
|
+
export async function isDirty(repo) {
|
|
67
|
+
const r = await runGit(repo, ['status', '--porcelain'], COMMIT_MS)
|
|
68
|
+
return r.ok && r.out.length > 0
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 拉取(只快进)。 */
|
|
72
|
+
export async function pull(repo) {
|
|
73
|
+
const r = await runGit(repo, ['pull', '--ff-only', '--quiet'], PULL_MS)
|
|
74
|
+
return { ok: r.ok, detail: r.ok ? '' : (r.err || r.out).slice(0, 200) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 提交全部改动。撞上另一个窗口的 index.lock 时退避重试;
|
|
79
|
+
* 重试仍失败就把改动留在工作区并返回失败,由下次提交带上。
|
|
80
|
+
*/
|
|
81
|
+
export async function commit(repo, message, attempts = 3) {
|
|
82
|
+
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
|
83
|
+
const add = await runGit(repo, ['add', '-A'], COMMIT_MS)
|
|
84
|
+
if (!add.ok) return { ok: false, committed: false, detail: (add.err || add.out).slice(0, 200) }
|
|
85
|
+
const done = await runGit(repo, ['commit', '-m', message, '--quiet'], COMMIT_MS)
|
|
86
|
+
if (done.ok) return { ok: true, committed: true, detail: '' }
|
|
87
|
+
const text = `${done.err}\n${done.out}`
|
|
88
|
+
if (/nothing to commit|no changes added/i.test(text)) return { ok: true, committed: false, detail: '' }
|
|
89
|
+
const locked = /index\.lock|Another git process|Unable to create|File exists/i.test(text)
|
|
90
|
+
if (locked && attempt < attempts) {
|
|
91
|
+
await sleep(150 * attempt)
|
|
92
|
+
continue
|
|
93
|
+
}
|
|
94
|
+
return { ok: false, committed: false, detail: text.trim().slice(0, 200) }
|
|
95
|
+
}
|
|
96
|
+
return { ok: false, committed: false, detail: 'commit retries exhausted' }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 后台推送:分离子进程,回合不等它,父进程退出也不等。 */
|
|
100
|
+
export function pushBackground(repo) {
|
|
101
|
+
try {
|
|
102
|
+
const child = spawn('git', ['-C', repo, 'push', '--quiet'], {
|
|
103
|
+
env: gitEnv(),
|
|
104
|
+
stdio: 'ignore',
|
|
105
|
+
windowsHide: true,
|
|
106
|
+
detached: true,
|
|
107
|
+
})
|
|
108
|
+
child.unref()
|
|
109
|
+
return true
|
|
110
|
+
} catch {
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 同步等待的推送,只给进程收尾用;超时即放弃。 */
|
|
116
|
+
export async function pushNow(repo) {
|
|
117
|
+
const r = await runGit(repo, ['push', '--quiet'], PUSH_MS)
|
|
118
|
+
return { ok: r.ok, detail: r.ok ? '' : (r.err || r.out).slice(0, 200) }
|
|
119
|
+
}
|