macro-memory 0.9.0 → 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.
- package/README.md +157 -266
- package/bin/macro-memory.mjs +526 -4
- package/docs/CHANGELOG.md +1120 -1
- package/docs/MAC.md +44 -6
- package/lib/core/client.js +56 -22
- package/lib/core/config.js +15 -2
- package/lib/core/daemon.js +336 -0
- package/lib/core/engine.js +7 -6
- package/lib/core/fence.js +1 -1
- package/lib/core/serve.js +37 -14
- package/lib/core/trust.js +6 -2
- package/lib/index.js +209 -3
- package/lib/macro/contract.js +31 -1
- package/lib/macro/defs/admin.js +4 -4
- package/lib/macro/defs/link.js +96 -9
- package/lib/macro/defs/read.js +11 -1
- package/lib/macro/defs/remember.js +89 -1
- package/lib/macro/defs/search.js +157 -6
- package/lib/macro/dreamledger.js +6 -1
- package/lib/macro/evidence.js +84 -0
- package/lib/macro/fakesites.js +93 -0
- package/lib/macro/fusion.js +16 -2
- package/lib/macro/linkflow.js +130 -5
- package/lib/macro/links.js +69 -0
- package/lib/macro/platform.js +74 -0
- package/lib/macro/portability.js +737 -0
- package/lib/macro/prompt.js +6 -6
- package/lib/macro/revisions.js +3 -13
- package/lib/macro/slots.js +252 -0
- package/lib/macro/snapshot.js +309 -1
- package/lib/macro/tools.js +49 -4
- package/lib/macro/topicpages.js +300 -0
- package/lib/mcp/server.js +6 -1
- package/lib/rerank/download.js +68 -0
- package/lib/rerank/provider.js +507 -0
- package/lib/rerank/runtime.js +246 -0
- package/lib/rerank/tokenizer.js +183 -0
- package/lib/semantic/download.js +68 -0
- package/lib/semantic/provider.js +205 -0
- package/lib/semantic/runtime.js +175 -0
- package/lib/semantic/tokenizer.js +169 -0
- package/package.json +1 -1
- package/vendor/VENDOR.json +4 -4
- package/vendor/dsh-memory-nebula/lib/host/adapters/meow.js +7 -1
- package/vendor/dsh-memory-nebula/lib/host/graph.js +183 -3
- package/vendor/dsh-memory-nebula/lib/index.js +75 -3
- package/vendor/dsh-memory-nebula/lib/web/app.js +5 -0
- package/vendor/dsh-memory-nebula/lib/web/i18n.js +1 -0
- package/vendor/meow-memory/lib/index.js +3205 -167
- package/vendor/meow-memory/lib/prompts/en/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/en/tools.md +1 -0
- package/vendor/meow-memory/lib/prompts/pt-br/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/pt-br/tools.md +1 -0
- package/vendor/meow-memory/lib/prompts/zh/labels.md +2 -0
- package/vendor/meow-memory/lib/prompts/zh/tools.md +1 -0
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* [0.18.0 · W4] 记忆的可搬运层:导出、导入、敏感信息浅扫描。
|
|
3
|
+
*
|
|
4
|
+
* 病(PLAN-COMMERCIAL §3.2 A / §3.3):
|
|
5
|
+
* ① 记忆只活在 `.dsh-meow/memory.db` 里,换机器、换工作区、换插件版本都搬不走。
|
|
6
|
+
* 用户能看见「5195 条记忆」,却拿不出一份能读、能带走、能再装回去的东西。
|
|
7
|
+
* ② 导出的意义在**导得回来**:只写不读的导出格式(比如只给人看的 Markdown)
|
|
8
|
+
* 在「搬家」这件事上等于零。所以这里必须有 round-trip——同一个 id、同一段正文,
|
|
9
|
+
* 出去再回来逐字相同。
|
|
10
|
+
* ③ 记忆里会混进密钥、token、卡号、身份证号。导出是这些内容**离开本机库**的那一步,
|
|
11
|
+
* 必须在出口处说一句「第 X 行疑似含敏感信息」——只提示,不改、不拦。
|
|
12
|
+
*
|
|
13
|
+
* 边界(改这个文件之前先读):
|
|
14
|
+
* - **不重写存储层**。读走 `Meow.getDb(ws, dir).list(level)`,写走同一个 store 的
|
|
15
|
+
* `insert(row)`(它本来就支持显式 id / created_at),不另开一条 INSERT 语句。
|
|
16
|
+
* 两份 schema 映射一定会漂:0.2.35 的教训。
|
|
17
|
+
* - **不碰别的插件的库**。星图手工连线是 `$DSH_HOME/memory-nebula/nebula.db`,
|
|
18
|
+
* 这里只读它来做 `links` 字段;导入时也只写 `links` 一张表,不重建图、不改缓存。
|
|
19
|
+
* - **导入默认只预览**。`--apply=<stamp>` 必须与 `importStamp()` 算出来的一字不差
|
|
20
|
+
* (§2.4 既有的危险动作范式:不接受裸 `--apply`)。
|
|
21
|
+
* - 导入是**全有或全无**的一条事务:任何一行校验失败就整批不写,先让人看清是哪一行。
|
|
22
|
+
* - 归档(status=archived)的条目默认也导出——「无损」包括把删掉的东西原样带走,
|
|
23
|
+
* 否则退回来的时候会发现自己少了几条。
|
|
24
|
+
*/
|
|
25
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
26
|
+
import { createHash } from 'node:crypto'
|
|
27
|
+
import { dirname, join } from 'node:path'
|
|
28
|
+
import * as Meow from '../../vendor/meow-memory/lib/index.js'
|
|
29
|
+
|
|
30
|
+
/** 层顺序:和 meow 自己的 LEVELS 保持一致,导出顺序稳定。 */
|
|
31
|
+
export const LEVELS = Array.isArray(Meow.LEVELS) ? Meow.LEVELS : ['soul', 'user', 'project', 'fact', 'lesson', 'topic', 'rules']
|
|
32
|
+
|
|
33
|
+
/** JSONL 每行的键顺序(前面九个是 PLAN §3.2 A 点名的,后面是保真补充)。 */
|
|
34
|
+
const JSONL_KEYS = [
|
|
35
|
+
'id',
|
|
36
|
+
'level',
|
|
37
|
+
'project',
|
|
38
|
+
'content',
|
|
39
|
+
'keywords',
|
|
40
|
+
'importance',
|
|
41
|
+
'status',
|
|
42
|
+
'created_at',
|
|
43
|
+
'links',
|
|
44
|
+
'title',
|
|
45
|
+
'subcategory',
|
|
46
|
+
'goal',
|
|
47
|
+
'corrected',
|
|
48
|
+
'source_session',
|
|
49
|
+
'hit_count',
|
|
50
|
+
'read_count',
|
|
51
|
+
'updated_at',
|
|
52
|
+
'last_accessed_at',
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
/** 敏感信息形态。判据只看「像不像」;卡号与身份证还要过校验位(见下方),否则误报一片。 */
|
|
56
|
+
const SECRET_PATTERNS = [
|
|
57
|
+
{ kind: 'openai-key', re: /\bsk-[A-Za-z0-9_-]{20,}\b/g },
|
|
58
|
+
{ kind: 'aws-key-id', re: /\bAKIA[0-9A-Z]{16}\b/g },
|
|
59
|
+
{ kind: 'github-token', re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/g },
|
|
60
|
+
{ kind: 'private-key', re: /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/g },
|
|
61
|
+
]
|
|
62
|
+
const CARD_RE = /\b(?:\d[ -]?){15,18}\d\b/g
|
|
63
|
+
const CN_ID_RE = /\b\d{17}[\dXx]\b/g
|
|
64
|
+
|
|
65
|
+
/** 这台机器拿不拿得到 node:sqlite(星图连线那一层要用;拿不到就只是没有 links)。 */
|
|
66
|
+
let DatabaseSyncCtor = null
|
|
67
|
+
try {
|
|
68
|
+
const mod = await import('node:sqlite')
|
|
69
|
+
const ctor = mod?.DatabaseSync ?? mod?.default?.DatabaseSync ?? null
|
|
70
|
+
if (typeof ctor === 'function') DatabaseSyncCtor = ctor
|
|
71
|
+
} catch {
|
|
72
|
+
/* 没有就没有:导出照常,只是 links 一栏空着 */
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const nowMs = () => Date.now()
|
|
76
|
+
|
|
77
|
+
/** 库文件路径;工作区为空时抛(调用方要给出人话)。 */
|
|
78
|
+
export function portableDbPath({ workspace = '', dir = '.dsh-meow' } = {}) {
|
|
79
|
+
const ws = String(workspace ?? '').trim()
|
|
80
|
+
if (ws === '') throw new Error('导出/导入需要一个工作区(--cwd 或 MACRO_MEMORY_WORKSPACE)')
|
|
81
|
+
try {
|
|
82
|
+
return Meow.memoryDbPath(ws, dir)
|
|
83
|
+
} catch {
|
|
84
|
+
return join(ws, dir, 'memory.db')
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 星图 sidecar 库路径。**只读**:不存在就当作没有手工连线。 */
|
|
89
|
+
export function nebulaDbPath({ home = '' } = {}) {
|
|
90
|
+
const root = String(home ?? '').trim() !== '' ? String(home).trim() : Meow.dshHomeDir()
|
|
91
|
+
return join(root, 'memory-nebula', 'nebula.db')
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* 读一个工作区的全部条目。
|
|
96
|
+
* @returns {{dbPath:string, exists:boolean, entries:object[], byLevel:Record<string,number>}}
|
|
97
|
+
*/
|
|
98
|
+
export function collectEntries({ workspace = '', dir = '.dsh-meow', levels = LEVELS, status = 'all', project = '' } = {}) {
|
|
99
|
+
const dbPath = portableDbPath({ workspace, dir })
|
|
100
|
+
const exists = existsSync(dbPath)
|
|
101
|
+
const out = []
|
|
102
|
+
const byLevel = {}
|
|
103
|
+
if (!exists) return { dbPath, exists, entries: out, byLevel }
|
|
104
|
+
const store = Meow.getDb(workspace, dir)
|
|
105
|
+
const wanted = levels.filter((l) => LEVELS.includes(l))
|
|
106
|
+
const proj = String(project ?? '').trim()
|
|
107
|
+
for (const level of wanted) {
|
|
108
|
+
let rows = []
|
|
109
|
+
try {
|
|
110
|
+
rows = store.list(level, status === 'all' ? {} : { status })
|
|
111
|
+
} catch {
|
|
112
|
+
rows = []
|
|
113
|
+
}
|
|
114
|
+
for (const row of rows) {
|
|
115
|
+
if (proj !== '' && String(row.project ?? '') !== proj) continue
|
|
116
|
+
out.push(normalizeEntry(row, level))
|
|
117
|
+
byLevel[level] = (byLevel[level] ?? 0) + 1
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
out.sort((a, b) => (a.created_at - b.created_at) || String(a.id).localeCompare(String(b.id)))
|
|
121
|
+
return { dbPath, exists, entries: out, byLevel }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 把 store 的行收敛成导出用的形状(键顺序固定,round-trip 才好对拍)。 */
|
|
125
|
+
export function normalizeEntry(row, level) {
|
|
126
|
+
return {
|
|
127
|
+
id: String(row.id ?? ''),
|
|
128
|
+
level: String(level ?? row.level ?? ''),
|
|
129
|
+
project: row.project == null ? null : String(row.project),
|
|
130
|
+
content: String(row.content ?? ''),
|
|
131
|
+
keywords: Array.isArray(row.keywords) ? row.keywords.map((k) => String(k)) : [],
|
|
132
|
+
importance: Number(row.importance ?? 1),
|
|
133
|
+
status: String(row.status ?? 'active'),
|
|
134
|
+
created_at: Number(row.created_at ?? 0),
|
|
135
|
+
links: [],
|
|
136
|
+
title: row.title == null ? null : String(row.title),
|
|
137
|
+
subcategory: row.subcategory == null ? null : String(row.subcategory),
|
|
138
|
+
goal: row.goal == null ? null : String(row.goal),
|
|
139
|
+
corrected: Number(row.corrected ?? 0),
|
|
140
|
+
source_session: row.source_session == null ? null : String(row.source_session),
|
|
141
|
+
hit_count: Number(row.hit_count ?? 0),
|
|
142
|
+
read_count: Number(row.read_count ?? 0),
|
|
143
|
+
updated_at: Number(row.updated_at ?? 0),
|
|
144
|
+
last_accessed_at: row.last_accessed_at == null ? null : Number(row.last_accessed_at),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 读星图的手工连线(只读,不建库)。
|
|
150
|
+
* @returns {{path:string, exists:boolean, rows:{a:string,b:string,note:string,createdAt:number,updatedAt:number}[], error:string}}
|
|
151
|
+
*/
|
|
152
|
+
export function readLinkRows({ home = '' } = {}) {
|
|
153
|
+
const path = nebulaDbPath({ home })
|
|
154
|
+
const out = { path, exists: existsSync(path), rows: [], error: '' }
|
|
155
|
+
if (!out.exists) return out
|
|
156
|
+
if (DatabaseSyncCtor === null) {
|
|
157
|
+
out.error = '这台机器的 Node 没有内置 node:sqlite,读不了星图连线'
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
let db = null
|
|
161
|
+
try {
|
|
162
|
+
db = new DatabaseSyncCtor(path, { readOnly: true })
|
|
163
|
+
const rows = db.prepare('SELECT a, b, note, created_at, updated_at FROM links ORDER BY updated_at DESC').all()
|
|
164
|
+
out.rows = rows.map((r) => ({
|
|
165
|
+
a: String(r.a),
|
|
166
|
+
b: String(r.b),
|
|
167
|
+
note: String(r.note ?? ''),
|
|
168
|
+
createdAt: Number(r.created_at ?? 0),
|
|
169
|
+
updatedAt: Number(r.updated_at ?? 0),
|
|
170
|
+
}))
|
|
171
|
+
} catch (err) {
|
|
172
|
+
out.error = String(err?.message ?? err)
|
|
173
|
+
} finally {
|
|
174
|
+
try {
|
|
175
|
+
db?.close()
|
|
176
|
+
} catch {
|
|
177
|
+
/* 关不掉不影响读到的内容 */
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return out
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 星图节点 id 的形状是 `meow:<工作区短键>:<层>:<记忆 id>`(见 nebula 的 adapters/meow.js)。
|
|
185
|
+
* 导出时只认后面两段:记忆 id 换台机器也一样,工作区短键则一定变。
|
|
186
|
+
*/
|
|
187
|
+
export function parseNodeId(nodeId) {
|
|
188
|
+
const s = String(nodeId ?? '')
|
|
189
|
+
const m = /^meow:[^:]*:(soul|user|project|fact|lesson|topic|rules):([0-9a-z][0-9a-z-]{5,})$/i.exec(s)
|
|
190
|
+
if (m) return { adapter: 'meow', level: m[1].toLowerCase(), id: m[2] }
|
|
191
|
+
const raw = s.split(':').pop()
|
|
192
|
+
if (raw && /^[0-9a-z][0-9a-z-]{5,}$/i.test(raw)) return { adapter: '', level: '', id: raw }
|
|
193
|
+
return null
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 工作区短键:与 nebula 的 `workspaceKey()` 同一套算法(title 去空格截 24)。 */
|
|
197
|
+
export function workspaceKeyOf(workspace, { home = '' } = {}) {
|
|
198
|
+
const ws = String(workspace ?? '').trim()
|
|
199
|
+
let title = ''
|
|
200
|
+
try {
|
|
201
|
+
const root = String(home ?? '').trim() !== '' ? String(home).trim() : Meow.dshHomeDir()
|
|
202
|
+
const file = join(root, 'storages', 'workspace.json')
|
|
203
|
+
if (existsSync(file)) {
|
|
204
|
+
const data = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
205
|
+
const table = data?.tables?.workspaces
|
|
206
|
+
if (table && typeof table === 'object') {
|
|
207
|
+
const want = ws.replace(/[\\/]+$/, '').toLowerCase()
|
|
208
|
+
for (const rec of Object.values(table)) {
|
|
209
|
+
const p = typeof rec?.path === 'string' ? rec.path.replace(/[\\/]+$/, '') : ''
|
|
210
|
+
if (p !== '' && p.toLowerCase() === want && typeof rec?.title === 'string' && rec.title.trim() !== '') {
|
|
211
|
+
title = rec.title
|
|
212
|
+
break
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
} catch {
|
|
218
|
+
/* 注册表读不到就用目录名兜底 */
|
|
219
|
+
}
|
|
220
|
+
if (title === '') {
|
|
221
|
+
const base = ws.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? ''
|
|
222
|
+
title = base === '' ? ws : base
|
|
223
|
+
}
|
|
224
|
+
return title.replace(/\s+/g, '').slice(0, 24)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* 把连线挂到条目上:只留两端都在导出集合里的(另一端不在,带出去也接不回来)。
|
|
229
|
+
* 星图节点 id 带 `meow:<工作区>:<层>:` 前缀,这里剥掉再按「层 + 记忆 id」对。
|
|
230
|
+
*/
|
|
231
|
+
export function attachLinks(entries, linkRows) {
|
|
232
|
+
const byId = new Map(entries.map((e) => [e.id, e]))
|
|
233
|
+
const byLevelId = new Map(entries.map((e) => [`${e.level}\u0000${e.id}`, e]))
|
|
234
|
+
const pick = (nodeId) => {
|
|
235
|
+
const p = parseNodeId(nodeId)
|
|
236
|
+
if (!p) return null
|
|
237
|
+
if (p.level !== '' && byLevelId.has(`${p.level}\u0000${p.id}`)) return byLevelId.get(`${p.level}\u0000${p.id}`)
|
|
238
|
+
return byId.get(p.id) ?? null
|
|
239
|
+
}
|
|
240
|
+
let n = 0
|
|
241
|
+
for (const row of linkRows) {
|
|
242
|
+
const a = pick(row.a)
|
|
243
|
+
const b = pick(row.b)
|
|
244
|
+
if (a && b && a !== b) {
|
|
245
|
+
a.links.push(b.id)
|
|
246
|
+
b.links.push(a.id)
|
|
247
|
+
n += 1
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
for (const e of entries) e.links = Array.from(new Set(e.links)).sort()
|
|
251
|
+
return { ids: byId.size, links: n }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 一条条目 → 一行 JSON(键顺序固定)。 */
|
|
255
|
+
export function entryToLine(entry) {
|
|
256
|
+
const obj = {}
|
|
257
|
+
for (const k of JSONL_KEYS) obj[k] = entry[k] ?? (k === 'keywords' || k === 'links' ? [] : null)
|
|
258
|
+
return JSON.stringify(obj)
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* 导出 JSONL。
|
|
263
|
+
* @returns {{text:string, lines:number}}
|
|
264
|
+
*/
|
|
265
|
+
export function toJsonl(entries) {
|
|
266
|
+
const lines = entries.map((e) => entryToLine(e))
|
|
267
|
+
return { text: lines.length === 0 ? '' : `${lines.join('\n')}\n`, lines: lines.length }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const pad2 = (n) => String(n).padStart(2, '0')
|
|
271
|
+
/** 人读的时间(本地时区,和人对表用)。 */
|
|
272
|
+
export function humanTime(ms) {
|
|
273
|
+
const n = Number(ms)
|
|
274
|
+
if (!Number.isFinite(n) || n <= 0) return '—'
|
|
275
|
+
const d = new Date(n)
|
|
276
|
+
return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* 导出 Markdown(纯文本查看器就能读:不依赖插件、不依赖表格对齐)。
|
|
281
|
+
* 按 project 分节;没有 project 的归到「未归类」。
|
|
282
|
+
*/
|
|
283
|
+
export function toMarkdown(entries, { workspace = '', generatedAt = nowMs() } = {}) {
|
|
284
|
+
const byProject = new Map()
|
|
285
|
+
for (const e of entries) {
|
|
286
|
+
const key = String(e.project ?? '').trim() === '' ? '未归类' : String(e.project).trim()
|
|
287
|
+
if (!byProject.has(key)) byProject.set(key, [])
|
|
288
|
+
byProject.get(key).push(e)
|
|
289
|
+
}
|
|
290
|
+
const names = Array.from(byProject.keys()).sort((a, b) => (a === '未归类' ? 1 : b === '未归类' ? -1 : a.localeCompare(b)))
|
|
291
|
+
const layerCount = {}
|
|
292
|
+
for (const e of entries) layerCount[e.level] = (layerCount[e.level] ?? 0) + 1
|
|
293
|
+
const lines = [
|
|
294
|
+
`# 宏记忆导出 · ${workspace === '' ? '(未知工作区)' : workspace}`,
|
|
295
|
+
'',
|
|
296
|
+
`生成时间:${humanTime(generatedAt)} · 共 ${entries.length} 条 · ${Object.entries(layerCount).map(([k, v]) => `${k} ${v}`).join(' / ') || '空'}`,
|
|
297
|
+
'(这份是给人读的;要导回库里请用 --format=jsonl 的那份)',
|
|
298
|
+
'',
|
|
299
|
+
]
|
|
300
|
+
if (entries.length === 0) {
|
|
301
|
+
lines.push('库里一条都没有。')
|
|
302
|
+
return lines.join('\n')
|
|
303
|
+
}
|
|
304
|
+
for (const name of names) {
|
|
305
|
+
const list = byProject.get(name)
|
|
306
|
+
lines.push(`## 项目:${name}(${list.length} 条)`, '')
|
|
307
|
+
for (const e of list) {
|
|
308
|
+
lines.push(...renderEntryMarkdown(e))
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
return lines.join('\n')
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function renderEntryMarkdown(e) {
|
|
315
|
+
const title = String(e.title ?? '').trim() === '' ? firstLine(e.content, 48) : String(e.title).trim()
|
|
316
|
+
const meta = [
|
|
317
|
+
`id:${e.id}`,
|
|
318
|
+
`重要度 ${e.importance} · 状态 ${e.status} · ${humanTime(e.created_at)}`,
|
|
319
|
+
]
|
|
320
|
+
if (e.keywords.length > 0) meta.push(`关键词:${e.keywords.join(' / ')}`)
|
|
321
|
+
if (e.links.length > 0) meta.push(`连线:${e.links.join(' / ')}`)
|
|
322
|
+
if (e.goal) meta.push(`目标:${e.goal}`)
|
|
323
|
+
const body = String(e.content ?? '').trim()
|
|
324
|
+
const lines = [`### [${e.level}] ${title}`, ...meta.map((m) => `- ${m}`), '', body, '', '---', '']
|
|
325
|
+
return lines
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function firstLine(text, max) {
|
|
329
|
+
const s = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
330
|
+
return s.length > max ? `${s.slice(0, max)}…` : s
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* 卡号还得看发卡行前缀(IIN)。
|
|
335
|
+
* 只用 Luhn 会有一成随机数字蒙过去:真实库里第一条假阳就是 `202611…36`
|
|
336
|
+
* 这种时间戳串——Luhn 过了,可谁家卡号也不是 2026 开头的。
|
|
337
|
+
* 认这几种:Visa 4 / MasterCard 51-55 与 2221-2720 / Amex 34-37 / JCB 35 /
|
|
338
|
+
* Discover 6011 与 65 / 银联 62。
|
|
339
|
+
*/
|
|
340
|
+
export function cardIinOk(digits) {
|
|
341
|
+
const s = String(digits ?? '').replace(/\D/g, '')
|
|
342
|
+
if (s.length < 16 || s.length > 19) return false
|
|
343
|
+
if (s[0] === '4') return true
|
|
344
|
+
if (/^5[1-5]/.test(s)) return true
|
|
345
|
+
if (/^2[2-7]/.test(s)) return true
|
|
346
|
+
if (/^3[47]/.test(s)) return true
|
|
347
|
+
if (/^35/.test(s)) return true
|
|
348
|
+
if (/^6011/.test(s)) return true
|
|
349
|
+
if (/^65/.test(s)) return true
|
|
350
|
+
if (/^62/.test(s)) return true
|
|
351
|
+
return false
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Luhn 校验:卡号形态里绝大多数随机数字都过不了这一关。 */
|
|
355
|
+
export function luhnOk(digits) {
|
|
356
|
+
const s = String(digits ?? '').replace(/\D/g, '')
|
|
357
|
+
if (s.length < 16 || s.length > 19) return false
|
|
358
|
+
let sum = 0
|
|
359
|
+
let alt = false
|
|
360
|
+
for (let i = s.length - 1; i >= 0; i -= 1) {
|
|
361
|
+
let n = Number(s[i])
|
|
362
|
+
if (alt) {
|
|
363
|
+
n *= 2
|
|
364
|
+
if (n > 9) n -= 9
|
|
365
|
+
}
|
|
366
|
+
sum += n
|
|
367
|
+
alt = !alt
|
|
368
|
+
}
|
|
369
|
+
return sum % 10 === 0
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** 18 位身份证校验位(GB 11643):随机 18 位数字约 11 分之一才能过。 */
|
|
373
|
+
export function cnIdOk(text) {
|
|
374
|
+
const s = String(text ?? '').trim()
|
|
375
|
+
if (!/^\d{17}[\dXx]$/.test(s)) return false
|
|
376
|
+
const y = Number(s.slice(6, 10))
|
|
377
|
+
const m = Number(s.slice(10, 12))
|
|
378
|
+
const d = Number(s.slice(12, 14))
|
|
379
|
+
if (y < 1900 || y > 2099 || m < 1 || m > 12 || d < 1 || d > 31) return false
|
|
380
|
+
const w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
|
|
381
|
+
const map = '10X98765432'
|
|
382
|
+
let sum = 0
|
|
383
|
+
for (let i = 0; i < 17; i += 1) sum += Number(s[i]) * w[i]
|
|
384
|
+
return map[sum % 11] === s[17].toUpperCase()
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** 掩码:只留前 6 个字符,够人对上「是哪一条」,又不把密钥本身再抄一遍。 */
|
|
388
|
+
function mask(sample) {
|
|
389
|
+
const s = String(sample)
|
|
390
|
+
if (s.length <= 8) return `${s.slice(0, 2)}…`
|
|
391
|
+
return `${s.slice(0, 6)}…${s.slice(-2)}`
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* 浅扫描一段文本里的敏感信息。
|
|
396
|
+
* @returns {{line:number, kind:string, sample:string}[]}
|
|
397
|
+
*/
|
|
398
|
+
export function scanSensitive(text) {
|
|
399
|
+
const hits = []
|
|
400
|
+
const lines = String(text ?? '').split('\n')
|
|
401
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
402
|
+
const line = lines[i]
|
|
403
|
+
for (const { kind, re } of SECRET_PATTERNS) {
|
|
404
|
+
re.lastIndex = 0
|
|
405
|
+
let m
|
|
406
|
+
while ((m = re.exec(line)) !== null) {
|
|
407
|
+
hits.push({ line: i + 1, kind, sample: mask(m[0]) })
|
|
408
|
+
if (m[0] === '') break
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
CARD_RE.lastIndex = 0
|
|
412
|
+
let cm
|
|
413
|
+
while ((cm = CARD_RE.exec(line)) !== null) {
|
|
414
|
+
if (luhnOk(cm[0]) && cardIinOk(cm[0])) hits.push({ line: i + 1, kind: 'bank-card', sample: mask(cm[0]) })
|
|
415
|
+
if (cm[0] === '') break
|
|
416
|
+
}
|
|
417
|
+
CN_ID_RE.lastIndex = 0
|
|
418
|
+
let im
|
|
419
|
+
while ((im = CN_ID_RE.exec(line)) !== null) {
|
|
420
|
+
if (cnIdOk(im[0])) hits.push({ line: i + 1, kind: 'cn-id', sample: mask(im[0]) })
|
|
421
|
+
if (im[0] === '') break
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
return hits
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** 敏感信息说成人话(导出回执末尾那一段)。 */
|
|
428
|
+
export function sensitiveReport(hits, totalLines) {
|
|
429
|
+
if (hits.length === 0) return `敏感信息:${totalLines} 行里没扫到(只提示,不改内容)`
|
|
430
|
+
const kinds = {}
|
|
431
|
+
for (const h of hits) kinds[h.kind] = (kinds[h.kind] ?? 0) + 1
|
|
432
|
+
const lines = [`敏感信息:${hits.length} 处(只提示,不改内容)——${Object.entries(kinds).map(([k, v]) => `${k} ${v}`).join(' / ')}`]
|
|
433
|
+
for (const h of hits.slice(0, 12)) lines.push(` 第 ${h.line} 行疑似含敏感信息:${h.kind}(${h.sample})`)
|
|
434
|
+
if (hits.length > 12) lines.push(` 另有 ${hits.length - 12} 处没逐条列出`)
|
|
435
|
+
return lines.join('\n')
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* 导入的确认印:同一份文件 + 同一个库 → 同一个印。
|
|
440
|
+
* 换文件或换库都会变,抄旧印没用。
|
|
441
|
+
*/
|
|
442
|
+
export function importStamp({ text = '', dbPath = '' } = {}) {
|
|
443
|
+
return createHash('sha256').update(String(text)).update('\u0000').update(String(dbPath)).digest('hex').slice(0, 8)
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* 解析 JSONL。空行跳过;`_meta` 行跳过;其余逐行校验。
|
|
448
|
+
* @returns {{entries:object[], invalid:{line:number, why:string}[], meta:object|null}}
|
|
449
|
+
*/
|
|
450
|
+
export function parseJsonl(text) {
|
|
451
|
+
const entries = []
|
|
452
|
+
const invalid = []
|
|
453
|
+
let meta = null
|
|
454
|
+
const lines = String(text ?? '').split('\n')
|
|
455
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
456
|
+
const raw = lines[i].trim()
|
|
457
|
+
if (raw === '') continue
|
|
458
|
+
let obj
|
|
459
|
+
try {
|
|
460
|
+
obj = JSON.parse(raw)
|
|
461
|
+
} catch (err) {
|
|
462
|
+
invalid.push({ line: i + 1, why: `不是合法 JSON:${String(err?.message ?? err).slice(0, 80)}` })
|
|
463
|
+
continue
|
|
464
|
+
}
|
|
465
|
+
if (obj && obj._meta !== undefined) {
|
|
466
|
+
meta = obj._meta
|
|
467
|
+
continue
|
|
468
|
+
}
|
|
469
|
+
if (!obj || typeof obj !== 'object') {
|
|
470
|
+
invalid.push({ line: i + 1, why: '不是一个对象' })
|
|
471
|
+
continue
|
|
472
|
+
}
|
|
473
|
+
const level = String(obj.level ?? '').trim()
|
|
474
|
+
if (!LEVELS.includes(level)) {
|
|
475
|
+
invalid.push({ line: i + 1, why: `level 不认识:${level === '' ? '(空)' : level}` })
|
|
476
|
+
continue
|
|
477
|
+
}
|
|
478
|
+
if (typeof obj.content !== 'string' || obj.content.trim() === '') {
|
|
479
|
+
invalid.push({ line: i + 1, why: 'content 是空的' })
|
|
480
|
+
continue
|
|
481
|
+
}
|
|
482
|
+
const id = typeof obj.id === 'string' ? obj.id.trim() : ''
|
|
483
|
+
if (id !== '' && !/^[0-9a-z][0-9a-z-]{5,}$/i.test(id)) {
|
|
484
|
+
invalid.push({ line: i + 1, why: `id 形状不对:${id.slice(0, 24)}` })
|
|
485
|
+
continue
|
|
486
|
+
}
|
|
487
|
+
entries.push({
|
|
488
|
+
id: id === '' ? null : id,
|
|
489
|
+
level,
|
|
490
|
+
project: obj.project == null ? null : String(obj.project),
|
|
491
|
+
content: obj.content,
|
|
492
|
+
keywords: Array.isArray(obj.keywords) ? obj.keywords.map((k) => String(k)) : [],
|
|
493
|
+
importance: Number.isFinite(Number(obj.importance)) ? Number(obj.importance) : 1,
|
|
494
|
+
status: ['active', 'stale', 'archived'].includes(String(obj.status)) ? String(obj.status) : 'active',
|
|
495
|
+
created_at: Number.isFinite(Number(obj.created_at)) && Number(obj.created_at) > 0 ? Number(obj.created_at) : nowMs(),
|
|
496
|
+
links: Array.isArray(obj.links) ? obj.links.map((x) => String(x)).filter((x) => x !== '') : [],
|
|
497
|
+
title: obj.title == null ? null : String(obj.title),
|
|
498
|
+
subcategory: obj.subcategory == null ? null : String(obj.subcategory),
|
|
499
|
+
goal: obj.goal == null ? null : String(obj.goal),
|
|
500
|
+
corrected: obj.corrected === true || Number(obj.corrected) === 1 ? 1 : 0,
|
|
501
|
+
source_session: obj.source_session == null ? null : String(obj.source_session),
|
|
502
|
+
hit_count: Number.isFinite(Number(obj.hit_count)) ? Number(obj.hit_count) : 0,
|
|
503
|
+
read_count: Number.isFinite(Number(obj.read_count)) ? Number(obj.read_count) : 0,
|
|
504
|
+
updated_at: Number.isFinite(Number(obj.updated_at)) && Number(obj.updated_at) > 0 ? Number(obj.updated_at) : Number(obj.created_at) || nowMs(),
|
|
505
|
+
last_accessed_at: obj.last_accessed_at == null ? null : Number(obj.last_accessed_at),
|
|
506
|
+
_line: i + 1,
|
|
507
|
+
})
|
|
508
|
+
}
|
|
509
|
+
return { entries, invalid, meta }
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** 把一条解析结果变成 store.insert 认的行。 */
|
|
513
|
+
function insertRowOf(e) {
|
|
514
|
+
return {
|
|
515
|
+
...(e.id === null ? {} : { id: e.id }),
|
|
516
|
+
level: e.level,
|
|
517
|
+
title: e.title,
|
|
518
|
+
content: e.content,
|
|
519
|
+
importance: e.importance,
|
|
520
|
+
keywords: e.keywords,
|
|
521
|
+
status: e.status,
|
|
522
|
+
corrected: e.corrected,
|
|
523
|
+
project: e.project ?? (e.level === 'project' ? '' : null),
|
|
524
|
+
subcategory: e.subcategory,
|
|
525
|
+
goal: e.goal,
|
|
526
|
+
source_session: e.source_session,
|
|
527
|
+
hit_count: e.hit_count,
|
|
528
|
+
created_at: e.created_at,
|
|
529
|
+
updated_at: e.updated_at,
|
|
530
|
+
last_accessed_at: e.last_accessed_at,
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* 导入。默认 dry-run(一个字节不写)。
|
|
536
|
+
*
|
|
537
|
+
* @param {object} opts
|
|
538
|
+
* @param {string} opts.workspace 工作区
|
|
539
|
+
* @param {string} [opts.dir]
|
|
540
|
+
* @param {string} opts.text JSONL 原文
|
|
541
|
+
* @param {boolean} [opts.overwrite] 同 id 已存在时替换(默认跳过)
|
|
542
|
+
* @param {boolean} [opts.dryRun]
|
|
543
|
+
* @param {string} [opts.apply] 必须等于 importStamp() 算出来的印
|
|
544
|
+
* @returns {{status:string, stamp:string, dbPath:string, entries:number, invalid:object[], inserted:number, skipped:number, replaced:number, links:number, why?:string}}
|
|
545
|
+
*/
|
|
546
|
+
export function importJsonl({ workspace = '', dir = '.dsh-meow', text = '', overwrite = false, dryRun = true, apply = '' } = {}) {
|
|
547
|
+
const dbPath = portableDbPath({ workspace, dir })
|
|
548
|
+
const stamp = importStamp({ text, dbPath })
|
|
549
|
+
const parsed = parseJsonl(text)
|
|
550
|
+
const report = {
|
|
551
|
+
status: 'dry-run',
|
|
552
|
+
stamp,
|
|
553
|
+
dbPath,
|
|
554
|
+
entries: parsed.entries.length,
|
|
555
|
+
invalid: parsed.invalid,
|
|
556
|
+
inserted: 0,
|
|
557
|
+
skipped: 0,
|
|
558
|
+
replaced: 0,
|
|
559
|
+
links: 0,
|
|
560
|
+
}
|
|
561
|
+
if (parsed.invalid.length > 0) {
|
|
562
|
+
report.status = 'invalid'
|
|
563
|
+
report.why = `有 ${parsed.invalid.length} 行没通过校验,整批不写(先改文件)`
|
|
564
|
+
return report
|
|
565
|
+
}
|
|
566
|
+
if (dryRun) {
|
|
567
|
+
// 预览也要知道会跳过几条:拿现库的 id 集合对一遍,不写。
|
|
568
|
+
const known = new Set()
|
|
569
|
+
if (existsSync(dbPath)) {
|
|
570
|
+
const store = Meow.getDb(workspace, dir)
|
|
571
|
+
for (const level of LEVELS) {
|
|
572
|
+
for (const row of store.list(level)) known.add(String(row.id))
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
for (const e of parsed.entries) if (e.id !== null && known.has(e.id)) report.skipped += 1
|
|
576
|
+
report.wouldInsert = parsed.entries.length - report.skipped
|
|
577
|
+
return report
|
|
578
|
+
}
|
|
579
|
+
if (String(apply) !== stamp) {
|
|
580
|
+
report.status = 'need-apply'
|
|
581
|
+
report.why = `真写要加 --apply=${stamp}(这个印只对这份文件 + 这个库有效)`
|
|
582
|
+
return report
|
|
583
|
+
}
|
|
584
|
+
if (parsed.entries.length === 0) {
|
|
585
|
+
report.status = 'empty'
|
|
586
|
+
report.why = '文件里没有可导入的条目'
|
|
587
|
+
return report
|
|
588
|
+
}
|
|
589
|
+
const store = Meow.getDb(workspace, dir)
|
|
590
|
+
const known = new Set()
|
|
591
|
+
for (const level of LEVELS) for (const row of store.list(level)) known.add(String(row.id))
|
|
592
|
+
let tx = false
|
|
593
|
+
try {
|
|
594
|
+
store.db.exec('BEGIN IMMEDIATE')
|
|
595
|
+
tx = true
|
|
596
|
+
for (const e of parsed.entries) {
|
|
597
|
+
const exists = e.id !== null && known.has(e.id)
|
|
598
|
+
if (exists && !overwrite) {
|
|
599
|
+
report.skipped += 1
|
|
600
|
+
continue
|
|
601
|
+
}
|
|
602
|
+
if (exists && overwrite) {
|
|
603
|
+
store.db.prepare(`DELETE FROM ${e.level} WHERE id = ?`).run(e.id)
|
|
604
|
+
report.replaced += 1
|
|
605
|
+
}
|
|
606
|
+
const row = store.insert(insertRowOf(e))
|
|
607
|
+
// meow 的 insert() 语句里没有 read_count 这一列(只有 hit_count),
|
|
608
|
+
// 但「无损」得算上它:同一事务里补一条 UPDATE,别让它悄悄归零。
|
|
609
|
+
if (e.read_count > 0) {
|
|
610
|
+
store.db.prepare(`UPDATE ${e.level} SET read_count = ? WHERE id = ?`).run(e.read_count, row.id)
|
|
611
|
+
}
|
|
612
|
+
known.add(String(row.id))
|
|
613
|
+
report.inserted += 1
|
|
614
|
+
if (e.id === null) e.id = String(row.id)
|
|
615
|
+
}
|
|
616
|
+
store.db.exec('COMMIT')
|
|
617
|
+
tx = false
|
|
618
|
+
} catch (err) {
|
|
619
|
+
if (tx) {
|
|
620
|
+
try {
|
|
621
|
+
store.db.exec('ROLLBACK')
|
|
622
|
+
} catch {
|
|
623
|
+
/* 回滚失败就让它带着原错误往上走 */
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
report.status = 'error'
|
|
627
|
+
report.why = String(err?.message ?? err)
|
|
628
|
+
return report
|
|
629
|
+
}
|
|
630
|
+
// 连线:另开一份 sidecar 写,只写 links 表;图会在下一轮巡检自己收进来。
|
|
631
|
+
report.links = restoreLinks(parsed.entries, { workspace })
|
|
632
|
+
report.status = 'imported'
|
|
633
|
+
return report
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 把条目里的 links 还原成星图手工边。
|
|
638
|
+
* 只写 `$DSH_HOME/memory-nebula/nebula.db` 的 links 表(nebula 自己的 `addLink` 也就是这一句),
|
|
639
|
+
* 不重建图、不碰缓存;下一轮巡检(约 12s)会把边收进图里。
|
|
640
|
+
*
|
|
641
|
+
* 写进去的是**完整节点 id**(`meow:<目标工作区短键>:<层>:<id>`),不是裸记忆 id:
|
|
642
|
+
* 建图时 `graph.js:808` 用 `index.get(m.a)` 精确查节点,裸 id 查不到,边会被静默丢掉。
|
|
643
|
+
*/
|
|
644
|
+
export function restoreLinks(entries, { workspace = '', home = '' } = {}) {
|
|
645
|
+
const path = nebulaDbPath({ home })
|
|
646
|
+
if (!existsSync(path) || DatabaseSyncCtor === null) return 0
|
|
647
|
+
const key = workspaceKeyOf(workspace, { home })
|
|
648
|
+
const nodeIdOf = (e) => `meow:${key}:${e.level}:${e.id}`
|
|
649
|
+
const byId = new Map(entries.filter((e) => e.id !== null).map((e) => [String(e.id), e]))
|
|
650
|
+
const pairs = []
|
|
651
|
+
for (const e of entries) {
|
|
652
|
+
if (e.id === null) continue
|
|
653
|
+
for (const other of e.links) {
|
|
654
|
+
const peer = byId.get(other)
|
|
655
|
+
if (!peer) continue
|
|
656
|
+
const x = nodeIdOf(e)
|
|
657
|
+
const y = nodeIdOf(peer)
|
|
658
|
+
if (x === y) continue
|
|
659
|
+
pairs.push(x < y ? [x, y] : [y, x])
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
if (pairs.length === 0) return 0
|
|
663
|
+
let db = null
|
|
664
|
+
let n = 0
|
|
665
|
+
try {
|
|
666
|
+
db = new DatabaseSyncCtor(path)
|
|
667
|
+
const now = nowMs()
|
|
668
|
+
const stmt = db.prepare(
|
|
669
|
+
`INSERT INTO links (id, a, b, note, created_at, updated_at) VALUES (?, ?, ?, '', ?, ?)
|
|
670
|
+
ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
|
|
671
|
+
)
|
|
672
|
+
const seen = new Set()
|
|
673
|
+
for (const [a, b] of pairs) {
|
|
674
|
+
const id = `${a}\u0000${b}`
|
|
675
|
+
if (seen.has(id)) continue
|
|
676
|
+
seen.add(id)
|
|
677
|
+
stmt.run(id, a, b, now, now)
|
|
678
|
+
n += 1
|
|
679
|
+
}
|
|
680
|
+
} catch {
|
|
681
|
+
return n
|
|
682
|
+
} finally {
|
|
683
|
+
try {
|
|
684
|
+
db?.close()
|
|
685
|
+
} catch {
|
|
686
|
+
/* 关不掉不影响已经写进去的边 */
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
return n
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** 导出一步到位:读库 → 挂连线 → 生成文本 → 扫敏感信息。 */
|
|
693
|
+
export function exportMemories({ workspace = '', dir = '.dsh-meow', format = 'jsonl', status = 'all', levels = LEVELS, project = '', withLinks = true, generatedAt = nowMs() } = {}) {
|
|
694
|
+
const collected = collectEntries({ workspace, dir, levels, status, project })
|
|
695
|
+
let linkInfo = { ids: 0, links: 0 }
|
|
696
|
+
let linkError = ''
|
|
697
|
+
if (withLinks && collected.exists) {
|
|
698
|
+
const lr = readLinkRows()
|
|
699
|
+
linkError = lr.error
|
|
700
|
+
if (lr.rows.length > 0) linkInfo = attachLinks(collected.entries, lr.rows)
|
|
701
|
+
}
|
|
702
|
+
const text = format === 'md' ? toMarkdown(collected.entries, { workspace, generatedAt }) : toJsonl(collected.entries).text
|
|
703
|
+
const hits = scanSensitive(text)
|
|
704
|
+
return {
|
|
705
|
+
workspace,
|
|
706
|
+
dbPath: collected.dbPath,
|
|
707
|
+
exists: collected.exists,
|
|
708
|
+
format,
|
|
709
|
+
entries: collected.entries.length,
|
|
710
|
+
byLevel: collected.byLevel,
|
|
711
|
+
links: linkInfo.links,
|
|
712
|
+
linkError,
|
|
713
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
714
|
+
text,
|
|
715
|
+
sensitive: hits,
|
|
716
|
+
generatedAt,
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/** 写文件(导出用;目录不存在就建)。 */
|
|
721
|
+
export function writeExportFile(file, text) {
|
|
722
|
+
const target = String(file ?? '').trim()
|
|
723
|
+
if (target === '') throw new Error('--to 要给一个文件路径')
|
|
724
|
+
// 目录不存在这一类错误最常见:先建一次再写,别让人手动 mkdir。
|
|
725
|
+
const dir = dirname(target)
|
|
726
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
727
|
+
writeFileSync(target, text, 'utf8')
|
|
728
|
+
return { file: target, bytes: statSync(target).size }
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** 读文件(导入用);读不到就把原因说清楚。 */
|
|
732
|
+
export function readImportFile(file) {
|
|
733
|
+
const target = String(file ?? '').trim()
|
|
734
|
+
if (target === '') throw new Error('--from 要给一个 JSONL 文件路径')
|
|
735
|
+
if (!existsSync(target)) throw new Error(`文件不存在:${target}`)
|
|
736
|
+
return readFileSync(target, 'utf8')
|
|
737
|
+
}
|