macro-memory 0.0.0-stage → 0.9.0

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.
Files changed (200) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +384 -2
  3. package/bin/macro-memory.mjs +732 -0
  4. package/docs/CHANGELOG.md +250 -0
  5. package/docs/MAC.md +156 -0
  6. package/docs/images/_architecture.svg +70 -0
  7. package/docs/images/_memory-flow.svg +75 -0
  8. package/docs/images/_token-budget.svg +40 -0
  9. package/docs/images/architecture.png +0 -0
  10. package/docs/images/hero.png +0 -0
  11. package/docs/images/memory-flow.png +0 -0
  12. package/docs/images/src/graph.html +78 -0
  13. package/docs/images/src/hero.html +88 -0
  14. package/docs/images/src/panel.html +63 -0
  15. package/docs/images/src/pipeline.html +97 -0
  16. package/docs/images/token-budget.png +0 -0
  17. package/lib/client.js +3811 -0
  18. package/lib/core/agents-file.js +95 -0
  19. package/lib/core/client.js +313 -0
  20. package/lib/core/compat/dsh-llm.js +78 -0
  21. package/lib/core/config.js +117 -0
  22. package/lib/core/engine.js +456 -0
  23. package/lib/core/fence.js +109 -0
  24. package/lib/core/index.js +102 -0
  25. package/lib/core/migrate.js +70 -0
  26. package/lib/core/mini-host.js +324 -0
  27. package/lib/core/owner.js +347 -0
  28. package/lib/core/paths.js +95 -0
  29. package/lib/core/serve.js +378 -0
  30. package/lib/core/trust.js +173 -0
  31. package/lib/index.js +567 -0
  32. package/lib/macro/brand.js +82 -0
  33. package/lib/macro/bridge.js +158 -0
  34. package/lib/macro/chain.js +206 -0
  35. package/lib/macro/contract.js +471 -0
  36. package/lib/macro/cost.js +164 -0
  37. package/lib/macro/defs/admin.js +528 -0
  38. package/lib/macro/defs/dream.js +24 -0
  39. package/lib/macro/defs/link.js +408 -0
  40. package/lib/macro/defs/project.js +237 -0
  41. package/lib/macro/defs/read.js +160 -0
  42. package/lib/macro/defs/remember.js +411 -0
  43. package/lib/macro/defs/search.js +899 -0
  44. package/lib/macro/defs/update.js +161 -0
  45. package/lib/macro/dreamledger.js +1398 -0
  46. package/lib/macro/facade.js +135 -0
  47. package/lib/macro/fusion.js +188 -0
  48. package/lib/macro/injectledger.js +843 -0
  49. package/lib/macro/linkflow.js +391 -0
  50. package/lib/macro/links.js +448 -0
  51. package/lib/macro/neighbor.js +1083 -0
  52. package/lib/macro/panel.js +96 -0
  53. package/lib/macro/platform.js +134 -0
  54. package/lib/macro/prompt.js +139 -0
  55. package/lib/macro/provenance.js +148 -0
  56. package/lib/macro/render.js +35 -0
  57. package/lib/macro/revisions.js +253 -0
  58. package/lib/macro/shared.js +113 -0
  59. package/lib/macro/shortid.js +114 -0
  60. package/lib/macro/snapshot.js +700 -0
  61. package/lib/macro/spend.js +312 -0
  62. package/lib/macro/store.js +238 -0
  63. package/lib/macro/supersede.js +197 -0
  64. package/lib/macro/tokencost.js +90 -0
  65. package/lib/macro/tools.js +67 -0
  66. package/lib/mcp/server.js +196 -0
  67. package/lib/mcp/stdio.js +151 -0
  68. package/lib/ui/page.js +300 -0
  69. package/lib/ui/server.js +226 -0
  70. package/package.json +56 -4
  71. package/vendor/VENDOR.json +39 -0
  72. package/vendor/cosmokit/LICENSE +21 -0
  73. package/vendor/cosmokit/README.md +30 -0
  74. package/vendor/cosmokit/lib/index.js +418 -0
  75. package/vendor/cosmokit/lib/types/array.d.ts +15 -0
  76. package/vendor/cosmokit/lib/types/array.d.ts.map +1 -0
  77. package/vendor/cosmokit/lib/types/index.d.ts +13 -0
  78. package/vendor/cosmokit/lib/types/index.d.ts.map +1 -0
  79. package/vendor/cosmokit/lib/types/misc.d.ts +41 -0
  80. package/vendor/cosmokit/lib/types/misc.d.ts.map +1 -0
  81. package/vendor/cosmokit/lib/types/string.d.ts +89 -0
  82. package/vendor/cosmokit/lib/types/string.d.ts.map +1 -0
  83. package/vendor/cosmokit/lib/types/time.d.ts +19 -0
  84. package/vendor/cosmokit/lib/types/time.d.ts.map +1 -0
  85. package/vendor/cosmokit/lib/types/types.d.ts +42 -0
  86. package/vendor/cosmokit/lib/types/types.d.ts.map +1 -0
  87. package/vendor/cosmokit/lib/types/volatile.d.ts +40 -0
  88. package/vendor/cosmokit/lib/types/volatile.d.ts.map +1 -0
  89. package/vendor/cosmokit/package.json +32 -0
  90. package/vendor/cosmokit/src/array.ts +42 -0
  91. package/vendor/cosmokit/src/index.ts +12 -0
  92. package/vendor/cosmokit/src/misc.ts +78 -0
  93. package/vendor/cosmokit/src/string.ts +113 -0
  94. package/vendor/cosmokit/src/time.ts +92 -0
  95. package/vendor/cosmokit/src/types.ts +168 -0
  96. package/vendor/cosmokit/src/volatile.ts +86 -0
  97. package/vendor/dsh-memory-nebula/CONTRIBUTING.md +48 -0
  98. package/vendor/dsh-memory-nebula/LICENSE +21 -0
  99. package/vendor/dsh-memory-nebula/README.en.md +203 -0
  100. package/vendor/dsh-memory-nebula/README.md +253 -0
  101. package/vendor/dsh-memory-nebula/SECURITY.md +43 -0
  102. package/vendor/dsh-memory-nebula/SUPPORT.md +33 -0
  103. package/vendor/dsh-memory-nebula/cordis.patch.yml +4 -0
  104. package/vendor/dsh-memory-nebula/lib/client.js +105 -0
  105. package/vendor/dsh-memory-nebula/lib/host/adapters/index.js +279 -0
  106. package/vendor/dsh-memory-nebula/lib/host/adapters/ingest.js +230 -0
  107. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +320 -0
  108. package/vendor/dsh-memory-nebula/lib/host/adapters/notes.js +305 -0
  109. package/vendor/dsh-memory-nebula/lib/host/adapters/sqlite.js +287 -0
  110. package/vendor/dsh-memory-nebula/lib/host/adapters/util.js +231 -0
  111. package/vendor/dsh-memory-nebula/lib/host/bridge.js +351 -0
  112. package/vendor/dsh-memory-nebula/lib/host/compress.js +97 -0
  113. package/vendor/dsh-memory-nebula/lib/host/demo.js +357 -0
  114. package/vendor/dsh-memory-nebula/lib/host/diagnostics.js +125 -0
  115. package/vendor/dsh-memory-nebula/lib/host/doctor.js +270 -0
  116. package/vendor/dsh-memory-nebula/lib/host/entities.js +230 -0
  117. package/vendor/dsh-memory-nebula/lib/host/graph.js +1762 -0
  118. package/vendor/dsh-memory-nebula/lib/host/graphcache.js +290 -0
  119. package/vendor/dsh-memory-nebula/lib/host/http.js +993 -0
  120. package/vendor/dsh-memory-nebula/lib/host/injectcfg.js +95 -0
  121. package/vendor/dsh-memory-nebula/lib/host/ledger.js +175 -0
  122. package/vendor/dsh-memory-nebula/lib/host/live.js +204 -0
  123. package/vendor/dsh-memory-nebula/lib/host/nebula.js +2105 -0
  124. package/vendor/dsh-memory-nebula/lib/host/page.js +75 -0
  125. package/vendor/dsh-memory-nebula/lib/host/path.js +83 -0
  126. package/vendor/dsh-memory-nebula/lib/host/recall.js +526 -0
  127. package/vendor/dsh-memory-nebula/lib/host/share.js +633 -0
  128. package/vendor/dsh-memory-nebula/lib/host/sources.js +266 -0
  129. package/vendor/dsh-memory-nebula/lib/host/store.js +333 -0
  130. package/vendor/dsh-memory-nebula/lib/host/text.js +410 -0
  131. package/vendor/dsh-memory-nebula/lib/host/transcripts.js +396 -0
  132. package/vendor/dsh-memory-nebula/lib/index.js +782 -0
  133. package/vendor/dsh-memory-nebula/lib/standalone.mjs +315 -0
  134. package/vendor/dsh-memory-nebula/lib/web/api.js +426 -0
  135. package/vendor/dsh-memory-nebula/lib/web/app.js +4172 -0
  136. package/vendor/dsh-memory-nebula/lib/web/i18n.js +580 -0
  137. package/vendor/dsh-memory-nebula/lib/web/index.html +174 -0
  138. package/vendor/dsh-memory-nebula/lib/web/nav.js +132 -0
  139. package/vendor/dsh-memory-nebula/lib/web/render.js +1890 -0
  140. package/vendor/dsh-memory-nebula/lib/web/space3d.js +1883 -0
  141. package/vendor/dsh-memory-nebula/lib/web/style.css +1402 -0
  142. package/vendor/dsh-memory-nebula/locale/en.json +7 -0
  143. package/vendor/dsh-memory-nebula/locale/zh.json +7 -0
  144. package/vendor/dsh-memory-nebula/market/assets/icon-180.png +0 -0
  145. package/vendor/dsh-memory-nebula/market/assets/icon.svg +40 -0
  146. package/vendor/dsh-memory-nebula/market/index.json +101 -0
  147. package/vendor/dsh-memory-nebula/package.json +87 -0
  148. package/vendor/dsh-memory-nebula/sidecar.ps1 +119 -0
  149. package/vendor/meow-memory/LICENSE +21 -0
  150. package/vendor/meow-memory/README.en.md +192 -0
  151. package/vendor/meow-memory/README.md +174 -0
  152. package/vendor/meow-memory/README.pt-br.md +180 -0
  153. package/vendor/meow-memory/cordis.patch.yml +7 -0
  154. package/vendor/meow-memory/lib/client.js +3354 -0
  155. package/vendor/meow-memory/lib/client.js.map +7 -0
  156. package/vendor/meow-memory/lib/index.js +13500 -0
  157. package/vendor/meow-memory/lib/index.js.map +7 -0
  158. package/vendor/meow-memory/lib/prompts/README.md +65 -0
  159. package/vendor/meow-memory/lib/prompts/en/dream-atomic.md +36 -0
  160. package/vendor/meow-memory/lib/prompts/en/dream-header.md +9 -0
  161. package/vendor/meow-memory/lib/prompts/en/dream-project-summary.md +12 -0
  162. package/vendor/meow-memory/lib/prompts/en/dream-topic.md +27 -0
  163. package/vendor/meow-memory/lib/prompts/en/external-memory-notice.md +8 -0
  164. package/vendor/meow-memory/lib/prompts/en/first-create-notice.md +8 -0
  165. package/vendor/meow-memory/lib/prompts/en/labels.md +104 -0
  166. package/vendor/meow-memory/lib/prompts/en/reflect.md +31 -0
  167. package/vendor/meow-memory/lib/prompts/en/system-guide.md +121 -0
  168. package/vendor/meow-memory/lib/prompts/en/tools.md +83 -0
  169. package/vendor/meow-memory/lib/prompts/en/welcome-guide.md +12 -0
  170. package/vendor/meow-memory/lib/prompts/pt-br/dream-atomic.md +36 -0
  171. package/vendor/meow-memory/lib/prompts/pt-br/dream-header.md +9 -0
  172. package/vendor/meow-memory/lib/prompts/pt-br/dream-project-summary.md +12 -0
  173. package/vendor/meow-memory/lib/prompts/pt-br/dream-topic.md +27 -0
  174. package/vendor/meow-memory/lib/prompts/pt-br/external-memory-notice.md +8 -0
  175. package/vendor/meow-memory/lib/prompts/pt-br/first-create-notice.md +8 -0
  176. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +104 -0
  177. package/vendor/meow-memory/lib/prompts/pt-br/reflect.md +31 -0
  178. package/vendor/meow-memory/lib/prompts/pt-br/system-guide.md +121 -0
  179. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +83 -0
  180. package/vendor/meow-memory/lib/prompts/pt-br/welcome-guide.md +12 -0
  181. package/vendor/meow-memory/lib/prompts/zh/dream-atomic.md +36 -0
  182. package/vendor/meow-memory/lib/prompts/zh/dream-header.md +9 -0
  183. package/vendor/meow-memory/lib/prompts/zh/dream-project-summary.md +19 -0
  184. package/vendor/meow-memory/lib/prompts/zh/dream-topic.md +27 -0
  185. package/vendor/meow-memory/lib/prompts/zh/external-memory-notice.md +8 -0
  186. package/vendor/meow-memory/lib/prompts/zh/first-create-notice.md +8 -0
  187. package/vendor/meow-memory/lib/prompts/zh/labels.md +104 -0
  188. package/vendor/meow-memory/lib/prompts/zh/reflect.md +30 -0
  189. package/vendor/meow-memory/lib/prompts/zh/system-guide.md +119 -0
  190. package/vendor/meow-memory/lib/prompts/zh/tools.md +83 -0
  191. package/vendor/meow-memory/lib/prompts/zh/welcome-guide.md +12 -0
  192. package/vendor/meow-memory/package.json +64 -0
  193. package/vendor/schemastery/LICENSE +21 -0
  194. package/vendor/schemastery/README.md +393 -0
  195. package/vendor/schemastery/lib/index.cjs +635 -0
  196. package/vendor/schemastery/lib/index.mjs +637 -0
  197. package/vendor/schemastery/lib/types/index.d.ts +211 -0
  198. package/vendor/schemastery/lib/types/index.d.ts.map +1 -0
  199. package/vendor/schemastery/package.json +39 -0
  200. package/vendor/schemastery/src/index.ts +962 -0
@@ -0,0 +1,253 @@
1
+ /**
2
+ * [macro-fusion 0.2.157] 改前留一版:可更新性的另一半是「改坏了能退回来」。
3
+ *
4
+ * 为什么有这一层:0.2.156 让读者看清「这条谁写的、还有人用吗」,但一眼看不见的是
5
+ * 「它被改过什么」。真库体检:513 条 active 里 **412 条** `updated_at` 明显晚于
6
+ * `created_at`(其中 lesson 260 条),而正文里带「(已被取代:…)」的只有 2 条——
7
+ * 说明绝大多数「改」是**正文被重写**,不是取代。重写是破坏性的:旧正文当场就没了,
8
+ * 事后一句「我改错了」没有任何退路。
9
+ *
10
+ * 所以这里只做三件事,一件都不多:
11
+ * 1. `saveRevision`:每次要写正文之前,把**旧正文**留底(同一条最多留 3 版,
12
+ * 与上一版逐字相同时不重复记——留底不是记流水账)。
13
+ * 2. `revisionContent`:按「上 N 版」取回一份旧正文,给 `memory_update(restore:N)` 用。
14
+ * 3. `revisionNote`:给回执一行「改过几次、最近一次是什么时候」,让「这条在演进」
15
+ * 和「这条一直没动」在阅读时就能分开。
16
+ *
17
+ * 纪律(与 chain.js / provenance.js 同源,都是被同一批教训换来的):
18
+ * - **没库不说话、也不建库**:先 `existsSync`,读不到就返回 null / 空串。
19
+ * - **只读不写地读**:`revisionNote` 不 markAccessed、不动 hit_count。
20
+ * - **留底有上限**:`REVISION_KEEP = 3`,常量只有一个出口(写侧清理与读侧范围都读它)。
21
+ * - **纯度优先**:`applyPatches` / `appendTo` / `shrinkGuard` 是纯函数,不碰库——
22
+ * 这样「按句改」的判据可以在探针里逐条量,不用先造一个库。
23
+ */
24
+ import { existsSync } from 'node:fs'
25
+ import { join } from 'node:path'
26
+ import * as Meow from '../../vendor/meow-memory/lib/index.js'
27
+
28
+ const REVISION_KEEP = 3
29
+ const TABLE = 'memory_revisions'
30
+ /** 结果比原文短到这个比例以下,必须显式 `allowShrink` 才许写(防「按句改」变成「整段删」)。 */
31
+ const SHRINK_FLOOR = 0.7
32
+
33
+ const DDL = `CREATE TABLE IF NOT EXISTS ${TABLE} (
34
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
35
+ memory_id TEXT NOT NULL,
36
+ level TEXT,
37
+ title TEXT,
38
+ content TEXT NOT NULL,
39
+ reason TEXT,
40
+ saved_at INTEGER NOT NULL
41
+ )`
42
+ const DDL_INDEX = `CREATE INDEX IF NOT EXISTS ${TABLE}_memory_id ON ${TABLE}(memory_id)`
43
+
44
+ function dbFile(workspace, dir) {
45
+ return join(workspace, dir, 'memory.db')
46
+ }
47
+
48
+ function hasDb(workspace, dir) {
49
+ if (typeof workspace !== 'string' || workspace === '') return false
50
+ return existsSync(dbFile(workspace, dir))
51
+ }
52
+
53
+ function readyDb(workspace, dir) {
54
+ const db = Meow.getDb(workspace, dir)
55
+ db.p(DDL).run()
56
+ db.p(DDL_INDEX).run()
57
+ return db
58
+ }
59
+
60
+ function fmtTs(ms) {
61
+ const n = Number(ms)
62
+ if (!Number.isFinite(n) || n <= 0) return ''
63
+ const d = new Date(n)
64
+ if (Number.isNaN(d.getTime())) return ''
65
+ const p = (x) => String(x).padStart(2, '0')
66
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
67
+ }
68
+
69
+ /** 当前这一条的正文与层(给「按句改」当底稿)。读不到就说读不到,不编。 */
70
+ export function currentRow({ workspace = '', dir = '.dsh-meow', id = '' } = {}) {
71
+ const out = { missing: '', row: null }
72
+ const want = String(id ?? '').trim()
73
+ if (want === '') {
74
+ out.missing = 'bad-arg'
75
+ return out
76
+ }
77
+ if (!hasDb(workspace, dir)) {
78
+ out.missing = 'no-db'
79
+ return out
80
+ }
81
+ try {
82
+ const read = Meow.readRowsByIds(workspace, dir, [want])
83
+ const rows = Array.isArray(read.rows) ? read.rows : []
84
+ const row = rows.find((r) => String(r.id ?? '').startsWith(want)) ?? rows[0] ?? null
85
+ if (row === null) {
86
+ out.missing = 'not-found'
87
+ return out
88
+ }
89
+ out.row = {
90
+ id: String(row.id ?? ''),
91
+ level: String(row.sessionLevel ?? ''),
92
+ title: String(row.title ?? ''),
93
+ content: String(row.content ?? ''),
94
+ }
95
+ return out
96
+ } catch (e) {
97
+ out.missing = `read-failed: ${e instanceof Error ? e.message : String(e)}`
98
+ return out
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 按句改:`patches` = `[{ find, replace }]`。
104
+ * **唯一命中**才算数:0 次=这段不在这一版正文里(可能已经改过或被改写);多次=
105
+ * 这句话不足以定位,要人补上下文。两种情况都**一个字都不写**,把理由原样说出来。
106
+ * 补丁按顺序作用(后一条看得到前一条的结果),这样「先改 A 再改 B」的直觉不会被推翻。
107
+ */
108
+ export function applyPatches(content, patches) {
109
+ let next = String(content ?? '')
110
+ const list = Array.isArray(patches) ? patches : []
111
+ if (list.length === 0) return { ok: false, why: 'patch 是空的:一条 {find, replace} 都没有' }
112
+ let changed = 0
113
+ for (let i = 0; i < list.length; i += 1) {
114
+ const one = list[i] ?? {}
115
+ const find = typeof one.find === 'string' ? one.find : ''
116
+ const replace = typeof one.replace === 'string' ? one.replace : ''
117
+ if (find === '') return { ok: false, why: `第 ${i + 1} 条 patch 的 find 是空串(空串会命中每一处,等于没定位)` }
118
+ const parts = next.split(find)
119
+ const hits = parts.length - 1
120
+ if (hits === 0) {
121
+ return { ok: false, why: `第 ${i + 1} 条 patch 要找的「${find.slice(0, 40)}」在这一版正文里找不到——可能已经改过,或者原文不是这几个字` }
122
+ }
123
+ if (hits > 1) {
124
+ return { ok: false, why: `第 ${i + 1} 条 patch 要找的「${find.slice(0, 40)}」出现了 ${hits} 次,定位不到唯一一处——把上下文带长一点再改` }
125
+ }
126
+ next = parts.join(replace)
127
+ changed += 1
128
+ }
129
+ return { ok: true, content: next, changed }
130
+ }
131
+
132
+ /** 追加一段:放在正文末尾,中间空一行(追一段不该把上一段连成一句)。 */
133
+ export function appendTo(content, extra) {
134
+ const before = String(content ?? '').replace(/\s+$/, '')
135
+ const add = String(extra ?? '').trim()
136
+ if (add === '') return { ok: false, why: 'append 是空的:没有要追加的内容' }
137
+ return { ok: true, content: before === '' ? add : `${before}\n\n${add}` }
138
+ }
139
+
140
+ /**
141
+ * 防误删闸门:按句改的本意是「改一句」,不该顺手把整段删光。
142
+ * 比原文短到 `SHRINK_FLOOR` 以下、又没有 `allowShrink: true`,就拒绝写。
143
+ * 短文本(< 40 字)不设闸——一句话本来就可以被改短,20 字砍到 8 字也未必是事故。
144
+ */
145
+ export function shrinkGuard(before, after, allowShrink = false) {
146
+ const b = String(before ?? '').length
147
+ const a = String(after ?? '').length
148
+ if (allowShrink === true) return { ok: true }
149
+ if (b < 40) return { ok: true }
150
+ if (a >= Math.ceil(b * SHRINK_FLOOR)) return { ok: true }
151
+ return {
152
+ ok: false,
153
+ why: `改完只剩 ${a} 字,原文 ${b} 字(少了 ${b - a} 字,超过三成)——这看着像整段被删,不像改一句。真要删就带 allowShrink: true 再调一次。`,
154
+ }
155
+ }
156
+
157
+ /** 留底。只留旧正文,不覆盖任何东西;同一条最多 `REVISION_KEEP` 版。 */
158
+ export function saveRevision({ workspace = '', dir = '.dsh-meow', id = '', level = '', title = '', content = '', reason = '' } = {}) {
159
+ const want = String(id ?? '').trim()
160
+ const body = String(content ?? '')
161
+ if (want === '' || body === '') return { saved: false, why: '空 id 或空正文,没什么可留的' }
162
+ if (!hasDb(workspace, dir)) return { saved: false, why: 'no-db' }
163
+ try {
164
+ const db = readyDb(workspace, dir)
165
+ const newest = db.p(`SELECT content FROM ${TABLE} WHERE memory_id = ? ORDER BY id DESC LIMIT 1`).get(want)
166
+ if (newest && String(newest.content ?? '') === body) {
167
+ // 上一版跟这一版逐字一样:再记一条只是流水账,读的人还得自己分辨哪条才是「上一版」。
168
+ return { saved: false, why: 'same-as-last', kept: revisionCount({ workspace, dir, id: want }) }
169
+ }
170
+ db.p(`INSERT INTO ${TABLE} (memory_id, level, title, content, reason, saved_at) VALUES (?,?,?,?,?,?)`).run(
171
+ want,
172
+ String(level ?? ''),
173
+ String(title ?? ''),
174
+ body,
175
+ String(reason ?? ''),
176
+ Date.now(),
177
+ )
178
+ db.p(
179
+ `DELETE FROM ${TABLE} WHERE memory_id = ? AND id NOT IN (SELECT id FROM ${TABLE} WHERE memory_id = ? ORDER BY id DESC LIMIT ${REVISION_KEEP})`,
180
+ ).run(want, want)
181
+ return { saved: true, kept: revisionCount({ workspace, dir, id: want }) }
182
+ } catch (e) {
183
+ return { saved: false, why: `save-failed: ${e instanceof Error ? e.message : String(e)}` }
184
+ }
185
+ }
186
+
187
+ export function revisionCount({ workspace = '', dir = '.dsh-meow', id = '' } = {}) {
188
+ const want = String(id ?? '').trim()
189
+ if (want === '' || !hasDb(workspace, dir)) return 0
190
+ try {
191
+ const row = Meow.getDb(workspace, dir).p(`SELECT COUNT(*) AS n FROM ${TABLE} WHERE memory_id = ?`).get(want)
192
+ return Number(row?.n ?? 0)
193
+ } catch {
194
+ return 0
195
+ }
196
+ }
197
+
198
+ /** 由新到旧列出留底的版本(不含正文,正文用 `revisionContent` 取)。 */
199
+ export function listRevisions({ workspace = '', dir = '.dsh-meow', id = '', limit = REVISION_KEEP } = {}) {
200
+ const want = String(id ?? '').trim()
201
+ if (want === '' || !hasDb(workspace, dir)) return []
202
+ try {
203
+ const rows = Meow.getDb(workspace, dir)
204
+ .p(`SELECT id, level, title, reason, saved_at, length(content) AS bytes FROM ${TABLE} WHERE memory_id = ? ORDER BY id DESC LIMIT ?`)
205
+ .all(want, Math.max(1, Math.min(REVISION_KEEP, Number(limit) || REVISION_KEEP)))
206
+ return (Array.isArray(rows) ? rows : []).map((r) => ({
207
+ id: Number(r.id ?? 0),
208
+ level: String(r.level ?? ''),
209
+ title: String(r.title ?? ''),
210
+ reason: String(r.reason ?? ''),
211
+ saved_at: Number(r.saved_at ?? 0),
212
+ bytes: Number(r.bytes ?? 0),
213
+ }))
214
+ } catch {
215
+ return []
216
+ }
217
+ }
218
+
219
+ /** 上 `back` 版的正文(back=1 就是改之前那一版)。没有就 null。 */
220
+ export function revisionContent({ workspace = '', dir = '.dsh-meow', id = '', back = 1 } = {}) {
221
+ const want = String(id ?? '').trim()
222
+ const n = Number(back)
223
+ if (want === '' || !hasDb(workspace, dir)) return null
224
+ if (!Number.isInteger(n) || n < 1 || n > REVISION_KEEP) return null
225
+ try {
226
+ const row = Meow.getDb(workspace, dir)
227
+ .p(`SELECT content FROM ${TABLE} WHERE memory_id = ? ORDER BY id DESC LIMIT 1 OFFSET ?`)
228
+ .get(want, n - 1)
229
+ return row ? String(row.content ?? '') : null
230
+ } catch {
231
+ return null
232
+ }
233
+ }
234
+
235
+ /** 回执里那一行:只在真改过的时候出现,改过几次、最近一次什么时候。 */
236
+ export function revisionNote({ workspace = '', dir = '.dsh-meow', id = '' } = {}) {
237
+ const want = String(id ?? '').trim()
238
+ if (want === '' || !hasDb(workspace, dir)) return ''
239
+ let rows = []
240
+ try {
241
+ rows = Meow.getDb(workspace, dir)
242
+ .p(`SELECT saved_at FROM ${TABLE} WHERE memory_id = ? ORDER BY id DESC LIMIT ${REVISION_KEEP}`)
243
+ .all(want)
244
+ } catch {
245
+ return ''
246
+ }
247
+ const list = Array.isArray(rows) ? rows : []
248
+ if (list.length === 0) return ''
249
+ const last = fmtTs(list[0].saved_at)
250
+ return `🕘 改过 ${list.length} 次${last ? `(最近 ${last})` : ''},留底的旧版本能退回去`
251
+ }
252
+
253
+ export { REVISION_KEEP, SHRINK_FLOOR }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 8 个统一工具共用的东西:枚举、输出形状、取值小工具。
3
+ *
4
+ * 单独一个文件是为了让 `defs/*.js` 各自只依赖它和 `linkflow.js`,
5
+ * 谁也不会反向依赖装配器 `tools.js`,加工具时不用动别人的 import(DESIGN §16)。
6
+ */
7
+ import * as Meow from '../../vendor/meow-memory/lib/index.js'
8
+
9
+ /** 以 meow 导出为准;vendor 换版本时不会因为枚举漂移而注册失败。 */
10
+ export const LEVELS =
11
+ Array.isArray(Meow.LEVELS) && Meow.LEVELS.length > 0
12
+ ? Meow.LEVELS
13
+ : ['soul', 'user', 'rules', 'fact', 'lesson', 'topic', 'project']
14
+
15
+ export const PROJECT_SUBCATEGORIES =
16
+ Array.isArray(Meow.PROJECT_SUBCATEGORIES) && Meow.PROJECT_SUBCATEGORIES.length > 0
17
+ ? Meow.PROJECT_SUBCATEGORIES
18
+ : ['overview', 'structure', 'decisions', 'quotes', 'ops', 'todo']
19
+
20
+ /** 所有统一工具都吐纯文本:模型读得懂,也没必要为 8 个工具各设计一套结构化输出。 */
21
+ export const TEXT_OUT = {
22
+ schema: { type: 'string' },
23
+ render: (_args, value) => [
24
+ { type: 'text', text: typeof value === 'string' ? value : safeJson(value) },
25
+ ],
26
+ }
27
+
28
+ export function safeJson(value) {
29
+ try {
30
+ return JSON.stringify(value, null, 2)
31
+ } catch {
32
+ return String(value)
33
+ }
34
+ }
35
+
36
+ /** 只把调用方真的给过的参数转给子插件——别用 undefined 覆盖 vendor 的默认值。 */
37
+ export function pick(source, keys) {
38
+ const out = {}
39
+ for (const key of keys) {
40
+ if (source[key] !== undefined) out[key] = source[key]
41
+ }
42
+ return out
43
+ }
44
+
45
+ /**
46
+ * [macro-fusion 0.2.62] 条数类参数的唯一出口:给多少就照办多少,改过了就得说出口。
47
+ *
48
+ * 以前 memory_read 里是「三元给默认 + `Number()`」后面接一句
49
+ * `if (!Number.isFinite(want) || want <= 0) return said`:非数字、负数、0 三种情况
50
+ * 一起被压成「这次没有邻居段」,读的人只会以为这条记忆压根没有邻居(DESIGN §72)。
51
+ *
52
+ * 约定:
53
+ * - 没给(undefined / null / 空串)→ 默认值,不说话;
54
+ * - 给了 0 → 照办 0(0 是什么意思由调用方定义),不说话;
55
+ * - 非数字 / 负数 → 回默认值,并把原值和原因写出来;
56
+ * - 非整数 → 抹掉小数,并说清「少掉的那半条不是你给的条件」;
57
+ * - 超出上界 → 夹到上界,并说清「结果是被改过的条件算出来的」。
58
+ */
59
+ export function countParam(name, raw, { min = 0, max = Number.POSITIVE_INFINITY, def } = {}) {
60
+ if (raw === undefined || raw === null) return { value: def, note: '' }
61
+ if (typeof raw === 'string' && raw.trim() === '') return { value: def, note: '' }
62
+ const n = Number(raw)
63
+ if (!Number.isFinite(n)) {
64
+ return {
65
+ value: def,
66
+ note: `${name} 给的是「${String(raw)}」,不是数字——这次按默认 ${def} 条算,不是你给的那个。`,
67
+ }
68
+ }
69
+ if (n < 0) {
70
+ return {
71
+ value: def,
72
+ note: `${name} 给的是「${n}」,是负数——条数没有「从后往前数」这回事,这次按默认 ${def} 条算。`,
73
+ }
74
+ }
75
+ if (n === 0) return { value: 0, note: '' }
76
+ const whole = Math.floor(n)
77
+ const clamped = Math.max(min, Math.min(max, whole))
78
+ const bits = []
79
+ if (whole !== n) bits.push(`条数只能是整数,这次按 ${clamped} 条算——少掉的那半条不是你给的条件`)
80
+ if (clamped !== whole) {
81
+ bits.push(`超出 ${min}–${max},这次按 ${clamped} 条算——结果是被改过的条件算出来的,不是你给的那个`)
82
+ }
83
+ if (bits.length === 0) return { value: whole, note: '' }
84
+ return { value: clamped, note: `${name} 给的是「${n}」,${bits.join(';')}。` }
85
+ }
86
+
87
+ /** 从星图 inspect 文本里只取「连接到的记忆」那一段,避免与 meow 的正文重复。 */
88
+ export function neighborSection(text, marker = '## 连接到的记忆') {
89
+ if (typeof text !== 'string') return ''
90
+ const at = text.indexOf(marker)
91
+ if (at < 0) return ''
92
+ return text.slice(at).trim()
93
+ }
94
+
95
+ /**
96
+ * [macro-fusion 0.2.77] 邻居段没拿到时的那句话。
97
+ * 以前 read.js 只写 `section ? said + '\n\n' + section : said`:星图失败或回执改了格式时,
98
+ * 那句解释被整段丢掉,读者只看得到正文——于是把「没带到」读成「这条记忆没有邻居」。
99
+ * 三种情况要说三种话,这里只认「段在不在」和「这一问查成没查成」,
100
+ * 不接收星图原文(内部错误不该原样甩给模型)。
101
+ */
102
+ export function neighborGapNote(section, reachable, raw = '') {
103
+ if (typeof section === 'string' && section.trim().length > 0) return ''
104
+ if (!reachable) {
105
+ return '星图这次没答上来(这一问没查成),所以邻居一条都没带到——这不是「这条记忆没有邻居」。'
106
+ }
107
+ const said = String(raw ?? '')
108
+ // 星图答上来了,但答的是「没这条记忆」:那是第三种情况,不能套「格式变了」。
109
+ if (/星图里没有|图是空的|还没有节点/.test(said)) {
110
+ return '星图这次没查到这条记忆(可能刚写还没入图,也可能 id 不对),所以没有邻居段——这不是「它没有邻居」。'
111
+ }
112
+ return '星图的回执里没有「连接到的记忆」这一段(多半是它改了格式),所以这次邻居没带到——这不是「这条记忆没有邻居」。'
113
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * 回执里的 id 该多短就多短(0.6.64)——**最短唯一前缀**。
3
+ *
4
+ * 为什么要有这一支:真库读出来的 id 是 `9 位 base36 时间戳 + '-' + 26 位 hex`,一共 36 字
5
+ * (例 `0mwvkk15w-7ea683b10ad5432b89ac03e91e`)。而所有回执里模型真正要的只是「够抄、能定位」:
6
+ *
7
+ * - 0.6.63 的项目全景目录每行印**完整 id**,真库 `dsh-macro-memory` 34 行光 id 就吃掉
8
+ * 1,224 字(3000 上限的 41%)。换成 9 字前缀,同样上限多列约 11 条。
9
+ * - 邻域块行首一直是 `id.slice(0, 8)`,看着够短,但真库 1,121 条里**8 位前缀撞 9 对**
10
+ * (id 开头就是同一批写入的 base36 时间戳)。撞车的短 id 指向两条,模型拿它去
11
+ * `memory_read` / `memory_update` / `mute` 会撞上歧义拒绝——回执还会读成「那条记忆不见了」。
12
+ *
13
+ * 判据与 vendor 自带的那份完全一致(`vendor/meow-memory/lib/index.js:7188` 的 `uniqueShortId`):
14
+ * 前缀在库里命中 ≤1 条就算唯一,8 位起、不唯一就往下加长。区别只在这里一次算完全表
15
+ * (7 条 `SELECT id` 摊一次),省得每条都发一句 `LIKE ?`。
16
+ *
17
+ * 边界:
18
+ * - 读写都吃前缀:`findByIdAll`(:683)对 <36 字按前缀跨层 `LIKE`,`update`(:715)同样;
19
+ * 所以短 id 不是「只给眼睛看」的缩略,抄回去就能用。
20
+ * - 星图那边给的常常**本身就是短 id**(8 位或 12 位前缀)。`shortenId` 会先把它解析回
21
+ * 唯一的那条完整 id,再给最短唯一前缀;解析不唯一就原样返回——不猜、不替它挑一条。
22
+ * - 库里查不到(工作区为空、表还没建)→ 返回 null,调用方退回老的 8 位切法,行为不变。
23
+ * - 不缓存:一条新写入的 id 可能和刚给出的前缀撞上,缓存下来的短 id 会悄悄变歧义。
24
+ * 7 条 `SELECT id` 在千条量级上是毫秒级,宁可每轮重算。
25
+ */
26
+
27
+ /** 最短也不短于 8 位:这是 meow 文档里「8 位短 id」的口径,老回执都按这个长度抄。 */
28
+ export const SHORT_ID_MIN = 8
29
+
30
+ /** 七层(与 vendor `LEVELS` 同序)。id 全局唯一,跨层一起算才安全。 */
31
+ const LEVELS = ['soul', 'user', 'rules', 'fact', 'lesson', 'topic', 'project']
32
+
33
+ /**
34
+ * 算出「完整 id → 最短唯一前缀」的表,外加一份排好序的全表(供短 id 反查)。
35
+ *
36
+ * @param {{ p: (sql: string) => { all: () => any[] } }} db meow 的 MemoryDb
37
+ * @returns {{byId: Map<string, string>, sorted: string[]} | null} 查不到任何 id 时 null
38
+ */
39
+ export function shortIdsOf(db) {
40
+ if (db === null || typeof db !== 'object' || typeof db.p !== 'function') return null
41
+ const ids = []
42
+ for (const level of LEVELS) {
43
+ try {
44
+ const rows = db.p(`SELECT id FROM ${level}`).all() ?? []
45
+ for (const row of rows) {
46
+ const id = String(row?.id ?? '')
47
+ if (id !== '') ids.push(id)
48
+ }
49
+ } catch {
50
+ // 这个工作区还没建这一层:跳过,不影响别的层。
51
+ }
52
+ }
53
+ if (ids.length === 0) return null
54
+ // 排序之后「前缀唯一」只需要跟左右的邻居比:同一前缀的 id 在字典序上必然相邻。
55
+ ids.sort()
56
+ const byId = new Map()
57
+ for (let i = 0; i < ids.length; i += 1) {
58
+ const id = ids[i]
59
+ const floor = Math.min(SHORT_ID_MIN, id.length)
60
+ let n = floor
61
+ while (n < id.length) {
62
+ const prefix = id.slice(0, n)
63
+ const prev = i > 0 ? ids[i - 1] : ''
64
+ const next = i + 1 < ids.length ? ids[i + 1] : ''
65
+ if (!prev.startsWith(prefix) && !next.startsWith(prefix)) break
66
+ n += 1
67
+ }
68
+ byId.set(id, id.slice(0, n))
69
+ }
70
+ return { byId, sorted: ids }
71
+ }
72
+
73
+ /**
74
+ * 给定 id(完整或已经截短)→ 它该被印成多长。
75
+ *
76
+ * 三种情况:
77
+ * ① 表里有这条完整 id → 直接给它的最短唯一前缀;
78
+ * ② 给的是短 id,且在全表里只命中一条 → 解析出那条,给它的最短唯一前缀;
79
+ * ③ 命中零条或多条 → 原样(前 8 位)退回,绝不替调用方在两条之间挑一条。
80
+ *
81
+ * @param {{byId: Map<string, string>, sorted: string[]} | null | undefined} index `shortIdsOf` 的结果
82
+ * @param {any} id 完整 id 或短 id
83
+ * @returns {string}
84
+ */
85
+ export function shortenId(index, id) {
86
+ const given = String(id ?? '')
87
+ if (given === '') return ''
88
+ if (index !== null && typeof index === 'object' && index.byId instanceof Map) {
89
+ const exact = index.byId.get(given)
90
+ if (typeof exact === 'string') return exact
91
+ const sorted = Array.isArray(index.sorted) ? index.sorted : []
92
+ // 二分找第一个 >= given 的位置,再往后扫命中前缀的:字典序相邻,命中不会散开。
93
+ let lo = 0
94
+ let hi = sorted.length
95
+ while (lo < hi) {
96
+ const mid = (lo + hi) >> 1
97
+ if (sorted[mid] < given) lo = mid + 1
98
+ else hi = mid
99
+ }
100
+ let hit = ''
101
+ let count = 0
102
+ for (let i = lo; i < sorted.length; i += 1) {
103
+ if (!sorted[i].startsWith(given)) break
104
+ count += 1
105
+ if (count > 1) break
106
+ hit = sorted[i]
107
+ }
108
+ if (count === 1) {
109
+ const short = index.byId.get(hit)
110
+ if (typeof short === 'string') return short
111
+ }
112
+ }
113
+ return given.slice(0, SHORT_ID_MIN)
114
+ }