macro-memory 0.9.1 → 0.26.8

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 (54) hide show
  1. package/README.md +157 -268
  2. package/bin/macro-memory.mjs +524 -5
  3. package/docs/CHANGELOG.md +1101 -0
  4. package/docs/MAC.md +44 -6
  5. package/lib/core/client.js +56 -22
  6. package/lib/core/config.js +15 -2
  7. package/lib/core/daemon.js +336 -0
  8. package/lib/core/engine.js +7 -6
  9. package/lib/core/fence.js +1 -1
  10. package/lib/core/serve.js +37 -14
  11. package/lib/core/trust.js +6 -2
  12. package/lib/index.js +209 -3
  13. package/lib/macro/contract.js +31 -1
  14. package/lib/macro/defs/admin.js +4 -4
  15. package/lib/macro/defs/link.js +96 -9
  16. package/lib/macro/defs/read.js +11 -1
  17. package/lib/macro/defs/remember.js +89 -1
  18. package/lib/macro/defs/search.js +157 -6
  19. package/lib/macro/dreamledger.js +6 -1
  20. package/lib/macro/evidence.js +84 -0
  21. package/lib/macro/fakesites.js +93 -0
  22. package/lib/macro/fusion.js +16 -2
  23. package/lib/macro/linkflow.js +130 -5
  24. package/lib/macro/links.js +69 -0
  25. package/lib/macro/platform.js +74 -0
  26. package/lib/macro/portability.js +737 -0
  27. package/lib/macro/prompt.js +6 -6
  28. package/lib/macro/revisions.js +3 -13
  29. package/lib/macro/slots.js +252 -0
  30. package/lib/macro/snapshot.js +309 -1
  31. package/lib/macro/tools.js +49 -4
  32. package/lib/macro/topicpages.js +300 -0
  33. package/lib/rerank/download.js +68 -0
  34. package/lib/rerank/provider.js +507 -0
  35. package/lib/rerank/runtime.js +246 -0
  36. package/lib/rerank/tokenizer.js +183 -0
  37. package/lib/semantic/download.js +68 -0
  38. package/lib/semantic/provider.js +205 -0
  39. package/lib/semantic/runtime.js +175 -0
  40. package/lib/semantic/tokenizer.js +169 -0
  41. package/package.json +1 -1
  42. package/vendor/VENDOR.json +4 -4
  43. package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +7 -1
  44. package/vendor/dsh-memory-nebula/lib/host/graph.js +183 -3
  45. package/vendor/dsh-memory-nebula/lib/index.js +75 -3
  46. package/vendor/dsh-memory-nebula/lib/web/app.js +5 -0
  47. package/vendor/dsh-memory-nebula/lib/web/i18n.js +1 -0
  48. package/vendor/meow-memory/lib/index.js +3205 -167
  49. package/vendor/meow-memory/lib/prompts/en/labels.md +2 -0
  50. package/vendor/meow-memory/lib/prompts/en/tools.md +1 -0
  51. package/vendor/meow-memory/lib/prompts/pt-br/labels.md +2 -0
  52. package/vendor/meow-memory/lib/prompts/pt-br/tools.md +1 -0
  53. package/vendor/meow-memory/lib/prompts/zh/labels.md +2 -0
  54. package/vendor/meow-memory/lib/prompts/zh/tools.md +1 -0
package/docs/MAC.md CHANGED
@@ -85,7 +85,8 @@ cp -R "dsh-macro-memory" ~/.dsh/profiles/desktop/node_modules/
85
85
  在仓库根目录(mac / Linux 上 `node` 用系统自带的也行,只要 ≥ 22.5):
86
86
 
87
87
  ```bash
88
- node tools/probe-platform.mjs # 平台账:23 条,唯一一支专为跨平台写的
88
+ node tools/probe-platform.mjs # 平台账:23 条(路径推演 / 字面量 / 工具 / 文档)
89
+ node tools/probe-mac.mjs # 跨平台动作账:27 条(M1 平台函数 → M5 产物链)
89
90
  node tools/probe-load.mjs # 装进去的这份能不能被宿主加载(问宿主自己的判据)
90
91
  node tools/check-client-bundle.mjs # 构建产物自洽
91
92
  node tools/doctor.mjs # 两棵树逐文件比对
@@ -94,6 +95,40 @@ node tools/check-all.mjs # 一次跑完(开发机上才有意义)
94
95
 
95
96
  `probe-platform.mjs` 数四本账:路径推演(三平台的宏目录、`$DSH_HOME` 三种取值)、字面量账(运行面除 `SAMPLE_HOME` 一处样例不许出现盘符;`process.platform` 与 `$DSH_HOME` 只许出现在 `platform.js`)、工具账(`cpTree`、`doctor` 的根、`check-market` 的 mac 路径、`accept-live` 的 `ps`)、文档账(本页、README 平台段、版本三处一致)。最后一条是阴性对照:判据对着故意写坏的样本必须判红。
96
97
 
98
+ `probe-mac.mjs` 数五本账(0.19.0 新增):M1 三个平台的判定 / 架构 / UDS 字节上限 / NFD 归一 / 打开浏览器 / GUI PATH;M2 建 socket 前量字节、`0600`、发现文件原子写、客户端 UDS→TCP 回退;M3 同一工作区 NFD 与 NFC 算出同一个信任键;M4 launchd / systemd / 计划任务的服务文件推演 + `--dry-run` 零副作用 + 卸载不碰库;M5 mac 产物签名三步与 SEA 垫片。每本账都带阴性对照,在 Windows 上就能跑,不需要一台 mac。
99
+
100
+ ### 4.1 后台常驻(唯一需要显式要求的写盘动作)
101
+
102
+ ```bash
103
+ macro-memory serve --install-agent --dry-run # 只打印服务文件与命令,一个字节不写
104
+ macro-memory serve --install-agent # 装:launchd / systemd --user / 计划任务
105
+ macro-memory serve --uninstall-agent # 卸:只删服务定义与发现文件,绝不删记忆库
106
+ ```
107
+
108
+ | 平台 | 落点 | 激活方式 |
109
+ | --- | --- | --- |
110
+ | macOS | `~/Library/LaunchAgents/io.macro-memory.serve.plist` | `launchctl bootstrap gui/<uid>`(老系统回退 `load -w`) |
111
+ | Linux | `$XDG_CONFIG_HOME/systemd/user/macro-memory-serve.service` | `systemctl --user enable --now` |
112
+ | Windows | `<数据目录>/serve-launcher.vbs` | `schtasks /Create /SC ONLOGON` |
113
+
114
+ 默认**不装**:不传 `--install-agent` 时插件的常驻策略与以前完全一样。plist 里的 `PATH` 由 `macGuiPath()` 补上 Homebrew 与系统目录——GUI 会话拿到的 PATH 通常短得找不到 `node`。
115
+
116
+ ### 4.2 UDS 与 TCP 双通
117
+
118
+ macOS / Linux 上除了 `127.0.0.1:<随机端口>`,还会挂一条 `<数据目录>/serve.sock`。建 socket 前先量 `sun_path` 字节上限(macOS **104**、Linux **108**),超了就不建,只留 TCP,并把原因写进 `serve.json` 的 `socketSkipped`。客户端优先 UDS,遇到 `ENOENT` / `ECONNREFUSED` / `EACCES` / `ENOTSOCK` / `EPERM` / `EINVAL` / `ENAMETOOLONG` 才回退 TCP;业务错不吞。
119
+
120
+ ### 4.3 NFD→NFC
121
+
122
+ macOS 的 APFS / Finder 会给 NFD 形式的路径(`e` + 组合重音),同一个目录两种字面。信任键与工作区键在算哈希前统一 `normalize('NFC')`,否则同一工作区会算出两个键、库分家。
123
+
124
+ ### 4.4 `ui --open`
125
+
126
+ `macro-memory ui --open` 起管理界面后交给系统默认浏览器:mac `open`、Linux `xdg-open`、Windows `cmd /c start`。
127
+
128
+ ### 4.5 mac 产物签名
129
+
130
+ `tools/build-sea.mjs --target=mac-arm64` 现在按三步走:注入前 `codesign --remove-signature`、postject 带 `--macho-segment-name NODE_SEA`、注入后 `codesign --force --sign -`(Apple Silicon 上未签名产物直接被内核拒绝)。SEA 引导器的临时目录按 `uid` 分家,并写一层 CJS 垫片把 `import(file://…)` 转发到正常 ESM 加载路径(Node 26 的 SEA 上下文禁止直接 import 文件 URL)。
131
+
97
132
  > `tools/sync-trees.mjs` 在 Windows 上走 `robocopy /E`,在 mac / Linux 上走 `fs.cpSync`——语义相同:**只增改,从不删除**。
98
133
 
99
134
  ---
@@ -137,20 +172,23 @@ node tools/restore-live-db.mjs --source ~/.dsh/macro-memory/restore/20261125-res
137
172
 
138
173
  ## 7. 已知限制
139
174
 
140
- - **没有 mac 真机读数**。0.7.0 的跨平台改动是「推演 + 静态审计 + 本机 Windows 全绿」,不是「在 mac 上跑过」。第 8 节就是补这一课的清单。
175
+ - **仍然没有 mac 真机读数**。0.19.0 把平台层补齐了(平台函数、UDS 加固、NFC 归一、后台常驻、产物签名),但全部是「推演 + 静态审计 + 本机 Windows 上 27 条判据全绿」,不是「在 mac 上跑过」。第 8 节就是补这一课的清单。
141
176
  - 快照层的 `node:sqlite` 已惰性化:取不到时只有快照/对比这一层降级(面板会说清楚),其余功能照常。但**引擎本身**(`vendor/meow-memory/lib/index.js`)仍是静态 import,Node 太老时整个插件加载不了——这是硬底线,不是可以兜的。
142
177
  - `tools/` 里的 `.ps1`(复原脚本的 Windows 版)在 mac / Linux 上用不了,用同名 `.mjs`。
178
+ - 二进制产物的**公证(notarization)没做**:`--sign -` 只是 ad-hoc 签名,够在本机跑,分发给别人时 Gatekeeper 仍会拦(要 Developer ID + `notarytool`,那是发版流程的事)。
143
179
  - 本页提到的路径都是**默认值**;`$DSH_HOME` 换过就按换过的算。
144
180
 
145
181
  ---
146
182
 
147
183
  ## 8. 待做的真机冒烟(发布前)
148
184
 
149
- 在一台 mac(Apple Silicon 优先)上,按顺序做完这四步,把结果贴回 CHANGELOG 的 0.7.0 条目:
185
+ 在一台 mac(Apple Silicon 优先)上,按顺序做完这六步,把结果贴回 CHANGELOG:
150
186
 
151
187
  1. **装**:市场装或手动放进 `~/.dsh/profiles/desktop/node_modules/dsh-macro-memory`,重启 DSH,确认进程没报错、工具列表里出现 8 个 `memory_*`。
152
- 2. **建库**:随便聊两轮让它写一条,确认 `~/.dsh/macro-memory/memory.db` 出现且 > 4 KB;`node tools/probe-platform.mjs` 在 mac 上应 23/23。
188
+ 2. **建库**:随便聊两轮让它写一条,确认 `~/.dsh/macro-memory/memory.db` 出现且 > 4 KB;`node tools/probe-platform.mjs` 应 23/23、`node tools/probe-mac.mjs` 应 27/27。
153
189
  3. **检索**:问一个刚记过的事,确认注入块里有那一条(账上 `picks=` 有它)。
154
- 4. **复原**:`node tools/restore-live-db.mjs --dry-run` 应认出 mac 的路径与进程;真跑一次(可对一份副本)确认备份目录落在 `~/DSH-备份/` 下、`integrity_check` 是 `ok`。
190
+ 4. **常驻**:`macro-memory serve --install-agent --dry-run` 看 plist 内容(`PATH` 里应有 `/opt/homebrew/bin`),再真装;`launchctl print gui/$(id -u)/io.macro-memory.serve` 应能查到;`macro-memory share` 应显示 shared;最后 `--uninstall-agent` 卸掉。
191
+ 5. **双通与归一**:`ls -l ~/.dsh/macro-memory/serve.sock` 应是 `srw-------`;把 `serve.json` 里的 `socketPath` 改成不存在的路径后 `macro-memory share` 应仍能连上(回退 TCP);在 Finder 里建一个带重音字符的目录当工作区,`macro-memory trust` 两次(NFC / NFD 两种输入)应只留一个 marker。
192
+ 6. **复原**:`node tools/restore-live-db.mjs --dry-run` 应认出 mac 的路径与进程;真跑一次(可对一份副本)确认备份目录落在 `~/DSH-备份/` 下、`integrity_check` 是 `ok`。
155
193
 
156
- 四步全过,就可以把「mac 已验」写进 README 的技术规格表。
194
+ 六步全过,就可以把「mac 已验」写进 README 的技术规格表。
@@ -60,7 +60,27 @@ export function writeServeInfo(dataDir, info, opts = {}) {
60
60
  if (opts.publish === false) return null
61
61
  fs.mkdirSync(dataDir, { recursive: true })
62
62
  const file = serveFilePath(dataDir)
63
- fs.writeFileSync(file, `${JSON.stringify(info, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
63
+ // 先写临时文件再 rename:别的进程任何时刻读到的要么是旧内容、要么是完整新内容,
64
+ // 不会读到写了一半的 JSON(发现文件坏掉表现为「服务明明活着却探不到」)。
65
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`
66
+ try {
67
+ fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
68
+ fs.renameSync(tmp, file)
69
+ } catch (err) {
70
+ try {
71
+ fs.rmSync(tmp, { force: true })
72
+ } catch {
73
+ // 清不掉临时文件不影响被发现文件写失败这件事
74
+ }
75
+ throw err
76
+ }
77
+ if (!isWindows()) {
78
+ try {
79
+ fs.chmodSync(file, 0o600)
80
+ } catch {
81
+ // 文件系统不支持 chmod 时不算失败(Windows 挂载盘、某些网络盘)
82
+ }
83
+ }
64
84
  return file
65
85
  }
66
86
 
@@ -81,26 +101,11 @@ export function makeRequestId() {
81
101
  return `${process.pid.toString(36)}-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`
82
102
  }
83
103
 
84
- /** 一次 HTTP 往返。Windows 走 `url`(127.0.0.1),Unix 优先 `socketPath`。 */
85
- export function request(info, method, urlPath, body, opts = {}) {
86
- const timeout = Number(opts.timeout ?? CALL_TIMEOUT_MS)
87
- const payload = body === undefined ? null : Buffer.from(JSON.stringify(body), 'utf8')
88
- const headers = {
89
- authorization: `Bearer ${info.token}`,
90
- accept: 'application/json',
91
- }
92
- if (payload) {
93
- headers['content-type'] = 'application/json'
94
- headers['content-length'] = String(payload.length)
95
- }
96
- const options = { method, path: urlPath, headers, timeout }
97
- if (!isWindows() && typeof info.socketPath === 'string' && info.socketPath.length > 0) {
98
- options.socketPath = info.socketPath
99
- } else {
100
- const u = new URL(info.url)
101
- options.host = u.hostname
102
- options.port = Number(u.port || 80)
103
- }
104
+ /** UDS 连不上时可以安全回退 TCP 的错误码:都是「这一条路不通」,不是业务错。 */
105
+ const UDS_FALLBACK_CODES = new Set(['ENOENT', 'ECONNREFUSED', 'EACCES', 'ENOTSOCK', 'EPERM', 'EINVAL', 'ENAMETOOLONG'])
106
+
107
+ /** 一次 HTTP 往返(不含选路)。 */
108
+ function requestOnce(options, payload) {
104
109
  return new Promise((resolve, reject) => {
105
110
  const req = http.request(options, (res) => {
106
111
  const chunks = []
@@ -117,7 +122,7 @@ export function request(info, method, urlPath, body, opts = {}) {
117
122
  })
118
123
  })
119
124
  req.on('timeout', () => {
120
- req.destroy(new Error(`超时(${timeout} ms)`))
125
+ req.destroy(new Error(`超时(${options.timeout} ms)`))
121
126
  })
122
127
  req.on('error', reject)
123
128
  if (payload) req.write(payload)
@@ -125,6 +130,35 @@ export function request(info, method, urlPath, body, opts = {}) {
125
130
  })
126
131
  }
127
132
 
133
+ /**
134
+ * 一次 HTTP 往返。Windows 走 `url`(127.0.0.1);Unix 优先 `socketPath`,
135
+ * UDS 这条路不通(socket 被删、权限变了、路径超长)时自动回退到同一份 serve.json 里的 TCP。
136
+ */
137
+ export function request(info, method, urlPath, body, opts = {}) {
138
+ const timeout = Number(opts.timeout ?? CALL_TIMEOUT_MS)
139
+ const payload = body === undefined ? null : Buffer.from(JSON.stringify(body), 'utf8')
140
+ const headers = {
141
+ authorization: `Bearer ${info.token}`,
142
+ accept: 'application/json',
143
+ }
144
+ if (payload) {
145
+ headers['content-type'] = 'application/json'
146
+ headers['content-length'] = String(payload.length)
147
+ }
148
+ const base = { method, path: urlPath, headers, timeout }
149
+ const tcpOptions = () => {
150
+ const u = new URL(info.url)
151
+ return { ...base, host: u.hostname, port: Number(u.port || 80) }
152
+ }
153
+ const hasTcp = typeof info.url === 'string' && info.url.length > 0
154
+ const useUds = !isWindows() && typeof info.socketPath === 'string' && info.socketPath.length > 0
155
+ if (!useUds) return requestOnce(tcpOptions(), payload)
156
+ return requestOnce({ ...base, socketPath: info.socketPath }, payload).catch((err) => {
157
+ if (!hasTcp || !UDS_FALLBACK_CODES.has(err?.code)) throw err
158
+ return requestOnce(tcpOptions(), payload)
159
+ })
160
+ }
161
+
128
162
  /**
129
163
  * 探一次服务:`/stats` 回 200 才算通。
130
164
  * @returns {Promise<{mode:'standalone'|'shared'|'stale', info?:object, stats?:object, reason?:string}>}
@@ -30,10 +30,23 @@ export function defaultConfig(overrides = {}) {
30
30
  homeDir: '',
31
31
  /** 这个 agent 是谁:写进 owner 与回执里的「(codex 记)」。 */
32
32
  agent: { id: '', label: '' },
33
- /** 各引擎的覆盖配置,形状与 DSH 侧一致(meow 的键原样透传)。 */
34
- engines: { meow: {}, nebula: {} },
33
+ /**
34
+ * 各引擎的覆盖配置,形状与 DSH 侧一致(meow 的键原样透传)。
35
+ *
36
+ * [macro-memory 0.17.0 · W3] 两个独立回滚面落在这里(见 docs/PLAN-COMMERCIAL.md §1.4);
37
+ * 默认值与 meow 的 `CONFIG_DEFAULTS` 必须一致,两处都改才算数:
38
+ * - `bandExpose: true` 档位露出(管「说不说」,不管「怎么排」)
39
+ * - `emptyGuard: false` 空手判定(默认关:行为改动,损失须先量化)
40
+ */
41
+ engines: {
42
+ meow: { bandExpose: true, emptyGuard: false },
43
+ nebula: {},
44
+ },
35
45
  /** 融合层(注入字符数、回执语言等)。 */
36
46
  macro: {},
47
+ /** CLI / MCP 侧的检索开关镜像(与 engines.meow 同值,便于只读工具直接读顶层)。 */
48
+ bandExpose: true,
49
+ emptyGuard: false,
37
50
  ...overrides,
38
51
  }
39
52
  }
@@ -0,0 +1,336 @@
1
+ /**
2
+ * daemon —— 跨平台用户级后台常驻服务(launchd / systemd --user / 计划任务)。
3
+ *
4
+ * 纪律(PLAN-UNIVERSAL §6 / U11,PLAN-MAC M4):
5
+ * 1. **默认绝不安装任何常驻**,只有用户显式传 `--install-agent` 才写盘;
6
+ * 2. `--dry-run` 打印完整服务文件与命令,零副作用(探针只跑这一条);
7
+ * 3. `--uninstall-agent` 与 `uninstall --purge` 只删服务定义与发现文件,**绝不删记忆库**;
8
+ * 4. `daemonSpec()` 是纯函数:在 Windows 上就能把 darwin / linux 的服务文件推演出来,
9
+ * 不必等一台 mac 到手——这也是本模块所有判据能被自检覆盖的前提。
10
+ */
11
+
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { spawnSync } from 'node:child_process'
15
+ import { currentPlatform, homeFor, macGuiPath, pathFor } from '../macro/platform.js'
16
+ import { resolveDataDir } from './paths.js'
17
+ import { serveFilePath } from './client.js'
18
+
19
+ export const MAC_LABEL = 'io.macro-memory.serve'
20
+ export const LINUX_SERVICE = 'macro-memory-serve.service'
21
+ export const WIN_TASK_NAME = 'MacroMemoryServe'
22
+
23
+ function xmlEscape(s) {
24
+ return String(s)
25
+ .replace(/&/g, '&amp;')
26
+ .replace(/</g, '&lt;')
27
+ .replace(/>/g, '&gt;')
28
+ .replace(/"/g, '&quot;')
29
+ .replace(/'/g, '&apos;')
30
+ }
31
+
32
+ /** systemd 的 Exec 行不是 shell:含空格/百分号要按它自己的规矩转义。 */
33
+ function systemdQuote(arg) {
34
+ const s = String(arg).replace(/%/g, '%%')
35
+ if (/^[A-Za-z0-9_./:=+-]+$/.test(s)) return s
36
+ return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
37
+ }
38
+
39
+ function vbsQuote(arg) {
40
+ return `"${String(arg).replace(/"/g, '""')}"`
41
+ }
42
+
43
+ function renderMacPlist({ label, programArgs, dataDir, cwd, envPath }) {
44
+ const logFile = pathFor('darwin').join(dataDir, 'serve.log')
45
+ const argsXml = programArgs.map((a) => ` <string>${xmlEscape(a)}</string>`).join('\n')
46
+ const workDirXml = cwd
47
+ ? ` <key>WorkingDirectory</key>\n <string>${xmlEscape(cwd)}</string>\n`
48
+ : ''
49
+ return [
50
+ '<?xml version="1.0" encoding="UTF-8"?>',
51
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
52
+ '<plist version="1.0">',
53
+ ' <dict>',
54
+ ' <key>Label</key>',
55
+ ` <string>${xmlEscape(label)}</string>`,
56
+ ' <key>ProgramArguments</key>',
57
+ ' <array>',
58
+ argsXml,
59
+ ' </array>',
60
+ workDirXml ? workDirXml.trimEnd() : null,
61
+ ' <key>RunAtLoad</key>',
62
+ ' <true/>',
63
+ ' <key>KeepAlive</key>',
64
+ ' <dict>',
65
+ ' <key>SuccessfulExit</key>',
66
+ ' <false/>',
67
+ ' </dict>',
68
+ ' <key>StandardOutPath</key>',
69
+ ` <string>${xmlEscape(logFile)}</string>`,
70
+ ' <key>StandardErrorPath</key>',
71
+ ` <string>${xmlEscape(logFile)}</string>`,
72
+ ' <key>EnvironmentVariables</key>',
73
+ ' <dict>',
74
+ ' <key>PATH</key>',
75
+ ` <string>${xmlEscape(macGuiPath(envPath))}</string>`,
76
+ ' </dict>',
77
+ ' </dict>',
78
+ '</plist>',
79
+ '',
80
+ ]
81
+ .filter((l) => l !== null)
82
+ .join('\n')
83
+ }
84
+
85
+ function renderLinuxUnit({ programArgs, dataDir, cwd }) {
86
+ const logFile = pathFor('linux').join(dataDir, 'serve.log').replace(/%/g, '%%')
87
+ const execStart = programArgs.map(systemdQuote).join(' ')
88
+ const lines = [
89
+ '[Unit]',
90
+ 'Description=Macro Memory Single-Writer Serve',
91
+ 'After=default.target',
92
+ '',
93
+ '[Service]',
94
+ 'Type=simple',
95
+ `ExecStart=${execStart}`,
96
+ ]
97
+ if (cwd) lines.push(`WorkingDirectory=${systemdQuote(cwd)}`)
98
+ lines.push(
99
+ 'Restart=on-failure',
100
+ 'RestartSec=3',
101
+ `StandardOutput=append:${logFile}`,
102
+ `StandardError=append:${logFile}`,
103
+ '',
104
+ '[Install]',
105
+ 'WantedBy=default.target',
106
+ '',
107
+ )
108
+ return lines.join('\n')
109
+ }
110
+
111
+ function renderWindowsLauncher({ programArgs }) {
112
+ const cmdLine = programArgs
113
+ .map((a) => {
114
+ const s = String(a)
115
+ return /[\s"]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s
116
+ })
117
+ .join(' ')
118
+ return [
119
+ "' Auto-generated by macro-memory serve --install-agent",
120
+ 'Set shell = CreateObject("WScript.Shell")',
121
+ `shell.Run ${vbsQuote(cmdLine)}, 0, False`,
122
+ '',
123
+ ].join('\r\n')
124
+ }
125
+
126
+ /**
127
+ * 生成指定平台的服务配置与安装/卸载命令(纯函数)。
128
+ * 传 `platform:'darwin'` 就在 Windows 上得到 mac 的 plist——判据靠这条才跑得起来。
129
+ */
130
+ export function daemonSpec(opts = {}) {
131
+ const platform = opts.platform ?? currentPlatform()
132
+ const env = opts.env ?? process.env
133
+ const home = opts.home ?? homeFor(platform)
134
+ const P = pathFor(platform)
135
+ const dataDir = resolveDataDir({ dir: opts.dataDir, platform, env, home })
136
+ const seaBin = typeof opts.seaBin === 'string' && opts.seaBin.length > 0 ? opts.seaBin : env?.MACRO_MEMORY_SEA_BIN
137
+ const execPath = typeof seaBin === 'string' && seaBin.length > 0 ? seaBin : opts.execPath ?? process.execPath
138
+ const entryScript = typeof seaBin === 'string' && seaBin.length > 0 ? '' : opts.entryScript ?? ''
139
+ const cwd = typeof opts.cwd === 'string' && opts.cwd.length > 0 ? opts.cwd : ''
140
+ const port = Number.isInteger(opts.port) && opts.port > 0 ? opts.port : 0
141
+
142
+ const programArgs = [execPath]
143
+ if (entryScript) programArgs.push(entryScript)
144
+ programArgs.push('serve', '--data-dir', dataDir)
145
+ if (cwd) programArgs.push('--cwd', cwd)
146
+ if (port > 0) programArgs.push('--port', String(port))
147
+
148
+ if (platform === 'darwin') {
149
+ const servicePath = P.join(home, 'Library', 'LaunchAgents', `${MAC_LABEL}.plist`)
150
+ const uid = typeof opts.uid === 'number' ? opts.uid : typeof process.getuid === 'function' ? process.getuid() : 501
151
+ const content = renderMacPlist({
152
+ label: MAC_LABEL,
153
+ programArgs,
154
+ dataDir,
155
+ cwd,
156
+ envPath: opts.envPath ?? env?.PATH ?? '',
157
+ })
158
+ return {
159
+ platform,
160
+ kind: 'launchd',
161
+ label: MAC_LABEL,
162
+ dataDir,
163
+ servicePath,
164
+ programArgs,
165
+ content,
166
+ installCmd: [
167
+ ['launchctl', ['bootout', `gui/${uid}`, servicePath]],
168
+ ['launchctl', ['bootstrap', `gui/${uid}`, servicePath]],
169
+ ],
170
+ fallbackInstallCmd: ['launchctl', ['load', '-w', servicePath]],
171
+ uninstallCmd: [['launchctl', ['bootout', `gui/${uid}`, servicePath]]],
172
+ fallbackUninstallCmd: ['launchctl', ['unload', servicePath]],
173
+ }
174
+ }
175
+
176
+ if (platform === 'linux') {
177
+ const xdgCfg =
178
+ typeof env?.XDG_CONFIG_HOME === 'string' && env.XDG_CONFIG_HOME.trim() !== ''
179
+ ? env.XDG_CONFIG_HOME.trim()
180
+ : P.join(home, '.config')
181
+ const servicePath = P.join(xdgCfg, 'systemd', 'user', LINUX_SERVICE)
182
+ const content = renderLinuxUnit({ programArgs, dataDir, cwd })
183
+ return {
184
+ platform,
185
+ kind: 'systemd-user',
186
+ label: LINUX_SERVICE,
187
+ dataDir,
188
+ servicePath,
189
+ programArgs,
190
+ content,
191
+ installCmd: [
192
+ ['systemctl', ['--user', 'daemon-reload']],
193
+ ['systemctl', ['--user', 'enable', '--now', LINUX_SERVICE]],
194
+ ],
195
+ uninstallCmd: [
196
+ ['systemctl', ['--user', 'disable', '--now', LINUX_SERVICE]],
197
+ ['systemctl', ['--user', 'daemon-reload']],
198
+ ],
199
+ }
200
+ }
201
+
202
+ const servicePath = P.join(dataDir, 'serve-launcher.vbs')
203
+ const content = renderWindowsLauncher({ programArgs })
204
+ return {
205
+ platform,
206
+ kind: 'schtasks',
207
+ label: WIN_TASK_NAME,
208
+ dataDir,
209
+ servicePath,
210
+ programArgs,
211
+ content,
212
+ installCmd: [
213
+ ['schtasks', ['/Create', '/F', '/SC', 'ONLOGON', '/TN', WIN_TASK_NAME, '/TR', `wscript.exe "${servicePath}"`]],
214
+ ['schtasks', ['/Run', '/TN', WIN_TASK_NAME]],
215
+ ],
216
+ uninstallCmd: [['schtasks', ['/Delete', '/F', '/TN', WIN_TASK_NAME]]],
217
+ }
218
+ }
219
+
220
+ function runCmd(cmd, args) {
221
+ return spawnSync(cmd, args, { encoding: 'utf8', timeout: 15000, windowsHide: true })
222
+ }
223
+
224
+ /** 安装并启用用户级后台服务;`dryRun:true` 不写文件、不调系统命令。 */
225
+ export function installDaemon(opts = {}) {
226
+ const spec = daemonSpec(opts)
227
+ if (opts.dryRun === true) {
228
+ return { ok: true, dryRun: true, kind: spec.kind, servicePath: spec.servicePath, activated: false, warning: null, spec }
229
+ }
230
+ fs.mkdirSync(path.dirname(spec.servicePath), { recursive: true })
231
+ fs.mkdirSync(spec.dataDir, { recursive: true })
232
+ fs.writeFileSync(spec.servicePath, spec.content, { encoding: 'utf8', mode: 0o644 })
233
+
234
+ const skipOs = opts.skipOs === true || process.env.MACRO_MEMORY_DAEMON_SKIP_OS === '1'
235
+ let activated = false
236
+ let warning = null
237
+ if (skipOs) {
238
+ warning = '已跳过系统服务激活(MACRO_MEMORY_DAEMON_SKIP_OS=1)'
239
+ } else if (spec.kind === 'launchd') {
240
+ runCmd(spec.installCmd[0][0], spec.installCmd[0][1])
241
+ const res = runCmd(spec.installCmd[1][0], spec.installCmd[1][1])
242
+ if (res.status === 0) {
243
+ activated = true
244
+ } else {
245
+ const fb = runCmd(spec.fallbackInstallCmd[0], spec.fallbackInstallCmd[1])
246
+ if (fb.status === 0) activated = true
247
+ else warning = String(res.stderr || fb.stderr || res.error?.message || `launchctl 加载失败,可手动运行 launchctl load -w ${spec.servicePath}`).trim()
248
+ }
249
+ } else if (spec.kind === 'systemd-user') {
250
+ const reload = runCmd(spec.installCmd[0][0], spec.installCmd[0][1])
251
+ const en = reload.status === 0 ? runCmd(spec.installCmd[1][0], spec.installCmd[1][1]) : reload
252
+ if (en.status === 0) {
253
+ activated = true
254
+ } else {
255
+ warning = String(en.stderr || en.error?.message || 'systemctl --user 不可用(例如无用户会话 dbus),服务文件已写入,可手工 enable').trim()
256
+ }
257
+ } else {
258
+ const create = runCmd(spec.installCmd[0][0], spec.installCmd[0][1])
259
+ if (create.status === 0) {
260
+ runCmd(spec.installCmd[1][0], spec.installCmd[1][1])
261
+ activated = true
262
+ } else {
263
+ warning = String(create.stderr || create.error?.message || 'schtasks 注册失败').trim()
264
+ }
265
+ }
266
+
267
+ return { ok: true, dryRun: false, kind: spec.kind, servicePath: spec.servicePath, activated, warning, spec }
268
+ }
269
+
270
+ /** 停止、卸载用户级后台服务并删服务文件;绝不删记忆库。 */
271
+ export function uninstallDaemon(opts = {}) {
272
+ const spec = daemonSpec(opts)
273
+ if (opts.dryRun === true) {
274
+ return { ok: true, dryRun: true, kind: spec.kind, servicePath: spec.servicePath, removed: false, stopped: false, spec }
275
+ }
276
+ const skipOs = opts.skipOs === true || process.env.MACRO_MEMORY_DAEMON_SKIP_OS === '1'
277
+ let stopped = false
278
+ if (skipOs) {
279
+ stopped = false
280
+ } else if (spec.kind === 'launchd') {
281
+ const res = runCmd(spec.uninstallCmd[0][0], spec.uninstallCmd[0][1])
282
+ if (res.status === 0) stopped = true
283
+ else if (spec.fallbackUninstallCmd) {
284
+ const fb = runCmd(spec.fallbackUninstallCmd[0], spec.fallbackUninstallCmd[1])
285
+ stopped = fb.status === 0
286
+ }
287
+ } else if (spec.kind === 'systemd-user') {
288
+ const res = runCmd(spec.uninstallCmd[0][0], spec.uninstallCmd[0][1])
289
+ stopped = res.status === 0
290
+ runCmd(spec.uninstallCmd[1][0], spec.uninstallCmd[1][1])
291
+ } else {
292
+ const res = runCmd(spec.uninstallCmd[0][0], spec.uninstallCmd[0][1])
293
+ stopped = res.status === 0
294
+ }
295
+
296
+ const existed = fs.existsSync(spec.servicePath)
297
+ try {
298
+ fs.rmSync(spec.servicePath, { force: true })
299
+ } catch {
300
+ // 删除失败按 removed=false 报告
301
+ }
302
+ const removed = existed && !fs.existsSync(spec.servicePath)
303
+
304
+ if (opts.cleanServeFiles !== false) {
305
+ try {
306
+ fs.rmSync(serveFilePath(spec.dataDir), { force: true })
307
+ fs.rmSync(path.join(spec.dataDir, 'serve.sock'), { force: true })
308
+ } catch {
309
+ // 清理发现文件失败不影响卸载结论
310
+ }
311
+ }
312
+
313
+ return { ok: true, dryRun: false, kind: spec.kind, servicePath: spec.servicePath, removed, stopped, spec }
314
+ }
315
+
316
+ /** 只读检查服务文件与系统注册状态。 */
317
+ export function daemonStatus(opts = {}) {
318
+ const spec = daemonSpec(opts)
319
+ const fileExists = fs.existsSync(spec.servicePath)
320
+ let registered = false
321
+ if (opts.probeOs !== false && spec.platform === currentPlatform()) {
322
+ try {
323
+ if (spec.kind === 'launchd') {
324
+ const uid = typeof process.getuid === 'function' ? process.getuid() : 501
325
+ registered = runCmd('launchctl', ['print', `gui/${uid}/${spec.label}`]).status === 0
326
+ } else if (spec.kind === 'systemd-user') {
327
+ registered = runCmd('systemctl', ['--user', 'is-enabled', spec.label]).status === 0
328
+ } else {
329
+ registered = runCmd('schtasks', ['/Query', '/TN', spec.label]).status === 0
330
+ }
331
+ } catch {
332
+ registered = false
333
+ }
334
+ }
335
+ return { kind: spec.kind, label: spec.label, servicePath: spec.servicePath, fileExists, registered }
336
+ }
@@ -19,6 +19,7 @@ import path from 'node:path'
19
19
  import fs from 'node:fs'
20
20
  import { createMiniHost } from './mini-host.js'
21
21
  import { detectHomeDir, resolveDataDir } from './paths.js'
22
+ import { normalizePathNFC } from '../macro/platform.js'
22
23
  import { ensureTrust, isTrusted, listTrusted, trustWorkspace } from './trust.js'
23
24
  import { checkSchema, readSchemaVersion, schemaRefusalText, stampSchema, SCHEMA_VERSION } from './migrate.js'
24
25
  import { buildVisibility, createOwnerStore, normalizeScope, tagOwners } from './owner.js'
@@ -257,7 +258,7 @@ export async function createMacroEngine(opts = {}) {
257
258
  if (closed) throw new Error('macro-memory:引擎已关闭,不再提供服务')
258
259
  const def = byName.get(name)
259
260
  if (!def) throw new Error(`macro-memory:没有这个工具 ${name}(有:${[...byName.keys()].join('、')})`)
260
- const cwd = path.resolve(execOptions.cwd ?? process.cwd())
261
+ const cwd = normalizePathNFC(path.resolve(execOptions.cwd ?? process.cwd()))
261
262
  const guard = ensureTrust({
262
263
  workspace: cwd,
263
264
  homeDir: homeNow(),
@@ -315,7 +316,7 @@ export async function createMacroEngine(opts = {}) {
315
316
  },
316
317
  /** 这个工作区信不信任(只读,不写 marker)。 */
317
318
  trustState(cwd = process.cwd()) {
318
- const ws = path.resolve(cwd)
319
+ const ws = normalizePathNFC(path.resolve(cwd))
319
320
  return {
320
321
  workspace: ws,
321
322
  dir: path.join(ws, meowDirReader()),
@@ -326,7 +327,7 @@ export async function createMacroEngine(opts = {}) {
326
327
  },
327
328
  /** 显式信任一个工作区(CLI 的 `macro-memory trust` 走这里)。 */
328
329
  trust(cwd = process.cwd(), source = 'macro-memory:cli') {
329
- const ws = path.resolve(cwd)
330
+ const ws = normalizePathNFC(path.resolve(cwd))
330
331
  const ok = trustWorkspace(ws, { homeDir: homeNow(), source })
331
332
  return { workspace: ws, trusted: ok, homeDir: homeNow() }
332
333
  },
@@ -341,7 +342,7 @@ export async function createMacroEngine(opts = {}) {
341
342
  },
342
343
  /** 库版本门状态(doctor / CLI migrate 用,只读不写)。 */
343
344
  schemaState(cwd = process.cwd()) {
344
- const ws = path.resolve(cwd)
345
+ const ws = normalizePathNFC(path.resolve(cwd))
345
346
  return { workspace: ws, dir: path.join(ws, meowDirReader()), ...schemaGate(ws, meowDirReader()) }
346
347
  },
347
348
  /**
@@ -353,7 +354,7 @@ export async function createMacroEngine(opts = {}) {
353
354
  * 老条目没有归属(0.9 之前写的一律没有)。
354
355
  */
355
356
  census(cwd = process.cwd()) {
356
- const ws = path.resolve(cwd)
357
+ const ws = normalizePathNFC(path.resolve(cwd))
357
358
  const dir = meowDirReader()
358
359
  const store = ownerStoreFor(ws, dir)
359
360
  const c = store && typeof store.census === 'function' ? store.census() : null
@@ -398,7 +399,7 @@ export async function createMacroEngine(opts = {}) {
398
399
  * 库比适配层新时**不降级**:那条路只能靠升级适配层,猜着打戳等于替别人做决定。
399
400
  */
400
401
  migrateSchema(cwd = process.cwd(), { to = SCHEMA_VERSION, dryRun = false } = {}) {
401
- const ws = path.resolve(cwd)
402
+ const ws = normalizePathNFC(path.resolve(cwd))
402
403
  const dir = meowDirReader()
403
404
  const file = path.join(ws, dir, 'memory.db')
404
405
  if (!fs.existsSync(file)) return { ok: false, reason: 'no-db', from: null, to, backup: null }
package/lib/core/fence.js CHANGED
@@ -25,7 +25,7 @@ export function detectEol(text) {
25
25
  }
26
26
 
27
27
  /**
28
- * 块正文。`l0` 是引擎给的常驻注入文本(1,266 字符那一份),不在这里改写语义,
28
+ * 块正文。`l0` 是引擎给的常驻注入文本(1,280 字符那一份),不在这里改写语义,
29
29
  * 只加一行业主说明(谁维护、怎么更新、怎么摘)。
30
30
  */
31
31
  export function renderBlock(l0, { sep = 0, eol = '\n', version = FENCE_VERSION } = {}) {